Add a flag --init to write a default config (#81)
## Summary: Steve pointed out (#73) that having genqlient with no arguments silently use a default config file was a bit confusing, and changed it to use `genqlient.yaml` by default (#74). Mark pointed out (#76) that this makes it a bit less convenient when you're starting from scratch; you have to go create a config file. In this commit I add a new init flag that creates you a config file before using it. Originally the suggestion was to use subcommands, e.g. we'd have `genqlient init` and `genqlient generate` and so on. But I couldn't think of anything else we might want subcommands for in the future, and it felt a little silly to make you type `generate` each time. So instead, I made it a flag, which has the nice property that you can do `genqlient --init` and it will generate and then use a config file. (I mean, maybe it will immediately crash because you don't have a schema, but hopefully that's still a useful clue as to what to do next!) The implmentation was fairly trivial. Since we now have a nice way to generate a default config, I removed the default values for most of the options; I've always felt they were probably more confusing than helpful. (And indeed, all the users I know of (Khan/webapp, and the much smaller project Steve was working on, are setting those options explicitly.) This required a slight change to the syntax to say "don't use context", which is probably also net clearer. I decided this is also a good time to pull in a proper CLI parser (#31); see ADR-504 for more on that choice. This also adds some nice help messages! Fixes #76, #31. Issue: https://github.com/Khan/genqlient/issues/76 ## Test plan: ``` go run . go run . --init go run . --init example/genqlient.yaml # refuses to clobber go run . --init example/newgenqlient.yaml ``` Author: benjaminjkraft Reviewers: dnerdy, aberkan, MiguelCastillo, StevenACoffman Required Reviewers: Approved By: dnerdy Checks: ✅ Test (1.17), ✅ Test (1.16), ✅ Test (1.15), ✅ Test (1.14), ✅ Lint, ✅ Test (1.17), ✅ Test (1.16), ✅ Test (1.15), ✅ Test (1.14), ✅ Lint Pull Request URL: https://github.com/Khan/genqlient/pull/81
This commit is contained in:
+34
-22
@@ -2,19 +2,14 @@ package generate
|
||||
|
||||
import (
|
||||
"go/token"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"gopkg.in/yaml.v2"
|
||||
)
|
||||
|
||||
var defaultConfig = &Config{
|
||||
Schema: "schema.graphql",
|
||||
Operations: []string{"genqlient.graphql"},
|
||||
Generated: "generated.go",
|
||||
ContextType: "context.Context",
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
// The filename with the GraphQL schema (in SDL format); defaults to
|
||||
// schema.graphql
|
||||
@@ -56,9 +51,9 @@ type Config struct {
|
||||
// Set to the fully-qualified name of a Go type which generated helpers
|
||||
// should accept and use as the context.Context for HTTP requests.
|
||||
//
|
||||
// Defaults to context.Context; set to the empty string to omit context
|
||||
// entirely (i.e. use context.Background()). Must be a type which
|
||||
// implements context.Context.
|
||||
// Defaults to context.Context; set to "-" to omit context entirely (i.e.
|
||||
// use context.Background()). Must be a type which implements
|
||||
// context.Context.
|
||||
ContextType string `yaml:"context_type"`
|
||||
|
||||
// If set, a function to get a graphql.Client, perhaps from the context.
|
||||
@@ -157,6 +152,10 @@ func (c *Config) ValidateAndFillDefaults(configFilename string) error {
|
||||
c.ExportOperations = filepath.Join(c.baseDir(), c.ExportOperations)
|
||||
}
|
||||
|
||||
if c.ContextType == "" {
|
||||
c.ContextType = "context.Context"
|
||||
}
|
||||
|
||||
if c.Package == "" {
|
||||
abs, err := filepath.Abs(c.Generated)
|
||||
if err != nil {
|
||||
@@ -175,23 +174,36 @@ func (c *Config) ValidateAndFillDefaults(configFilename string) error {
|
||||
}
|
||||
|
||||
func ReadAndValidateConfig(filename string) (*Config, error) {
|
||||
config := *defaultConfig
|
||||
if filename != "" {
|
||||
text, err := ioutil.ReadFile(filename)
|
||||
if err != nil {
|
||||
return nil, errorf(nil, "unreadable config file %v: %v", filename, err)
|
||||
}
|
||||
|
||||
err = yaml.UnmarshalStrict(text, &config)
|
||||
if err != nil {
|
||||
return nil, errorf(nil, "invalid config file %v: %v", filename, err)
|
||||
}
|
||||
text, err := ioutil.ReadFile(filename)
|
||||
if err != nil {
|
||||
return nil, errorf(nil, "unreadable config file %v: %v", filename, err)
|
||||
}
|
||||
|
||||
err := config.ValidateAndFillDefaults(filename)
|
||||
var config Config
|
||||
err = yaml.UnmarshalStrict(text, &config)
|
||||
if err != nil {
|
||||
return nil, errorf(nil, "invalid config file %v: %v", filename, err)
|
||||
}
|
||||
|
||||
err = config.ValidateAndFillDefaults(filename)
|
||||
if err != nil {
|
||||
return nil, errorf(nil, "invalid config file %v: %v", filename, err)
|
||||
}
|
||||
|
||||
return &config, nil
|
||||
}
|
||||
|
||||
func initConfig(filename string) error {
|
||||
// TODO(benkraft): Embed this config file into the binary, see
|
||||
// https://github.com/Khan/genqlient/issues/9.
|
||||
r, err := os.Open(filepath.Join(thisDir, "default_genqlient.yaml"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
w, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = io.Copy(w, r)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
# Default genqlient config, see
|
||||
# go doc github.com/Khan/genqlient/generate.Config
|
||||
# for more options.
|
||||
schema: schema.graphql
|
||||
operations:
|
||||
- genqlient.graphql
|
||||
generated: generated.go
|
||||
@@ -103,7 +103,7 @@ func newGenerator(
|
||||
}
|
||||
}
|
||||
|
||||
if g.Config.ContextType != "" {
|
||||
if g.Config.ContextType != "-" {
|
||||
_, err := g.addRef(g.Config.ContextType)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid context_type: %w", err)
|
||||
|
||||
+30
-16
@@ -10,6 +10,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/Khan/genqlient/internal/testutil"
|
||||
"gopkg.in/yaml.v2"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -80,6 +81,7 @@ func TestGenerate(t *testing.T) {
|
||||
Package: "test",
|
||||
Generated: goFilename,
|
||||
ExportOperations: queriesFilename,
|
||||
ContextType: "-",
|
||||
Bindings: map[string]*TypeBinding{
|
||||
"ID": {Type: "github.com/Khan/genqlient/internal/testutil.ID"},
|
||||
"DateTime": {Type: "time.Time"},
|
||||
@@ -120,6 +122,22 @@ func TestGenerate(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func defaultConfig(t *testing.T) *Config {
|
||||
// Parse the config that `genqlient --init` generates, to make sure that
|
||||
// works.
|
||||
var config Config
|
||||
b, err := ioutil.ReadFile("default_genqlient.yaml")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
err = yaml.UnmarshalStrict(b, &config)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return &config
|
||||
}
|
||||
|
||||
// TestGenerateWithConfig tests several configuration options that affect
|
||||
// generated code but don't require particular query structures to test.
|
||||
//
|
||||
@@ -131,24 +149,20 @@ func TestGenerateWithConfig(t *testing.T) {
|
||||
fakeConfigFilename string
|
||||
config *Config // omits Schema and Operations, set below.
|
||||
}{
|
||||
{"DefaultConfig", "genqlient.yaml", defaultConfig},
|
||||
{"DefaultConfig", "genqlient.yaml", defaultConfig(t)},
|
||||
{"Subpackage", "genqlient.yaml", &Config{
|
||||
Generated: "mypkg/myfile.go",
|
||||
ContextType: "context.Context", // (from defaultConfig)
|
||||
Generated: "mypkg/myfile.go",
|
||||
}},
|
||||
{"SubpackageConfig", "mypkg/genqlient.yaml", &Config{
|
||||
Generated: "myfile.go", // (relative to genqlient.yaml)
|
||||
ContextType: "context.Context",
|
||||
Generated: "myfile.go", // (relative to genqlient.yaml)
|
||||
}},
|
||||
{"PackageName", "genqlient.yaml", &Config{
|
||||
Generated: "myfile.go",
|
||||
Package: "mypkg",
|
||||
ContextType: "context.Context",
|
||||
Generated: "myfile.go",
|
||||
Package: "mypkg",
|
||||
}},
|
||||
{"ExportOperations", "genqlient.yaml", &Config{
|
||||
Generated: "generated.go",
|
||||
ExportOperations: "operations.json",
|
||||
ContextType: "context.Context",
|
||||
}},
|
||||
{"CustomContext", "genqlient.yaml", &Config{
|
||||
Generated: "generated.go",
|
||||
@@ -156,12 +170,11 @@ func TestGenerateWithConfig(t *testing.T) {
|
||||
}},
|
||||
{"NoContext", "genqlient.yaml", &Config{
|
||||
Generated: "generated.go",
|
||||
ContextType: "",
|
||||
ContextType: "-",
|
||||
}},
|
||||
{"ClientGetter", "genqlient.yaml", &Config{
|
||||
Generated: "generated.go",
|
||||
ClientGetter: "github.com/Khan/genqlient/internal/testutil.GetClientFromContext",
|
||||
ContextType: "context.Context",
|
||||
}},
|
||||
{"ClientGetterCustomContext", "genqlient.yaml", &Config{
|
||||
Generated: "generated.go",
|
||||
@@ -171,7 +184,7 @@ func TestGenerateWithConfig(t *testing.T) {
|
||||
{"ClientGetterNoContext", "genqlient.yaml", &Config{
|
||||
Generated: "generated.go",
|
||||
ClientGetter: "github.com/Khan/genqlient/internal/testutil.GetClientFromNowhere",
|
||||
ContextType: "",
|
||||
ContextType: "-",
|
||||
}},
|
||||
}
|
||||
|
||||
@@ -240,10 +253,11 @@ func TestGenerateErrors(t *testing.T) {
|
||||
|
||||
t.Run(sourceFilename, func(t *testing.T) {
|
||||
_, err := Generate(&Config{
|
||||
Schema: filepath.Join(errorsDir, schemaFilename),
|
||||
Operations: []string{filepath.Join(errorsDir, sourceFilename)},
|
||||
Package: "test",
|
||||
Generated: os.DevNull,
|
||||
Schema: filepath.Join(errorsDir, schemaFilename),
|
||||
Operations: []string{filepath.Join(errorsDir, sourceFilename)},
|
||||
Package: "test",
|
||||
Generated: os.DevNull,
|
||||
ContextType: "context.Context",
|
||||
Bindings: map[string]*TypeBinding{
|
||||
"ValidScalar": {Type: "string"},
|
||||
"InvalidScalar": {Type: "bogus"},
|
||||
|
||||
+24
-15
@@ -6,6 +6,8 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/alexflint/go-arg"
|
||||
)
|
||||
|
||||
func readConfigGenerateAndWrite(configFilename string) error {
|
||||
@@ -36,25 +38,32 @@ func readConfigGenerateAndWrite(configFilename string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
type cliArgs struct {
|
||||
ConfigFilename string `arg:"positional" placeholder:"CONFIG" default:"genqlient.yaml" help:"path to genqlient configuration (default genqlient.yaml)"`
|
||||
Init bool `arg:"--init" help:"write out and use a default config file"`
|
||||
}
|
||||
|
||||
func (cliArgs) Description() string {
|
||||
return strings.TrimSpace(`
|
||||
Generates GraphQL client code for a given schema and queries.
|
||||
See https://github.com/Khan/genqlient for full documentation.
|
||||
`)
|
||||
}
|
||||
|
||||
func Main() {
|
||||
var err error
|
||||
defer func() {
|
||||
exitIfError := func(err error) {
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}()
|
||||
|
||||
switch len(os.Args) {
|
||||
case 2:
|
||||
err = readConfigGenerateAndWrite(os.Args[1])
|
||||
case 1:
|
||||
err = readConfigGenerateAndWrite("genqlient.yaml")
|
||||
default:
|
||||
argv0 := os.Args[0]
|
||||
if strings.Contains(argv0, string(filepath.Separator)+"go-build") {
|
||||
argv0 = "go run github.com/Khan/genqlient"
|
||||
}
|
||||
err = errorf(nil, "usage: %s [config]", argv0)
|
||||
}
|
||||
|
||||
var args cliArgs
|
||||
arg.MustParse(&args)
|
||||
if args.Init {
|
||||
err := initConfig(args.ConfigFilename)
|
||||
exitIfError(err)
|
||||
}
|
||||
err := readConfigGenerateAndWrite(args.ConfigFilename)
|
||||
exitIfError(err)
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ package {{.Config.Package}}
|
||||
{{range .Operations}}
|
||||
{{.Doc}}
|
||||
func {{.Name}}(
|
||||
{{if $.Config.ContextType -}}
|
||||
{{if ne $.Config.ContextType "-" -}}
|
||||
ctx {{ref $.Config.ContextType}},
|
||||
{{end}}
|
||||
{{- if not $.Config.ClientGetter -}}
|
||||
@@ -47,7 +47,7 @@ func {{.Name}}(
|
||||
|
||||
var err error
|
||||
{{if $.Config.ClientGetter -}}
|
||||
client, err := {{ref $.Config.ClientGetter}}({{if $.Config.ContextType}}ctx{{else}}{{end}})
|
||||
client, err := {{ref $.Config.ClientGetter}}({{if ne $.Config.ContextType "-"}}ctx{{else}}{{end}})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -55,7 +55,7 @@ func {{.Name}}(
|
||||
|
||||
var retval {{.ResponseName}}
|
||||
err = client.MakeRequest(
|
||||
{{if $.Config.ContextType}}ctx{{else}}nil{{end}},
|
||||
{{if ne $.Config.ContextType "-"}}ctx{{else}}nil{{end}},
|
||||
"{{.Name}}",
|
||||
`{{.Body}}`,
|
||||
&retval,
|
||||
|
||||
@@ -9,6 +9,8 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
// TODO(benkraft): Embed templates into the binary, see
|
||||
// https://github.com/Khan/genqlient/issues/9.
|
||||
_, thisFilename, _, _ = runtime.Caller(0)
|
||||
thisDir = filepath.Dir(thisFilename)
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user