-
Notifications
You must be signed in to change notification settings - Fork 653
/
Copy pathmain.go
228 lines (205 loc) · 6.41 KB
/
main.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
// SPDX-FileCopyrightText: Copyright The Lima Authors
// SPDX-License-Identifier: Apache-2.0
package main
import (
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
"strings"
"github.com/lima-vm/lima/pkg/debugutil"
"github.com/lima-vm/lima/pkg/fsutil"
"github.com/lima-vm/lima/pkg/osutil"
"github.com/lima-vm/lima/pkg/store/dirnames"
"github.com/lima-vm/lima/pkg/version"
"github.com/mattn/go-isatty"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
const (
DefaultInstanceName = "default"
basicCommand = "basic"
advancedCommand = "advanced"
)
func main() {
if runtime.GOOS == "windows" {
extras, hasExtra := os.LookupEnv("_LIMA_WINDOWS_EXTRA_PATH")
if hasExtra && strings.TrimSpace(extras) != "" {
p := os.Getenv("PATH")
err := os.Setenv("PATH", strings.TrimSpace(extras)+string(filepath.ListSeparator)+p)
if err != nil {
logrus.Warning("Can't add extras to PATH, relying entirely on system PATH")
}
}
}
if err := newApp().Execute(); err != nil {
handleExitCoder(err)
logrus.Fatal(err)
}
}
func newApp() *cobra.Command {
templatesDir := "$PREFIX/share/lima/templates"
if exe, err := os.Executable(); err == nil {
binDir := filepath.Dir(exe)
prefixDir := filepath.Dir(binDir)
templatesDir = filepath.Join(prefixDir, "share/lima/templates")
}
rootCmd := &cobra.Command{
Use: "limactl",
Short: "Lima: Linux virtual machines",
Version: strings.TrimPrefix(version.Version, "v"),
Example: fmt.Sprintf(` Start the default instance:
$ limactl start
Open a shell:
$ lima
Run a container:
$ lima nerdctl run -d --name nginx -p 8080:80 nginx:alpine
Stop the default instance:
$ limactl stop
See also template YAMLs: %s`, templatesDir),
SilenceUsage: true,
SilenceErrors: true,
DisableAutoGenTag: true,
}
rootCmd.PersistentFlags().String("log-level", "", "Set the logging level [trace, debug, info, warn, error]")
rootCmd.PersistentFlags().String("log-format", "text", "Set the logging format [text, json]")
rootCmd.PersistentFlags().Bool("debug", false, "Debug mode")
// TODO: "survey" does not support using cygwin terminal on windows yet
rootCmd.PersistentFlags().Bool("tty", isatty.IsTerminal(os.Stdout.Fd()), "Enable TUI interactions such as opening an editor. Defaults to true when stdout is a terminal. Set to false for automation.")
rootCmd.PersistentFlags().BoolP("yes", "y", false, "Alias of --tty=false")
rootCmd.PersistentPreRunE = func(cmd *cobra.Command, _ []string) error {
l, _ := cmd.Flags().GetString("log-level")
if l != "" {
lvl, err := logrus.ParseLevel(l)
if err != nil {
return err
}
logrus.SetLevel(lvl)
}
logFormat, _ := cmd.Flags().GetString("log-format")
switch logFormat {
case "json":
formatter := new(logrus.JSONFormatter)
logrus.StandardLogger().SetFormatter(formatter)
case "text":
// logrus use text format by default.
if runtime.GOOS == "windows" && isatty.IsCygwinTerminal(os.Stderr.Fd()) {
formatter := new(logrus.TextFormatter)
// the default setting does not recognize cygwin on windows
formatter.ForceColors = true
logrus.StandardLogger().SetFormatter(formatter)
}
default:
return fmt.Errorf("unsupported log-format: %q", logFormat)
}
debug, _ := cmd.Flags().GetBool("debug")
if debug {
logrus.SetLevel(logrus.DebugLevel)
debugutil.Debug = true
}
if osutil.IsBeingRosettaTranslated() && cmd.Parent().Name() != "completion" && cmd.Name() != "generate-doc" && cmd.Name() != "validate" {
// running under rosetta would provide inappropriate runtime.GOARCH info, see: https://github.com/lima-vm/lima/issues/543
// allow commands that are used for packaging to run under rosetta to allow cross-architecture builds
return errors.New("limactl is running under rosetta, please reinstall lima with native arch")
}
if os.Geteuid() == 0 && cmd.Name() != "generate-doc" {
return errors.New("must not run as the root user")
}
// Make sure either $HOME or $LIMA_HOME is defined, so we don't need
// to check for errors later
dir, err := dirnames.LimaDir()
if err != nil {
return err
}
// Make sure that directory is on a local filesystem, not on NFS
// if the directory does not yet exist, check the home directory
_, err = os.Stat(dir)
if errors.Is(err, os.ErrNotExist) {
dir = filepath.Dir(dir)
}
nfs, err := fsutil.IsNFS(dir)
if err != nil {
return err
}
if nfs {
return errors.New("must not run on NFS dir")
}
if cmd.Flags().Changed("yes") && cmd.Flags().Changed("tty") {
return errors.New("cannot use both --tty and --yes flags at the same time")
}
if cmd.Flags().Changed("yes") {
// Sets the value of the yesValue flag by using the yes flag.
yesValue, _ := cmd.Flags().GetBool("yes")
if yesValue {
// Sets to the default value false
err := cmd.Flags().Set("tty", "false")
if err != nil {
return err
}
}
}
return nil
}
rootCmd.AddGroup(&cobra.Group{ID: "basic", Title: "Basic Commands:"})
rootCmd.AddGroup(&cobra.Group{ID: "advanced", Title: "Advanced Commands:"})
rootCmd.AddCommand(
newCreateCommand(),
newStartCommand(),
newStopCommand(),
newShellCommand(),
newCopyCommand(),
newListCommand(),
newDeleteCommand(),
newValidateCommand(),
newPruneCommand(),
newHostagentCommand(),
newGuestInstallCommand(),
newInfoCommand(),
newShowSSHCommand(),
newDebugCommand(),
newEditCommand(),
newFactoryResetCommand(),
newDiskCommand(),
newUsernetCommand(),
newGenDocCommand(),
newGenSchemaCommand(),
newSnapshotCommand(),
newProtectCommand(),
newUnprotectCommand(),
newTunnelCommand(),
newTemplateCommand(),
newRestartCommand(),
)
for _, cmd := range additionalAdvancedCommands() {
rootCmd.AddCommand(cmd)
}
return rootCmd
}
type ExitCoder interface {
error
ExitCode() int
}
func handleExitCoder(err error) {
if err == nil {
return
}
if exitErr, ok := err.(ExitCoder); ok {
os.Exit(exitErr.ExitCode()) //nolint:revive // it's intentional to call os.Exit in this function
return
}
}
// WrapArgsError annotates cobra args error with some context, so the error message is more user-friendly.
func WrapArgsError(argFn cobra.PositionalArgs) cobra.PositionalArgs {
return func(cmd *cobra.Command, args []string) error {
err := argFn(cmd, args)
if err == nil {
return nil
}
return fmt.Errorf("%q %s.\nSee '%s --help'.\n\nUsage: %s\n\n%s",
cmd.CommandPath(), err.Error(),
cmd.CommandPath(),
cmd.UseLine(), cmd.Short,
)
}
}