-
Notifications
You must be signed in to change notification settings - Fork 884
Expand file tree
/
Copy pathmain.go
More file actions
289 lines (261 loc) · 8.27 KB
/
main.go
File metadata and controls
289 lines (261 loc) · 8.27 KB
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
// SPDX-FileCopyrightText: Copyright The Lima Authors
// SPDX-License-Identifier: Apache-2.0
package main
import (
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
"strings"
"github.com/mattn/go-isatty"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/lima-vm/lima/v2/cmd/yq"
"github.com/lima-vm/lima/v2/pkg/debugutil"
"github.com/lima-vm/lima/v2/pkg/driver/external/server"
"github.com/lima-vm/lima/v2/pkg/fsutil"
"github.com/lima-vm/lima/v2/pkg/limatype/dirnames"
"github.com/lima-vm/lima/v2/pkg/osutil"
"github.com/lima-vm/lima/v2/pkg/plugins"
"github.com/lima-vm/lima/v2/pkg/version"
)
const (
DefaultInstanceName = "default"
basicCommand = "basic"
advancedCommand = "advanced"
)
func main() {
if os.Geteuid() == 0 && (len(os.Args) < 2 || os.Args[1] != "generate-doc") {
fmt.Fprint(os.Stderr, "limactl: must not run as the root user\n")
os.Exit(1)
}
yq.MaybeRunYQ()
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")
}
}
}
err := newApp().Execute()
server.StopAllExternalDrivers()
osutil.HandleExitError(err)
if err != nil {
logrus.Fatal(err)
}
}
func processGlobalFlags(rootCmd *cobra.Command) error {
// --log-level will override --debug, but will not reset debugutil.Debug
if debug, _ := rootCmd.Flags().GetBool("debug"); debug {
logrus.SetLevel(logrus.DebugLevel)
debugutil.Debug = true
}
l, _ := rootCmd.Flags().GetString("log-level")
if l != "" {
lvl, err := logrus.ParseLevel(l)
if err != nil {
return err
}
logrus.SetLevel(lvl)
}
logFormat, _ := rootCmd.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)
}
return nil
}
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 {
if err := processGlobalFlags(rootCmd); err != nil {
return err
}
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")
}
// 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
}
nfs, err := fsutil.IsNFS(dir)
if err != nil {
return err
}
if nfs {
logrus.Warn("LIMA_HOME should not be on an NFS mount")
}
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") {
switch cmd.Name() {
case "clone", "edit", "rename":
logrus.Warn("--yes flag is deprecated (--tty=false is still supported and works in the same way. Also consider using --start)")
}
// 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.AddGroup(&cobra.Group{ID: "plugin", Title: "Available Plugins (Experimental):"})
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(),
newSudoersCommand(),
newAutostartCommand(),
newStartAtLoginCommand(),
newNetworkCommand(),
newCloneCommand(),
newRenameCommand(),
newWatchCommand(),
newYQRestrictionsHelpCommand(),
)
addPluginCommands(rootCmd)
return rootCmd
}
func addPluginCommands(rootCmd *cobra.Command) {
// The global options are only processed when rootCmd.Execute() is called.
// Let's take a sneak peek here to help debug the plugin discovery code.
if len(os.Args) > 1 && os.Args[1] == "--debug" {
logrus.SetLevel(logrus.DebugLevel)
}
allPlugins, err := plugins.Discover()
if err != nil {
logrus.Warnf("Failed to discover plugins: %v", err)
return
}
for _, plugin := range allPlugins {
pluginCmd := &cobra.Command{
Use: plugin.Name,
Short: plugin.Description,
GroupID: "plugin",
DisableFlagParsing: true,
SilenceErrors: true,
SilenceUsage: true,
PreRunE: func(*cobra.Command, []string) error {
for i, arg := range os.Args {
if arg == plugin.Name {
// parse global options but ignore plugin options
err := rootCmd.ParseFlags(os.Args[1:i])
if err == nil {
err = processGlobalFlags(rootCmd)
}
return err
}
}
// unreachable
return nil
},
Run: func(cmd *cobra.Command, _ []string) {
for i, arg := range os.Args {
if arg == plugin.Name {
// ignore global options
plugin.Run(cmd.Context(), os.Args[i+1:])
// plugin.Run() never returns because it calls os.Exit()
}
}
// unreachable
},
}
// Don't show the url scheme helper in the help output.
if strings.HasPrefix(plugin.Name, "url-") {
pluginCmd.Hidden = true
}
rootCmd.AddCommand(pluginCmd)
}
}
// 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,
)
}
}