跳到主要内容

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

浏览文件

edit.go

233 行 · 6.3 KB历史下载
1// SPDX-FileCopyrightText: Copyright The Lima Authors
2// SPDX-License-Identifier: Apache-2.0
3
4package main
5
6import (
7 "bytes"
8 "errors"
9 "fmt"
10 "os"
11 "path/filepath"
12
13 "github.com/sirupsen/logrus"
14 "github.com/spf13/cobra"
15
16 "github.com/lima-vm/lima/v2/cmd/limactl/editflags"
17 "github.com/lima-vm/lima/v2/pkg/autostart"
18 "github.com/lima-vm/lima/v2/pkg/driver/external/server"
19 "github.com/lima-vm/lima/v2/pkg/driverutil"
20 "github.com/lima-vm/lima/v2/pkg/editutil"
21 "github.com/lima-vm/lima/v2/pkg/instance"
22 "github.com/lima-vm/lima/v2/pkg/limatype"
23 "github.com/lima-vm/lima/v2/pkg/limatype/dirnames"
24 "github.com/lima-vm/lima/v2/pkg/limatype/filenames"
25 "github.com/lima-vm/lima/v2/pkg/limayaml"
26 "github.com/lima-vm/lima/v2/pkg/networks/reconcile"
27 "github.com/lima-vm/lima/v2/pkg/store"
28 "github.com/lima-vm/lima/v2/pkg/uiutil"
29 "github.com/lima-vm/lima/v2/pkg/yqutil"
30)
31
32func newEditCommand() *cobra.Command {
33 editCommand := &cobra.Command{
34 Use: "edit INSTANCE|FILE.yaml",
35 Short: "Edit an instance of Lima or a template",
36 Args: WrapArgsError(cobra.MaximumNArgs(1)),
37 RunE: editAction,
38 ValidArgsFunction: editBashComplete,
39 GroupID: basicCommand,
40 }
41 editCommand.Flags().Bool("start", false, "Start the instance after editing")
42 editflags.RegisterEdit(editCommand, "")
43 return editCommand
44}
45
46func editAction(cmd *cobra.Command, args []string) error {
47 ctx := cmd.Context()
48 var arg string
49 if len(args) > 0 {
50 arg = args[0]
51 }
52
53 var filePath string
54 var err error
55 var inst *limatype.Instance
56
57 if arg == "" {
58 arg = DefaultInstanceName
59 }
60 if err := dirnames.ValidateInstName(arg); err == nil {
61 inst, err = store.Inspect(ctx, arg)
62 if err != nil {
63 if errors.Is(err, os.ErrNotExist) {
64 return fmt.Errorf("instance %#q not found", arg)
65 }
66 return err
67 }
68 if inst.Status == limatype.StatusRunning {
69 return errors.New("cannot edit a running instance")
70 }
71 filePath = filepath.Join(inst.Dir, filenames.LimaYAML)
72 } else {
73 // absolute path is required for `limayaml.Validate`
74 filePath, err = filepath.Abs(arg)
75 if err != nil {
76 return err
77 }
78 }
79
80 yContent, err := os.ReadFile(filePath)
81 if err != nil {
82 return err
83 }
84 flags := cmd.Flags()
85 tty, err := flags.GetBool("tty")
86 if err != nil {
87 return err
88 }
89 var params map[string]string
90 if flags.Changed("param") {
91 var y limatype.LimaYAML
92 if err := limayaml.Unmarshal(yContent, &y, filePath); err != nil {
93 return err
94 }
95 params = y.Param
96 }
97 yqExprs, err := editflags.YQExpressions(flags, false, params)
98 if err != nil {
99 return err
100 }
101 var yBytes []byte
102 if len(yqExprs) > 0 {
103 yq := yqutil.Join(yqExprs)
104 yBytes, err = yqutil.EvaluateExpression(ctx, yq, yContent)
105 if err != nil {
106 return err
107 }
108 } else if tty {
109 var hdr string
110 if inst != nil {
111 hdr = fmt.Sprintf("# Please edit the following configuration for Lima instance %#q\n", inst.Name)
112 } else {
113 hdr = fmt.Sprintf("# Please edit the following configuration %#q\n", filePath)
114 }
115 hdr += "# and an empty file will abort the edit.\n"
116 hdr += "\n"
117 hdr += editutil.GenerateEditorWarningHeader()
118 yBytes, err = editutil.OpenEditor(ctx, yContent, hdr)
119 if err != nil {
120 return err
121 }
122 }
123 if len(yBytes) == 0 {
124 logrus.Info("Aborting, as requested by saving the file with empty content")
125 return nil
126 }
127 if bytes.Equal(yBytes, yContent) {
128 logrus.Info("Aborting, no changes made to the instance")
129 return nil
130 }
131 y, err := limayaml.LoadWithWarnings(ctx, yBytes, filePath)
132 if err != nil {
133 return err
134 }
135 // If VMType is not specified, we go with the default platform driver.
136 if err := driverutil.ResolveVMType(y); err != nil {
137 return err
138 }
139 if err := limayaml.Validate(y, false); err != nil {
140 return saveRejectedYAML(yBytes, err)
141 }
142 var start bool
143 if inst != nil {
144 inst.Config = y
145 limaDriver, err := driverutil.CreateConfiguredDriver(ctx, inst, 0)
146 if err != nil {
147 return err
148 }
149 defer func() {
150 if !start {
151 server.Stop(inst.Dir, true)
152 }
153 }()
154 if err := limaDriver.Validate(ctx); err != nil {
155 return saveRejectedYAML(yBytes, err)
156 }
157 if err := limayaml.Validate(inst.Config, true); err != nil {
158 return saveRejectedYAML(yBytes, err)
159 }
160 }
161
162 if err := limayaml.ValidateAgainstLatestConfig(ctx, yBytes, yContent); err != nil {
163 return saveRejectedYAML(yBytes, err)
164 }
165
166 if err := os.WriteFile(filePath, yBytes, 0o644); err != nil {
167 return err
168 }
169
170 if inst != nil {
171 logrus.Infof("Instance %#q configuration edited", inst.Name)
172 }
173
174 if inst == nil {
175 // edited a limayaml file directly
176 return nil
177 }
178
179 start, err = flags.GetBool("start")
180 if err != nil {
181 return err
182 }
183
184 if tty && !flags.Changed("start") {
185 start, err = askWhetherToStart(cmd)
186 if err != nil {
187 return err
188 }
189 }
190 if !start {
191 return nil
192 }
193 // Network reconciliation will be performed by the process launched by the autostart manager
194 if registered, err := autostart.IsRegistered(ctx, inst); err != nil && !errors.Is(err, autostart.ErrNotSupported) {
195 return fmt.Errorf("failed to check if the autostart entry for instance %#q is registered: %w", inst.Name, err)
196 } else if !registered {
197 err = reconcile.Reconcile(ctx, inst.Name)
198 if err != nil {
199 return err
200 }
201 }
202
203 // store.Inspect() syncs values between inst.YAML and the store.
204 // This call applies the validated template to the store.
205 inst, err = store.Inspect(ctx, inst.Name)
206 if err != nil {
207 return err
208 }
209 return instance.Start(ctx, inst, false, false)
210}
211
212func askWhetherToStart(cmd *cobra.Command) (bool, error) {
213 isTTY := uiutil.InputIsTTY(cmd.InOrStdin())
214 if isTTY {
215 message := "Do you want to start the instance now? "
216 return uiutil.Confirm(message, true)
217 }
218 return false, nil
219}
220
221func editBashComplete(cmd *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
222 return bashCompleteInstanceNames(cmd)
223}
224
225// saveRejectedYAML writes the rejected config and returns an error.
226func saveRejectedYAML(y []byte, origErr error) error {
227 rejectedYAML := "lima.REJECTED.yaml"
228 if writeErr := os.WriteFile(rejectedYAML, y, 0o644); writeErr != nil {
229 return fmt.Errorf("the YAML is invalid, attempted to save the buffer as %#q but failed: %w", rejectedYAML, errors.Join(writeErr, origErr))
230 }
231 // TODO: may need to support editing the rejected YAML
232 return fmt.Errorf("the YAML is invalid, saved the buffer as %#q: %w", rejectedYAML, origErr)
233}