跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

editflags.go

519 行 · 17.6 KB历史下载
1// SPDX-FileCopyrightText: Copyright The Lima Authors
2// SPDX-License-Identifier: Apache-2.0
3
4package editflags
5
6import (
7 "errors"
8 "fmt"
9 "math/bits"
10 "runtime"
11 "slices"
12 "strconv"
13 "strings"
14
15 "github.com/pbnjay/memory"
16 "github.com/sirupsen/logrus"
17 "github.com/spf13/cobra"
18 flag "github.com/spf13/pflag"
19
20 "github.com/lima-vm/lima/v2/pkg/localpathutil"
21 "github.com/lima-vm/lima/v2/pkg/registry"
22)
23
24// RegisterEdit registers flags related to in-place YAML modification, for `limactl edit`.
25func RegisterEdit(cmd *cobra.Command, commentPrefix string) {
26 flags := cmd.Flags()
27
28 flags.Int("cpus", 0, commentPrefix+"Number of CPUs") // Similar to colima's --cpu, but the flag name is slightly different (cpu vs cpus)
29 _ = cmd.RegisterFlagCompletionFunc("cpus", func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) {
30 var res []string
31 for _, f := range completeCPUs(runtime.NumCPU()) {
32 res = append(res, strconv.Itoa(f))
33 }
34 return res, cobra.ShellCompDirectiveNoFileComp
35 })
36
37 flags.IPSlice("dns", nil, commentPrefix+"Specify custom DNS (disable host resolver)") // colima-compatible
38
39 flags.Float32("memory", 0, commentPrefix+"Memory in GiB") // colima-compatible
40 _ = cmd.RegisterFlagCompletionFunc("memory", func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) {
41 var res []string
42 for _, f := range completeMemoryGiB(memory.TotalMemory()) {
43 res = append(res, fmt.Sprintf("%.1f", f))
44 }
45 return res, cobra.ShellCompDirectiveNoFileComp
46 })
47
48 flags.StringSlice("mount", nil, commentPrefix+"Directories to mount, suffix ':w' for writable (Do not specify directories that overlap with the existing mounts)") // colima-compatible
49 flags.StringSlice("mount-only", nil, commentPrefix+"Similar to --mount, but overrides the existing mounts")
50
51 flags.Bool("mount-none", false, commentPrefix+"Remove all mounts")
52
53 flags.String("mount-type", "", commentPrefix+"Mount type (reverse-sshfs, 9p, virtiofs)") // Similar to colima's --mount-type=(sshfs|9p|virtiofs), but "reverse-sshfs" is Lima is called "sshfs" in colima
54 _ = cmd.RegisterFlagCompletionFunc("mount-type", func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) {
55 return []string{"reverse-sshfs", "9p", "virtiofs"}, cobra.ShellCompDirectiveNoFileComp
56 })
57
58 flags.Bool("mount-writable", false, commentPrefix+"Make all mounts writable")
59 flags.Bool("mount-inotify", false, commentPrefix+"Enable inotify for mounts")
60
61 flags.StringSlice("network", nil, commentPrefix+"Additional networks, e.g., \"vzNAT\" or \"lima:shared\" to assign vmnet IP")
62 _ = cmd.RegisterFlagCompletionFunc("network", func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) {
63 // TODO: retrieve the lima:* network list from networks.yaml
64 return []string{"lima:shared", "lima:bridged", "lima:host", "lima:user-v2", "vzNAT"}, cobra.ShellCompDirectiveNoFileComp
65 })
66
67 flags.Bool("nested-virt", false, commentPrefix+"Enable nested virtualization")
68
69 flags.Bool("rosetta", false, commentPrefix+"Enable Rosetta (for vz instances)")
70
71 flags.StringArray("set", []string{}, commentPrefix+"Modify the template inplace, using yq syntax. Can be passed multiple times. See 'limactl help yq-restrictions' for limitations.")
72 flags.StringArray("param", []string{}, commentPrefix+"Set a template parameter, e.g. name=value. Can be passed multiple times.")
73
74 flags.Uint16("ssh-port", 0, commentPrefix+"SSH port (0 for random)") // colima-compatible
75 _ = cmd.RegisterFlagCompletionFunc("ssh-port", func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) {
76 // Until Lima v2.0, 60022 was the default SSH port for the instance named "default".
77 return []string{"60022"}, cobra.ShellCompDirectiveNoFileComp
78 })
79
80 // negative performance impact: https://gitlab.com/qemu-project/qemu/-/issues/334
81 flags.Bool("video", false, commentPrefix+"Enable video output (has negative performance impact for QEMU)")
82
83 flags.Float32("disk", 0, commentPrefix+"Disk size in GiB") // colima-compatible
84 _ = cmd.RegisterFlagCompletionFunc("disk", func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) {
85 return []string{"10", "30", "50", "100", "200"}, cobra.ShellCompDirectiveNoFileComp
86 })
87
88 flags.String("vm-type", "", commentPrefix+"Virtual machine type")
89 _ = cmd.RegisterFlagCompletionFunc("vm-type", func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) {
90 var drivers []string
91 for k := range registry.List() {
92 drivers = append(drivers, k)
93 }
94 return drivers, cobra.ShellCompDirectiveNoFileComp
95 })
96
97 flags.String("shell", "", commentPrefix+"User login shell in the guest (e.g. /bin/bash, /bin/zsh)")
98 _ = cmd.RegisterFlagCompletionFunc("shell", func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) {
99 return []string{"/bin/bash", "/bin/zsh", "cmd.exe", "powershell.exe", "pwsh.exe"}, cobra.ShellCompDirectiveNoFileComp
100 })
101}
102
103// RegisterCreate registers flags related to in-place YAML modification, for `limactl create`.
104func RegisterCreate(cmd *cobra.Command, commentPrefix string) {
105 RegisterEdit(cmd, commentPrefix)
106 flags := cmd.Flags()
107
108 flags.String("arch", "", commentPrefix+"Machine architecture (x86_64, aarch64, riscv64, armv7l, s390x, ppc64le)") // colima-compatible
109 _ = cmd.RegisterFlagCompletionFunc("arch", func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) {
110 return []string{"x86_64", "aarch64", "riscv64", "armv7l", "s390x", "ppc64le"}, cobra.ShellCompDirectiveNoFileComp
111 })
112
113 flags.String("image-variant", "", commentPrefix+"Image variant")
114
115 flags.String("arch-variant", "", commentPrefix+`Architecture variant (e.g. "v3" for x86-64-v3)`)
116
117 flags.String("containerd", "", commentPrefix+"containerd mode (user, system, user+system, none)")
118 _ = cmd.RegisterFlagCompletionFunc("containerd", func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) {
119 return []string{"user", "system", "user+system", "none"}, cobra.ShellCompDirectiveNoFileComp
120 })
121
122 flags.Bool("plain", false, commentPrefix+"Plain mode. Disables mounts, port forwarding, containerd, etc.")
123
124 flags.StringArray("port-forward", nil, commentPrefix+"Port forwards (host:guest), e.g., '8080:80' or '9090:9090,static=true' for static port-forwards")
125 _ = cmd.RegisterFlagCompletionFunc("port-forward", func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) {
126 return []string{"8080:80", "3000:3000", "8080:80,static=true"}, cobra.ShellCompDirectiveNoFileComp
127 })
128
129 flags.String("audio-device", "", commentPrefix+"Audio device backend (e.g., 'pa', 'coreaudio', 'none')")
130 flags.String("audio-interface", "", commentPrefix+"Audio virtual hardware interface ('hda' or 'virtio')")
131 flags.Bool("audio-microphone", false, commentPrefix+"Attach an audio input stream as well as playback (vz only)")
132}
133
134func defaultExprFunc(expr string) func(v *flag.Flag) ([]string, error) {
135 return func(v *flag.Flag) ([]string, error) {
136 return []string{fmt.Sprintf(expr, v.Value)}, nil
137 }
138}
139
140func ParsePortForward(spec string) (hostPort, guestPort string, isStatic bool, err error) {
141 parts := strings.Split(spec, ",")
142 if len(parts) > 2 {
143 return "", "", false, fmt.Errorf("invalid port forward format %#q, expected HOST:GUEST or HOST:GUEST,static=true", spec)
144 }
145
146 portParts := strings.Split(strings.TrimSpace(parts[0]), ":")
147 if len(portParts) != 2 {
148 return "", "", false, fmt.Errorf("invalid port forward format %#q, expected HOST:GUEST", parts[0])
149 }
150
151 hostPort = strings.TrimSpace(portParts[0])
152 guestPort = strings.TrimSpace(portParts[1])
153
154 if len(parts) == 2 {
155 staticPart := strings.TrimSpace(parts[1])
156 if staticValue, ok := strings.CutPrefix(staticPart, "static="); ok {
157 isStatic, err = strconv.ParseBool(staticValue)
158 if err != nil {
159 return "", "", false, fmt.Errorf("invalid value for static parameter: %#q", staticValue)
160 }
161 } else {
162 return "", "", false, fmt.Errorf("invalid parameter %#q, expected `static=` followed by a boolean value", staticPart)
163 }
164 }
165
166 return hostPort, guestPort, isStatic, nil
167}
168
169func BuildPortForwardExpression(portForwards []string) (string, error) {
170 if len(portForwards) == 0 {
171 return "", nil
172 }
173
174 ports := make([]string, len(portForwards))
175 for i, spec := range portForwards {
176 hostPort, guestPort, isStatic, err := ParsePortForward(spec)
177 if err != nil {
178 return "", err
179 }
180 ports[i] = fmt.Sprintf(`{"guestPort": %q, "hostPort": %q, "static": %v}`, guestPort, hostPort, isStatic)
181 }
182 expr := fmt.Sprintf(".portForwards += [%s]", strings.Join(ports, ","))
183 return expr, nil
184}
185
186func BuildParamExpressions(params []string, allowedParams map[string]string) ([]string, error) {
187 exprs := make([]string, len(params))
188 for i, param := range params {
189 key, value, ok := strings.Cut(param, "=")
190 if !ok {
191 return nil, fmt.Errorf("invalid parameter %#q, expected NAME=VALUE", param)
192 }
193 if _, ok := allowedParams[key]; !ok {
194 return nil, fmt.Errorf("template does not define param %#q", key)
195 }
196 exprs[i] = fmt.Sprintf(".param[%q] = %q", key, value)
197 }
198 return exprs, nil
199}
200
201func buildMountListExpression(ss []string) (string, error) {
202 mounts := make([]string, len(ss))
203 for i, s := range ss {
204 writable := strings.HasSuffix(s, ":w")
205 loc, err := localpathutil.Expand(strings.TrimSuffix(s, ":w"))
206 if err != nil {
207 return "", err
208 }
209 mounts[i] = fmt.Sprintf(`{"location": %q, "mountPoint": %q, "writable": %v}`, loc, loc, writable)
210 }
211 expr := fmt.Sprintf("[%s]", strings.Join(mounts, ","))
212 return expr, nil
213}
214
215// YQExpressions returns YQ expressions.
216func YQExpressions(flags *flag.FlagSet, newInstance bool, params map[string]string) ([]string, error) {
217 type def struct {
218 flagName string
219 exprFunc func(*flag.Flag) ([]string, error)
220 onlyValidForNewInstances bool
221 experimental bool
222 }
223 d := defaultExprFunc
224 defs := []def{
225 {
226 "cpus",
227 func(_ *flag.Flag) ([]string, error) {
228 numCpus, err := flags.GetInt("cpus")
229 if err != nil {
230 return nil, err
231 }
232 if numCpus < 0 {
233 return nil, errors.New("invalid value for number of cpus, must be >= 0")
234 }
235 return []string{fmt.Sprintf(".cpus = %d", numCpus)}, nil
236 },
237 false,
238 false,
239 },
240 {
241 "dns",
242 func(_ *flag.Flag) ([]string, error) {
243 ipSlice, err := flags.GetIPSlice("dns")
244 if err != nil {
245 return nil, err
246 }
247 ips := make([]string, len(ipSlice))
248 for i, ip := range ipSlice {
249 ips[i] = `"` + ip.String() + `"`
250 }
251 expr := fmt.Sprintf(".dns += [%s] | .dns |= unique | .hostResolver.enabled=false", strings.Join(ips, ","))
252 logrus.Warnf("Disabling HostResolver, as custom DNS addresses (%v) are specified", ipSlice)
253 return []string{expr}, nil
254 },
255 false,
256 false,
257 },
258 {"memory", d(".memory = \"%sGiB\""), false, false},
259 {
260 "mount",
261 func(_ *flag.Flag) ([]string, error) {
262 ss, err := flags.GetStringSlice("mount")
263 slices.Reverse(ss)
264 if err != nil {
265 return nil, err
266 }
267 mountListExpr, err := buildMountListExpression(ss)
268 if err != nil {
269 return nil, err
270 }
271 // mount options take precedence over template settings
272 expr := fmt.Sprintf(".mounts = %s + .mounts", mountListExpr)
273 mountOnly, err := flags.GetStringSlice("mount-only")
274 if err != nil {
275 return nil, err
276 }
277 if len(mountOnly) > 0 {
278 return nil, errors.New("flag `--mount` conflicts with `--mount-only`")
279 }
280 return []string{expr}, nil
281 },
282 false,
283 false,
284 },
285 {
286 "mount-only",
287 func(_ *flag.Flag) ([]string, error) {
288 ss, err := flags.GetStringSlice("mount-only")
289 if err != nil {
290 return nil, err
291 }
292 mountListExpr, err := buildMountListExpression(ss)
293 if err != nil {
294 return nil, err
295 }
296 expr := `.mounts = ` + mountListExpr
297 return []string{expr}, nil
298 },
299 false,
300 false,
301 },
302 {
303 "mount-none",
304 func(_ *flag.Flag) ([]string, error) {
305 incompatibleFlagNames := []string{"mount", "mount-only"}
306 for _, name := range incompatibleFlagNames {
307 ss, err := flags.GetStringSlice(name)
308 if err != nil {
309 return nil, err
310 }
311 if len(ss) > 0 {
312 return nil, errors.New("flag `--mount-none` conflicts with `" + name + "`")
313 }
314 }
315 return []string{".mounts = null"}, nil
316 },
317 false,
318 false,
319 },
320 {"mount-type", d(".mountType = %q"), false, false},
321 {"vm-type", d(".vmType = %q"), false, false},
322 {"mount-inotify", d(".mountInotify = %s"), false, true},
323 {"mount-writable", d(".mounts[].writable = %s"), false, false},
324 {
325 "network",
326 func(_ *flag.Flag) ([]string, error) {
327 ss, err := flags.GetStringSlice("network")
328 if err != nil {
329 return nil, err
330 }
331 networks := make([]string, len(ss))
332 for i, s := range ss {
333 // CLI syntax is still experimental (YAML syntax is out of experimental)
334 switch {
335 case s == "vzNAT":
336 networks[i] = `{"vzNAT": true}`
337 case strings.HasPrefix(s, "lima:"):
338 network := strings.TrimPrefix(s, "lima:")
339 networks[i] = fmt.Sprintf(`{"lima": %q}`, network)
340 default:
341 return nil, fmt.Errorf("network name must be `vzNAT` or `lima:*`, got %#q", s)
342 }
343 }
344 expr := fmt.Sprintf(`.networks += [%s] | .networks |= unique_by(.lima)`, strings.Join(networks, ","))
345 return []string{expr}, nil
346 },
347 false,
348 false,
349 },
350
351 {"nested-virt", d(".nestedVirtualization = %s"), false, false},
352 {
353 "rosetta",
354 func(_ *flag.Flag) ([]string, error) {
355 b, err := flags.GetBool("rosetta")
356 if err != nil {
357 return nil, err
358 }
359 return []string{fmt.Sprintf(".vmOpts.vz.rosetta.enabled = %v | .vmOpts.vz.rosetta.binfmt = %v", b, b)}, nil
360 },
361 false,
362 false,
363 },
364 {"set", func(v *flag.Flag) ([]string, error) {
365 return v.Value.(flag.SliceValue).GetSlice(), nil
366 }, false, false},
367 {"param", func(_ *flag.Flag) ([]string, error) {
368 ss, err := flags.GetStringArray("param")
369 if err != nil {
370 return nil, err
371 }
372 return BuildParamExpressions(ss, params)
373 }, false, false},
374 {
375 "video",
376 func(_ *flag.Flag) ([]string, error) {
377 b, err := flags.GetBool("video")
378 if err != nil {
379 return nil, err
380 }
381 if b {
382 return []string{".video.display = \"default\""}, nil
383 }
384 return []string{".video.display = \"none\""}, nil
385 },
386 false,
387 false,
388 },
389 {"audio-device", d(".audio.device = %q"), false, true},
390 {"audio-interface", d(".audio.interface = %q"), false, true},
391 {"audio-microphone", d(".audio.microphone = %s"), false, true},
392 {"ssh-port", d(".ssh.localPort = %s"), false, false},
393 {
394 "image-variant",
395 func(_ *flag.Flag) ([]string, error) {
396 variant, err := flags.GetString("image-variant")
397 if err != nil {
398 return nil, err
399 }
400 if variant == "" {
401 return nil, errors.New("`--image-variant` must not be empty")
402 }
403 expr := fmt.Sprintf(`.images = [.images[] | select(.variant == %q)]`, variant)
404 return []string{expr}, nil
405 },
406 true,
407 false,
408 },
409 {
410 "arch-variant",
411 func(_ *flag.Flag) ([]string, error) {
412 archVariant, err := flags.GetString("arch-variant")
413 if err != nil {
414 return nil, err
415 }
416 if archVariant == "" {
417 return nil, errors.New("`--arch-variant` must not be empty")
418 }
419 expr := fmt.Sprintf(`.images = [.images[] | select(.archVariant == %q)]`, archVariant)
420 return []string{expr}, nil
421 },
422 true,
423 false,
424 },
425 {"arch", d(".arch = %q"), true, false},
426 {
427 "containerd",
428 func(_ *flag.Flag) ([]string, error) {
429 s, err := flags.GetString("containerd")
430 if err != nil {
431 return nil, err
432 }
433 switch s {
434 case "user":
435 return []string{`.containerd.user = true | .containerd.system = false`}, nil
436 case "system":
437 return []string{`.containerd.user = false | .containerd.system = true`}, nil
438 case "user+system", "system+user":
439 return []string{`.containerd.user = true | .containerd.system = true`}, nil
440 case "none":
441 return []string{`.containerd.user = false | .containerd.system = false`}, nil
442 default:
443 return nil, fmt.Errorf("expected one of [`user`, `system`, `user+system`, `none`], got %#q", s)
444 }
445 },
446 true,
447 false,
448 },
449 {"disk", d(".disk= \"%sGiB\""), false, false},
450 {"plain", d(".plain = %s"), true, false},
451 {
452 "port-forward",
453 func(_ *flag.Flag) ([]string, error) {
454 ss, err := flags.GetStringArray("port-forward")
455 if err != nil {
456 return nil, err
457 }
458 value, err := BuildPortForwardExpression(ss)
459 if err != nil {
460 return nil, err
461 }
462 return []string{value}, nil
463 },
464 false,
465 false,
466 },
467 {"shell", d(".user.shell = %q"), false, false},
468 }
469 var exprs []string
470 for _, def := range defs {
471 v := flags.Lookup(def.flagName)
472 if v != nil && v.Changed {
473 if def.experimental {
474 logrus.Warnf("`--%s` is experimental", def.flagName)
475 }
476 if def.onlyValidForNewInstances && !newInstance {
477 logrus.Warnf("`--%s` is not applicable to an existing instance (Hint: create a new instance with `limactl create --%s=%s --name=NAME`)",
478 def.flagName, def.flagName, v.Value.String())
479 continue
480 }
481 newExprs, err := def.exprFunc(v)
482 if err != nil {
483 return exprs, fmt.Errorf("error while processing flag %#q: %w", def.flagName, err)
484 }
485 exprs = append(exprs, newExprs...)
486 }
487 }
488 return exprs, nil
489}
490
491func isPowerOfTwo(x int) bool {
492 return bits.OnesCount(uint(x)) == 1
493}
494
495func completeCPUs(hostCPUs int) []int {
496 var res []int
497 for i := 1; i <= hostCPUs; i *= 2 {
498 res = append(res, i)
499 }
500 if !isPowerOfTwo(hostCPUs) {
501 res = append(res, hostCPUs)
502 }
503 return res
504}
505
506func completeMemoryGiB(hostMemory uint64) []float32 {
507 hostMemoryHalfGiB := int(hostMemory / 2 / 1024 / 1024 / 1024)
508 var res []float32
509 if hostMemoryHalfGiB < 1 {
510 res = append(res, 0.5)
511 }
512 for i := 1; i <= hostMemoryHalfGiB; i *= 2 {
513 res = append(res, float32(i))
514 }
515 if hostMemoryHalfGiB > 1 && !isPowerOfTwo(hostMemoryHalfGiB) {
516 res = append(res, float32(hostMemoryHalfGiB))
517 }
518 return res
519}