| // Copyright 2019 The Fuchsia Authors. All rights reserved. |
| // Use of this source code is governed by a BSD-style license that can be |
| // found in the LICENSE file. |
| |
| package main |
| |
| import ( |
| "context" |
| "errors" |
| "flag" |
| "log" |
| "path/filepath" |
| |
| "fuchsia.googlesource.com/infra/infra/fxicfg" |
| "github.com/google/subcommands" |
| luci "go.chromium.org/luci/starlark/interpreter" |
| ) |
| |
| // TODO(IN-1102): Delete all files in the output dir that weren't generated by this |
| // run to prevent "zombie" configs. |
| type GenerateCommand struct { |
| diffOnly bool |
| } |
| |
| func (*GenerateCommand) Name() string { |
| return "generate" |
| } |
| |
| func (*GenerateCommand) Usage() string { |
| return "generate main.star" |
| } |
| |
| func (*GenerateCommand) Synopsis() string { |
| return "generates infrastructure configs from Starlark sources" |
| } |
| |
| func (cmd *GenerateCommand) SetFlags(f *flag.FlagSet) { |
| flag.BoolVar(&cmd.diffOnly, "diff", false, "Whether to display changes and exit without writing files") |
| } |
| |
| func (cmd *GenerateCommand) Execute(ctx context.Context, f *flag.FlagSet, _ ...interface{}) subcommands.ExitStatus { |
| if err := cmd.validateFlags(f); err != nil { |
| log.Println(err) |
| return subcommands.ExitFailure |
| } |
| if err := cmd.execute(ctx, f.Arg(0)); err != nil { |
| log.Println(err) |
| return subcommands.ExitFailure |
| } |
| return subcommands.ExitSuccess |
| } |
| |
| func (cmd *GenerateCommand) execute(ctx context.Context, path string) error { |
| root, main := filepath.Dir(path), filepath.Base(path) |
| state, _, err := fxicfg.Generate(luci.FileSystemLoader(root), main) |
| if err != nil { |
| return err |
| } |
| |
| if cmd.diffOnly { |
| // TODO(IN-1102) |
| return errors.New("unimplemented: -diff") |
| } |
| |
| if err := fxicfg.CommitState(state); err != nil { |
| return err |
| } |
| return nil |
| } |
| |
| func (cmd *GenerateCommand) validateFlags(f *flag.FlagSet) error { |
| if f.NArg() == 0 { |
| return errors.New("expected one positional argument") |
| } |
| return nil |
| } |