github.com/windmeup/goreleaser@v1.21.95/cmd/schema.go (about)

     1  package cmd
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"os"
     7  	"path/filepath"
     8  
     9  	"github.com/invopop/jsonschema"
    10  	"github.com/spf13/cobra"
    11  	"github.com/windmeup/goreleaser/pkg/config"
    12  )
    13  
    14  type schemaCmd struct {
    15  	cmd    *cobra.Command
    16  	output string
    17  }
    18  
    19  func newSchemaCmd() *schemaCmd {
    20  	root := &schemaCmd{}
    21  	cmd := &cobra.Command{
    22  		Use:               "jsonschema",
    23  		Aliases:           []string{"schema"},
    24  		Short:             "outputs goreleaser's JSON schema",
    25  		SilenceUsage:      true,
    26  		SilenceErrors:     true,
    27  		Args:              cobra.NoArgs,
    28  		ValidArgsFunction: cobra.NoFileCompletions,
    29  		RunE: func(cmd *cobra.Command, args []string) error {
    30  			schema := jsonschema.Reflect(&config.Project{})
    31  			schema.Definitions["FileInfo"] = jsonschema.Reflect(&config.FileInfo{})
    32  			schema.Description = "goreleaser configuration definition file"
    33  			bts, err := json.MarshalIndent(schema, "	", "	")
    34  			if err != nil {
    35  				return fmt.Errorf("failed to create jsonschema: %w", err)
    36  			}
    37  			if root.output == "-" {
    38  				fmt.Println(string(bts))
    39  				return nil
    40  			}
    41  			if err := os.MkdirAll(filepath.Dir(root.output), 0o755); err != nil {
    42  				return fmt.Errorf("failed to write jsonschema file: %w", err)
    43  			}
    44  			if err := os.WriteFile(root.output, bts, 0o666); err != nil {
    45  				return fmt.Errorf("failed to write jsonschema file: %w", err)
    46  			}
    47  			return nil
    48  		},
    49  	}
    50  
    51  	cmd.Flags().StringVarP(&root.output, "output", "o", "-", "Where to save the JSONSchema file")
    52  	_ = cmd.MarkFlagFilename("output", "json")
    53  
    54  	root.cmd = cmd
    55  	return root
    56  }