|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "errors" |
| 5 | + "os" |
| 6 | + "path/filepath" |
| 7 | + "strings" |
| 8 | + |
| 9 | + networks "github.com/lima-vm/lima/pkg/networks/reconcile" |
| 10 | + "github.com/lima-vm/lima/pkg/start" |
| 11 | + "github.com/lima-vm/lima/pkg/store" |
| 12 | + "github.com/sirupsen/logrus" |
| 13 | + "github.com/spf13/cobra" |
| 14 | +) |
| 15 | + |
| 16 | +func newFactoryResetCommand() *cobra.Command { |
| 17 | + var resetCommand = &cobra.Command{ |
| 18 | + Use: "factory-reset INSTANCE", |
| 19 | + Short: "Factory reset an instance of Lima", |
| 20 | + Args: cobra.MaximumNArgs(1), |
| 21 | + RunE: factoryResetAction, |
| 22 | + ValidArgsFunction: factoryResetBashComplete, |
| 23 | + } |
| 24 | + return resetCommand |
| 25 | +} |
| 26 | + |
| 27 | +func factoryResetAction(cmd *cobra.Command, args []string) error { |
| 28 | + instName := DefaultInstanceName |
| 29 | + if len(args) > 0 { |
| 30 | + instName = args[0] |
| 31 | + } |
| 32 | + |
| 33 | + inst, err := store.Inspect(instName) |
| 34 | + if err != nil { |
| 35 | + if errors.Is(err, os.ErrNotExist) { |
| 36 | + logrus.Infof("Instance %q not found", instName) |
| 37 | + return nil |
| 38 | + } |
| 39 | + return err |
| 40 | + } |
| 41 | + |
| 42 | + stopInstanceForcibly(inst) |
| 43 | + |
| 44 | + fi, err := os.ReadDir(inst.Dir) |
| 45 | + if err != nil { |
| 46 | + return err |
| 47 | + } |
| 48 | + for _, f := range fi { |
| 49 | + path := filepath.Join(inst.Dir, f.Name()) |
| 50 | + if !strings.HasSuffix(path, ".yaml") && !strings.HasSuffix(path, ".yml") { |
| 51 | + logrus.Infof("Removing %q", path) |
| 52 | + if err := os.Remove(path); err != nil { |
| 53 | + logrus.Error(err) |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + logrus.Infof("Instance %q has been factory reset", instName) |
| 58 | + |
| 59 | + startNow, err := askWhetherToStart() |
| 60 | + if err != nil { |
| 61 | + return err |
| 62 | + } |
| 63 | + if !startNow { |
| 64 | + return nil |
| 65 | + } |
| 66 | + ctx := cmd.Context() |
| 67 | + err = networks.Reconcile(ctx, inst.Name) |
| 68 | + if err != nil { |
| 69 | + return err |
| 70 | + } |
| 71 | + return start.Start(ctx, inst) |
| 72 | +} |
| 73 | + |
| 74 | +func factoryResetBashComplete(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { |
| 75 | + return bashCompleteInstanceNames(cmd) |
| 76 | +} |
0 commit comments