跳到主要内容

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

浏览文件

list.go

423 行 · 11.7 KB历史下载
1// SPDX-FileCopyrightText: Copyright The Lima Authors
2// SPDX-License-Identifier: Apache-2.0
3
4package main
5
6import (
7 "bufio"
8 "bytes"
9 "context"
10 "encoding/json"
11 "errors"
12 "fmt"
13 "os"
14 "reflect"
15 "slices"
16 "strings"
17
18 "github.com/cheggaaa/pb/v3/termutil"
19 "github.com/mikefarah/yq/v4/pkg/yqlib"
20 "github.com/sirupsen/logrus"
21 "github.com/spf13/cobra"
22
23 "github.com/lima-vm/lima/v2/pkg/limatype"
24 "github.com/lima-vm/lima/v2/pkg/limatype/dirnames"
25 "github.com/lima-vm/lima/v2/pkg/store"
26 "github.com/lima-vm/lima/v2/pkg/uiutil"
27 "github.com/lima-vm/lima/v2/pkg/yqutil"
28)
29
30func fieldNames() []string {
31 names := []string{}
32 t := reflect.TypeFor[store.FormatData]()
33 for f := range t.Fields() {
34 if f.Anonymous {
35 for embedded := range f.Type.Fields() {
36 if tag := f.Tag.Get("lima"); tag != "deprecated" {
37 names = append(names, embedded.Name)
38 }
39 }
40 } else {
41 if tag := f.Tag.Get("lima"); tag != "deprecated" {
42 names = append(names, f.Name)
43 }
44 }
45 }
46 return names
47}
48
49func newListCommand() *cobra.Command {
50 listCommand := &cobra.Command{
51 Use: "list [flags] [INSTANCE]...",
52 Aliases: []string{"ls"},
53 Short: "List instances of Lima",
54 Long: `List instances of Lima.
55
56The output can be presented in one of several formats, using the --format <format> flag.
57
58 --format json - Output in JSON format
59 --format yaml - Output in YAML format
60 --format table - Output in table format
61 --format '{{ <go template> }}' - If the format begins and ends with '{{ }}', then it is used as a go template.
62
63Filtering instances:
64 --filter EXPR - Filter instances using yq expression (this is equivalent to --yq 'select(EXPR)')
65 Can be specified multiple times (combined with AND logic) and it works with all output formats.
66 Examples:
67 --filter '.status == "Running"'
68 --filter '.vmType == "vz"'
69 --filter '.status == "Running"' --filter '.vmType == "vz"' (Same as AND)
70` + store.FormatHelp + `
71The following legacy flags continue to function:
72 --json - equal to '--format json'`,
73 Args: WrapArgsError(cobra.ArbitraryArgs),
74 RunE: listAction,
75 ValidArgsFunction: listBashComplete,
76 GroupID: basicCommand,
77 }
78
79 listCommand.Flags().StringP("format", "f", "table", "Output format, one of: json, yaml, table, go-template")
80 listCommand.Flags().Bool("list-fields", false, "List fields available for format")
81 listCommand.Flags().Bool("json", false, "Same as --format=json")
82 listCommand.Flags().BoolP("quiet", "q", false, "Only show names")
83 listCommand.Flags().Bool("all-fields", false, "Show all fields")
84 listCommand.Flags().StringArray("yq", nil, "Apply yq expression to each instance")
85 listCommand.Flags().StringArrayP("filter", "l", nil, "Filter instances using yq expression (equivalent to --yq 'select(EXPR)')")
86
87 return listCommand
88}
89
90func instanceMatches(arg string, instances []string) []string {
91 matches := []string{}
92 for _, instance := range instances {
93 if instance == arg {
94 matches = append(matches, instance)
95 }
96 }
97 return matches
98}
99
100// unmatchedInstancesError is created when unmatched instance names found.
101type unmatchedInstancesError struct{}
102
103// Error implements error.
104func (unmatchedInstancesError) Error() string {
105 return "unmatched instances"
106}
107
108// ExitCode implements ExitCoder.
109func (unmatchedInstancesError) ExitCode() int {
110 return 1
111}
112
113func brokenInstance(instanceName string, inspectErr error) *limatype.Instance {
114 instDir, err := dirnames.InstanceDir(instanceName)
115 if err != nil {
116 return nil
117 }
118 if _, err := os.Stat(instDir); err != nil {
119 return nil
120 }
121 return &limatype.Instance{
122 Name: instanceName,
123 Dir: instDir,
124 Status: limatype.StatusBroken,
125 Errors: []error{inspectErr},
126 }
127}
128
129func listAction(cmd *cobra.Command, args []string) error {
130 ctx := cmd.Context()
131 quiet, err := cmd.Flags().GetBool("quiet")
132 if err != nil {
133 return err
134 }
135 format, err := cmd.Flags().GetString("format")
136 if err != nil {
137 return err
138 }
139 listFields, err := cmd.Flags().GetBool("list-fields")
140 if err != nil {
141 return err
142 }
143 jsonFormat, err := cmd.Flags().GetBool("json")
144 if err != nil {
145 return err
146 }
147 yq, err := cmd.Flags().GetStringArray("yq")
148 if err != nil {
149 return err
150 }
151 filter, err := cmd.Flags().GetStringArray("filter")
152 if err != nil {
153 return err
154 }
155
156 if jsonFormat {
157 format = "json"
158 }
159
160 // conflicts
161 if jsonFormat && cmd.Flags().Changed("format") {
162 return errors.New("option --json conflicts with option --format")
163 }
164 if listFields && cmd.Flags().Changed("format") {
165 return errors.New("option --list-fields conflicts with option --format")
166 }
167 if len(yq) != 0 {
168 if cmd.Flags().Changed("format") && format != "json" && format != "yaml" {
169 return errors.New("option --yq only works with --format json or yaml")
170 }
171 if listFields {
172 return errors.New("option --list-fields conflicts with option --yq")
173 }
174 }
175 if len(filter) != 0 {
176 if listFields {
177 return errors.New("option --list-fields conflicts with option --filter")
178 }
179 }
180
181 if quiet && format != "table" {
182 return errors.New("option --quiet can only be used with '--format table'")
183 }
184
185 if listFields {
186 names := fieldNames()
187 slices.Sort(names)
188 fmt.Fprintln(cmd.OutOrStdout(), strings.Join(names, "\n"))
189 return nil
190 }
191
192 if err := store.Validate(); err != nil {
193 logrus.Warnf("The directory %#q does not look like a valid Lima directory: %v", store.Directory(), err)
194 }
195
196 allInstances, err := store.Instances()
197 if err != nil {
198 return err
199 }
200 if len(args) == 0 && len(allInstances) == 0 {
201 logrus.Warn("No instance found. Run `limactl create` to create an instance.")
202 return nil
203 }
204
205 instanceNames := []string{}
206 unmatchedInstances := false
207 if len(args) > 0 {
208 for _, arg := range args {
209 matches := instanceMatches(arg, allInstances)
210 if len(matches) > 0 {
211 instanceNames = append(instanceNames, matches...)
212 } else {
213 logrus.Warnf("No instance matching %v found.", arg)
214 unmatchedInstances = true
215 }
216 }
217 } else {
218 instanceNames = allInstances
219 }
220
221 if quiet && len(yq) == 0 && len(filter) == 0 {
222 for _, instName := range instanceNames {
223 fmt.Fprintln(cmd.OutOrStdout(), instName)
224 }
225 if unmatchedInstances {
226 return unmatchedInstancesError{}
227 }
228 return nil
229 }
230
231 // get the state and config for all the requested instances
232 var instances []*limatype.Instance
233 for _, instanceName := range instanceNames {
234 instance, err := store.Inspect(ctx, instanceName)
235 if err != nil {
236 if errors.Is(err, os.ErrNotExist) {
237 if broken := brokenInstance(instanceName, err); broken != nil {
238 instances = append(instances, broken)
239 continue
240 }
241 logrus.Warnf("Skipping instance %#q: %v (being cloned or deleted?)", instanceName, err)
242 if len(args) > 0 {
243 unmatchedInstances = true
244 }
245 continue
246 }
247 return fmt.Errorf("unable to load instance %s: %w", instanceName, err)
248 }
249 instances = append(instances, instance)
250 }
251
252 if len(filter) > 0 {
253 var filterExprs []string
254 for _, f := range filter {
255 filterExprs = append(filterExprs, "select("+f+")")
256 }
257 instances, err = filterInstances(ctx, instances, filterExprs)
258 if err != nil {
259 return err
260 }
261 }
262
263 if quiet && len(yq) == 0 {
264 for _, instance := range instances {
265 fmt.Fprintln(cmd.OutOrStdout(), instance.Name)
266 }
267 if unmatchedInstances {
268 return unmatchedInstancesError{}
269 }
270 return nil
271 }
272
273 for _, instance := range instances {
274 if len(instance.Errors) > 0 {
275 logrus.WithField("errors", instance.Errors).Warnf("instance %#q has errors", instance.Name)
276 }
277 }
278
279 allFields, err := cmd.Flags().GetBool("all-fields")
280 if err != nil {
281 return err
282 }
283
284 options := store.PrintOptions{AllFields: allFields}
285 isTTY := uiutil.OutputIsTTY(cmd.OutOrStdout())
286 if isTTY {
287 if w, err := termutil.TerminalWidth(); err == nil {
288 options.TerminalWidth = w
289 }
290 }
291
292 // --yq implies --format json unless --format has been explicitly specified
293 if len(yq) != 0 && !cmd.Flags().Changed("format") {
294 format = "json"
295 }
296
297 // Always pipe JSON and YAML through yq to colorize it if isTTY
298 if len(yq) == 0 && (format == "json" || format == "yaml") {
299 yq = append(yq, ".")
300 }
301
302 if len(yq) == 0 {
303 err = store.PrintInstances(cmd.OutOrStdout(), instances, format, &options)
304 if err == nil && unmatchedInstances {
305 return unmatchedInstancesError{}
306 }
307 return err
308 }
309
310 if quiet {
311 yq = append(yq, ".name")
312 }
313 yqExpr := strings.Join(yq, " | ")
314
315 buf := new(bytes.Buffer)
316 err = store.PrintInstances(buf, instances, format, &options)
317 if err != nil {
318 return err
319 }
320
321 if format == "json" {
322 // The JSON encoder will create empty objects (YAML maps), even when they have the ",omitempty" tag.
323 deleteEmptyObjects := `del(.. | select(tag == "!!map" and length == 0))`
324 yqExpr += " | " + deleteEmptyObjects
325
326 encoderPrefs := yqlib.ConfiguredJSONPreferences.Copy()
327 encoderPrefs.ColorsEnabled = false
328 encoderPrefs.Indent = 0
329 plainEncoder := yqlib.NewJSONEncoder(encoderPrefs)
330 // Using non-0 indent means the instance will be printed over multiple lines,
331 // so is no longer in JSON Lines format. This is a compromise for readability.
332 encoderPrefs.Indent = 4
333 encoderPrefs.ColorsEnabled = true
334 colorEncoder := yqlib.NewJSONEncoder(encoderPrefs)
335
336 // Each line contains the JSON object for one Lima instance.
337 scanner := bufio.NewScanner(buf)
338 for scanner.Scan() {
339 var str string
340 if str, err = yqutil.EvaluateExpressionWithEncoder(yqExpr, scanner.Text(), plainEncoder); err != nil {
341 return err
342 }
343 // Repeatedly delete empty objects until there are none left.
344 for {
345 length := len(str)
346 if str, err = yqutil.EvaluateExpressionWithEncoder(deleteEmptyObjects, str, plainEncoder); err != nil {
347 return err
348 }
349 if len(str) >= length {
350 break
351 }
352 }
353 if isTTY {
354 // pretty-print and colorize the output
355 if str, err = yqutil.EvaluateExpressionWithEncoder(".", str, colorEncoder); err != nil {
356 return err
357 }
358 }
359 if _, err = fmt.Fprint(cmd.OutOrStdout(), str); err != nil {
360 return err
361 }
362 }
363 err = scanner.Err()
364 if err == nil && unmatchedInstances {
365 return unmatchedInstancesError{}
366 }
367 return err
368 }
369
370 var str string
371 if isTTY {
372 // This branch is trading the better formatting from yamlfmt for colorizing from yqlib.
373 if str, err = yqutil.EvaluateExpressionPlain(yqExpr, buf.String(), true); err != nil {
374 return err
375 }
376 } else {
377 var res []byte
378 if res, err = yqutil.EvaluateExpression(ctx, yqExpr, buf.Bytes()); err != nil {
379 return err
380 }
381 str = string(res)
382 }
383 _, err = fmt.Fprint(cmd.OutOrStdout(), str)
384 if err == nil && unmatchedInstances {
385 return unmatchedInstancesError{}
386 }
387 return err
388}
389
390func listBashComplete(cmd *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
391 return bashCompleteInstanceNames(cmd)
392}
393
394// filterInstances applies yq expressions to instances and returns the filtered results.
395func filterInstances(ctx context.Context, instances []*limatype.Instance, yqExprs []string) ([]*limatype.Instance, error) {
396 if len(yqExprs) == 0 {
397 return instances, nil
398 }
399
400 // the yq expression is evaluated with yqutil.EvaluateExpression, which disables environment variable access
401 // and file operations, mitigating injection attacks like ".name=strenv(SOME_SECRET_ENV)" which could
402 // trick Lima into exposing environment variables.
403 yqExpr := strings.Join(yqExprs, " | ")
404
405 var filteredInstances []*limatype.Instance
406 for _, instance := range instances {
407 jsonBytes, err := json.Marshal(instance)
408 if err != nil {
409 return nil, fmt.Errorf("failed to marshal instance %#q: %w", instance.Name, err)
410 }
411
412 result, err := yqutil.EvaluateExpression(ctx, yqExpr, jsonBytes)
413 if err != nil {
414 return nil, fmt.Errorf("failed to apply filter %#q: %w", yqExpr, err)
415 }
416
417 if len(bytes.TrimSpace(result)) > 0 {
418 filteredInstances = append(filteredInstances, instance)
419 }
420 }
421
422 return filteredInstances, nil
423}