| 1 | |
| 2 | |
| 3 | |
| 4 | package main |
| 5 | |
| 6 | import ( |
| 7 | "errors" |
| 8 | |
| 9 | "github.com/spf13/cobra" |
| 10 | |
| 11 | "github.com/lima-vm/lima/v2/pkg/instance" |
| 12 | "github.com/lima-vm/lima/v2/pkg/networks/reconcile" |
| 13 | "github.com/lima-vm/lima/v2/pkg/store" |
| 14 | ) |
| 15 | |
| 16 | func newStopCommand() *cobra.Command { |
| 17 | stopCmd := &cobra.Command{ |
| 18 | Use: "stop INSTANCE [INSTANCE, ...]", |
| 19 | Short: "Stop an instance", |
| 20 | Args: WrapArgsError(cobra.ArbitraryArgs), |
| 21 | RunE: stopAction, |
| 22 | ValidArgsFunction: stopBashComplete, |
| 23 | GroupID: basicCommand, |
| 24 | } |
| 25 | |
| 26 | stopCmd.Flags().BoolP("force", "f", false, "Force stop the instance") |
| 27 | return stopCmd |
| 28 | } |
| 29 | |
| 30 | func stopAction(cmd *cobra.Command, args []string) error { |
| 31 | ctx := cmd.Context() |
| 32 | |
| 33 | instNames := args |
| 34 | if len(instNames) == 0 { |
| 35 | instNames = []string{DefaultInstanceName} |
| 36 | } |
| 37 | |
| 38 | force, err := cmd.Flags().GetBool("force") |
| 39 | if err != nil { |
| 40 | return err |
| 41 | } |
| 42 | |
| 43 | var errs []error |
| 44 | for _, instName := range instNames { |
| 45 | inst, err := store.Inspect(ctx, instName) |
| 46 | if err != nil { |
| 47 | errs = append(errs, err) |
| 48 | continue |
| 49 | } |
| 50 | |
| 51 | if force { |
| 52 | instance.StopForcibly(inst) |
| 53 | } else if err := instance.StopGracefully(ctx, inst, false); err != nil { |
| 54 | errs = append(errs, err) |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | TODO: |
| 59 | if err := reconcile.Reconcile(ctx, ""); err != nil { |
| 60 | errs = append(errs, err) |
| 61 | } |
| 62 | return errors.Join(errs...) |
| 63 | } |
| 64 | |
| 65 | func stopBashComplete(cmd *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) { |
| 66 | return bashCompleteInstanceNames(cmd) |
| 67 | } |