-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathgen.go
2533 lines (2305 loc) · 72.9 KB
/
gen.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2011 Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"bytes"
"encoding/json"
"errors"
"flag"
"fmt"
"go/format"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
"unicode"
"google.golang.org/api/google-api-go-generator/internal/disco"
"google.golang.org/api/internal/version"
)
const (
googleDiscoveryURL = "https://www.googleapis.com/discovery/v1/apis"
generatorVersion = "2018018"
)
var (
apiToGenerate = flag.String("api", "*", "The API ID to generate, like 'tasks:v1'. A value of '*' means all.")
useCache = flag.Bool("cache", true, "Use cache of discovered Google API discovery documents.")
genDir = flag.String("gendir", defaultGenDir(), "Directory to use to write out generated Go files")
build = flag.Bool("build", false, "Compile generated packages.")
install = flag.Bool("install", false, "Install generated packages.")
apisURL = flag.String("discoveryurl", googleDiscoveryURL, "URL to root discovery document")
publicOnly = flag.Bool("publiconly", true, "Only build public, released APIs. Only applicable for Google employees.")
jsonFile = flag.String("api_json_file", "", "If non-empty, the path to a local file on disk containing the API to generate. Exclusive with setting --api.")
output = flag.String("output", "", "(optional) Path to source output file. If not specified, the API name and version are used to construct an output path (e.g. tasks/v1).")
apiPackageBase = flag.String("api_pkg_base", "google.golang.org/api", "Go package prefix to use for all generated APIs.")
baseURL = flag.String("base_url", "", "(optional) Override the default service API URL. If empty, the service's root URL will be used.")
headerPath = flag.String("header_path", "", "If non-empty, prepend the contents of this file to generated services.")
gensupportPkg = flag.String("gensupport_pkg", "google.golang.org/api/gensupport", "Go package path of the 'api/gensupport' support package.")
googleapiPkg = flag.String("googleapi_pkg", "google.golang.org/api/googleapi", "Go package path of the 'api/googleapi' support package.")
optionPkg = flag.String("option_pkg", "google.golang.org/api/option", "Go package path of the 'api/option' support package.")
htransportPkg = flag.String("htransport_pkg", "google.golang.org/api/transport/http", "Go package path of the 'api/transport/http' support package.")
copyrightYear = flag.String("copyright_year", fmt.Sprintf("%d", time.Now().Year()), "Year for copyright.")
serviceTypes = []string{"Service", "APIService"}
)
// API represents an API to generate, as well as its state while it's
// generating.
type API struct {
// Fields needed before generating code, to select and find the APIs
// to generate.
// These fields usually come from the "directory item" JSON objects
// that are provided by the googleDiscoveryURL. We unmarshal a directory
// item directly into this struct.
ID string `json:"id"`
Name string `json:"name"`
Version string `json:"version"`
DiscoveryLink string `json:"discoveryRestUrl"` // absolute
doc *disco.Document
// TODO(jba): remove m when we've fully converted to using disco.
m map[string]interface{}
forceJSON []byte // if non-nil, the JSON schema file. else fetched.
usedNames namePool
schemas map[string]*Schema // apiName -> schema
responseTypes map[string]bool
p func(format string, args ...interface{}) // print raw
pn func(format string, args ...interface{}) // print with newline
}
func (a *API) sortedSchemaNames() (names []string) {
for name := range a.schemas {
names = append(names, name)
}
sort.Strings(names)
return
}
func (a *API) Schema(name string) *Schema {
return a.schemas[name]
}
type generateError struct {
api *API
error error
}
func (e *generateError) Error() string {
return fmt.Sprintf("API %s failed to generate code: %v", e.api.ID, e.error)
}
type compileError struct {
api *API
output string
}
func (e *compileError) Error() string {
return fmt.Sprintf("API %s failed to compile:\n%v", e.api.ID, e.output)
}
func main() {
flag.Parse()
if *install {
*build = true
}
var (
apiIds = []string{}
matches = []*API{}
errors = []error{}
)
for _, api := range getAPIs() {
apiIds = append(apiIds, api.ID)
if !api.want() {
continue
}
matches = append(matches, api)
log.Printf("Generating API %s", api.ID)
err := api.WriteGeneratedCode()
if err != nil && err != errNoDoc {
errors = append(errors, &generateError{api, err})
continue
}
if *build && err == nil {
var args []string
if *install {
args = append(args, "install")
} else {
args = append(args, "build")
}
args = append(args, api.Target())
out, err := exec.Command("go", args...).CombinedOutput()
if err != nil {
errors = append(errors, &compileError{api, string(out)})
}
}
}
if len(matches) == 0 {
log.Fatalf("No APIs matched %q; options are %v", *apiToGenerate, apiIds)
}
if len(errors) > 0 {
log.Printf("%d API(s) failed to generate or compile:", len(errors))
for _, ce := range errors {
log.Println(ce.Error())
}
os.Exit(1)
}
}
func (a *API) want() bool {
if *jsonFile != "" {
// Return true early, before calling a.JSONFile()
// which will require a GOPATH be set. This is for
// integration with Google's build system genrules
// where there is no GOPATH.
return true
}
// Skip this API if we're in cached mode and the files don't exist on disk.
if *useCache {
if _, err := os.Stat(a.JSONFile()); os.IsNotExist(err) {
return false
}
}
return *apiToGenerate == "*" || *apiToGenerate == a.ID
}
func getAPIs() []*API {
if *jsonFile != "" {
return getAPIsFromFile()
}
var bytes []byte
var source string
apiListFile := filepath.Join(genDirRoot(), "api-list.json")
if *useCache {
if !*publicOnly {
log.Fatalf("-cache=true not compatible with -publiconly=false")
}
var err error
bytes, err = ioutil.ReadFile(apiListFile)
if err != nil {
log.Fatal(err)
}
source = apiListFile
} else {
bytes = slurpURL(*apisURL)
if *publicOnly {
if err := writeFile(apiListFile, bytes); err != nil {
log.Fatal(err)
}
}
source = *apisURL
}
apis, err := unmarshalAPIs(bytes)
if err != nil {
log.Fatalf("error decoding JSON in %s: %v", source, err)
}
if !*publicOnly && *apiToGenerate != "*" {
apis = append(apis, apiFromID(*apiToGenerate))
}
return apis
}
func unmarshalAPIs(bytes []byte) ([]*API, error) {
var itemObj struct{ Items []*API }
if err := json.Unmarshal(bytes, &itemObj); err != nil {
return nil, err
}
return itemObj.Items, nil
}
func apiFromID(apiID string) *API {
parts := strings.Split(apiID, ":")
if len(parts) != 2 {
log.Fatalf("malformed API name: %q", apiID)
}
return &API{
ID: apiID,
Name: parts[0],
Version: parts[1],
}
}
// getAPIsFromFile handles the case of generating exactly one API
// from the flag given in --api_json_file
func getAPIsFromFile() []*API {
if *apiToGenerate != "*" {
log.Fatalf("Can't set --api with --api_json_file.")
}
if !*publicOnly {
log.Fatalf("Can't set --publiconly with --api_json_file.")
}
a, err := apiFromFile(*jsonFile)
if err != nil {
log.Fatal(err)
}
return []*API{a}
}
func apiFromFile(file string) (*API, error) {
jsonBytes, err := ioutil.ReadFile(file)
if err != nil {
return nil, fmt.Errorf("Error reading %s: %v", file, err)
}
doc, err := disco.NewDocument(jsonBytes)
if err != nil {
return nil, fmt.Errorf("reading document from %q: %v", file, err)
}
a := &API{
ID: doc.ID,
Name: doc.Name,
Version: doc.Version,
forceJSON: jsonBytes,
doc: doc,
}
return a, nil
}
func writeFile(file string, contents []byte) error {
// Don't write it if the contents are identical.
existing, err := ioutil.ReadFile(file)
if err == nil && (bytes.Equal(existing, contents) || basicallyEqual(existing, contents)) {
return nil
}
outdir := filepath.Dir(file)
if err = os.MkdirAll(outdir, 0755); err != nil {
return fmt.Errorf("failed to Mkdir %s: %v", outdir, err)
}
return ioutil.WriteFile(file, contents, 0644)
}
var ignoreLines = regexp.MustCompile(`(?m)^\s+"(?:etag|revision)": ".+\n`)
// basicallyEqual reports whether a and b are equal except for boring
// differences like ETag updates.
func basicallyEqual(a, b []byte) bool {
return ignoreLines.Match(a) && ignoreLines.Match(b) &&
bytes.Equal(ignoreLines.ReplaceAll(a, nil), ignoreLines.ReplaceAll(b, nil))
}
func slurpURL(urlStr string) []byte {
if *useCache {
log.Fatalf("Invalid use of slurpURL in cached mode for URL %s", urlStr)
}
req, err := http.NewRequest("GET", urlStr, nil)
if err != nil {
log.Fatal(err)
}
if *publicOnly {
req.Header.Add("X-User-IP", "0.0.0.0") // hack
}
res, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatalf("Error fetching URL %s: %v", urlStr, err)
}
if res.StatusCode >= 300 {
log.Printf("WARNING: URL %s served status code %d", urlStr, res.StatusCode)
return nil
}
bs, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Fatalf("Error reading body of URL %s: %v", urlStr, err)
}
return bs
}
func panicf(format string, args ...interface{}) {
panic(fmt.Sprintf(format, args...))
}
// namePool keeps track of used names and assigns free ones based on a
// preferred name
type namePool struct {
m map[string]bool // lazily initialized
}
// oddVersionRE matches unusual API names like directory_v1.
var oddVersionRE = regexp.MustCompile(`^(.+)_(v[\d\.]+)$`)
// renameVersion conditionally rewrites the provided version such
// that the final path component of the import path doesn't look
// like a Go identifier. This keeps the consistency that import paths
// for the generated Go packages look like:
// google.golang.org/api/NAME/v<version>
// and have package NAME.
// See https://github.com/google/google-api-go-client/issues/78
func renameVersion(version string) string {
if version == "alpha" || version == "beta" {
return "v0." + version
}
if m := oddVersionRE.FindStringSubmatch(version); m != nil {
return m[1] + "/" + m[2]
}
return version
}
func (p *namePool) Get(preferred string) string {
if p.m == nil {
p.m = make(map[string]bool)
}
name := preferred
tries := 0
for p.m[name] {
tries++
name = fmt.Sprintf("%s%d", preferred, tries)
}
p.m[name] = true
return name
}
func genDirRoot() string {
if *genDir == "" {
log.Fatalf("-gendir option must be set.")
}
return *genDir
}
func defaultGenDir() string {
// TODO(cbro): consider using $CWD
paths := filepath.SplitList(os.Getenv("GOPATH"))
if len(paths) == 0 {
return ""
}
return filepath.Join(paths[0], "src", "google.golang.org", "api")
}
func (a *API) SourceDir() string {
return filepath.Join(genDirRoot(), a.Package(), renameVersion(a.Version))
}
func (a *API) DiscoveryURL() string {
if a.DiscoveryLink == "" {
log.Fatalf("API %s has no DiscoveryLink", a.ID)
}
return a.DiscoveryLink
}
func (a *API) Package() string {
return strings.ToLower(a.Name)
}
func (a *API) Target() string {
return fmt.Sprintf("%s/%s/%s", *apiPackageBase, a.Package(), renameVersion(a.Version))
}
// ServiceType returns the name of the type to use for the root API struct
// (typically "Service").
func (a *API) ServiceType() string {
switch a.Name {
case "appengine", "content": // retained for historical compatibility.
return "APIService"
default:
for _, t := range serviceTypes {
if _, ok := a.schemas[t]; !ok {
return t
}
}
panic("all service types are used, please consider introducing a new type to serviceTypes.")
}
}
// GetName returns a free top-level function/type identifier in the package.
// It tries to return your preferred match if it's free.
func (a *API) GetName(preferred string) string {
return a.usedNames.Get(preferred)
}
func (a *API) apiBaseURL() string {
var base, rel string
switch {
case *baseURL != "":
base, rel = *baseURL, a.doc.BasePath
case a.doc.RootURL != "":
base, rel = a.doc.RootURL, a.doc.ServicePath
default:
base, rel = *apisURL, a.doc.BasePath
}
return resolveRelative(base, rel)
}
func (a *API) needsDataWrapper() bool {
for _, feature := range a.doc.Features {
if feature == "dataWrapper" {
return true
}
}
return false
}
func (a *API) jsonBytes() []byte {
if a.forceJSON == nil {
var slurp []byte
var err error
if *useCache {
slurp, err = ioutil.ReadFile(a.JSONFile())
if err != nil {
log.Fatal(err)
}
} else {
slurp = slurpURL(a.DiscoveryURL())
if slurp != nil {
// Make sure that keys are sorted by re-marshalling.
d := make(map[string]interface{})
json.Unmarshal(slurp, &d)
if err != nil {
log.Fatal(err)
}
var err error
slurp, err = json.MarshalIndent(d, "", " ")
if err != nil {
log.Fatal(err)
}
}
}
a.forceJSON = slurp
}
return a.forceJSON
}
func (a *API) JSONFile() string {
return filepath.Join(a.SourceDir(), a.Package()+"-api.json")
}
var errNoDoc = errors.New("could not read discovery doc")
// WriteGeneratedCode generates code for a.
// It returns errNoDoc if we couldn't read the discovery doc.
func (a *API) WriteGeneratedCode() error {
genfilename := *output
jsonBytes := a.jsonBytes()
// Skip generation if we don't have the discovery doc.
if jsonBytes == nil {
// No message here, because slurpURL printed one.
return errNoDoc
}
if genfilename == "" {
if err := writeFile(a.JSONFile(), jsonBytes); err != nil {
return err
}
outdir := a.SourceDir()
err := os.MkdirAll(outdir, 0755)
if err != nil {
return fmt.Errorf("failed to Mkdir %s: %v", outdir, err)
}
pkg := a.Package()
genfilename = filepath.Join(outdir, pkg+"-gen.go")
}
code, err := a.GenerateCode()
errw := writeFile(genfilename, code)
if err == nil {
err = errw
}
if err != nil {
return err
}
return nil
}
var docsLink string
func (a *API) GenerateCode() ([]byte, error) {
pkg := a.Package()
jsonBytes := a.jsonBytes()
var err error
if a.doc == nil {
a.doc, err = disco.NewDocument(jsonBytes)
if err != nil {
return nil, err
}
}
// Buffer the output in memory, for gofmt'ing later.
var buf bytes.Buffer
a.p = func(format string, args ...interface{}) {
_, err := fmt.Fprintf(&buf, format, args...)
if err != nil {
panic(err)
}
}
a.pn = func(format string, args ...interface{}) {
a.p(format+"\n", args...)
}
wf := func(path string) error {
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
_, err = io.Copy(&buf, f)
return err
}
p, pn := a.p, a.pn
if *headerPath != "" {
if err := wf(*headerPath); err != nil {
return nil, err
}
}
pn(`// Copyright %s Google LLC.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Code generated file. DO NOT EDIT.
`, *copyrightYear)
pn("// Package %s provides access to the %s.", pkg, a.doc.Title)
if r := replacementPackage[pkg]; r != "" {
pn("//")
pn("// This package is DEPRECATED. Use package %s instead.", r)
}
docsLink = a.doc.DocumentationLink
if docsLink != "" {
pn("//")
pn("// For product documentation, see: %s", docsLink)
}
pn("//")
pn("// Creating a client")
pn("//")
pn("// Usage example:")
pn("//")
pn("// import %q", a.Target())
pn("// ...")
pn("// ctx := context.Background()")
pn("// %sService, err := %s.NewService(ctx)", pkg, pkg)
pn("//")
pn("// In this example, Google Application Default Credentials are used for authentication.")
pn("//")
pn("// For information on how to create and obtain Application Default Credentials, see https://developers.google.com/identity/protocols/application-default-credentials.")
pn("//")
pn("// Other authentication options")
pn("//")
if len(a.doc.Auth.OAuth2Scopes) > 1 {
pn(`// By default, all available scopes (see "Constants") are used to authenticate. To restrict scopes, use option.WithScopes:`)
pn("//")
// NOTE: the first scope tends to be the broadest. Use the last one to demonstrate restriction.
pn("// %sService, err := %s.NewService(ctx, option.WithScopes(%s.%s))", pkg, pkg, pkg, scopeIdentifierFromURL(a.doc.Auth.OAuth2Scopes[len(a.doc.Auth.OAuth2Scopes)-1].URL))
pn("//")
}
pn("// To use an API key for authentication (note: some APIs do not support API keys), use option.WithAPIKey:")
pn("//")
pn(`// %sService, err := %s.NewService(ctx, option.WithAPIKey("AIza..."))`, pkg, pkg)
pn("//")
pn("// To use an OAuth token (e.g., a user token obtained via a three-legged OAuth flow), use option.WithTokenSource:")
pn("//")
pn("// config := &oauth2.Config{...}")
pn("// // ...")
pn("// token, err := config.Exchange(ctx, ...)")
pn("// %sService, err := %s.NewService(ctx, option.WithTokenSource(config.TokenSource(ctx, token)))", pkg, pkg)
pn("//")
pn("// See https://godoc.org/google.golang.org/api/option/ for details on options.")
pn("package %s // import %q", pkg, a.Target())
p("\n")
pn("import (")
for _, imp := range []string{
"bytes",
"context",
"encoding/json",
"errors",
"fmt",
"io",
"net/http",
"net/url",
"strconv",
"strings",
} {
pn(" %q", imp)
}
pn("")
for _, imp := range []struct {
pkg string
lname string
}{
{*gensupportPkg, "gensupport"},
{*googleapiPkg, "googleapi"},
{*optionPkg, "option"},
{*htransportPkg, "htransport"},
} {
pn(" %s %q", imp.lname, imp.pkg)
}
pn(")")
pn("\n// Always reference these packages, just in case the auto-generated code")
pn("// below doesn't.")
pn("var _ = bytes.NewBuffer")
pn("var _ = strconv.Itoa")
pn("var _ = fmt.Sprintf")
pn("var _ = json.NewDecoder")
pn("var _ = io.Copy")
pn("var _ = url.Parse")
pn("var _ = gensupport.MarshalJSON")
pn("var _ = googleapi.Version")
pn("var _ = errors.New")
pn("var _ = strings.Replace")
pn("var _ = context.Canceled")
pn("")
pn("const apiId = %q", a.doc.ID)
pn("const apiName = %q", a.doc.Name)
pn("const apiVersion = %q", a.doc.Version)
pn("const basePath = %q", a.apiBaseURL())
a.generateScopeConstants()
a.PopulateSchemas()
service := a.ServiceType()
// Reserve names (ignore return value; we're the first caller).
a.GetName("New")
a.GetName(service)
pn("// NewService creates a new %s.", service)
pn("func NewService(ctx context.Context, opts ...option.ClientOption) (*%s, error) {", service)
if len(a.doc.Auth.OAuth2Scopes) != 0 {
pn("scopesOption := option.WithScopes(")
for _, scope := range a.doc.Auth.OAuth2Scopes {
pn("%q,", scope.URL)
}
pn(")")
pn("// NOTE: prepend, so we don't override user-specified scopes.")
pn("opts = append([]option.ClientOption{scopesOption}, opts...)")
}
pn("client, endpoint, err := htransport.NewClient(ctx, opts...)")
pn("if err != nil { return nil, err }")
pn("s, err := New(client)")
pn("if err != nil { return nil, err }")
pn(`if endpoint != "" { s.BasePath = endpoint }`)
pn("return s, nil")
pn("}\n")
pn("// New creates a new %s. It uses the provided http.Client for requests.", service)
pn("//")
pn("// Deprecated: please use NewService instead.")
pn("// To provide a custom HTTP client, use option.WithHTTPClient.")
pn("// If you are using google.golang.org/api/googleapis/transport.APIKey, use option.WithAPIKey with NewService instead.")
pn("func New(client *http.Client) (*%s, error) {", service)
pn("if client == nil { return nil, errors.New(\"client is nil\") }")
pn("s := &%s{client: client, BasePath: basePath}", service)
for _, res := range a.doc.Resources { // add top level resources.
pn("s.%s = New%s(s)", resourceGoField(res, nil), resourceGoType(res))
}
pn("return s, nil")
pn("}")
pn("\ntype %s struct {", service)
pn(" client *http.Client")
pn(" BasePath string // API endpoint base URL")
pn(" UserAgent string // optional additional User-Agent fragment")
for _, res := range a.doc.Resources {
pn("\n\t%s\t*%s", resourceGoField(res, nil), resourceGoType(res))
}
pn("}")
pn("\nfunc (s *%s) userAgent() string {", service)
pn(` if s.UserAgent == "" { return googleapi.UserAgent }`)
pn(` return googleapi.UserAgent + " " + s.UserAgent`)
pn("}\n")
for _, res := range a.doc.Resources {
a.generateResource(res)
}
a.responseTypes = make(map[string]bool)
for _, meth := range a.APIMethods() {
meth.cacheResponseTypes(a)
}
for _, res := range a.doc.Resources {
a.cacheResourceResponseTypes(res)
}
for _, name := range a.sortedSchemaNames() {
a.schemas[name].writeSchemaCode(a)
}
for _, meth := range a.APIMethods() {
meth.generateCode()
}
for _, res := range a.doc.Resources {
a.generateResourceMethods(res)
}
clean, err := format.Source(buf.Bytes())
if err != nil {
return buf.Bytes(), err
}
return clean, nil
}
func (a *API) generateScopeConstants() {
scopes := a.doc.Auth.OAuth2Scopes
if len(scopes) == 0 {
return
}
a.pn("// OAuth2 scopes used by this API.")
a.pn("const (")
n := 0
for _, scope := range scopes {
if n > 0 {
a.p("\n")
}
n++
ident := scopeIdentifierFromURL(scope.URL)
if scope.Description != "" {
a.p("%s", asComment("\t", scope.Description))
}
a.pn("\t%s = %q", ident, scope.URL)
}
a.p(")\n\n")
}
func scopeIdentifierFromURL(urlStr string) string {
const prefix = "https://www.googleapis.com/auth/"
if !strings.HasPrefix(urlStr, prefix) {
const https = "https://"
if !strings.HasPrefix(urlStr, https) {
log.Fatalf("Unexpected oauth2 scope %q doesn't start with %q", urlStr, https)
}
ident := validGoIdentifer(depunct(urlStr[len(https):], true)) + "Scope"
return ident
}
ident := validGoIdentifer(initialCap(urlStr[len(prefix):])) + "Scope"
return ident
}
// Schema is a disco.Schema that has been bestowed an identifier, whether by
// having an "id" field at the top of the schema or with an
// automatically generated one in populateSubSchemas.
//
// TODO: While sub-types shouldn't need to be promoted to schemas,
// API.GenerateCode iterates over API.schemas to figure out what
// top-level Go types to write. These should be separate concerns.
type Schema struct {
api *API
typ *disco.Schema
apiName string // the native API-defined name of this type
goName string // lazily populated by GoName
goReturnType string // lazily populated by GoReturnType
props []*Property
}
type Property struct {
s *Schema // the containing Schema
p *disco.Property
assignedGoName string
}
func (p *Property) Type() *disco.Schema {
return p.p.Schema
}
func (p *Property) GoName() string {
return initialCap(p.p.Name)
}
func (p *Property) Default() string {
return p.p.Schema.Default
}
func (p *Property) Description() string {
return p.p.Schema.Description
}
func (p *Property) Enum() ([]string, bool) {
typ := p.p.Schema
if typ.Enums != nil {
return typ.Enums, true
}
// Check if this has an array of string enums.
if typ.ItemSchema != nil {
if enums := typ.ItemSchema.Enums; enums != nil && typ.ItemSchema.Type == "string" {
return enums, true
}
}
return nil, false
}
func (p *Property) EnumDescriptions() []string {
if desc := p.p.Schema.EnumDescriptions; desc != nil {
return desc
}
// Check if this has an array of string enum descriptions.
if items := p.p.Schema.ItemSchema; items != nil {
if desc := items.EnumDescriptions; desc != nil {
return desc
}
}
return nil
}
func (p *Property) Pattern() (string, bool) {
return p.p.Schema.Pattern, (p.p.Schema.Pattern != "")
}
func (p *Property) TypeAsGo() string {
return p.s.api.typeAsGo(p.Type(), false)
}
// A FieldName uniquely identifies a field within a Schema struct for an API.
type fieldName struct {
api string // The ID of an API.
schema string // The Go name of a Schema struct.
field string // The Go name of a field.
}
// pointerFields is a list of fields that should use a pointer type.
// This makes it possible to distinguish between a field being unset vs having
// an empty value.
var pointerFields = []fieldName{
{api: "androidpublisher:v1.1", schema: "InappPurchase", field: "PurchaseType"},
{api: "androidpublisher:v2", schema: "ProductPurchase", field: "PurchaseType"},
{api: "androidpublisher:v3", schema: "ProductPurchase", field: "PurchaseType"},
{api: "androidpublisher:v2", schema: "SubscriptionPurchase", field: "CancelReason"},
{api: "androidpublisher:v2", schema: "SubscriptionPurchase", field: "PaymentState"},
{api: "androidpublisher:v2", schema: "SubscriptionPurchase", field: "PurchaseType"},
{api: "androidpublisher:v3", schema: "SubscriptionPurchase", field: "PurchaseType"},
{api: "cloudmonitoring:v2beta2", schema: "Point", field: "BoolValue"},
{api: "cloudmonitoring:v2beta2", schema: "Point", field: "DoubleValue"},
{api: "cloudmonitoring:v2beta2", schema: "Point", field: "Int64Value"},
{api: "cloudmonitoring:v2beta2", schema: "Point", field: "StringValue"},
{api: "compute:alpha", schema: "Scheduling", field: "AutomaticRestart"},
{api: "compute:beta", schema: "MetadataItems", field: "Value"},
{api: "compute:beta", schema: "Scheduling", field: "AutomaticRestart"},
{api: "compute:v1", schema: "MetadataItems", field: "Value"},
{api: "compute:v1", schema: "Scheduling", field: "AutomaticRestart"},
{api: "content:v2", schema: "AccountUser", field: "Admin"},
{api: "datastore:v1beta2", schema: "Property", field: "BlobKeyValue"},
{api: "datastore:v1beta2", schema: "Property", field: "BlobValue"},
{api: "datastore:v1beta2", schema: "Property", field: "BooleanValue"},
{api: "datastore:v1beta2", schema: "Property", field: "DateTimeValue"},
{api: "datastore:v1beta2", schema: "Property", field: "DoubleValue"},
{api: "datastore:v1beta2", schema: "Property", field: "Indexed"},
{api: "datastore:v1beta2", schema: "Property", field: "IntegerValue"},
{api: "datastore:v1beta2", schema: "Property", field: "StringValue"},
{api: "datastore:v1beta3", schema: "Value", field: "BlobValue"},
{api: "datastore:v1beta3", schema: "Value", field: "BooleanValue"},
{api: "datastore:v1beta3", schema: "Value", field: "DoubleValue"},
{api: "datastore:v1beta3", schema: "Value", field: "IntegerValue"},
{api: "datastore:v1beta3", schema: "Value", field: "StringValue"},
{api: "datastore:v1beta3", schema: "Value", field: "TimestampValue"},
{api: "genomics:v1beta2", schema: "Dataset", field: "IsPublic"},
{api: "monitoring:v3", schema: "TypedValue", field: "BoolValue"},
{api: "monitoring:v3", schema: "TypedValue", field: "DoubleValue"},
{api: "monitoring:v3", schema: "TypedValue", field: "Int64Value"},
{api: "monitoring:v3", schema: "TypedValue", field: "StringValue"},
{api: "servicecontrol:v1", schema: "MetricValue", field: "BoolValue"},
{api: "servicecontrol:v1", schema: "MetricValue", field: "DoubleValue"},
{api: "servicecontrol:v1", schema: "MetricValue", field: "Int64Value"},
{api: "servicecontrol:v1", schema: "MetricValue", field: "StringValue"},
{api: "sqladmin:v1beta4", schema: "Settings", field: "StorageAutoResize"},
{api: "storage:v1", schema: "BucketLifecycleRuleCondition", field: "IsLive"},
{api: "storage:v1beta2", schema: "BucketLifecycleRuleCondition", field: "IsLive"},
{api: "tasks:v1", schema: "Task", field: "Completed"},
{api: "youtube:v3", schema: "ChannelSectionSnippet", field: "Position"},
}
// forcePointerType reports whether p should be represented as a pointer type in its parent schema struct.
func (p *Property) forcePointerType() bool {
if p.UnfortunateDefault() {
return true
}
name := fieldName{api: p.s.api.ID, schema: p.s.GoName(), field: p.GoName()}
for _, pf := range pointerFields {
if pf == name {
return true
}
}
return false
}
// UnfortunateDefault reports whether p may be set to a zero value, but has a non-zero default.
func (p *Property) UnfortunateDefault() bool {
switch p.TypeAsGo() {
default:
return false
case "bool":
return p.Default() == "true"
case "string":
if p.Default() == "" {
return false
}
// String fields are considered to "allow" a zero value if either:
// (a) they are an enum, and one of the permitted enum values is the empty string, or
// (b) they have a validation pattern which matches the empty string.
pattern, hasPat := p.Pattern()
enum, hasEnum := p.Enum()
if hasPat && hasEnum {
log.Printf("Encountered enum property which also has a pattern: %#v", p)
return false // don't know how to handle this, so ignore.
}
return (hasPat && emptyPattern(pattern)) ||
(hasEnum && emptyEnum(enum))
case "float64", "int64", "uint64", "int32", "uint32":
if p.Default() == "" {
return false
}
if f, err := strconv.ParseFloat(p.Default(), 64); err == nil {
return f != 0.0
}
// The default value has an unexpected form. Whatever it is, it's non-zero.
return true
}
}
// emptyPattern reports whether a pattern matches the empty string.
func emptyPattern(pattern string) bool {
if re, err := regexp.Compile(pattern); err == nil {
return re.MatchString("")
}
log.Printf("Encountered bad pattern: %s", pattern)
return false
}
// emptyEnum reports whether a property enum list contains the empty string.
func emptyEnum(enum []string) bool {
for _, val := range enum {
if val == "" {
return true
}
}
return false
}
func (a *API) typeAsGo(s *disco.Schema, elidePointers bool) string {
switch s.Kind {
case disco.SimpleKind:
return mustSimpleTypeConvert(s.Type, s.Format)
case disco.ArrayKind:
as := s.ElementSchema()
if as.Type == "string" {