diff options
author | Michael Muré <batolettre@gmail.com> | 2018-09-14 12:40:31 +0200 |
---|---|---|
committer | Michael Muré <batolettre@gmail.com> | 2018-09-14 12:41:59 +0200 |
commit | b478cd1bcb4756b20f7f4b15fcf81f23e1a60a02 (patch) | |
tree | 8ce232dcab3dd00708f8ba66c334472457e5980d /vendor/github.com/99designs/gqlgen/codegen/templates | |
parent | a3fc9abb921f5ce7084d6ab7473442d0b72b1d78 (diff) | |
download | git-bug-b478cd1bcb4756b20f7f4b15fcf81f23e1a60a02.tar.gz |
graphql: update gqlgen to 0.5.1
fix #6
Diffstat (limited to 'vendor/github.com/99designs/gqlgen/codegen/templates')
11 files changed, 798 insertions, 0 deletions
diff --git a/vendor/github.com/99designs/gqlgen/codegen/templates/args.gotpl b/vendor/github.com/99designs/gqlgen/codegen/templates/args.gotpl new file mode 100644 index 00000000..870a99ed --- /dev/null +++ b/vendor/github.com/99designs/gqlgen/codegen/templates/args.gotpl @@ -0,0 +1,13 @@ + args := map[string]interface{}{} + {{- range $i, $arg := . }} + var arg{{$i}} {{$arg.Signature }} + if tmp, ok := rawArgs[{{$arg.GQLName|quote}}]; ok { + var err error + {{$arg.Unmarshal (print "arg" $i) "tmp" }} + if err != nil { + return nil, err + } + } + args[{{$arg.GQLName|quote}}] = arg{{$i}} + {{- end }} + return args, nil diff --git a/vendor/github.com/99designs/gqlgen/codegen/templates/data.go b/vendor/github.com/99designs/gqlgen/codegen/templates/data.go new file mode 100644 index 00000000..d168fa31 --- /dev/null +++ b/vendor/github.com/99designs/gqlgen/codegen/templates/data.go @@ -0,0 +1,13 @@ +package templates + +var data = map[string]string{ + "args.gotpl": "\targs := map[string]interface{}{}\n\t{{- range $i, $arg := . }}\n\t\tvar arg{{$i}} {{$arg.Signature }}\n\t\tif tmp, ok := rawArgs[{{$arg.GQLName|quote}}]; ok {\n\t\t\tvar err error\n\t\t\t{{$arg.Unmarshal (print \"arg\" $i) \"tmp\" }}\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\targs[{{$arg.GQLName|quote}}] = arg{{$i}}\n\t{{- end }}\n\treturn args, nil\n", + "field.gotpl": "{{ $field := . }}\n{{ $object := $field.Object }}\n\n{{- if $object.Stream }}\n\tfunc (ec *executionContext) _{{$object.GQLType}}_{{$field.GQLName}}(ctx context.Context, field graphql.CollectedField) func() graphql.Marshaler {\n\t\t{{- if $field.Args }}\n\t\t\trawArgs := field.ArgumentMap(ec.Variables)\n\t\t\targs, err := {{ $field.ArgsFunc }}(rawArgs)\n\t\t\tif err != nil {\n\t\t\t\tec.Error(ctx, err)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t{{- end }}\n\t\tctx = graphql.WithResolverContext(ctx, &graphql.ResolverContext{\n\t\t\tField: field,\n\t\t})\n\t\tresults, err := ec.resolvers.{{ $field.ShortInvocation }}\n\t\tif err != nil {\n\t\t\tec.Error(ctx, err)\n\t\t\treturn nil\n\t\t}\n\t\treturn func() graphql.Marshaler {\n\t\t\tres, ok := <-results\n\t\t\tif !ok {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tvar out graphql.OrderedMap\n\t\t\tout.Add(field.Alias, func() graphql.Marshaler { {{ $field.WriteJson }} }())\n\t\t\treturn &out\n\t\t}\n\t}\n{{ else }}\n\t// nolint: vetshadow\n\tfunc (ec *executionContext) _{{$object.GQLType}}_{{$field.GQLName}}(ctx context.Context, field graphql.CollectedField, {{if not $object.Root}}obj *{{$object.FullName}}{{end}}) graphql.Marshaler {\n\t\t{{- if $field.Args }}\n\t\t\trawArgs := field.ArgumentMap(ec.Variables)\n\t\t\targs, err := {{ $field.ArgsFunc }}(rawArgs)\n\t\t\tif err != nil {\n\t\t\t\tec.Error(ctx, err)\n\t\t\t\treturn graphql.Null\n\t\t\t}\n\t\t{{- end }}\n\t\trctx := &graphql.ResolverContext{\n\t\t\tObject: {{$object.GQLType|quote}},\n\t\t\tArgs: {{if $field.Args }}args{{else}}nil{{end}},\n\t\t\tField: field,\n\t\t}\n\t\tctx = graphql.WithResolverContext(ctx, rctx)\n\t\tresTmp := ec.FieldMiddleware(ctx, {{if $object.Root}}nil{{else}}obj{{end}}, func(ctx context.Context) (interface{}, error) {\n\t\t\t{{- if $field.IsResolver }}\n\t\t\t\treturn ec.resolvers.{{ $field.ShortInvocation }}\n\t\t\t{{- else if $field.IsMethod }}\n\t\t\t\t{{- if $field.NoErr }}\n\t\t\t\t\treturn {{$field.GoReceiverName}}.{{$field.GoFieldName}}({{ $field.CallArgs }}), nil\n\t\t\t\t{{- else }}\n\t\t\t\t\treturn {{$field.GoReceiverName}}.{{$field.GoFieldName}}({{ $field.CallArgs }})\n\t\t\t\t{{- end }}\n\t\t\t{{- else if $field.IsVariable }}\n\t\t\t\treturn {{$field.GoReceiverName}}.{{$field.GoFieldName}}, nil\n\t\t\t{{- end }}\n\t\t})\n\t\tif resTmp == nil {\n\t\t\t{{- if $field.ASTType.NonNull }}\n\t\t\t\tif !ec.HasError(rctx) {\n\t\t\t\t\tec.Errorf(ctx, \"must not be null\")\n\t\t\t\t}\n\t\t\t{{- end }}\n\t\t\treturn graphql.Null\n\t\t}\n\t\tres := resTmp.({{$field.Signature}})\n\t\trctx.Result = res\n\t\t{{ $field.WriteJson }}\n\t}\n{{ end }}\n", + "generated.gotpl": "// Code generated by github.com/99designs/gqlgen, DO NOT EDIT.\n\npackage {{ .PackageName }}\n\nimport (\n{{- range $import := .Imports }}\n\t{{- $import.Write }}\n{{ end }}\n)\n\n// NewExecutableSchema creates an ExecutableSchema from the ResolverRoot interface.\nfunc NewExecutableSchema(cfg Config) graphql.ExecutableSchema {\n\treturn &executableSchema{\n\t\tresolvers: cfg.Resolvers,\n\t\tdirectives: cfg.Directives,\n\t\tcomplexity: cfg.Complexity,\n\t}\n}\n\ntype Config struct {\n\tResolvers ResolverRoot\n\tDirectives DirectiveRoot\n\tComplexity ComplexityRoot\n}\n\ntype ResolverRoot interface {\n{{- range $object := .Objects -}}\n\t{{ if $object.HasResolvers -}}\n\t\t{{$object.GQLType}}() {{$object.GQLType}}Resolver\n\t{{ end }}\n{{- end }}\n}\n\ntype DirectiveRoot struct {\n{{ range $directive := .Directives }}\n\t{{ $directive.Declaration }}\n{{ end }}\n}\n\ntype ComplexityRoot struct {\n{{ range $object := .Objects }}\n\t{{ if not $object.IsReserved -}}\n\t\t{{ $object.GQLType|toCamel }} struct {\n\t\t{{ range $field := $object.Fields -}}\n\t\t\t{{ if not $field.IsReserved -}}\n\t\t\t\t{{ $field.GQLName|toCamel }} {{ $field.ComplexitySignature }}\n\t\t\t{{ end }}\n\t\t{{- end }}\n\t\t}\n\t{{- end }}\n{{ end }}\n}\n\n{{ range $object := .Objects -}}\n\t{{ if $object.HasResolvers }}\n\t\ttype {{$object.GQLType}}Resolver interface {\n\t\t{{ range $field := $object.Fields -}}\n\t\t\t{{ $field.ShortResolverDeclaration }}\n\t\t{{ end }}\n\t\t}\n\t{{- end }}\n{{- end }}\n\n{{ range $object := .Objects -}}\n\t{{ range $field := $object.Fields -}}\n\t\t{{ if $field.Args }}\n\t\t\tfunc {{ $field.ArgsFunc }}(rawArgs map[string]interface{}) (map[string]interface{}, error) {\n\t\t\t{{ template \"args.gotpl\" $field.Args }}\n\t\t\t}\n\t\t{{ end }}\n\t{{ end }}\n{{- end }}\n\n{{ range $directive := .Directives }}\n\t{{ if $directive.Args }}\n\t\tfunc {{ $directive.ArgsFunc }}(rawArgs map[string]interface{}) (map[string]interface{}, error) {\n\t\t{{ template \"args.gotpl\" $directive.Args }}\n\t\t}\n\t{{ end }}\n{{ end }}\n\ntype executableSchema struct {\n\tresolvers ResolverRoot\n\tdirectives DirectiveRoot\n\tcomplexity ComplexityRoot\n}\n\nfunc (e *executableSchema) Schema() *ast.Schema {\n\treturn parsedSchema\n}\n\nfunc (e *executableSchema) Complexity(typeName, field string, childComplexity int, rawArgs map[string]interface{}) (int, bool) {\n\tswitch typeName + \".\" + field {\n\t{{ range $object := .Objects }}\n\t\t{{ if not $object.IsReserved }}\n\t\t\t{{ range $field := $object.Fields }}\n\t\t\t\t{{ if not $field.IsReserved }}\n\t\t\t\t\tcase \"{{$object.GQLType}}.{{$field.GQLName}}\":\n\t\t\t\t\t\tif e.complexity.{{$object.GQLType|toCamel}}.{{$field.GQLName|toCamel}} == nil {\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t\t{{ if $field.Args }}\n\t\t\t\t\t\t\targs, err := {{ $field.ArgsFunc }}(rawArgs)\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\treturn 0, false\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t{{ end }}\n\t\t\t\t\t\treturn e.complexity.{{$object.GQLType|toCamel}}.{{$field.GQLName|toCamel}}(childComplexity{{if $field.Args}}, {{$field.ComplexityArgs}} {{end}}), true\n\t\t\t\t{{ end }}\n\t\t\t{{ end }}\n\t\t{{ end }}\n\t{{ end }}\n\t}\n\treturn 0, false\n}\n\nfunc (e *executableSchema) Query(ctx context.Context, op *ast.OperationDefinition) *graphql.Response {\n\t{{- if .QueryRoot }}\n\t\tec := executionContext{graphql.GetRequestContext(ctx), e}\n\n\t\tbuf := ec.RequestMiddleware(ctx, func(ctx context.Context) []byte {\n\t\t\tdata := ec._{{.QueryRoot.GQLType}}(ctx, op.SelectionSet)\n\t\t\tvar buf bytes.Buffer\n\t\t\tdata.MarshalGQL(&buf)\n\t\t\treturn buf.Bytes()\n\t\t})\n\n\t\treturn &graphql.Response{\n\t\t\tData: buf,\n\t\t\tErrors: ec.Errors,\n\t\t}\n\t{{- else }}\n\t\treturn graphql.ErrorResponse(ctx, \"queries are not supported\")\n\t{{- end }}\n}\n\nfunc (e *executableSchema) Mutation(ctx context.Context, op *ast.OperationDefinition) *graphql.Response {\n\t{{- if .MutationRoot }}\n\t\tec := executionContext{graphql.GetRequestContext(ctx), e}\n\n\t\tbuf := ec.RequestMiddleware(ctx, func(ctx context.Context) []byte {\n\t\t\tdata := ec._{{.MutationRoot.GQLType}}(ctx, op.SelectionSet)\n\t\t\tvar buf bytes.Buffer\n\t\t\tdata.MarshalGQL(&buf)\n\t\t\treturn buf.Bytes()\n\t\t})\n\n\t\treturn &graphql.Response{\n\t\t\tData: buf,\n\t\t\tErrors: ec.Errors,\n\t\t}\n\t{{- else }}\n\t\treturn graphql.ErrorResponse(ctx, \"mutations are not supported\")\n\t{{- end }}\n}\n\nfunc (e *executableSchema) Subscription(ctx context.Context, op *ast.OperationDefinition) func() *graphql.Response {\n\t{{- if .SubscriptionRoot }}\n\t\tec := executionContext{graphql.GetRequestContext(ctx), e}\n\n\t\tnext := ec._{{.SubscriptionRoot.GQLType}}(ctx, op.SelectionSet)\n\t\tif ec.Errors != nil {\n\t\t\treturn graphql.OneShot(&graphql.Response{Data: []byte(\"null\"), Errors: ec.Errors})\n\t\t}\n\n\t\tvar buf bytes.Buffer\n\t\treturn func() *graphql.Response {\n\t\t\tbuf := ec.RequestMiddleware(ctx, func(ctx context.Context) []byte {\n\t\t\t\tbuf.Reset()\n\t\t\t\tdata := next()\n\n\t\t\t\tif data == nil {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\tdata.MarshalGQL(&buf)\n\t\t\t\treturn buf.Bytes()\n\t\t\t})\n\n\t\t\tif buf == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\treturn &graphql.Response{\n\t\t\t\tData: buf,\n\t\t\t\tErrors: ec.Errors,\n\t\t\t}\n\t\t}\n\t{{- else }}\n\t\treturn graphql.OneShot(graphql.ErrorResponse(ctx, \"subscriptions are not supported\"))\n\t{{- end }}\n}\n\ntype executionContext struct {\n\t*graphql.RequestContext\n\t*executableSchema\n}\n\n{{- range $object := .Objects }}\n\t{{ template \"object.gotpl\" $object }}\n\n\t{{- range $field := $object.Fields }}\n\t\t{{ template \"field.gotpl\" $field }}\n\t{{ end }}\n{{- end}}\n\n{{- range $interface := .Interfaces }}\n\t{{ template \"interface.gotpl\" $interface }}\n{{- end }}\n\n{{- range $input := .Inputs }}\n\t{{ template \"input.gotpl\" $input }}\n{{- end }}\n\nfunc (ec *executionContext) FieldMiddleware(ctx context.Context, obj interface{}, next graphql.Resolver) (ret interface{}) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = nil\n\t\t}\n\t}()\n\t{{- if .Directives }}\n\trctx := graphql.GetResolverContext(ctx)\n\tfor _, d := range rctx.Field.Definition.Directives {\n\t\tswitch d.Name {\n\t\t{{- range $directive := .Directives }}\n\t\tcase \"{{$directive.Name}}\":\n\t\t\tif ec.directives.{{$directive.Name|ucFirst}} != nil {\n\t\t\t\t{{- if $directive.Args }}\n\t\t\t\t\trawArgs := d.ArgumentMap(ec.Variables)\n\t\t\t\t\targs, err := {{ $directive.ArgsFunc }}(rawArgs)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tec.Error(ctx, err)\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t}\n\t\t\t\t{{- end }}\n\t\t\t\tn := next\n\t\t\t\tnext = func(ctx context.Context) (interface{}, error) {\n\t\t\t\t\treturn ec.directives.{{$directive.Name|ucFirst}}({{$directive.CallArgs}})\n\t\t\t\t}\n\t\t\t}\n\t\t{{- end }}\n\t\t}\n\t}\n\t{{- end }}\n\tres, err := ec.ResolverMiddleware(ctx, next)\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn nil\n\t}\n\treturn res\n}\n\nfunc (ec *executionContext) introspectSchema() *introspection.Schema {\n\treturn introspection.WrapSchema(parsedSchema)\n}\n\nfunc (ec *executionContext) introspectType(name string) *introspection.Type {\n\treturn introspection.WrapTypeFromDef(parsedSchema, parsedSchema.Types[name])\n}\n\nvar parsedSchema = gqlparser.MustLoadSchema(\n\t&ast.Source{Name: {{.SchemaFilename|quote}}, Input: {{.SchemaRaw|rawQuote}}},\n)\n", + "input.gotpl": "\t{{- if .IsMarshaled }}\n\tfunc Unmarshal{{ .GQLType }}(v interface{}) ({{.FullName}}, error) {\n\t\tvar it {{.FullName}}\n\t\tvar asMap = v.(map[string]interface{})\n\t\t{{ range $field := .Fields}}\n\t\t\t{{- if $field.Default}}\n\t\t\t\tif _, present := asMap[{{$field.GQLName|quote}}] ; !present {\n\t\t\t\t\tasMap[{{$field.GQLName|quote}}] = {{ $field.Default | dump }}\n\t\t\t\t}\n\t\t\t{{- end}}\n\t\t{{- end }}\n\n\t\tfor k, v := range asMap {\n\t\t\tswitch k {\n\t\t\t{{- range $field := .Fields }}\n\t\t\tcase {{$field.GQLName|quote}}:\n\t\t\t\tvar err error\n\t\t\t\t{{ $field.Unmarshal (print \"it.\" $field.GoFieldName) \"v\" }}\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn it, err\n\t\t\t\t}\n\t\t\t{{- end }}\n\t\t\t}\n\t\t}\n\n\t\treturn it, nil\n\t}\n\t{{- end }}\n", + "interface.gotpl": "{{- $interface := . }}\n\nfunc (ec *executionContext) _{{$interface.GQLType}}(ctx context.Context, sel ast.SelectionSet, obj *{{$interface.FullName}}) graphql.Marshaler {\n\tswitch obj := (*obj).(type) {\n\tcase nil:\n\t\treturn graphql.Null\n\t{{- range $implementor := $interface.Implementors }}\n\t\t{{- if $implementor.ValueReceiver }}\n\t\t\tcase {{$implementor.FullName}}:\n\t\t\t\treturn ec._{{$implementor.GQLType}}(ctx, sel, &obj)\n\t\t{{- end}}\n\t\tcase *{{$implementor.FullName}}:\n\t\t\treturn ec._{{$implementor.GQLType}}(ctx, sel, obj)\n\t{{- end }}\n\tdefault:\n\t\tpanic(fmt.Errorf(\"unexpected type %T\", obj))\n\t}\n}\n", + "models.gotpl": "// Code generated by github.com/99designs/gqlgen, DO NOT EDIT.\n\npackage {{ .PackageName }}\n\nimport (\n{{- range $import := .Imports }}\n\t{{- $import.Write }}\n{{ end }}\n)\n\n{{ range $model := .Models }}\n\t{{with .Description}} {{.|prefixLines \"// \"}} {{end}}\n\t{{- if .IsInterface }}\n\t\ttype {{.GoType}} interface {}\n\t{{- else }}\n\t\ttype {{.GoType}} struct {\n\t\t\t{{- range $field := .Fields }}\n\t\t\t\t{{- with .Description}}\n\t\t\t\t\t{{.|prefixLines \"// \"}}\n\t\t\t\t{{- end}}\n\t\t\t\t{{- if $field.GoFieldName }}\n\t\t\t\t\t{{ $field.GoFieldName }} {{$field.Signature}} `json:\"{{$field.GQLName}}\"`\n\t\t\t\t{{- else }}\n\t\t\t\t\t{{ $field.GoFKName }} {{$field.GoFKType}}\n\t\t\t\t{{- end }}\n\t\t\t{{- end }}\n\t\t}\n\t{{- end }}\n{{- end}}\n\n{{ range $enum := .Enums }}\n\t{{with .Description}}{{.|prefixLines \"// \"}} {{end}}\n\ttype {{.GoType}} string\n\tconst (\n\t{{- range $value := .Values}}\n\t\t{{- with .Description}}\n\t\t\t{{.|prefixLines \"// \"}}\n\t\t{{- end}}\n\t\t{{$enum.GoType}}{{ .Name|toCamel }} {{$enum.GoType}} = {{.Name|quote}}\n\t{{- end }}\n\t)\n\n\tfunc (e {{.GoType}}) IsValid() bool {\n\t\tswitch e {\n\t\tcase {{ range $index, $element := .Values}}{{if $index}},{{end}}{{ $enum.GoType }}{{ $element.Name|toCamel }}{{end}}:\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n\n\tfunc (e {{.GoType}}) String() string {\n\t\treturn string(e)\n\t}\n\n\tfunc (e *{{.GoType}}) UnmarshalGQL(v interface{}) error {\n\t\tstr, ok := v.(string)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"enums must be strings\")\n\t\t}\n\n\t\t*e = {{.GoType}}(str)\n\t\tif !e.IsValid() {\n\t\t\treturn fmt.Errorf(\"%s is not a valid {{.GQLType}}\", str)\n\t\t}\n\t\treturn nil\n\t}\n\n\tfunc (e {{.GoType}}) MarshalGQL(w io.Writer) {\n\t\tfmt.Fprint(w, strconv.Quote(e.String()))\n\t}\n\n{{- end }}\n", + "object.gotpl": "{{ $object := . }}\n\nvar {{ $object.GQLType|lcFirst}}Implementors = {{$object.Implementors}}\n\n// nolint: gocyclo, errcheck, gas, goconst\n{{- if .Stream }}\nfunc (ec *executionContext) _{{$object.GQLType}}(ctx context.Context, sel ast.SelectionSet) func() graphql.Marshaler {\n\tfields := graphql.CollectFields(ctx, sel, {{$object.GQLType|lcFirst}}Implementors)\n\tctx = graphql.WithResolverContext(ctx, &graphql.ResolverContext{\n\t\tObject: {{$object.GQLType|quote}},\n\t})\n\tif len(fields) != 1 {\n\t\tec.Errorf(ctx, \"must subscribe to exactly one stream\")\n\t\treturn nil\n\t}\n\n\tswitch fields[0].Name {\n\t{{- range $field := $object.Fields }}\n\tcase \"{{$field.GQLName}}\":\n\t\treturn ec._{{$object.GQLType}}_{{$field.GQLName}}(ctx, fields[0])\n\t{{- end }}\n\tdefault:\n\t\tpanic(\"unknown field \" + strconv.Quote(fields[0].Name))\n\t}\n}\n{{- else }}\nfunc (ec *executionContext) _{{$object.GQLType}}(ctx context.Context, sel ast.SelectionSet{{if not $object.Root}}, obj *{{$object.FullName}} {{end}}) graphql.Marshaler {\n\tfields := graphql.CollectFields(ctx, sel, {{$object.GQLType|lcFirst}}Implementors)\n\t{{if $object.Root}}\n\t\tctx = graphql.WithResolverContext(ctx, &graphql.ResolverContext{\n\t\t\tObject: {{$object.GQLType|quote}},\n\t\t})\n\t{{end}}\n\n\t{{if $object.IsConcurrent}} var wg sync.WaitGroup {{end}}\n\tout := graphql.NewOrderedMap(len(fields))\n\tinvalid := false\n\tfor i, field := range fields {\n\t\tout.Keys[i] = field.Alias\n\n\t\tswitch field.Name {\n\t\tcase \"__typename\":\n\t\t\tout.Values[i] = graphql.MarshalString({{$object.GQLType|quote}})\n\t\t{{- range $field := $object.Fields }}\n\t\tcase \"{{$field.GQLName}}\":\n\t\t\t{{- if $field.IsConcurrent }}\n\t\t\t\twg.Add(1)\n\t\t\t\tgo func(i int, field graphql.CollectedField) {\n\t\t\t{{- end }}\n\t\t\t\tout.Values[i] = ec._{{$object.GQLType}}_{{$field.GQLName}}(ctx, field{{if not $object.Root}}, obj{{end}})\n\t\t\t\t{{- if $field.ASTType.NonNull }}\n\t\t\t\t\tif out.Values[i] == graphql.Null {\n\t\t\t\t\t\tinvalid = true\n\t\t\t\t\t}\n\t\t\t\t{{- end }}\n\t\t\t{{- if $field.IsConcurrent }}\n\t\t\t\t\twg.Done()\n\t\t\t\t}(i, field)\n\t\t\t{{- end }}\n\t\t{{- end }}\n\t\tdefault:\n\t\t\tpanic(\"unknown field \" + strconv.Quote(field.Name))\n\t\t}\n\t}\n\t{{if $object.IsConcurrent}} wg.Wait() {{end}}\n\tif invalid { return graphql.Null }\n\treturn out\n}\n{{- end }}\n", + "resolver.gotpl": "//go:generate gorunpkg github.com/99designs/gqlgen\n\npackage {{ .PackageName }}\n\nimport (\n{{- range $import := .Imports }}\n\t{{- $import.Write }}\n{{ end }}\n)\n\ntype {{.ResolverType}} struct {}\n\n{{ range $object := .Objects -}}\n\t{{- if $object.HasResolvers -}}\n\t\tfunc (r *{{$.ResolverType}}) {{$object.GQLType}}() {{ $object.ResolverInterface.FullName }} {\n\t\t\treturn &{{lcFirst $object.GQLType}}Resolver{r}\n\t\t}\n\t{{ end -}}\n{{ end }}\n\n{{ range $object := .Objects -}}\n\t{{- if $object.HasResolvers -}}\n\t\ttype {{lcFirst $object.GQLType}}Resolver struct { *Resolver }\n\n\t\t{{ range $field := $object.Fields -}}\n\t\t\t{{- if $field.IsResolver -}}\n\t\t\tfunc (r *{{lcFirst $object.GQLType}}Resolver) {{ $field.ShortResolverDeclaration }} {\n\t\t\t\tpanic(\"not implemented\")\n\t\t\t}\n\t\t\t{{ end -}}\n\t\t{{ end -}}\n\t{{ end -}}\n{{ end }}\n", + "server.gotpl": "package main\n\nimport (\n{{- range $import := .Imports }}\n\t{{- $import.Write }}\n{{ end }}\n)\n\nconst defaultPort = \"8080\"\n\nfunc main() {\n\tport := os.Getenv(\"PORT\")\n\tif port == \"\" {\n\t\tport = defaultPort\n\t}\n\n\thttp.Handle(\"/\", handler.Playground(\"GraphQL playground\", \"/query\"))\n\thttp.Handle(\"/query\", handler.GraphQL({{.ExecPackageName}}.NewExecutableSchema({{.ExecPackageName}}.Config{Resolvers: &{{.ResolverPackageName}}.Resolver{}})))\n\n\tlog.Printf(\"connect to http://localhost:%s/ for GraphQL playground\", port)\n\tlog.Fatal(http.ListenAndServe(\":\" + port, nil))\n}\n", +} diff --git a/vendor/github.com/99designs/gqlgen/codegen/templates/field.gotpl b/vendor/github.com/99designs/gqlgen/codegen/templates/field.gotpl new file mode 100644 index 00000000..b33f2123 --- /dev/null +++ b/vendor/github.com/99designs/gqlgen/codegen/templates/field.gotpl @@ -0,0 +1,74 @@ +{{ $field := . }} +{{ $object := $field.Object }} + +{{- if $object.Stream }} + func (ec *executionContext) _{{$object.GQLType}}_{{$field.GQLName}}(ctx context.Context, field graphql.CollectedField) func() graphql.Marshaler { + {{- if $field.Args }} + rawArgs := field.ArgumentMap(ec.Variables) + args, err := {{ $field.ArgsFunc }}(rawArgs) + if err != nil { + ec.Error(ctx, err) + return nil + } + {{- end }} + ctx = graphql.WithResolverContext(ctx, &graphql.ResolverContext{ + Field: field, + }) + results, err := ec.resolvers.{{ $field.ShortInvocation }} + if err != nil { + ec.Error(ctx, err) + return nil + } + return func() graphql.Marshaler { + res, ok := <-results + if !ok { + return nil + } + var out graphql.OrderedMap + out.Add(field.Alias, func() graphql.Marshaler { {{ $field.WriteJson }} }()) + return &out + } + } +{{ else }} + // nolint: vetshadow + func (ec *executionContext) _{{$object.GQLType}}_{{$field.GQLName}}(ctx context.Context, field graphql.CollectedField, {{if not $object.Root}}obj *{{$object.FullName}}{{end}}) graphql.Marshaler { + {{- if $field.Args }} + rawArgs := field.ArgumentMap(ec.Variables) + args, err := {{ $field.ArgsFunc }}(rawArgs) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + {{- end }} + rctx := &graphql.ResolverContext{ + Object: {{$object.GQLType|quote}}, + Args: {{if $field.Args }}args{{else}}nil{{end}}, + Field: field, + } + ctx = graphql.WithResolverContext(ctx, rctx) + resTmp := ec.FieldMiddleware(ctx, {{if $object.Root}}nil{{else}}obj{{end}}, func(ctx context.Context) (interface{}, error) { + {{- if $field.IsResolver }} + return ec.resolvers.{{ $field.ShortInvocation }} + {{- else if $field.IsMethod }} + {{- if $field.NoErr }} + return {{$field.GoReceiverName}}.{{$field.GoFieldName}}({{ $field.CallArgs }}), nil + {{- else }} + return {{$field.GoReceiverName}}.{{$field.GoFieldName}}({{ $field.CallArgs }}) + {{- end }} + {{- else if $field.IsVariable }} + return {{$field.GoReceiverName}}.{{$field.GoFieldName}}, nil + {{- end }} + }) + if resTmp == nil { + {{- if $field.ASTType.NonNull }} + if !ec.HasError(rctx) { + ec.Errorf(ctx, "must not be null") + } + {{- end }} + return graphql.Null + } + res := resTmp.({{$field.Signature}}) + rctx.Result = res + {{ $field.WriteJson }} + } +{{ end }} diff --git a/vendor/github.com/99designs/gqlgen/codegen/templates/generated.gotpl b/vendor/github.com/99designs/gqlgen/codegen/templates/generated.gotpl new file mode 100644 index 00000000..8250bc7a --- /dev/null +++ b/vendor/github.com/99designs/gqlgen/codegen/templates/generated.gotpl @@ -0,0 +1,263 @@ +// Code generated by github.com/99designs/gqlgen, DO NOT EDIT. + +package {{ .PackageName }} + +import ( +{{- range $import := .Imports }} + {{- $import.Write }} +{{ end }} +) + +// NewExecutableSchema creates an ExecutableSchema from the ResolverRoot interface. +func NewExecutableSchema(cfg Config) graphql.ExecutableSchema { + return &executableSchema{ + resolvers: cfg.Resolvers, + directives: cfg.Directives, + complexity: cfg.Complexity, + } +} + +type Config struct { + Resolvers ResolverRoot + Directives DirectiveRoot + Complexity ComplexityRoot +} + +type ResolverRoot interface { +{{- range $object := .Objects -}} + {{ if $object.HasResolvers -}} + {{$object.GQLType}}() {{$object.GQLType}}Resolver + {{ end }} +{{- end }} +} + +type DirectiveRoot struct { +{{ range $directive := .Directives }} + {{ $directive.Declaration }} +{{ end }} +} + +type ComplexityRoot struct { +{{ range $object := .Objects }} + {{ if not $object.IsReserved -}} + {{ $object.GQLType|toCamel }} struct { + {{ range $field := $object.Fields -}} + {{ if not $field.IsReserved -}} + {{ $field.GQLName|toCamel }} {{ $field.ComplexitySignature }} + {{ end }} + {{- end }} + } + {{- end }} +{{ end }} +} + +{{ range $object := .Objects -}} + {{ if $object.HasResolvers }} + type {{$object.GQLType}}Resolver interface { + {{ range $field := $object.Fields -}} + {{ $field.ShortResolverDeclaration }} + {{ end }} + } + {{- end }} +{{- end }} + +{{ range $object := .Objects -}} + {{ range $field := $object.Fields -}} + {{ if $field.Args }} + func {{ $field.ArgsFunc }}(rawArgs map[string]interface{}) (map[string]interface{}, error) { + {{ template "args.gotpl" $field.Args }} + } + {{ end }} + {{ end }} +{{- end }} + +{{ range $directive := .Directives }} + {{ if $directive.Args }} + func {{ $directive.ArgsFunc }}(rawArgs map[string]interface{}) (map[string]interface{}, error) { + {{ template "args.gotpl" $directive.Args }} + } + {{ end }} +{{ end }} + +type executableSchema struct { + resolvers ResolverRoot + directives DirectiveRoot + complexity ComplexityRoot +} + +func (e *executableSchema) Schema() *ast.Schema { + return parsedSchema +} + +func (e *executableSchema) Complexity(typeName, field string, childComplexity int, rawArgs map[string]interface{}) (int, bool) { + switch typeName + "." + field { + {{ range $object := .Objects }} + {{ if not $object.IsReserved }} + {{ range $field := $object.Fields }} + {{ if not $field.IsReserved }} + case "{{$object.GQLType}}.{{$field.GQLName}}": + if e.complexity.{{$object.GQLType|toCamel}}.{{$field.GQLName|toCamel}} == nil { + break + } + {{ if $field.Args }} + args, err := {{ $field.ArgsFunc }}(rawArgs) + if err != nil { + return 0, false + } + {{ end }} + return e.complexity.{{$object.GQLType|toCamel}}.{{$field.GQLName|toCamel}}(childComplexity{{if $field.Args}}, {{$field.ComplexityArgs}} {{end}}), true + {{ end }} + {{ end }} + {{ end }} + {{ end }} + } + return 0, false +} + +func (e *executableSchema) Query(ctx context.Context, op *ast.OperationDefinition) *graphql.Response { + {{- if .QueryRoot }} + ec := executionContext{graphql.GetRequestContext(ctx), e} + + buf := ec.RequestMiddleware(ctx, func(ctx context.Context) []byte { + data := ec._{{.QueryRoot.GQLType}}(ctx, op.SelectionSet) + var buf bytes.Buffer + data.MarshalGQL(&buf) + return buf.Bytes() + }) + + return &graphql.Response{ + Data: buf, + Errors: ec.Errors, + } + {{- else }} + return graphql.ErrorResponse(ctx, "queries are not supported") + {{- end }} +} + +func (e *executableSchema) Mutation(ctx context.Context, op *ast.OperationDefinition) *graphql.Response { + {{- if .MutationRoot }} + ec := executionContext{graphql.GetRequestContext(ctx), e} + + buf := ec.RequestMiddleware(ctx, func(ctx context.Context) []byte { + data := ec._{{.MutationRoot.GQLType}}(ctx, op.SelectionSet) + var buf bytes.Buffer + data.MarshalGQL(&buf) + return buf.Bytes() + }) + + return &graphql.Response{ + Data: buf, + Errors: ec.Errors, + } + {{- else }} + return graphql.ErrorResponse(ctx, "mutations are not supported") + {{- end }} +} + +func (e *executableSchema) Subscription(ctx context.Context, op *ast.OperationDefinition) func() *graphql.Response { + {{- if .SubscriptionRoot }} + ec := executionContext{graphql.GetRequestContext(ctx), e} + + next := ec._{{.SubscriptionRoot.GQLType}}(ctx, op.SelectionSet) + if ec.Errors != nil { + return graphql.OneShot(&graphql.Response{Data: []byte("null"), Errors: ec.Errors}) + } + + var buf bytes.Buffer + return func() *graphql.Response { + buf := ec.RequestMiddleware(ctx, func(ctx context.Context) []byte { + buf.Reset() + data := next() + + if data == nil { + return nil + } + data.MarshalGQL(&buf) + return buf.Bytes() + }) + + if buf == nil { + return nil + } + + return &graphql.Response{ + Data: buf, + Errors: ec.Errors, + } + } + {{- else }} + return graphql.OneShot(graphql.ErrorResponse(ctx, "subscriptions are not supported")) + {{- end }} +} + +type executionContext struct { + *graphql.RequestContext + *executableSchema +} + +{{- range $object := .Objects }} + {{ template "object.gotpl" $object }} + + {{- range $field := $object.Fields }} + {{ template "field.gotpl" $field }} + {{ end }} +{{- end}} + +{{- range $interface := .Interfaces }} + {{ template "interface.gotpl" $interface }} +{{- end }} + +{{- range $input := .Inputs }} + {{ template "input.gotpl" $input }} +{{- end }} + +func (ec *executionContext) FieldMiddleware(ctx context.Context, obj interface{}, next graphql.Resolver) (ret interface{}) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + {{- if .Directives }} + rctx := graphql.GetResolverContext(ctx) + for _, d := range rctx.Field.Definition.Directives { + switch d.Name { + {{- range $directive := .Directives }} + case "{{$directive.Name}}": + if ec.directives.{{$directive.Name|ucFirst}} != nil { + {{- if $directive.Args }} + rawArgs := d.ArgumentMap(ec.Variables) + args, err := {{ $directive.ArgsFunc }}(rawArgs) + if err != nil { + ec.Error(ctx, err) + return nil + } + {{- end }} + n := next + next = func(ctx context.Context) (interface{}, error) { + return ec.directives.{{$directive.Name|ucFirst}}({{$directive.CallArgs}}) + } + } + {{- end }} + } + } + {{- end }} + res, err := ec.ResolverMiddleware(ctx, next) + if err != nil { + ec.Error(ctx, err) + return nil + } + return res +} + +func (ec *executionContext) introspectSchema() *introspection.Schema { + return introspection.WrapSchema(parsedSchema) +} + +func (ec *executionContext) introspectType(name string) *introspection.Type { + return introspection.WrapTypeFromDef(parsedSchema, parsedSchema.Types[name]) +} + +var parsedSchema = gqlparser.MustLoadSchema( + &ast.Source{Name: {{.SchemaFilename|quote}}, Input: {{.SchemaRaw|rawQuote}}}, +) diff --git a/vendor/github.com/99designs/gqlgen/codegen/templates/input.gotpl b/vendor/github.com/99designs/gqlgen/codegen/templates/input.gotpl new file mode 100644 index 00000000..f543608d --- /dev/null +++ b/vendor/github.com/99designs/gqlgen/codegen/templates/input.gotpl @@ -0,0 +1,28 @@ + {{- if .IsMarshaled }} + func Unmarshal{{ .GQLType }}(v interface{}) ({{.FullName}}, error) { + var it {{.FullName}} + var asMap = v.(map[string]interface{}) + {{ range $field := .Fields}} + {{- if $field.Default}} + if _, present := asMap[{{$field.GQLName|quote}}] ; !present { + asMap[{{$field.GQLName|quote}}] = {{ $field.Default | dump }} + } + {{- end}} + {{- end }} + + for k, v := range asMap { + switch k { + {{- range $field := .Fields }} + case {{$field.GQLName|quote}}: + var err error + {{ $field.Unmarshal (print "it." $field.GoFieldName) "v" }} + if err != nil { + return it, err + } + {{- end }} + } + } + + return it, nil + } + {{- end }} diff --git a/vendor/github.com/99designs/gqlgen/codegen/templates/interface.gotpl b/vendor/github.com/99designs/gqlgen/codegen/templates/interface.gotpl new file mode 100644 index 00000000..84cbe500 --- /dev/null +++ b/vendor/github.com/99designs/gqlgen/codegen/templates/interface.gotpl @@ -0,0 +1,18 @@ +{{- $interface := . }} + +func (ec *executionContext) _{{$interface.GQLType}}(ctx context.Context, sel ast.SelectionSet, obj *{{$interface.FullName}}) graphql.Marshaler { + switch obj := (*obj).(type) { + case nil: + return graphql.Null + {{- range $implementor := $interface.Implementors }} + {{- if $implementor.ValueReceiver }} + case {{$implementor.FullName}}: + return ec._{{$implementor.GQLType}}(ctx, sel, &obj) + {{- end}} + case *{{$implementor.FullName}}: + return ec._{{$implementor.GQLType}}(ctx, sel, obj) + {{- end }} + default: + panic(fmt.Errorf("unexpected type %T", obj)) + } +} diff --git a/vendor/github.com/99designs/gqlgen/codegen/templates/models.gotpl b/vendor/github.com/99designs/gqlgen/codegen/templates/models.gotpl new file mode 100644 index 00000000..7427d71d --- /dev/null +++ b/vendor/github.com/99designs/gqlgen/codegen/templates/models.gotpl @@ -0,0 +1,72 @@ +// Code generated by github.com/99designs/gqlgen, DO NOT EDIT. + +package {{ .PackageName }} + +import ( +{{- range $import := .Imports }} + {{- $import.Write }} +{{ end }} +) + +{{ range $model := .Models }} + {{with .Description}} {{.|prefixLines "// "}} {{end}} + {{- if .IsInterface }} + type {{.GoType}} interface {} + {{- else }} + type {{.GoType}} struct { + {{- range $field := .Fields }} + {{- with .Description}} + {{.|prefixLines "// "}} + {{- end}} + {{- if $field.GoFieldName }} + {{ $field.GoFieldName }} {{$field.Signature}} `json:"{{$field.GQLName}}"` + {{- else }} + {{ $field.GoFKName }} {{$field.GoFKType}} + {{- end }} + {{- end }} + } + {{- end }} +{{- end}} + +{{ range $enum := .Enums }} + {{with .Description}}{{.|prefixLines "// "}} {{end}} + type {{.GoType}} string + const ( + {{- range $value := .Values}} + {{- with .Description}} + {{.|prefixLines "// "}} + {{- end}} + {{$enum.GoType}}{{ .Name|toCamel }} {{$enum.GoType}} = {{.Name|quote}} + {{- end }} + ) + + func (e {{.GoType}}) IsValid() bool { + switch e { + case {{ range $index, $element := .Values}}{{if $index}},{{end}}{{ $enum.GoType }}{{ $element.Name|toCamel }}{{end}}: + return true + } + return false + } + + func (e {{.GoType}}) String() string { + return string(e) + } + + func (e *{{.GoType}}) UnmarshalGQL(v interface{}) error { + str, ok := v.(string) + if !ok { + return fmt.Errorf("enums must be strings") + } + + *e = {{.GoType}}(str) + if !e.IsValid() { + return fmt.Errorf("%s is not a valid {{.GQLType}}", str) + } + return nil + } + + func (e {{.GoType}}) MarshalGQL(w io.Writer) { + fmt.Fprint(w, strconv.Quote(e.String())) + } + +{{- end }} diff --git a/vendor/github.com/99designs/gqlgen/codegen/templates/object.gotpl b/vendor/github.com/99designs/gqlgen/codegen/templates/object.gotpl new file mode 100644 index 00000000..e98cbe1e --- /dev/null +++ b/vendor/github.com/99designs/gqlgen/codegen/templates/object.gotpl @@ -0,0 +1,69 @@ +{{ $object := . }} + +var {{ $object.GQLType|lcFirst}}Implementors = {{$object.Implementors}} + +// nolint: gocyclo, errcheck, gas, goconst +{{- if .Stream }} +func (ec *executionContext) _{{$object.GQLType}}(ctx context.Context, sel ast.SelectionSet) func() graphql.Marshaler { + fields := graphql.CollectFields(ctx, sel, {{$object.GQLType|lcFirst}}Implementors) + ctx = graphql.WithResolverContext(ctx, &graphql.ResolverContext{ + Object: {{$object.GQLType|quote}}, + }) + if len(fields) != 1 { + ec.Errorf(ctx, "must subscribe to exactly one stream") + return nil + } + + switch fields[0].Name { + {{- range $field := $object.Fields }} + case "{{$field.GQLName}}": + return ec._{{$object.GQLType}}_{{$field.GQLName}}(ctx, fields[0]) + {{- end }} + default: + panic("unknown field " + strconv.Quote(fields[0].Name)) + } +} +{{- else }} +func (ec *executionContext) _{{$object.GQLType}}(ctx context.Context, sel ast.SelectionSet{{if not $object.Root}}, obj *{{$object.FullName}} {{end}}) graphql.Marshaler { + fields := graphql.CollectFields(ctx, sel, {{$object.GQLType|lcFirst}}Implementors) + {{if $object.Root}} + ctx = graphql.WithResolverContext(ctx, &graphql.ResolverContext{ + Object: {{$object.GQLType|quote}}, + }) + {{end}} + + {{if $object.IsConcurrent}} var wg sync.WaitGroup {{end}} + out := graphql.NewOrderedMap(len(fields)) + invalid := false + for i, field := range fields { + out.Keys[i] = field.Alias + + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString({{$object.GQLType|quote}}) + {{- range $field := $object.Fields }} + case "{{$field.GQLName}}": + {{- if $field.IsConcurrent }} + wg.Add(1) + go func(i int, field graphql.CollectedField) { + {{- end }} + out.Values[i] = ec._{{$object.GQLType}}_{{$field.GQLName}}(ctx, field{{if not $object.Root}}, obj{{end}}) + {{- if $field.ASTType.NonNull }} + if out.Values[i] == graphql.Null { + invalid = true + } + {{- end }} + {{- if $field.IsConcurrent }} + wg.Done() + }(i, field) + {{- end }} + {{- end }} + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + {{if $object.IsConcurrent}} wg.Wait() {{end}} + if invalid { return graphql.Null } + return out +} +{{- end }} diff --git a/vendor/github.com/99designs/gqlgen/codegen/templates/resolver.gotpl b/vendor/github.com/99designs/gqlgen/codegen/templates/resolver.gotpl new file mode 100644 index 00000000..dd8acf24 --- /dev/null +++ b/vendor/github.com/99designs/gqlgen/codegen/templates/resolver.gotpl @@ -0,0 +1,33 @@ +//go:generate gorunpkg github.com/99designs/gqlgen + +package {{ .PackageName }} + +import ( +{{- range $import := .Imports }} + {{- $import.Write }} +{{ end }} +) + +type {{.ResolverType}} struct {} + +{{ range $object := .Objects -}} + {{- if $object.HasResolvers -}} + func (r *{{$.ResolverType}}) {{$object.GQLType}}() {{ $object.ResolverInterface.FullName }} { + return &{{lcFirst $object.GQLType}}Resolver{r} + } + {{ end -}} +{{ end }} + +{{ range $object := .Objects -}} + {{- if $object.HasResolvers -}} + type {{lcFirst $object.GQLType}}Resolver struct { *Resolver } + + {{ range $field := $object.Fields -}} + {{- if $field.IsResolver -}} + func (r *{{lcFirst $object.GQLType}}Resolver) {{ $field.ShortResolverDeclaration }} { + panic("not implemented") + } + {{ end -}} + {{ end -}} + {{ end -}} +{{ end }} diff --git a/vendor/github.com/99designs/gqlgen/codegen/templates/server.gotpl b/vendor/github.com/99designs/gqlgen/codegen/templates/server.gotpl new file mode 100644 index 00000000..f23b30e1 --- /dev/null +++ b/vendor/github.com/99designs/gqlgen/codegen/templates/server.gotpl @@ -0,0 +1,22 @@ +package main + +import ( +{{- range $import := .Imports }} + {{- $import.Write }} +{{ end }} +) + +const defaultPort = "8080" + +func main() { + port := os.Getenv("PORT") + if port == "" { + port = defaultPort + } + + http.Handle("/", handler.Playground("GraphQL playground", "/query")) + http.Handle("/query", handler.GraphQL({{.ExecPackageName}}.NewExecutableSchema({{.ExecPackageName}}.Config{Resolvers: &{{.ResolverPackageName}}.Resolver{}}))) + + log.Printf("connect to http://localhost:%s/ for GraphQL playground", port) + log.Fatal(http.ListenAndServe(":" + port, nil)) +} diff --git a/vendor/github.com/99designs/gqlgen/codegen/templates/templates.go b/vendor/github.com/99designs/gqlgen/codegen/templates/templates.go new file mode 100644 index 00000000..df909cb5 --- /dev/null +++ b/vendor/github.com/99designs/gqlgen/codegen/templates/templates.go @@ -0,0 +1,193 @@ +//go:generate go run ./inliner/inliner.go + +package templates + +import ( + "bytes" + "fmt" + "io/ioutil" + "os" + "path/filepath" + "sort" + "strconv" + "strings" + "text/template" + "unicode" + + "log" + + "github.com/pkg/errors" + "golang.org/x/tools/imports" +) + +func Run(name string, tpldata interface{}) (*bytes.Buffer, error) { + t := template.New("").Funcs(template.FuncMap{ + "ucFirst": ucFirst, + "lcFirst": lcFirst, + "quote": strconv.Quote, + "rawQuote": rawQuote, + "toCamel": ToCamel, + "dump": dump, + "prefixLines": prefixLines, + }) + + for filename, data := range data { + _, err := t.New(filename).Parse(data) + if err != nil { + panic(err) + } + } + + buf := &bytes.Buffer{} + err := t.Lookup(name).Execute(buf, tpldata) + if err != nil { + return nil, err + } + + return buf, nil +} + +func ucFirst(s string) string { + if s == "" { + return "" + } + r := []rune(s) + r[0] = unicode.ToUpper(r[0]) + return string(r) +} + +func lcFirst(s string) string { + if s == "" { + return "" + } + + r := []rune(s) + r[0] = unicode.ToLower(r[0]) + return string(r) +} + +func isDelimiter(c rune) bool { + return c == '-' || c == '_' || unicode.IsSpace(c) +} + +func ToCamel(s string) string { + buffer := make([]rune, 0, len(s)) + upper := true + lastWasUpper := false + + for _, c := range s { + if isDelimiter(c) { + upper = true + continue + } + if !lastWasUpper && unicode.IsUpper(c) { + upper = true + } + + if upper { + buffer = append(buffer, unicode.ToUpper(c)) + } else { + buffer = append(buffer, unicode.ToLower(c)) + } + upper = false + lastWasUpper = unicode.IsUpper(c) + } + + return string(buffer) +} + +func rawQuote(s string) string { + return "`" + strings.Replace(s, "`", "`+\"`\"+`", -1) + "`" +} + +func dump(val interface{}) string { + switch val := val.(type) { + case int: + return strconv.Itoa(val) + case int64: + return fmt.Sprintf("%d", val) + case float64: + return fmt.Sprintf("%f", val) + case string: + return strconv.Quote(val) + case bool: + return strconv.FormatBool(val) + case nil: + return "nil" + case []interface{}: + var parts []string + for _, part := range val { + parts = append(parts, dump(part)) + } + return "[]interface{}{" + strings.Join(parts, ",") + "}" + case map[string]interface{}: + buf := bytes.Buffer{} + buf.WriteString("map[string]interface{}{") + var keys []string + for key := range val { + keys = append(keys, key) + } + sort.Strings(keys) + + for _, key := range keys { + data := val[key] + + buf.WriteString(strconv.Quote(key)) + buf.WriteString(":") + buf.WriteString(dump(data)) + buf.WriteString(",") + } + buf.WriteString("}") + return buf.String() + default: + panic(fmt.Errorf("unsupported type %T", val)) + } +} + +func prefixLines(prefix, s string) string { + return prefix + strings.Replace(s, "\n", "\n"+prefix, -1) +} + +func RenderToFile(tpl string, filename string, data interface{}) error { + var buf *bytes.Buffer + buf, err := Run(tpl, data) + if err != nil { + return errors.Wrap(err, filename+" generation failed") + } + + if err := write(filename, buf.Bytes()); err != nil { + return err + } + + log.Println(filename) + + return nil +} + +func gofmt(filename string, b []byte) ([]byte, error) { + out, err := imports.Process(filename, b, nil) + if err != nil { + return b, errors.Wrap(err, "unable to gofmt") + } + return out, nil +} + +func write(filename string, b []byte) error { + err := os.MkdirAll(filepath.Dir(filename), 0755) + if err != nil { + return errors.Wrap(err, "failed to create directory") + } + + formatted, err := gofmt(filename, b) + if err != nil { + fmt.Fprintf(os.Stderr, "gofmt failed: %s\n", err.Error()) + formatted = b + } + + err = ioutil.WriteFile(filename, formatted, 0644) + if err != nil { + return errors.Wrapf(err, "failed to write %s", filename) + } + + return nil +} |