github.com/vmware/govmomi@v0.37.2/govc/device/remove.go (about)

     1  /*
     2  Copyright (c) 2014-2017 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 device
    18  
    19  import (
    20  	"context"
    21  	"flag"
    22  	"fmt"
    23  
    24  	"github.com/vmware/govmomi/govc/cli"
    25  	"github.com/vmware/govmomi/govc/flags"
    26  )
    27  
    28  type remove struct {
    29  	*flags.VirtualMachineFlag
    30  	keepFiles bool
    31  }
    32  
    33  func init() {
    34  	cli.Register("device.remove", &remove{})
    35  }
    36  
    37  func (cmd *remove) Register(ctx context.Context, f *flag.FlagSet) {
    38  	cmd.VirtualMachineFlag, ctx = flags.NewVirtualMachineFlag(ctx)
    39  	cmd.VirtualMachineFlag.Register(ctx, f)
    40  	f.BoolVar(&cmd.keepFiles, "keep", false, "Keep files in datastore")
    41  }
    42  
    43  func (cmd *remove) Process(ctx context.Context) error {
    44  	if err := cmd.VirtualMachineFlag.Process(ctx); err != nil {
    45  		return err
    46  	}
    47  	return nil
    48  }
    49  
    50  func (cmd *remove) Usage() string {
    51  	return "DEVICE..."
    52  }
    53  
    54  func (cmd *remove) Description() string {
    55  	return `Remove DEVICE from VM.
    56  
    57  Examples:
    58    govc device.remove -vm $name cdrom-3000
    59    govc device.remove -vm $name disk-1000
    60    govc device.remove -vm $name -keep disk-*`
    61  }
    62  
    63  func (cmd *remove) Run(ctx context.Context, f *flag.FlagSet) error {
    64  	vm, err := cmd.VirtualMachine()
    65  	if err != nil {
    66  		return err
    67  	}
    68  
    69  	if vm == nil {
    70  		return flag.ErrHelp
    71  	}
    72  
    73  	devices, err := vm.Device(ctx)
    74  	if err != nil {
    75  		return err
    76  	}
    77  
    78  	for _, name := range f.Args() {
    79  		device := match(name, devices)
    80  		if len(device) == 0 {
    81  			return fmt.Errorf("device '%s' not found", name)
    82  		}
    83  
    84  		if err = vm.RemoveDevice(ctx, cmd.keepFiles, device...); err != nil {
    85  			return err
    86  		}
    87  	}
    88  
    89  	return nil
    90  }