| // 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" |
| "fmt" |
| "io" |
| |
| "log" |
| "os" |
| |
| "fuchsia.googlesource.com/infra/infra/cmd/specs/generators" |
| "github.com/google/subcommands" |
| ) |
| |
| // StarlarkCodeGenerator transforms a text protobuf message read from the given io.Reader |
| // into the starlark code that would generate that same message when executed by fxicfg. |
| // The output is written to the given io.Writer. |
| // |
| // This relies on the generated Golang protobuf API being checked in to the fxcicfg pkg. |
| type StarlarkCodeGenerator interface { |
| Generate(io.Reader) error |
| } |
| |
| // FuchsiaPyID is the ID used to select the Fuchsia spec generator. |
| const FuchsiaPyID = "fuchsia" |
| |
| // ToStarlarkCommand generates starlark code from a spec. |
| type ToStarlarkCommand struct { |
| // The selected StarlarkCodeGenerator. |
| recipe string |
| } |
| |
| func (*ToStarlarkCommand) Name() string { return "to_starlark" } |
| func (*ToStarlarkCommand) Usage() string { return "cat /path/to/spec | to_starlark" } |
| func (*ToStarlarkCommand) Synopsis() string { |
| return "Generates the fxicfg starlark code that would produce the input spec" |
| } |
| |
| func (cmd *ToStarlarkCommand) SetFlags(f *flag.FlagSet) { |
| f.StringVar(&cmd.recipe, "recipe", FuchsiaPyID, fmt.Sprintf("The recipe whose api is being generated. Options: %v", []string{ |
| FuchsiaPyID, |
| })) |
| } |
| |
| func (cmd *ToStarlarkCommand) Execute(ctx context.Context, f *flag.FlagSet, _ ...interface{}) subcommands.ExitStatus { |
| generator, err := cmd.selectGenerator(cmd.recipe) |
| if err != nil { |
| log.Fatalf("invalid generator: %v", cmd.recipe) |
| } |
| if err := generator.Generate(os.Stdin); err != nil { |
| log.Fatalf("failed to generate spec: %v", err) |
| } |
| return subcommands.ExitFailure |
| } |
| |
| func (cmd *ToStarlarkCommand) selectGenerator(key string) (StarlarkCodeGenerator, error) { |
| switch key { |
| case FuchsiaPyID: |
| return generators.NewFuchsiaPySpecGenerator(os.Stdout), nil |
| default: |
| return nil, errors.New("generator not found") |
| } |
| } |