github.com/vmware/govmomi@v0.43.0/govc/vm/dataset/ls.go (about)

     1  /*
     2  Copyright (c) 2023-2023 VMware, Inc. All Rights Reserved.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8  http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package dataset
    18  
    19  import (
    20  	"context"
    21  	"flag"
    22  	"fmt"
    23  	"io"
    24  
    25  	"github.com/vmware/govmomi/govc/cli"
    26  	"github.com/vmware/govmomi/govc/flags"
    27  	"github.com/vmware/govmomi/vapi/vm/dataset"
    28  )
    29  
    30  type ls struct {
    31  	*flags.VirtualMachineFlag
    32  	*flags.OutputFlag
    33  }
    34  
    35  func init() {
    36  	cli.Register("vm.dataset.ls", &ls{})
    37  }
    38  
    39  func (cmd *ls) Register(ctx context.Context, f *flag.FlagSet) {
    40  	cmd.OutputFlag, ctx = flags.NewOutputFlag(ctx)
    41  	cmd.OutputFlag.Register(ctx, f)
    42  	cmd.VirtualMachineFlag, ctx = flags.NewVirtualMachineFlag(ctx)
    43  	cmd.VirtualMachineFlag.Register(ctx, f)
    44  }
    45  
    46  func (cmd *ls) Process(ctx context.Context) error {
    47  	if err := cmd.VirtualMachineFlag.Process(ctx); err != nil {
    48  		return err
    49  	}
    50  	return cmd.OutputFlag.Process(ctx)
    51  }
    52  
    53  func (cmd *ls) Description() string {
    54  	return `List datasets.
    55  
    56  Examples:
    57    govc vm.dataset.ls -vm $vm
    58    govc vm.dataset.ls -vm $vm -json | jq '.[].description'`
    59  }
    60  
    61  type lsResult []dataset.Summary
    62  
    63  func (r lsResult) Write(w io.Writer) error {
    64  	for _, d := range r {
    65  		fmt.Fprintln(w, d.Name)
    66  	}
    67  	return nil
    68  }
    69  
    70  func (cmd *ls) Run(ctx context.Context, f *flag.FlagSet) error {
    71  	vm, err := cmd.VirtualMachineFlag.VirtualMachine()
    72  	if err != nil {
    73  		return err
    74  	}
    75  	if vm == nil {
    76  		return flag.ErrHelp
    77  	}
    78  	vmId := vm.Reference().Value
    79  
    80  	c, err := cmd.RestClient()
    81  	if err != nil {
    82  		return err
    83  	}
    84  	mgr := dataset.NewManager(c)
    85  	l, err := mgr.ListDataSets(ctx, vmId)
    86  	if err != nil {
    87  		return err
    88  	}
    89  	return cmd.WriteResult(lsResult(l))
    90  }