| 1 | |
| 2 | |
| 3 | |
| 4 | package main |
| 5 | |
| 6 | import ( |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | |
| 10 | "github.com/sirupsen/logrus" |
| 11 | "github.com/spf13/cobra" |
| 12 | |
| 13 | "github.com/lima-vm/lima/v2/pkg/store" |
| 14 | ) |
| 15 | |
| 16 | func newProtectCommand() *cobra.Command { |
| 17 | protectCommand := &cobra.Command{ |
| 18 | Use: "protect INSTANCE [INSTANCE, ...]", |
| 19 | Short: "Protect an instance to prohibit accidental removal", |
| 20 | Long: `Protect an instance to prohibit accidental removal via the 'limactl delete' command. |
| 21 | The instance is not being protected against removal via '/bin/rm', Finder, etc.`, |
| 22 | Args: WrapArgsError(cobra.MinimumNArgs(1)), |
| 23 | RunE: protectAction, |
| 24 | ValidArgsFunction: protectBashComplete, |
| 25 | GroupID: advancedCommand, |
| 26 | } |
| 27 | return protectCommand |
| 28 | } |
| 29 | |
| 30 | func protectAction(cmd *cobra.Command, args []string) error { |
| 31 | ctx := cmd.Context() |
| 32 | var errs []error |
| 33 | for _, instName := range args { |
| 34 | inst, err := store.Inspect(ctx, instName) |
| 35 | if err != nil { |
| 36 | errs = append(errs, fmt.Errorf("failed to inspect instance %#q: %w", instName, err)) |
| 37 | continue |
| 38 | } |
| 39 | if inst.Protected { |
| 40 | logrus.Warnf("Instance %#q is already protected. Skipping.", instName) |
| 41 | continue |
| 42 | } |
| 43 | if err := inst.Protect(); err != nil { |
| 44 | errs = append(errs, fmt.Errorf("failed to protect instance %#q: %w", instName, err)) |
| 45 | continue |
| 46 | } |
| 47 | logrus.Infof("Protected %#q", instName) |
| 48 | } |
| 49 | return errors.Join(errs...) |
| 50 | } |
| 51 | |
| 52 | func protectBashComplete(cmd *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) { |
| 53 | return bashCompleteInstanceNames(cmd) |
| 54 | } |