| 1 | |
| 2 | |
| 3 | |
| 4 | package main |
| 5 | |
| 6 | import ( |
| 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 | |
| 30 | func 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 | |
| 49 | func 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 | |
| 56 | The 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 | |
| 63 | Filtering 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 + ` |
| 71 | The 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 | |
| 90 | func 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 | |
| 101 | type unmatchedInstancesError struct{} |
| 102 | |
| 103 | |
| 104 | func (unmatchedInstancesError) Error() string { |
| 105 | return "unmatched instances" |
| 106 | } |
| 107 | |
| 108 | |
| 109 | func (unmatchedInstancesError) ExitCode() int { |
| 110 | return 1 |
| 111 | } |
| 112 | |
| 113 | func 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 | |
| 129 | func 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 | |
| 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 | |
| 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 | |
| 293 | if len(yq) != 0 && !cmd.Flags().Changed("format") { |
| 294 | format = "json" |
| 295 | } |
| 296 | |
| 297 | |
| 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 | |
| 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 | |
| 331 | |
| 332 | encoderPrefs.Indent = 4 |
| 333 | encoderPrefs.ColorsEnabled = true |
| 334 | colorEncoder := yqlib.NewJSONEncoder(encoderPrefs) |
| 335 | |
| 336 | |
| 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 | |
| 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 | |
| 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 | |
| 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 | |
| 390 | func listBashComplete(cmd *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) { |
| 391 | return bashCompleteInstanceNames(cmd) |
| 392 | } |
| 393 | |
| 394 | |
| 395 | func filterInstances(ctx context.Context, instances []*limatype.Instance, yqExprs []string) ([]*limatype.Instance, error) { |
| 396 | if len(yqExprs) == 0 { |
| 397 | return instances, nil |
| 398 | } |
| 399 | |
| 400 | |
| 401 | |
| 402 | |
| 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 | } |