|
| 1 | +package generate |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "flag" |
| 6 | + "fmt" |
| 7 | + "os" |
| 8 | + |
| 9 | + "runtime" |
| 10 | + |
| 11 | + "github.com/mitchellh/cli" |
| 12 | + "github.com/protoconf/protoconf-terraform/pkg/importing" |
| 13 | +) |
| 14 | + |
| 15 | +type cliCommand struct { |
| 16 | + ui cli.Ui |
| 17 | +} |
| 18 | + |
| 19 | +type cliConfig struct { |
| 20 | + importPath string |
| 21 | + outputPath string |
| 22 | +} |
| 23 | + |
| 24 | +func newFlagSet() (*flag.FlagSet, *cliConfig) { |
| 25 | + flags := flag.NewFlagSet("", flag.ExitOnError) |
| 26 | + flags.Usage = func() { |
| 27 | + fmt.Fprintln(flags.Output(), "Usage: [OPTION]...") |
| 28 | + flags.PrintDefaults() |
| 29 | + } |
| 30 | + |
| 31 | + config := &cliConfig{} |
| 32 | + flags.StringVar(&config.importPath, "import_path", fmt.Sprintf(".terraform/providers/*/*/*/*/%s_%s", runtime.GOOS, runtime.GOARCH), "Path of terraform plugins") |
| 33 | + flags.StringVar(&config.outputPath, "output", "src", "Path to write proto files to.") |
| 34 | + |
| 35 | + return flags, config |
| 36 | +} |
| 37 | + |
| 38 | +func (c *cliCommand) Run(args []string) int { |
| 39 | + flags, config := newFlagSet() |
| 40 | + flags.Parse(args) |
| 41 | + |
| 42 | + g := importing.NewGenerator(config.importPath, config.outputPath, c.ui) |
| 43 | + err := g.PopulateProviders() |
| 44 | + if err != nil { |
| 45 | + c.ui.Error(fmt.Sprintf("Failed to generate providers: %v", err)) |
| 46 | + return 1 |
| 47 | + } |
| 48 | + err = g.Save() |
| 49 | + if err != nil { |
| 50 | + c.ui.Error(fmt.Sprintf("failed to write proto files: %v", err)) |
| 51 | + return 1 |
| 52 | + } |
| 53 | + return 0 |
| 54 | +} |
| 55 | + |
| 56 | +func (c *cliCommand) Help() string { |
| 57 | + var b bytes.Buffer |
| 58 | + b.WriteString(c.Synopsis()) |
| 59 | + b.WriteString("\n") |
| 60 | + flags, _ := newFlagSet() |
| 61 | + flags.SetOutput(&b) |
| 62 | + flags.Usage() |
| 63 | + return b.String() |
| 64 | +} |
| 65 | + |
| 66 | +func (c *cliCommand) Synopsis() string { |
| 67 | + return "Creates proto files from terraform providers schema" |
| 68 | +} |
| 69 | + |
| 70 | +// NewCommand is a cli.CommandFactory |
| 71 | +func NewCommand() (cli.Command, error) { |
| 72 | + ui := &cli.BasicUi{ |
| 73 | + Reader: os.Stdin, |
| 74 | + Writer: os.Stdout, |
| 75 | + ErrorWriter: os.Stderr, |
| 76 | + } |
| 77 | + return &cliCommand{ui: ui}, nil |
| 78 | +} |
0 commit comments