github.com/snyk/vervet/v6@v6.2.4/internal/cmd/compiler.go (about) 1 package cmd 2 3 import ( 4 "fmt" 5 "os" 6 7 "github.com/urfave/cli/v2" 8 9 "github.com/snyk/vervet/v6/config" 10 "github.com/snyk/vervet/v6/internal/compiler" 11 ) 12 13 // BuildCommand is the `vervet build` subcommand. 14 var BuildCommand = cli.Command{ 15 Name: "build", 16 Usage: "Build versioned resources into versioned OpenAPI specs", 17 ArgsUsage: "[input resources root] [output api root]", 18 Flags: []cli.Flag{ 19 &cli.StringFlag{ 20 Name: "config", 21 Aliases: []string{"c", "conf"}, 22 Usage: "Project configuration file", 23 }, 24 &cli.StringFlag{ 25 Name: "include", 26 Aliases: []string{"I"}, 27 Usage: "OpenAPI specification to include in build output", 28 }, 29 }, 30 Action: Build, 31 } 32 33 // Build compiles versioned resources into versioned API specs. 34 func Build(ctx *cli.Context) error { 35 project, err := projectFromContext(ctx) 36 if err != nil { 37 return err 38 } 39 comp, err := compiler.New(ctx.Context, project) 40 if err != nil { 41 return err 42 } 43 err = comp.BuildAll(ctx.Context) 44 if err != nil { 45 return err 46 } 47 return nil 48 } 49 50 func projectFromContext(ctx *cli.Context) (*config.Project, error) { 51 var project *config.Project 52 if ctx.Args().Len() == 0 { 53 var configPath string 54 if s := ctx.String("config"); s != "" { 55 configPath = s 56 } else { 57 configPath = ".vervet.yaml" 58 } 59 f, err := os.Open(configPath) 60 if err != nil { 61 return nil, fmt.Errorf("failed to open %q: %w", configPath, err) 62 } 63 defer f.Close() 64 project, err = config.Load(f) 65 if err != nil { 66 return nil, err 67 } 68 } else { 69 api := &config.API{ 70 Resources: []*config.ResourceSet{{ 71 Path: ctx.Args().Get(0), 72 }}, 73 Output: &config.Output{ 74 Path: ctx.Args().Get(1), 75 }, 76 } 77 if includePath := ctx.String("include"); includePath != "" { 78 api.Overlays = append(api.Overlays, &config.Overlay{ 79 Include: includePath, 80 }) 81 } 82 project = &config.Project{ 83 APIs: map[string]*config.API{ 84 "": api, 85 }, 86 } 87 } 88 return project, nil 89 }