/
delete.go
85 lines (75 loc) · 2.57 KB
/
delete.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package main
import (
"context"
"errors"
"fmt"
"os"
"runtime"
"github.com/lima-vm/lima/pkg/autostart"
networks "github.com/lima-vm/lima/pkg/networks/reconcile"
"github.com/lima-vm/lima/pkg/stop"
"github.com/lima-vm/lima/pkg/store"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
func newDeleteCommand() *cobra.Command {
deleteCommand := &cobra.Command{
Use: "delete INSTANCE [INSTANCE, ...]",
Aliases: []string{"remove", "rm"},
Short: "Delete an instance of Lima.",
Args: WrapArgsError(cobra.MinimumNArgs(1)),
RunE: deleteAction,
ValidArgsFunction: deleteBashComplete,
GroupID: basicCommand,
}
deleteCommand.Flags().BoolP("force", "f", false, "forcibly kill the processes")
return deleteCommand
}
func deleteAction(cmd *cobra.Command, args []string) error {
force, err := cmd.Flags().GetBool("force")
if err != nil {
return err
}
for _, instName := range args {
inst, err := store.Inspect(instName)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
logrus.Warnf("Ignoring non-existent instance %q", instName)
continue
}
return err
}
if err := deleteInstance(cmd.Context(), inst, force); err != nil {
return fmt.Errorf("failed to delete instance %q: %w", instName, err)
}
if runtime.GOOS == "darwin" || runtime.GOOS == "linux" {
deleted, err := autostart.DeleteStartAtLoginEntry(runtime.GOOS, instName)
if err != nil && !errors.Is(err, os.ErrNotExist) {
logrus.WithError(err).Warnf("The autostart file for instance %q does not exist", instName)
} else if deleted {
logrus.Infof("The autostart file %q has been deleted", autostart.GetFilePath(runtime.GOOS, instName))
}
}
logrus.Infof("Deleted %q (%q)", instName, inst.Dir)
}
return networks.Reconcile(cmd.Context(), "")
}
func deleteInstance(ctx context.Context, inst *store.Instance, force bool) error {
if inst.Protected {
return fmt.Errorf("instance is protected to prohibit accidental removal (Hint: use `limactl unprotect`)")
}
if !force && inst.Status != store.StatusStopped {
return fmt.Errorf("expected status %q, got %q", store.StatusStopped, inst.Status)
}
stopInstanceForcibly(inst)
if err := stop.Unregister(ctx, inst); err != nil {
return fmt.Errorf("failed to unregister %q: %w", inst.Dir, err)
}
if err := os.RemoveAll(inst.Dir); err != nil {
return fmt.Errorf("failed to remove %q: %w", inst.Dir, err)
}
return nil
}
func deleteBashComplete(cmd *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
return bashCompleteInstanceNames(cmd)
}