github.com/codykaup/genqlient@v0.6.2/generate/main.go (about) 1 // Package generate provides programmatic access to genqlient's functionality, 2 // and documentation of its configuration options. For general usage 3 // documentation, see the project [GitHub]. 4 // 5 // [GitHub]: https://github.com/codykaup/genqlient 6 package generate 7 8 import ( 9 "fmt" 10 "os" 11 "path/filepath" 12 "strings" 13 14 "github.com/alexflint/go-arg" 15 ) 16 17 func readConfigGenerateAndWrite(configFilename string) error { 18 var config *Config 19 var err error 20 if configFilename != "" { 21 config, err = ReadAndValidateConfig(configFilename) 22 if err != nil { 23 return err 24 } 25 } else { 26 config, err = ReadAndValidateConfigFromDefaultLocations() 27 if err != nil { 28 return err 29 } 30 } 31 32 generated, err := Generate(config) 33 if err != nil { 34 return err 35 } 36 37 for filename, content := range generated { 38 err = os.MkdirAll(filepath.Dir(filename), 0o755) 39 if err != nil { 40 return errorf(nil, 41 "could not create parent directory for generated file %v: %v", 42 filename, err) 43 } 44 45 err = os.WriteFile(filename, content, 0o644) 46 if err != nil { 47 return errorf(nil, "could not write generated file %v: %v", 48 filename, err) 49 } 50 } 51 return nil 52 } 53 54 type cliArgs struct { 55 ConfigFilename string `arg:"positional" placeholder:"CONFIG" default:"" help:"path to genqlient configuration (default: genqlient.yaml in current or any parent directory)"` 56 Init bool `arg:"--init" help:"write out and use a default config file"` 57 } 58 59 func (cliArgs) Description() string { 60 return strings.TrimSpace(` 61 Generates GraphQL client code for a given schema and queries. 62 See https://github.com/codykaup/genqlient for full documentation. 63 `) 64 } 65 66 // Main is the command-line entrypoint to genqlient; it's equivalent to calling 67 // 68 // go run github.com/codykaup/genqlient 69 // 70 // For lower-level control over genqlient's operation, see [Generate]. 71 func Main() { 72 exitIfError := func(err error) { 73 if err != nil { 74 fmt.Println(err) 75 os.Exit(1) 76 } 77 } 78 79 var args cliArgs 80 arg.MustParse(&args) 81 if args.Init { 82 filename := args.ConfigFilename 83 if filename == "" { 84 filename = "genqlient.yaml" 85 } 86 87 err := initConfig(filename) 88 exitIfError(err) 89 } 90 err := readConfigGenerateAndWrite(args.ConfigFilename) 91 exitIfError(err) 92 }