Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
lima-vm
GitHub Repository: lima-vm/lima
Path: blob/master/cmd/limactl/factory-reset.go
1645 views
1
// SPDX-FileCopyrightText: Copyright The Lima Authors
2
// SPDX-License-Identifier: Apache-2.0
3
4
package main
5
6
import (
7
"errors"
8
"os"
9
"path/filepath"
10
"strings"
11
12
"github.com/sirupsen/logrus"
13
"github.com/spf13/cobra"
14
15
"github.com/lima-vm/lima/v2/pkg/cidata"
16
"github.com/lima-vm/lima/v2/pkg/instance"
17
"github.com/lima-vm/lima/v2/pkg/limatype/filenames"
18
"github.com/lima-vm/lima/v2/pkg/store"
19
)
20
21
func newFactoryResetCommand() *cobra.Command {
22
resetCommand := &cobra.Command{
23
Use: "factory-reset INSTANCE",
24
Short: "Factory reset an instance of Lima",
25
Args: WrapArgsError(cobra.MaximumNArgs(1)),
26
RunE: factoryResetAction,
27
ValidArgsFunction: factoryResetBashComplete,
28
GroupID: advancedCommand,
29
}
30
return resetCommand
31
}
32
33
func factoryResetAction(cmd *cobra.Command, args []string) error {
34
ctx := cmd.Context()
35
instName := DefaultInstanceName
36
if len(args) > 0 {
37
instName = args[0]
38
}
39
40
inst, err := store.Inspect(ctx, instName)
41
if err != nil {
42
if errors.Is(err, os.ErrNotExist) {
43
logrus.Infof("Instance %q not found", instName)
44
return nil
45
}
46
return err
47
}
48
if inst.Protected {
49
return errors.New("instance is protected to prohibit accidental factory-reset (Hint: use `limactl unprotect`)")
50
}
51
52
instance.StopForcibly(inst)
53
54
fi, err := os.ReadDir(inst.Dir)
55
if err != nil {
56
return err
57
}
58
retain := map[string]struct{}{
59
filenames.LimaVersion: {},
60
filenames.Protected: {},
61
filenames.VzIdentifier: {},
62
}
63
for _, f := range fi {
64
path := filepath.Join(inst.Dir, f.Name())
65
if _, ok := retain[f.Name()]; !ok && !strings.HasSuffix(path, ".yaml") && !strings.HasSuffix(path, ".yml") {
66
logrus.Infof("Removing %q", path)
67
if err := os.Remove(path); err != nil {
68
logrus.Error(err)
69
}
70
}
71
}
72
// Regenerate the cloud-config.yaml, to reflect any changes to the global _config
73
if err := cidata.GenerateCloudConfig(ctx, inst.Dir, instName, inst.Config); err != nil {
74
logrus.Error(err)
75
}
76
77
logrus.Infof("Instance %q has been factory reset", instName)
78
return nil
79
}
80
81
func factoryResetBashComplete(cmd *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
82
return bashCompleteInstanceNames(cmd)
83
}
84
85