| 1 | |
| 2 | |
| 3 | |
| 4 | package main |
| 5 | |
| 6 | import ( |
| 7 | "context" |
| 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/pkg/driverutil" |
| 17 | "github.com/lima-vm/lima/v2/pkg/limatmpl" |
| 18 | "github.com/lima-vm/lima/v2/pkg/limatype/dirnames" |
| 19 | "github.com/lima-vm/lima/v2/pkg/limayaml" |
| 20 | "github.com/lima-vm/lima/v2/pkg/uiutil" |
| 21 | "github.com/lima-vm/lima/v2/pkg/yqutil" |
| 22 | ) |
| 23 | |
| 24 | func newTemplateCommand() *cobra.Command { |
| 25 | templateCommand := &cobra.Command{ |
| 26 | Use: "template", |
| 27 | Aliases: []string{"tmpl"}, |
| 28 | Short: "Lima template management (EXPERIMENTAL)", |
| 29 | SilenceUsage: true, |
| 30 | SilenceErrors: true, |
| 31 | GroupID: advancedCommand, |
| 32 | PreRun: func(*cobra.Command, []string) { |
| 33 | logrus.Warn("`limactl template` is experimental") |
| 34 | }, |
| 35 | } |
| 36 | templateCommand.AddCommand( |
| 37 | newTemplateCopyCommand(), |
| 38 | newTemplateValidateCommand(), |
| 39 | newTemplateYQCommand(), |
| 40 | newTemplateURLCommand(), |
| 41 | ) |
| 42 | return templateCommand |
| 43 | } |
| 44 | |
| 45 | |
| 46 | func newValidateCommand() *cobra.Command { |
| 47 | validateCommand := newTemplateValidateCommand() |
| 48 | validateCommand.GroupID = advancedCommand |
| 49 | return validateCommand |
| 50 | } |
| 51 | |
| 52 | var templateCopyExample = ` Template locators are local files, file://, https://, or template: URLs |
| 53 | |
| 54 | # Copy default template to STDOUT |
| 55 | limactl template copy template:default - |
| 56 | |
| 57 | # Copy template from web location to local file and embed all external references |
| 58 | # (this does not embed template: references) |
| 59 | limactl template copy --embed https://example.com/lima.yaml mighty-machine.yaml |
| 60 | ` |
| 61 | |
| 62 | func newTemplateCopyCommand() *cobra.Command { |
| 63 | templateCopyCommand := &cobra.Command{ |
| 64 | Use: "copy [OPTIONS] TEMPLATE [DEST]", |
| 65 | Short: "Copy template", |
| 66 | Long: "Copy a template via locator to a local file or stdout (default)", |
| 67 | Example: templateCopyExample, |
| 68 | Args: WrapArgsError(cobra.RangeArgs(1, 2)), |
| 69 | RunE: templateCopyAction, |
| 70 | } |
| 71 | templateCopyCommand.Flags().Bool("embed", false, "Embed external dependencies into template") |
| 72 | templateCopyCommand.Flags().Bool("embed-all", false, "Embed all dependencies into template") |
| 73 | templateCopyCommand.Flags().Bool("fill", false, "Fill defaults") |
| 74 | templateCopyCommand.Flags().Bool("verbatim", false, "Don't make locators absolute") |
| 75 | return templateCopyCommand |
| 76 | } |
| 77 | |
| 78 | func fillDefaults(ctx context.Context, tmpl *limatmpl.Template) error { |
| 79 | limaDir, err := dirnames.LimaDir() |
| 80 | if err != nil { |
| 81 | return err |
| 82 | } |
| 83 | |
| 84 | |
| 85 | filePath := filepath.Join(limaDir, tmpl.Name+".yaml") |
| 86 | tmpl.Config, err = limayaml.Load(ctx, tmpl.Bytes, filePath) |
| 87 | if err != nil { |
| 88 | return err |
| 89 | } |
| 90 | tmpl.Bytes, err = limayaml.Marshal(tmpl.Config, false) |
| 91 | if err != nil { |
| 92 | return err |
| 93 | } |
| 94 | |
| 95 | if err := driverutil.ResolveVMType(tmpl.Config); err != nil { |
| 96 | return err |
| 97 | } |
| 98 | return nil |
| 99 | } |
| 100 | |
| 101 | func templateCopyAction(cmd *cobra.Command, args []string) error { |
| 102 | ctx := cmd.Context() |
| 103 | source := args[0] |
| 104 | target := "-" |
| 105 | if len(args) > 1 { |
| 106 | target = args[1] |
| 107 | } |
| 108 | embed, err := cmd.Flags().GetBool("embed") |
| 109 | if err != nil { |
| 110 | return err |
| 111 | } |
| 112 | embedAll, err := cmd.Flags().GetBool("embed-all") |
| 113 | if err != nil { |
| 114 | return err |
| 115 | } |
| 116 | fill, err := cmd.Flags().GetBool("fill") |
| 117 | if err != nil { |
| 118 | return err |
| 119 | } |
| 120 | verbatim, err := cmd.Flags().GetBool("verbatim") |
| 121 | if err != nil { |
| 122 | return err |
| 123 | } |
| 124 | if fill { |
| 125 | embedAll = true |
| 126 | } |
| 127 | if embedAll { |
| 128 | embed = true |
| 129 | } |
| 130 | if embed && verbatim { |
| 131 | return errors.New("--verbatim cannot be used with any of --embed, --embed-all, or --fill") |
| 132 | } |
| 133 | tmpl, err := limatmpl.Read(ctx, "", source) |
| 134 | if err != nil { |
| 135 | return err |
| 136 | } |
| 137 | if len(tmpl.Bytes) == 0 { |
| 138 | return fmt.Errorf("don't know how to interpret %#q as a template locator", source) |
| 139 | } |
| 140 | if !verbatim { |
| 141 | if embed { |
| 142 | |
| 143 | if err := tmpl.Embed(ctx, embedAll, fill); err != nil { |
| 144 | return err |
| 145 | } |
| 146 | } else { |
| 147 | if err := tmpl.UseAbsLocators(ctx); err != nil { |
| 148 | return err |
| 149 | } |
| 150 | } |
| 151 | } |
| 152 | if fill { |
| 153 | if err := fillDefaults(ctx, tmpl); err != nil { |
| 154 | return err |
| 155 | } |
| 156 | } |
| 157 | if target == "-" && uiutil.OutputIsTTY(cmd.OutOrStdout()) { |
| 158 | |
| 159 | out, err := yqutil.EvaluateExpressionPlain(".", string(tmpl.Bytes), true) |
| 160 | if err == nil { |
| 161 | _, err = fmt.Fprint(cmd.OutOrStdout(), out) |
| 162 | } |
| 163 | return err |
| 164 | } |
| 165 | |
| 166 | writer := cmd.OutOrStdout() |
| 167 | if target != "-" { |
| 168 | file, err := os.OpenFile(target, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644) |
| 169 | if err != nil { |
| 170 | return err |
| 171 | } |
| 172 | defer file.Close() |
| 173 | writer = file |
| 174 | } |
| 175 | _, err = fmt.Fprint(writer, string(tmpl.Bytes)) |
| 176 | return err |
| 177 | } |
| 178 | |
| 179 | const templateYQHelp = `Use the builtin YQ evaluator to extract information from a template. |
| 180 | External references are embedded and default values are filled in |
| 181 | before the YQ expression is evaluated. |
| 182 | |
| 183 | Example: |
| 184 | limactl template yq template:default '.images[].location' |
| 185 | |
| 186 | The example command is equivalent to using an external yq command like this: |
| 187 | limactl template copy --fill template:default - | yq '.images[].location' |
| 188 | ` |
| 189 | |
| 190 | func newTemplateYQCommand() *cobra.Command { |
| 191 | templateYQCommand := &cobra.Command{ |
| 192 | Use: "yq TEMPLATE EXPR", |
| 193 | Short: "Query template expressions", |
| 194 | Long: templateYQHelp, |
| 195 | Args: WrapArgsError(cobra.ExactArgs(2)), |
| 196 | RunE: templateYQAction, |
| 197 | } |
| 198 | return templateYQCommand |
| 199 | } |
| 200 | |
| 201 | func templateYQAction(cmd *cobra.Command, args []string) error { |
| 202 | ctx := cmd.Context() |
| 203 | locator := args[0] |
| 204 | expr := args[1] |
| 205 | tmpl, err := limatmpl.Read(ctx, "", locator) |
| 206 | if err != nil { |
| 207 | return err |
| 208 | } |
| 209 | if len(tmpl.Bytes) == 0 { |
| 210 | return fmt.Errorf("don't know how to interpret %#q as a template locator", locator) |
| 211 | } |
| 212 | if err := tmpl.Embed(cmd.Context(), true, true); err != nil { |
| 213 | return err |
| 214 | } |
| 215 | if err := fillDefaults(ctx, tmpl); err != nil { |
| 216 | return err |
| 217 | } |
| 218 | colorsEnabled := uiutil.OutputIsTTY(cmd.OutOrStdout()) |
| 219 | out, err := yqutil.EvaluateExpressionPlain(expr, string(tmpl.Bytes), colorsEnabled) |
| 220 | if err == nil { |
| 221 | _, err = fmt.Fprint(cmd.OutOrStdout(), out) |
| 222 | } |
| 223 | return err |
| 224 | } |
| 225 | |
| 226 | func newTemplateValidateCommand() *cobra.Command { |
| 227 | templateValidateCommand := &cobra.Command{ |
| 228 | Use: "validate TEMPLATE [TEMPLATE, ...]", |
| 229 | Short: "Validate YAML templates", |
| 230 | Args: WrapArgsError(cobra.MinimumNArgs(1)), |
| 231 | RunE: templateValidateAction, |
| 232 | } |
| 233 | templateValidateCommand.Flags().Bool("fill", false, "Fill defaults") |
| 234 | return templateValidateCommand |
| 235 | } |
| 236 | |
| 237 | func templateValidateAction(cmd *cobra.Command, args []string) error { |
| 238 | ctx := cmd.Context() |
| 239 | fill, err := cmd.Flags().GetBool("fill") |
| 240 | if err != nil { |
| 241 | return err |
| 242 | } |
| 243 | limaDir, err := dirnames.LimaDir() |
| 244 | if err != nil { |
| 245 | return err |
| 246 | } |
| 247 | |
| 248 | for _, arg := range args { |
| 249 | tmpl, err := limatmpl.Read(ctx, "", arg) |
| 250 | if err != nil { |
| 251 | return err |
| 252 | } |
| 253 | if len(tmpl.Bytes) == 0 { |
| 254 | return fmt.Errorf("don't know how to interpret %#q as a template locator", arg) |
| 255 | } |
| 256 | if tmpl.Name == "" { |
| 257 | return fmt.Errorf("can't determine instance name from template locator %#q", arg) |
| 258 | } |
| 259 | |
| 260 | if err := tmpl.Embed(cmd.Context(), true, fill); err != nil { |
| 261 | return err |
| 262 | } |
| 263 | |
| 264 | |
| 265 | filePath := filepath.Join(limaDir, tmpl.Name+".yaml") |
| 266 | y, err := limayaml.Load(ctx, tmpl.Bytes, filePath) |
| 267 | if err != nil { |
| 268 | return err |
| 269 | } |
| 270 | |
| 271 | if err := driverutil.ResolveVMType(y); err != nil { |
| 272 | return err |
| 273 | } |
| 274 | if err := limayaml.Validate(y, false); err != nil { |
| 275 | return fmt.Errorf("failed to validate YAML file %#q: %w", arg, err) |
| 276 | } |
| 277 | logrus.Infof("%#q: OK", arg) |
| 278 | if fill { |
| 279 | b, err := limayaml.Marshal(y, len(args) > 1) |
| 280 | if err != nil { |
| 281 | return fmt.Errorf("failed to marshal template %#q again after filling defaults: %w", arg, err) |
| 282 | } |
| 283 | fmt.Fprint(cmd.OutOrStdout(), string(b)) |
| 284 | } |
| 285 | } |
| 286 | |
| 287 | return nil |
| 288 | } |
| 289 | |
| 290 | func newTemplateURLCommand() *cobra.Command { |
| 291 | templateURLCommand := &cobra.Command{ |
| 292 | Use: "url CUSTOM_URL", |
| 293 | Short: "Transform custom template URLs to regular file or https URLs", |
| 294 | Args: WrapArgsError(cobra.ExactArgs(1)), |
| 295 | RunE: templateURLAction, |
| 296 | } |
| 297 | return templateURLCommand |
| 298 | } |
| 299 | |
| 300 | func templateURLAction(cmd *cobra.Command, args []string) error { |
| 301 | url, err := limatmpl.TransformCustomURL(cmd.Context(), args[0]) |
| 302 | if err != nil { |
| 303 | return err |
| 304 | } |
| 305 | _, err = fmt.Fprintln(cmd.OutOrStdout(), url) |
| 306 | return err |
| 307 | } |