github.com/humans-group/gqlgen@v0.7.2/cmd/gen.go (about)

     1  package cmd
     2  
     3  import (
     4  	"fmt"
     5  	"io/ioutil"
     6  	"os"
     7  
     8  	"github.com/99designs/gqlgen/codegen"
     9  	"github.com/pkg/errors"
    10  	"github.com/urfave/cli"
    11  )
    12  
    13  var genCmd = cli.Command{
    14  	Name:  "generate",
    15  	Usage: "generate a graphql server based on schema",
    16  	Flags: []cli.Flag{
    17  		cli.BoolFlag{Name: "verbose, v", Usage: "show logs"},
    18  		cli.StringFlag{Name: "config, c", Usage: "the config filename"},
    19  	},
    20  	Action: func(ctx *cli.Context) {
    21  		var config *codegen.Config
    22  		var err error
    23  		if configFilename := ctx.String("config"); configFilename != "" {
    24  			config, err = codegen.LoadConfig(configFilename)
    25  			if err != nil {
    26  				fmt.Fprintln(os.Stderr, err.Error())
    27  				os.Exit(1)
    28  			}
    29  		} else {
    30  			config, err = codegen.LoadConfigFromDefaultLocations()
    31  			if os.IsNotExist(errors.Cause(err)) {
    32  				config = codegen.DefaultConfig()
    33  			} else if err != nil {
    34  				fmt.Fprintln(os.Stderr, err.Error())
    35  				os.Exit(1)
    36  			}
    37  		}
    38  
    39  		for _, filename := range config.SchemaFilename {
    40  			var schemaRaw []byte
    41  			schemaRaw, err = ioutil.ReadFile(filename)
    42  			if err != nil {
    43  				fmt.Fprintln(os.Stderr, "unable to open schema: "+err.Error())
    44  				os.Exit(1)
    45  			}
    46  			config.SchemaStr[filename] = string(schemaRaw)
    47  		}
    48  
    49  		if err = config.Check(); err != nil {
    50  			fmt.Fprintln(os.Stderr, "invalid config format: "+err.Error())
    51  			os.Exit(1)
    52  		}
    53  
    54  		err = codegen.Generate(*config)
    55  		if err != nil {
    56  			fmt.Fprintln(os.Stderr, err.Error())
    57  			os.Exit(2)
    58  		}
    59  	},
    60  }