Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 

2373 řádky
67 KiB

  1. // Copyright 2011 Google Inc. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package main
  5. import (
  6. "bytes"
  7. "encoding/json"
  8. "errors"
  9. "flag"
  10. "fmt"
  11. "go/format"
  12. "io"
  13. "io/ioutil"
  14. "log"
  15. "net/http"
  16. "net/url"
  17. "os"
  18. "os/exec"
  19. "path/filepath"
  20. "regexp"
  21. "sort"
  22. "strconv"
  23. "strings"
  24. "unicode"
  25. "google.golang.org/api/google-api-go-generator/internal/disco"
  26. )
  27. const (
  28. googleDiscoveryURL = "https://www.googleapis.com/discovery/v1/apis"
  29. generatorVersion = "2018018"
  30. )
  31. var (
  32. apiToGenerate = flag.String("api", "*", "The API ID to generate, like 'tasks:v1'. A value of '*' means all.")
  33. useCache = flag.Bool("cache", true, "Use cache of discovered Google API discovery documents.")
  34. genDir = flag.String("gendir", "", "Directory to use to write out generated Go files")
  35. build = flag.Bool("build", false, "Compile generated packages.")
  36. install = flag.Bool("install", false, "Install generated packages.")
  37. apisURL = flag.String("discoveryurl", googleDiscoveryURL, "URL to root discovery document")
  38. publicOnly = flag.Bool("publiconly", true, "Only build public, released APIs. Only applicable for Google employees.")
  39. 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.")
  40. 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).")
  41. apiPackageBase = flag.String("api_pkg_base", "google.golang.org/api", "Go package prefix to use for all generated APIs.")
  42. baseURL = flag.String("base_url", "", "(optional) Override the default service API URL. If empty, the service's root URL will be used.")
  43. headerPath = flag.String("header_path", "", "If non-empty, prepend the contents of this file to generated services.")
  44. contextHTTPPkg = flag.String("ctxhttp_pkg", "golang.org/x/net/context/ctxhttp", "Go package path of the 'ctxhttp' package.")
  45. contextPkg = flag.String("context_pkg", "golang.org/x/net/context", "Go package path of the 'context' package.")
  46. gensupportPkg = flag.String("gensupport_pkg", "google.golang.org/api/gensupport", "Go package path of the 'api/gensupport' support package.")
  47. googleapiPkg = flag.String("googleapi_pkg", "google.golang.org/api/googleapi", "Go package path of the 'api/googleapi' support package.")
  48. serviceTypes = []string{"Service", "APIService"}
  49. )
  50. // API represents an API to generate, as well as its state while it's
  51. // generating.
  52. type API struct {
  53. // Fields needed before generating code, to select and find the APIs
  54. // to generate.
  55. // These fields usually come from the "directory item" JSON objects
  56. // that are provided by the googleDiscoveryURL. We unmarshal a directory
  57. // item directly into this struct.
  58. ID string `json:"id"`
  59. Name string `json:"name"`
  60. Version string `json:"version"`
  61. DiscoveryLink string `json:"discoveryRestUrl"` // absolute
  62. doc *disco.Document
  63. // TODO(jba): remove m when we've fully converted to using disco.
  64. m map[string]interface{}
  65. forceJSON []byte // if non-nil, the JSON schema file. else fetched.
  66. usedNames namePool
  67. schemas map[string]*Schema // apiName -> schema
  68. responseTypes map[string]bool
  69. p func(format string, args ...interface{}) // print raw
  70. pn func(format string, args ...interface{}) // print with newline
  71. }
  72. func (a *API) sortedSchemaNames() (names []string) {
  73. for name := range a.schemas {
  74. names = append(names, name)
  75. }
  76. sort.Strings(names)
  77. return
  78. }
  79. func (a *API) Schema(name string) *Schema {
  80. return a.schemas[name]
  81. }
  82. type generateError struct {
  83. api *API
  84. error error
  85. }
  86. func (e *generateError) Error() string {
  87. return fmt.Sprintf("API %s failed to generate code: %v", e.api.ID, e.error)
  88. }
  89. type compileError struct {
  90. api *API
  91. output string
  92. }
  93. func (e *compileError) Error() string {
  94. return fmt.Sprintf("API %s failed to compile:\n%v", e.api.ID, e.output)
  95. }
  96. func main() {
  97. flag.Parse()
  98. if *install {
  99. *build = true
  100. }
  101. var (
  102. apiIds = []string{}
  103. matches = []*API{}
  104. errors = []error{}
  105. )
  106. for _, api := range getAPIs() {
  107. apiIds = append(apiIds, api.ID)
  108. if !api.want() {
  109. continue
  110. }
  111. matches = append(matches, api)
  112. log.Printf("Generating API %s", api.ID)
  113. err := api.WriteGeneratedCode()
  114. if err != nil && err != errNoDoc {
  115. errors = append(errors, &generateError{api, err})
  116. continue
  117. }
  118. if *build && err == nil {
  119. var args []string
  120. if *install {
  121. args = append(args, "install")
  122. } else {
  123. args = append(args, "build")
  124. }
  125. args = append(args, api.Target())
  126. out, err := exec.Command("go", args...).CombinedOutput()
  127. if err != nil {
  128. errors = append(errors, &compileError{api, string(out)})
  129. }
  130. }
  131. }
  132. if len(matches) == 0 {
  133. log.Fatalf("No APIs matched %q; options are %v", *apiToGenerate, apiIds)
  134. }
  135. if len(errors) > 0 {
  136. log.Printf("%d API(s) failed to generate or compile:", len(errors))
  137. for _, ce := range errors {
  138. log.Printf(ce.Error())
  139. }
  140. os.Exit(1)
  141. }
  142. }
  143. func (a *API) want() bool {
  144. if *jsonFile != "" {
  145. // Return true early, before calling a.JSONFile()
  146. // which will require a GOPATH be set. This is for
  147. // integration with Google's build system genrules
  148. // where there is no GOPATH.
  149. return true
  150. }
  151. // Skip this API if we're in cached mode and the files don't exist on disk.
  152. if *useCache {
  153. if _, err := os.Stat(a.JSONFile()); os.IsNotExist(err) {
  154. return false
  155. }
  156. }
  157. return *apiToGenerate == "*" || *apiToGenerate == a.ID
  158. }
  159. func getAPIs() []*API {
  160. if *jsonFile != "" {
  161. return getAPIsFromFile()
  162. }
  163. var bytes []byte
  164. var source string
  165. apiListFile := filepath.Join(genDirRoot(), "api-list.json")
  166. if *useCache {
  167. if !*publicOnly {
  168. log.Fatalf("-cache=true not compatible with -publiconly=false")
  169. }
  170. var err error
  171. bytes, err = ioutil.ReadFile(apiListFile)
  172. if err != nil {
  173. log.Fatal(err)
  174. }
  175. source = apiListFile
  176. } else {
  177. bytes = slurpURL(*apisURL)
  178. if *publicOnly {
  179. if err := writeFile(apiListFile, bytes); err != nil {
  180. log.Fatal(err)
  181. }
  182. }
  183. source = *apisURL
  184. }
  185. apis, err := unmarshalAPIs(bytes)
  186. if err != nil {
  187. log.Fatalf("error decoding JSON in %s: %v", source, err)
  188. }
  189. if !*publicOnly && *apiToGenerate != "*" {
  190. apis = append(apis, apiFromID(*apiToGenerate))
  191. }
  192. return apis
  193. }
  194. func unmarshalAPIs(bytes []byte) ([]*API, error) {
  195. var itemObj struct{ Items []*API }
  196. if err := json.Unmarshal(bytes, &itemObj); err != nil {
  197. return nil, err
  198. }
  199. return itemObj.Items, nil
  200. }
  201. func apiFromID(apiID string) *API {
  202. parts := strings.Split(apiID, ":")
  203. if len(parts) != 2 {
  204. log.Fatalf("malformed API name: %q", apiID)
  205. }
  206. return &API{
  207. ID: apiID,
  208. Name: parts[0],
  209. Version: parts[1],
  210. }
  211. }
  212. // getAPIsFromFile handles the case of generating exactly one API
  213. // from the flag given in --api_json_file
  214. func getAPIsFromFile() []*API {
  215. if *apiToGenerate != "*" {
  216. log.Fatalf("Can't set --api with --api_json_file.")
  217. }
  218. if !*publicOnly {
  219. log.Fatalf("Can't set --publiconly with --api_json_file.")
  220. }
  221. a, err := apiFromFile(*jsonFile)
  222. if err != nil {
  223. log.Fatal(err)
  224. }
  225. return []*API{a}
  226. }
  227. func apiFromFile(file string) (*API, error) {
  228. jsonBytes, err := ioutil.ReadFile(file)
  229. if err != nil {
  230. return nil, fmt.Errorf("Error reading %s: %v", file, err)
  231. }
  232. doc, err := disco.NewDocument(jsonBytes)
  233. if err != nil {
  234. return nil, fmt.Errorf("reading document from %q: %v", file, err)
  235. }
  236. a := &API{
  237. ID: doc.ID,
  238. Name: doc.Name,
  239. Version: doc.Version,
  240. forceJSON: jsonBytes,
  241. doc: doc,
  242. }
  243. return a, nil
  244. }
  245. func writeFile(file string, contents []byte) error {
  246. // Don't write it if the contents are identical.
  247. existing, err := ioutil.ReadFile(file)
  248. if err == nil && (bytes.Equal(existing, contents) || basicallyEqual(existing, contents)) {
  249. return nil
  250. }
  251. outdir := filepath.Dir(file)
  252. if err = os.MkdirAll(outdir, 0755); err != nil {
  253. return fmt.Errorf("failed to Mkdir %s: %v", outdir, err)
  254. }
  255. return ioutil.WriteFile(file, contents, 0644)
  256. }
  257. var ignoreLines = regexp.MustCompile(`(?m)^\s+"(?:etag|revision)": ".+\n`)
  258. // basicallyEqual reports whether a and b are equal except for boring
  259. // differences like ETag updates.
  260. func basicallyEqual(a, b []byte) bool {
  261. return ignoreLines.Match(a) && ignoreLines.Match(b) &&
  262. bytes.Equal(ignoreLines.ReplaceAll(a, nil), ignoreLines.ReplaceAll(b, nil))
  263. }
  264. func slurpURL(urlStr string) []byte {
  265. if *useCache {
  266. log.Fatalf("Invalid use of slurpURL in cached mode for URL %s", urlStr)
  267. }
  268. req, err := http.NewRequest("GET", urlStr, nil)
  269. if err != nil {
  270. log.Fatal(err)
  271. }
  272. if *publicOnly {
  273. req.Header.Add("X-User-IP", "0.0.0.0") // hack
  274. }
  275. res, err := http.DefaultClient.Do(req)
  276. if err != nil {
  277. log.Fatalf("Error fetching URL %s: %v", urlStr, err)
  278. }
  279. if res.StatusCode >= 300 {
  280. log.Printf("WARNING: URL %s served status code %d", urlStr, res.StatusCode)
  281. return nil
  282. }
  283. bs, err := ioutil.ReadAll(res.Body)
  284. if err != nil {
  285. log.Fatalf("Error reading body of URL %s: %v", urlStr, err)
  286. }
  287. return bs
  288. }
  289. func panicf(format string, args ...interface{}) {
  290. panic(fmt.Sprintf(format, args...))
  291. }
  292. // namePool keeps track of used names and assigns free ones based on a
  293. // preferred name
  294. type namePool struct {
  295. m map[string]bool // lazily initialized
  296. }
  297. // oddVersionRE matches unusual API names like directory_v1.
  298. var oddVersionRE = regexp.MustCompile(`^(.+)_(v[\d\.]+)$`)
  299. // renameVersion conditionally rewrites the provided version such
  300. // that the final path component of the import path doesn't look
  301. // like a Go identifier. This keeps the consistency that import paths
  302. // for the generated Go packages look like:
  303. // google.golang.org/api/NAME/v<version>
  304. // and have package NAME.
  305. // See https://github.com/google/google-api-go-client/issues/78
  306. func renameVersion(version string) string {
  307. if version == "alpha" || version == "beta" {
  308. return "v0." + version
  309. }
  310. if m := oddVersionRE.FindStringSubmatch(version); m != nil {
  311. return m[1] + "/" + m[2]
  312. }
  313. return version
  314. }
  315. func (p *namePool) Get(preferred string) string {
  316. if p.m == nil {
  317. p.m = make(map[string]bool)
  318. }
  319. name := preferred
  320. tries := 0
  321. for p.m[name] {
  322. tries++
  323. name = fmt.Sprintf("%s%d", preferred, tries)
  324. }
  325. p.m[name] = true
  326. return name
  327. }
  328. func genDirRoot() string {
  329. if *genDir != "" {
  330. return *genDir
  331. }
  332. paths := filepath.SplitList(os.Getenv("GOPATH"))
  333. if len(paths) == 0 {
  334. log.Fatalf("No GOPATH set.")
  335. }
  336. return filepath.Join(paths[0], "src", "google.golang.org", "api")
  337. }
  338. func (a *API) SourceDir() string {
  339. return filepath.Join(genDirRoot(), a.Package(), renameVersion(a.Version))
  340. }
  341. func (a *API) DiscoveryURL() string {
  342. if a.DiscoveryLink == "" {
  343. log.Fatalf("API %s has no DiscoveryLink", a.ID)
  344. }
  345. return a.DiscoveryLink
  346. }
  347. func (a *API) Package() string {
  348. return strings.ToLower(a.Name)
  349. }
  350. func (a *API) Target() string {
  351. return fmt.Sprintf("%s/%s/%s", *apiPackageBase, a.Package(), renameVersion(a.Version))
  352. }
  353. // ServiceType returns the name of the type to use for the root API struct
  354. // (typically "Service").
  355. func (a *API) ServiceType() string {
  356. switch a.Name {
  357. case "appengine", "content": // retained for historical compatibility.
  358. return "APIService"
  359. default:
  360. for _, t := range serviceTypes {
  361. if _, ok := a.schemas[t]; !ok {
  362. return t
  363. }
  364. }
  365. panic("all service types are used, please consider introducing a new type to serviceTypes.")
  366. }
  367. }
  368. // GetName returns a free top-level function/type identifier in the package.
  369. // It tries to return your preferred match if it's free.
  370. func (a *API) GetName(preferred string) string {
  371. return a.usedNames.Get(preferred)
  372. }
  373. func (a *API) apiBaseURL() string {
  374. var base, rel string
  375. switch {
  376. case *baseURL != "":
  377. base, rel = *baseURL, a.doc.BasePath
  378. case a.doc.RootURL != "":
  379. base, rel = a.doc.RootURL, a.doc.ServicePath
  380. default:
  381. base, rel = *apisURL, a.doc.BasePath
  382. }
  383. return resolveRelative(base, rel)
  384. }
  385. func (a *API) needsDataWrapper() bool {
  386. for _, feature := range a.doc.Features {
  387. if feature == "dataWrapper" {
  388. return true
  389. }
  390. }
  391. return false
  392. }
  393. func (a *API) jsonBytes() []byte {
  394. if a.forceJSON == nil {
  395. var slurp []byte
  396. var err error
  397. if *useCache {
  398. slurp, err = ioutil.ReadFile(a.JSONFile())
  399. if err != nil {
  400. log.Fatal(err)
  401. }
  402. } else {
  403. slurp = slurpURL(a.DiscoveryURL())
  404. if slurp != nil {
  405. // Make sure that keys are sorted by re-marshalling.
  406. d := make(map[string]interface{})
  407. json.Unmarshal(slurp, &d)
  408. if err != nil {
  409. log.Fatal(err)
  410. }
  411. var err error
  412. slurp, err = json.MarshalIndent(d, "", " ")
  413. if err != nil {
  414. log.Fatal(err)
  415. }
  416. }
  417. }
  418. a.forceJSON = slurp
  419. }
  420. return a.forceJSON
  421. }
  422. func (a *API) JSONFile() string {
  423. return filepath.Join(a.SourceDir(), a.Package()+"-api.json")
  424. }
  425. var errNoDoc = errors.New("could not read discovery doc")
  426. // WriteGeneratedCode generates code for a.
  427. // It returns errNoDoc if we couldn't read the discovery doc.
  428. func (a *API) WriteGeneratedCode() error {
  429. genfilename := *output
  430. jsonBytes := a.jsonBytes()
  431. // Skip generation if we don't have the discovery doc.
  432. if jsonBytes == nil {
  433. // No message here, because slurpURL printed one.
  434. return errNoDoc
  435. }
  436. if genfilename == "" {
  437. if err := writeFile(a.JSONFile(), jsonBytes); err != nil {
  438. return err
  439. }
  440. outdir := a.SourceDir()
  441. err := os.MkdirAll(outdir, 0755)
  442. if err != nil {
  443. return fmt.Errorf("failed to Mkdir %s: %v", outdir, err)
  444. }
  445. pkg := a.Package()
  446. genfilename = filepath.Join(outdir, pkg+"-gen.go")
  447. }
  448. code, err := a.GenerateCode()
  449. errw := writeFile(genfilename, code)
  450. if err == nil {
  451. err = errw
  452. }
  453. if err != nil {
  454. return err
  455. }
  456. return nil
  457. }
  458. var docsLink string
  459. func (a *API) GenerateCode() ([]byte, error) {
  460. pkg := a.Package()
  461. jsonBytes := a.jsonBytes()
  462. var err error
  463. if a.doc == nil {
  464. a.doc, err = disco.NewDocument(jsonBytes)
  465. if err != nil {
  466. return nil, err
  467. }
  468. }
  469. // Buffer the output in memory, for gofmt'ing later.
  470. var buf bytes.Buffer
  471. a.p = func(format string, args ...interface{}) {
  472. _, err := fmt.Fprintf(&buf, format, args...)
  473. if err != nil {
  474. panic(err)
  475. }
  476. }
  477. a.pn = func(format string, args ...interface{}) {
  478. a.p(format+"\n", args...)
  479. }
  480. wf := func(path string) error {
  481. f, err := os.Open(path)
  482. if err != nil {
  483. return err
  484. }
  485. defer f.Close()
  486. _, err = io.Copy(&buf, f)
  487. return err
  488. }
  489. p, pn := a.p, a.pn
  490. if *headerPath != "" {
  491. if err := wf(*headerPath); err != nil {
  492. return nil, err
  493. }
  494. }
  495. pn("// Package %s provides access to the %s.", pkg, a.doc.Title)
  496. docsLink = a.doc.DocumentationLink
  497. if docsLink != "" {
  498. pn("//")
  499. pn("// See %s", docsLink)
  500. }
  501. pn("//\n// Usage example:")
  502. pn("//")
  503. pn("// import %q", a.Target())
  504. pn("// ...")
  505. pn("// %sService, err := %s.New(oauthHttpClient)", pkg, pkg)
  506. pn("package %s // import %q", pkg, a.Target())
  507. p("\n")
  508. pn("import (")
  509. for _, imp := range []struct {
  510. pkg string
  511. lname string
  512. }{
  513. {"bytes", ""},
  514. {"encoding/json", ""},
  515. {"errors", ""},
  516. {"fmt", ""},
  517. {"io", ""},
  518. {"net/http", ""},
  519. {"net/url", ""},
  520. {"strconv", ""},
  521. {"strings", ""},
  522. {*contextHTTPPkg, "ctxhttp"},
  523. {*contextPkg, "context"},
  524. {*gensupportPkg, "gensupport"},
  525. {*googleapiPkg, "googleapi"},
  526. } {
  527. if imp.lname == "" {
  528. pn(" %q", imp.pkg)
  529. } else {
  530. pn(" %s %q", imp.lname, imp.pkg)
  531. }
  532. }
  533. pn(")")
  534. pn("\n// Always reference these packages, just in case the auto-generated code")
  535. pn("// below doesn't.")
  536. pn("var _ = bytes.NewBuffer")
  537. pn("var _ = strconv.Itoa")
  538. pn("var _ = fmt.Sprintf")
  539. pn("var _ = json.NewDecoder")
  540. pn("var _ = io.Copy")
  541. pn("var _ = url.Parse")
  542. pn("var _ = gensupport.MarshalJSON")
  543. pn("var _ = googleapi.Version")
  544. pn("var _ = errors.New")
  545. pn("var _ = strings.Replace")
  546. pn("var _ = context.Canceled")
  547. pn("var _ = ctxhttp.Do")
  548. pn("")
  549. pn("const apiId = %q", a.doc.ID)
  550. pn("const apiName = %q", a.doc.Name)
  551. pn("const apiVersion = %q", a.doc.Version)
  552. pn("const basePath = %q", a.apiBaseURL())
  553. a.generateScopeConstants()
  554. a.PopulateSchemas()
  555. service := a.ServiceType()
  556. // Reserve names (ignore return value; we're the first caller).
  557. a.GetName("New")
  558. a.GetName(service)
  559. pn("func New(client *http.Client) (*%s, error) {", service)
  560. pn("if client == nil { return nil, errors.New(\"client is nil\") }")
  561. pn("s := &%s{client: client, BasePath: basePath}", service)
  562. for _, res := range a.doc.Resources { // add top level resources.
  563. pn("s.%s = New%s(s)", resourceGoField(res), resourceGoType(res))
  564. }
  565. pn("return s, nil")
  566. pn("}")
  567. pn("\ntype %s struct {", service)
  568. pn(" client *http.Client")
  569. pn(" BasePath string // API endpoint base URL")
  570. pn(" UserAgent string // optional additional User-Agent fragment")
  571. for _, res := range a.doc.Resources {
  572. pn("\n\t%s\t*%s", resourceGoField(res), resourceGoType(res))
  573. }
  574. pn("}")
  575. pn("\nfunc (s *%s) userAgent() string {", service)
  576. pn(` if s.UserAgent == "" { return googleapi.UserAgent }`)
  577. pn(` return googleapi.UserAgent + " " + s.UserAgent`)
  578. pn("}\n")
  579. for _, res := range a.doc.Resources {
  580. a.generateResource(res)
  581. }
  582. a.responseTypes = make(map[string]bool)
  583. for _, meth := range a.APIMethods() {
  584. meth.cacheResponseTypes(a)
  585. }
  586. for _, res := range a.doc.Resources {
  587. a.cacheResourceResponseTypes(res)
  588. }
  589. for _, name := range a.sortedSchemaNames() {
  590. a.schemas[name].writeSchemaCode(a)
  591. }
  592. for _, meth := range a.APIMethods() {
  593. meth.generateCode()
  594. }
  595. for _, res := range a.doc.Resources {
  596. a.generateResourceMethods(res)
  597. }
  598. clean, err := format.Source(buf.Bytes())
  599. if err != nil {
  600. return buf.Bytes(), err
  601. }
  602. return clean, nil
  603. }
  604. func (a *API) generateScopeConstants() {
  605. scopes := a.doc.Auth.OAuth2Scopes
  606. if len(scopes) == 0 {
  607. return
  608. }
  609. a.pn("// OAuth2 scopes used by this API.")
  610. a.pn("const (")
  611. n := 0
  612. for _, scope := range scopes {
  613. if n > 0 {
  614. a.p("\n")
  615. }
  616. n++
  617. ident := scopeIdentifierFromURL(scope.URL)
  618. if scope.Description != "" {
  619. a.p("%s", asComment("\t", scope.Description))
  620. }
  621. a.pn("\t%s = %q", ident, scope.URL)
  622. }
  623. a.p(")\n\n")
  624. }
  625. func scopeIdentifierFromURL(urlStr string) string {
  626. const prefix = "https://www.googleapis.com/auth/"
  627. if !strings.HasPrefix(urlStr, prefix) {
  628. const https = "https://"
  629. if !strings.HasPrefix(urlStr, https) {
  630. log.Fatalf("Unexpected oauth2 scope %q doesn't start with %q", urlStr, https)
  631. }
  632. ident := validGoIdentifer(depunct(urlStr[len(https):], true)) + "Scope"
  633. return ident
  634. }
  635. ident := validGoIdentifer(initialCap(urlStr[len(prefix):])) + "Scope"
  636. return ident
  637. }
  638. // Schema is a disco.Schema that has been bestowed an identifier, whether by
  639. // having an "id" field at the top of the schema or with an
  640. // automatically generated one in populateSubSchemas.
  641. //
  642. // TODO: While sub-types shouldn't need to be promoted to schemas,
  643. // API.GenerateCode iterates over API.schemas to figure out what
  644. // top-level Go types to write. These should be separate concerns.
  645. type Schema struct {
  646. api *API
  647. typ *disco.Schema
  648. apiName string // the native API-defined name of this type
  649. goName string // lazily populated by GoName
  650. goReturnType string // lazily populated by GoReturnType
  651. props []*Property
  652. }
  653. type Property struct {
  654. s *Schema // the containing Schema
  655. p *disco.Property
  656. assignedGoName string
  657. }
  658. func (p *Property) Type() *disco.Schema {
  659. return p.p.Schema
  660. }
  661. func (p *Property) GoName() string {
  662. return initialCap(p.p.Name)
  663. }
  664. func (p *Property) Default() string {
  665. return p.p.Schema.Default
  666. }
  667. func (p *Property) Description() string {
  668. return p.p.Schema.Description
  669. }
  670. func (p *Property) Enum() ([]string, bool) {
  671. typ := p.p.Schema
  672. if typ.Enums != nil {
  673. return typ.Enums, true
  674. }
  675. // Check if this has an array of string enums.
  676. if typ.ItemSchema != nil {
  677. if enums := typ.ItemSchema.Enums; enums != nil && typ.ItemSchema.Type == "string" {
  678. return enums, true
  679. }
  680. }
  681. return nil, false
  682. }
  683. func (p *Property) EnumDescriptions() []string {
  684. if desc := p.p.Schema.EnumDescriptions; desc != nil {
  685. return desc
  686. }
  687. // Check if this has an array of string enum descriptions.
  688. if items := p.p.Schema.ItemSchema; items != nil {
  689. if desc := items.EnumDescriptions; desc != nil {
  690. return desc
  691. }
  692. }
  693. return nil
  694. }
  695. func (p *Property) Pattern() (string, bool) {
  696. return p.p.Schema.Pattern, (p.p.Schema.Pattern != "")
  697. }
  698. func (p *Property) TypeAsGo() string {
  699. return p.s.api.typeAsGo(p.Type(), false)
  700. }
  701. // A FieldName uniquely identifies a field within a Schema struct for an API.
  702. type fieldName struct {
  703. api string // The ID of an API.
  704. schema string // The Go name of a Schema struct.
  705. field string // The Go name of a field.
  706. }
  707. // pointerFields is a list of fields that should use a pointer type.
  708. // This makes it possible to distinguish between a field being unset vs having
  709. // an empty value.
  710. var pointerFields = []fieldName{
  711. {api: "androidpublisher:v2", schema: "SubscriptionPurchase", field: "CancelReason"},
  712. {api: "androidpublisher:v2", schema: "SubscriptionPurchase", field: "PaymentState"},
  713. {api: "cloudmonitoring:v2beta2", schema: "Point", field: "BoolValue"},
  714. {api: "cloudmonitoring:v2beta2", schema: "Point", field: "DoubleValue"},
  715. {api: "cloudmonitoring:v2beta2", schema: "Point", field: "Int64Value"},
  716. {api: "cloudmonitoring:v2beta2", schema: "Point", field: "StringValue"},
  717. {api: "compute:alpha", schema: "Scheduling", field: "AutomaticRestart"},
  718. {api: "compute:beta", schema: "MetadataItems", field: "Value"},
  719. {api: "compute:beta", schema: "Scheduling", field: "AutomaticRestart"},
  720. {api: "compute:v1", schema: "MetadataItems", field: "Value"},
  721. {api: "compute:v1", schema: "Scheduling", field: "AutomaticRestart"},
  722. {api: "content:v2", schema: "AccountUser", field: "Admin"},
  723. {api: "datastore:v1beta2", schema: "Property", field: "BlobKeyValue"},
  724. {api: "datastore:v1beta2", schema: "Property", field: "BlobValue"},
  725. {api: "datastore:v1beta2", schema: "Property", field: "BooleanValue"},
  726. {api: "datastore:v1beta2", schema: "Property", field: "DateTimeValue"},
  727. {api: "datastore:v1beta2", schema: "Property", field: "DoubleValue"},
  728. {api: "datastore:v1beta2", schema: "Property", field: "Indexed"},
  729. {api: "datastore:v1beta2", schema: "Property", field: "IntegerValue"},
  730. {api: "datastore:v1beta2", schema: "Property", field: "StringValue"},
  731. {api: "datastore:v1beta3", schema: "Value", field: "BlobValue"},
  732. {api: "datastore:v1beta3", schema: "Value", field: "BooleanValue"},
  733. {api: "datastore:v1beta3", schema: "Value", field: "DoubleValue"},
  734. {api: "datastore:v1beta3", schema: "Value", field: "IntegerValue"},
  735. {api: "datastore:v1beta3", schema: "Value", field: "StringValue"},
  736. {api: "datastore:v1beta3", schema: "Value", field: "TimestampValue"},
  737. {api: "genomics:v1beta2", schema: "Dataset", field: "IsPublic"},
  738. {api: "monitoring:v3", schema: "TypedValue", field: "BoolValue"},
  739. {api: "monitoring:v3", schema: "TypedValue", field: "DoubleValue"},
  740. {api: "monitoring:v3", schema: "TypedValue", field: "Int64Value"},
  741. {api: "monitoring:v3", schema: "TypedValue", field: "StringValue"},
  742. {api: "servicecontrol:v1", schema: "MetricValue", field: "BoolValue"},
  743. {api: "servicecontrol:v1", schema: "MetricValue", field: "DoubleValue"},
  744. {api: "servicecontrol:v1", schema: "MetricValue", field: "Int64Value"},
  745. {api: "servicecontrol:v1", schema: "MetricValue", field: "StringValue"},
  746. {api: "sqladmin:v1beta4", schema: "Settings", field: "StorageAutoResize"},
  747. {api: "storage:v1", schema: "BucketLifecycleRuleCondition", field: "IsLive"},
  748. {api: "storage:v1beta2", schema: "BucketLifecycleRuleCondition", field: "IsLive"},
  749. {api: "tasks:v1", schema: "Task", field: "Completed"},
  750. {api: "youtube:v3", schema: "ChannelSectionSnippet", field: "Position"},
  751. }
  752. // forcePointerType reports whether p should be represented as a pointer type in its parent schema struct.
  753. func (p *Property) forcePointerType() bool {
  754. if p.UnfortunateDefault() {
  755. return true
  756. }
  757. name := fieldName{api: p.s.api.ID, schema: p.s.GoName(), field: p.GoName()}
  758. for _, pf := range pointerFields {
  759. if pf == name {
  760. return true
  761. }
  762. }
  763. return false
  764. }
  765. // UnfortunateDefault reports whether p may be set to a zero value, but has a non-zero default.
  766. func (p *Property) UnfortunateDefault() bool {
  767. switch p.TypeAsGo() {
  768. default:
  769. return false
  770. case "bool":
  771. return p.Default() == "true"
  772. case "string":
  773. if p.Default() == "" {
  774. return false
  775. }
  776. // String fields are considered to "allow" a zero value if either:
  777. // (a) they are an enum, and one of the permitted enum values is the empty string, or
  778. // (b) they have a validation pattern which matches the empty string.
  779. pattern, hasPat := p.Pattern()
  780. enum, hasEnum := p.Enum()
  781. if hasPat && hasEnum {
  782. log.Printf("Encountered enum property which also has a pattern: %#v", p)
  783. return false // don't know how to handle this, so ignore.
  784. }
  785. return (hasPat && emptyPattern(pattern)) ||
  786. (hasEnum && emptyEnum(enum))
  787. case "float64", "int64", "uint64", "int32", "uint32":
  788. if p.Default() == "" {
  789. return false
  790. }
  791. if f, err := strconv.ParseFloat(p.Default(), 64); err == nil {
  792. return f != 0.0
  793. }
  794. // The default value has an unexpected form. Whatever it is, it's non-zero.
  795. return true
  796. }
  797. }
  798. // emptyPattern reports whether a pattern matches the empty string.
  799. func emptyPattern(pattern string) bool {
  800. if re, err := regexp.Compile(pattern); err == nil {
  801. return re.MatchString("")
  802. }
  803. log.Printf("Encountered bad pattern: %s", pattern)
  804. return false
  805. }
  806. // emptyEnum reports whether a property enum list contains the empty string.
  807. func emptyEnum(enum []string) bool {
  808. for _, val := range enum {
  809. if val == "" {
  810. return true
  811. }
  812. }
  813. return false
  814. }
  815. func (a *API) typeAsGo(s *disco.Schema, elidePointers bool) string {
  816. switch s.Kind {
  817. case disco.SimpleKind:
  818. return mustSimpleTypeConvert(s.Type, s.Format)
  819. case disco.ArrayKind:
  820. as := s.ElementSchema()
  821. if as.Type == "string" {
  822. switch as.Format {
  823. case "int64":
  824. return "googleapi.Int64s"
  825. case "uint64":
  826. return "googleapi.Uint64s"
  827. case "int32":
  828. return "googleapi.Int32s"
  829. case "uint32":
  830. return "googleapi.Uint32s"
  831. case "float64":
  832. return "googleapi.Float64s"
  833. }
  834. }
  835. return "[]" + a.typeAsGo(as, elidePointers)
  836. case disco.ReferenceKind:
  837. rs := s.RefSchema
  838. if rs.Kind == disco.SimpleKind {
  839. // Simple top-level schemas get named types (see writeSchemaCode).
  840. // Use the name instead of using the equivalent simple Go type.
  841. return a.schemaNamed(rs.Name).GoName()
  842. }
  843. return a.typeAsGo(rs, elidePointers)
  844. case disco.MapKind:
  845. es := s.ElementSchema()
  846. if es.Type == "string" {
  847. // If the element schema has a type "string", it's going to be
  848. // transmitted as a string, and the Go map type must reflect that.
  849. // This is true even if the format is, say, "int64". When type =
  850. // "string" and format = "int64" at top level, we can use the json
  851. // "string" tag option to unmarshal the string to an int64, but
  852. // inside a map we can't.
  853. return "map[string]string"
  854. }
  855. // Due to historical baggage (maps used to be a separate code path),
  856. // the element types of maps never have pointers in them. From this
  857. // level down, elide pointers in types.
  858. return "map[string]" + a.typeAsGo(es, true)
  859. case disco.AnyStructKind:
  860. return "googleapi.RawMessage"
  861. case disco.StructKind:
  862. tls := a.schemaNamed(s.Name)
  863. if elidePointers || s.Variant != nil {
  864. return tls.GoName()
  865. }
  866. return "*" + tls.GoName()
  867. default:
  868. panic(fmt.Sprintf("unhandled typeAsGo for %+v", s))
  869. }
  870. }
  871. func (a *API) schemaNamed(name string) *Schema {
  872. s := a.schemas[name]
  873. if s == nil {
  874. panicf("no top-level schema named %q", name)
  875. }
  876. return s
  877. }
  878. func (s *Schema) properties() []*Property {
  879. if s.props != nil {
  880. return s.props
  881. }
  882. if s.typ.Kind != disco.StructKind {
  883. panic("called properties on non-object schema")
  884. }
  885. for _, p := range s.typ.Properties {
  886. s.props = append(s.props, &Property{
  887. s: s,
  888. p: p,
  889. })
  890. }
  891. return s.props
  892. }
  893. func (s *Schema) HasContentType() bool {
  894. for _, p := range s.properties() {
  895. if p.GoName() == "ContentType" && p.TypeAsGo() == "string" {
  896. return true
  897. }
  898. }
  899. return false
  900. }
  901. func (s *Schema) populateSubSchemas() (outerr error) {
  902. defer func() {
  903. r := recover()
  904. if r == nil {
  905. return
  906. }
  907. outerr = fmt.Errorf("%v", r)
  908. }()
  909. addSubStruct := func(subApiName string, t *disco.Schema) {
  910. if s.api.schemas[subApiName] != nil {
  911. panic("dup schema apiName: " + subApiName)
  912. }
  913. if t.Name != "" {
  914. panic("subtype already has name: " + t.Name)
  915. }
  916. t.Name = subApiName
  917. subs := &Schema{
  918. api: s.api,
  919. typ: t,
  920. apiName: subApiName,
  921. }
  922. s.api.schemas[subApiName] = subs
  923. err := subs.populateSubSchemas()
  924. if err != nil {
  925. panicf("in sub-struct %q: %v", subApiName, err)
  926. }
  927. }
  928. switch s.typ.Kind {
  929. case disco.StructKind:
  930. for _, p := range s.properties() {
  931. subApiName := fmt.Sprintf("%s.%s", s.apiName, p.p.Name)
  932. switch p.Type().Kind {
  933. case disco.SimpleKind, disco.ReferenceKind, disco.AnyStructKind:
  934. // Do nothing.
  935. case disco.MapKind:
  936. mt := p.Type().ElementSchema()
  937. if mt.Kind == disco.SimpleKind || mt.Kind == disco.ReferenceKind {
  938. continue
  939. }
  940. addSubStruct(subApiName, mt)
  941. case disco.ArrayKind:
  942. at := p.Type().ElementSchema()
  943. if at.Kind == disco.SimpleKind || at.Kind == disco.ReferenceKind {
  944. continue
  945. }
  946. addSubStruct(subApiName, at)
  947. case disco.StructKind:
  948. addSubStruct(subApiName, p.Type())
  949. default:
  950. panicf("Unknown type for %q: %s", subApiName, p.Type())
  951. }
  952. }
  953. case disco.ArrayKind:
  954. subApiName := fmt.Sprintf("%s.Item", s.apiName)
  955. switch at := s.typ.ElementSchema(); at.Kind {
  956. case disco.SimpleKind, disco.ReferenceKind, disco.AnyStructKind:
  957. // Do nothing.
  958. case disco.MapKind:
  959. mt := at.ElementSchema()
  960. if k := mt.Kind; k != disco.SimpleKind && k != disco.ReferenceKind {
  961. addSubStruct(subApiName, mt)
  962. }
  963. case disco.ArrayKind:
  964. at := at.ElementSchema()
  965. if k := at.Kind; k != disco.SimpleKind && k != disco.ReferenceKind {
  966. addSubStruct(subApiName, at)
  967. }
  968. case disco.StructKind:
  969. addSubStruct(subApiName, at)
  970. default:
  971. panicf("Unknown array type for %q: %s", subApiName, at)
  972. }
  973. case disco.AnyStructKind, disco.MapKind, disco.SimpleKind, disco.ReferenceKind:
  974. // Do nothing.
  975. default:
  976. fmt.Fprintf(os.Stderr, "in populateSubSchemas, schema is: %v", s.typ)
  977. panicf("populateSubSchemas: unsupported type for schema %q", s.apiName)
  978. panic("unreachable")
  979. }
  980. return nil
  981. }
  982. // GoName returns (or creates and returns) the bare Go name
  983. // of the apiName, making sure that it's a proper Go identifier
  984. // and doesn't conflict with an existing name.
  985. func (s *Schema) GoName() string {
  986. if s.goName == "" {
  987. if s.typ.Kind == disco.MapKind {
  988. s.goName = s.api.typeAsGo(s.typ, false)
  989. } else {
  990. base := initialCap(s.apiName)
  991. s.goName = s.api.GetName(base)
  992. if base == "Service" && s.goName != "Service" {
  993. // Detect the case where a resource is going to clash with the
  994. // root service object.
  995. panicf("Clash on name Service")
  996. }
  997. }
  998. }
  999. return s.goName
  1000. }
  1001. // GoReturnType returns the Go type to use as the return type.
  1002. // If a type is a struct, it will return *StructType,
  1003. // for a map it will return map[string]ValueType,
  1004. // for (not yet supported) slices it will return []ValueType.
  1005. func (s *Schema) GoReturnType() string {
  1006. if s.goReturnType == "" {
  1007. if s.typ.Kind == disco.MapKind {
  1008. s.goReturnType = s.GoName()
  1009. } else {
  1010. s.goReturnType = "*" + s.GoName()
  1011. }
  1012. }
  1013. return s.goReturnType
  1014. }
  1015. func (s *Schema) writeSchemaCode(api *API) {
  1016. switch s.typ.Kind {
  1017. case disco.SimpleKind:
  1018. apitype := s.typ.Type
  1019. typ := mustSimpleTypeConvert(apitype, s.typ.Format)
  1020. s.api.pn("\ntype %s %s", s.GoName(), typ)
  1021. case disco.StructKind:
  1022. s.writeSchemaStruct(api)
  1023. case disco.MapKind, disco.AnyStructKind:
  1024. // Do nothing.
  1025. case disco.ArrayKind:
  1026. log.Printf("TODO writeSchemaCode for arrays for %s", s.GoName())
  1027. default:
  1028. fmt.Fprintf(os.Stderr, "in writeSchemaCode, schema is: %+v", s.typ)
  1029. panicf("writeSchemaCode: unsupported type for schema %q", s.apiName)
  1030. }
  1031. }
  1032. func (s *Schema) writeVariant(api *API, v *disco.Variant) {
  1033. s.api.p("\ntype %s map[string]interface{}\n\n", s.GoName())
  1034. // Write out the "Type" method that identifies the variant type.
  1035. s.api.pn("func (t %s) Type() string {", s.GoName())
  1036. s.api.pn(" return googleapi.VariantType(t)")
  1037. s.api.p("}\n\n")
  1038. // Write out helper methods to convert each possible variant.
  1039. for _, m := range v.Map {
  1040. if m.TypeValue == "" && m.Ref == "" {
  1041. log.Printf("TODO variant %s ref %s not yet supported.", m.TypeValue, m.Ref)
  1042. continue
  1043. }
  1044. s.api.pn("func (t %s) %s() (r %s, ok bool) {", s.GoName(), initialCap(m.TypeValue), m.Ref)
  1045. s.api.pn(" if t.Type() != %q {", initialCap(m.TypeValue))
  1046. s.api.pn(" return r, false")
  1047. s.api.pn(" }")
  1048. s.api.pn(" ok = googleapi.ConvertVariant(map[string]interface{}(t), &r)")
  1049. s.api.pn(" return r, ok")
  1050. s.api.p("}\n\n")
  1051. }
  1052. }
  1053. func (s *Schema) Description() string {
  1054. return s.typ.Description
  1055. }
  1056. func (s *Schema) writeSchemaStruct(api *API) {
  1057. if v := s.typ.Variant; v != nil {
  1058. s.writeVariant(api, v)
  1059. return
  1060. }
  1061. s.api.p("\n")
  1062. des := s.Description()
  1063. if des != "" {
  1064. s.api.p("%s", asComment("", fmt.Sprintf("%s: %s", s.GoName(), des)))
  1065. }
  1066. s.api.pn("type %s struct {", s.GoName())
  1067. np := new(namePool)
  1068. forceSendName := np.Get("ForceSendFields")
  1069. nullFieldsName := np.Get("NullFields")
  1070. if s.isResponseType() {
  1071. np.Get("ServerResponse") // reserve the name
  1072. }
  1073. firstFieldName := "" // used to store a struct field name for use in documentation.
  1074. for i, p := range s.properties() {
  1075. if i > 0 {
  1076. s.api.p("\n")
  1077. }
  1078. pname := np.Get(p.GoName())
  1079. if pname[0] == '@' {
  1080. // HACK(cbro): ignore JSON-LD special fields until we can figure out
  1081. // the correct Go representation for them.
  1082. continue
  1083. }
  1084. p.assignedGoName = pname
  1085. des := p.Description()
  1086. if des != "" {
  1087. s.api.p("%s", asComment("\t", fmt.Sprintf("%s: %s", pname, des)))
  1088. }
  1089. addFieldValueComments(s.api.p, p, "\t", des != "")
  1090. var extraOpt string
  1091. if p.Type().IsIntAsString() {
  1092. extraOpt += ",string"
  1093. }
  1094. typ := p.TypeAsGo()
  1095. if p.forcePointerType() {
  1096. typ = "*" + typ
  1097. }
  1098. s.api.pn(" %s %s `json:\"%s,omitempty%s\"`", pname, typ, p.p.Name, extraOpt)
  1099. if firstFieldName == "" {
  1100. firstFieldName = pname
  1101. }
  1102. }
  1103. if s.isResponseType() {
  1104. if firstFieldName != "" {
  1105. s.api.p("\n")
  1106. }
  1107. s.api.p("%s", asComment("\t", "ServerResponse contains the HTTP response code and headers from the server."))
  1108. s.api.pn(" googleapi.ServerResponse `json:\"-\"`")
  1109. }
  1110. if firstFieldName == "" {
  1111. // There were no fields in the struct, so there is no point
  1112. // adding any custom JSON marshaling code.
  1113. s.api.pn("}")
  1114. return
  1115. }
  1116. commentFmtStr := "%s is a list of field names (e.g. %q) to " +
  1117. "unconditionally include in API requests. By default, fields " +
  1118. "with empty values are omitted from API requests. However, " +
  1119. "any non-pointer, non-interface field appearing in %s will " +
  1120. "be sent to the server regardless of whether the field is " +
  1121. "empty or not. This may be used to include empty fields in " +
  1122. "Patch requests."
  1123. comment := fmt.Sprintf(commentFmtStr, forceSendName, firstFieldName, forceSendName)
  1124. s.api.p("\n")
  1125. s.api.p("%s", asComment("\t", comment))
  1126. s.api.pn("\t%s []string `json:\"-\"`", forceSendName)
  1127. commentFmtStr = "%s is a list of field names (e.g. %q) to " +
  1128. "include in API requests with the JSON null value. " +
  1129. "By default, fields with empty values are omitted from API requests. However, " +
  1130. "any field with an empty value appearing in %s will be sent to the server as null. " +
  1131. "It is an error if a field in this list has a non-empty value. This may be used to " +
  1132. "include null fields in Patch requests."
  1133. comment = fmt.Sprintf(commentFmtStr, nullFieldsName, firstFieldName, nullFieldsName)
  1134. s.api.p("\n")
  1135. s.api.p("%s", asComment("\t", comment))
  1136. s.api.pn("\t%s []string `json:\"-\"`", nullFieldsName)
  1137. s.api.pn("}")
  1138. s.writeSchemaMarshal(forceSendName, nullFieldsName)
  1139. s.writeSchemaUnmarshal()
  1140. }
  1141. // writeSchemaMarshal writes a custom MarshalJSON function for s, which allows
  1142. // fields to be explicitly transmitted by listing them in the field identified
  1143. // by forceSendFieldName, and allows fields to be transmitted with the null value
  1144. // by listing them in the field identified by nullFieldsName.
  1145. func (s *Schema) writeSchemaMarshal(forceSendFieldName, nullFieldsName string) {
  1146. s.api.pn("func (s *%s) MarshalJSON() ([]byte, error) {", s.GoName())
  1147. s.api.pn("\ttype NoMethod %s", s.GoName())
  1148. // pass schema as methodless type to prevent subsequent calls to MarshalJSON from recursing indefinitely.
  1149. s.api.pn("\traw := NoMethod(*s)")
  1150. s.api.pn("\treturn gensupport.MarshalJSON(raw, s.%s, s.%s)", forceSendFieldName, nullFieldsName)
  1151. s.api.pn("}")
  1152. }
  1153. func (s *Schema) writeSchemaUnmarshal() {
  1154. var floatProps []*Property
  1155. for _, p := range s.properties() {
  1156. if p.p.Schema.Type == "number" {
  1157. floatProps = append(floatProps, p)
  1158. }
  1159. }
  1160. if len(floatProps) == 0 {
  1161. return
  1162. }
  1163. pn := s.api.pn
  1164. pn("\nfunc (s *%s) UnmarshalJSON(data []byte) error {", s.GoName())
  1165. pn(" type NoMethod %s", s.GoName()) // avoid infinite recursion
  1166. pn(" var s1 struct {")
  1167. // Hide the float64 fields of the schema with fields that correctly
  1168. // unmarshal special values.
  1169. for _, p := range floatProps {
  1170. typ := "gensupport.JSONFloat64"
  1171. if p.forcePointerType() {
  1172. typ = "*" + typ
  1173. }
  1174. pn("%s %s `json:\"%s\"`", p.assignedGoName, typ, p.p.Name)
  1175. }
  1176. pn(" *NoMethod") // embed the schema
  1177. pn(" }")
  1178. // Set the schema value into the wrapper so its other fields are unmarshaled.
  1179. pn(" s1.NoMethod = (*NoMethod)(s)")
  1180. pn(" if err := json.Unmarshal(data, &s1); err != nil {")
  1181. pn(" return err")
  1182. pn(" }")
  1183. // Copy each shadowing field into the field it shadows.
  1184. for _, p := range floatProps {
  1185. n := p.assignedGoName
  1186. if p.forcePointerType() {
  1187. pn("if s1.%s != nil { s.%s = (*float64)(s1.%s) }", n, n, n)
  1188. } else {
  1189. pn("s.%s = float64(s1.%s)", n, n)
  1190. }
  1191. }
  1192. pn(" return nil")
  1193. pn("}")
  1194. }
  1195. // isResponseType returns true for all types that are used as a response.
  1196. func (s *Schema) isResponseType() bool {
  1197. return s.api.responseTypes["*"+s.goName]
  1198. }
  1199. // PopulateSchemas reads all the API types ("schemas") from the JSON file
  1200. // and converts them to *Schema instances, returning an identically
  1201. // keyed map, additionally containing subresources. For instance,
  1202. //
  1203. // A resource "Foo" of type "object" with a property "bar", also of type
  1204. // "object" (an anonymous sub-resource), will get a synthetic API name
  1205. // of "Foo.bar".
  1206. //
  1207. // A resource "Foo" of type "array" with an "items" of type "object"
  1208. // will get a synthetic API name of "Foo.Item".
  1209. func (a *API) PopulateSchemas() {
  1210. if a.schemas != nil {
  1211. panic("")
  1212. }
  1213. a.schemas = make(map[string]*Schema)
  1214. for name, ds := range a.doc.Schemas {
  1215. s := &Schema{
  1216. api: a,
  1217. apiName: name,
  1218. typ: ds,
  1219. }
  1220. a.schemas[name] = s
  1221. err := s.populateSubSchemas()
  1222. if err != nil {
  1223. panicf("Error populating schema with API name %q: %v", name, err)
  1224. }
  1225. }
  1226. }
  1227. func (a *API) generateResource(r *disco.Resource) {
  1228. pn := a.pn
  1229. t := resourceGoType(r)
  1230. pn(fmt.Sprintf("func New%s(s *%s) *%s {", t, a.ServiceType(), t))
  1231. pn("rs := &%s{s : s}", t)
  1232. for _, res := range r.Resources {
  1233. pn("rs.%s = New%s(s)", resourceGoField(res), resourceGoType(res))
  1234. }
  1235. pn("return rs")
  1236. pn("}")
  1237. pn("\ntype %s struct {", t)
  1238. pn(" s *%s", a.ServiceType())
  1239. for _, res := range r.Resources {
  1240. pn("\n\t%s\t*%s", resourceGoField(res), resourceGoType(res))
  1241. }
  1242. pn("}")
  1243. for _, res := range r.Resources {
  1244. a.generateResource(res)
  1245. }
  1246. }
  1247. func (a *API) cacheResourceResponseTypes(r *disco.Resource) {
  1248. for _, meth := range a.resourceMethods(r) {
  1249. meth.cacheResponseTypes(a)
  1250. }
  1251. for _, res := range r.Resources {
  1252. a.cacheResourceResponseTypes(res)
  1253. }
  1254. }
  1255. func (a *API) generateResourceMethods(r *disco.Resource) {
  1256. for _, meth := range a.resourceMethods(r) {
  1257. meth.generateCode()
  1258. }
  1259. for _, res := range r.Resources {
  1260. a.generateResourceMethods(res)
  1261. }
  1262. }
  1263. func resourceGoField(r *disco.Resource) string {
  1264. return initialCap(r.Name)
  1265. }
  1266. func resourceGoType(r *disco.Resource) string {
  1267. return initialCap(r.FullName + "Service")
  1268. }
  1269. func (a *API) resourceMethods(r *disco.Resource) []*Method {
  1270. ms := []*Method{}
  1271. for _, m := range r.Methods {
  1272. ms = append(ms, &Method{
  1273. api: a,
  1274. r: r,
  1275. m: m,
  1276. })
  1277. }
  1278. return ms
  1279. }
  1280. type Method struct {
  1281. api *API
  1282. r *disco.Resource // or nil if a API-level (top-level) method
  1283. m *disco.Method
  1284. params []*Param // all Params, of each type, lazily set by first access to Parameters
  1285. }
  1286. func (m *Method) Id() string {
  1287. return m.m.ID
  1288. }
  1289. func (m *Method) responseType() *Schema {
  1290. return m.api.schemas[m.m.Response.RefSchema.Name]
  1291. }
  1292. func (m *Method) supportsMediaUpload() bool {
  1293. return m.m.MediaUpload != nil
  1294. }
  1295. func (m *Method) mediaUploadPath() string {
  1296. return m.m.MediaUpload.Protocols["simple"].Path
  1297. }
  1298. func (m *Method) supportsMediaDownload() bool {
  1299. if m.supportsMediaUpload() {
  1300. // storage.objects.insert claims support for download in
  1301. // addition to upload but attempting to do so fails.
  1302. // This situation doesn't apply to any other methods.
  1303. return false
  1304. }
  1305. return m.m.SupportsMediaDownload
  1306. }
  1307. func (m *Method) supportsPaging() (*pageTokenGenerator, string, bool) {
  1308. ptg := m.pageTokenGenerator()
  1309. if ptg == nil {
  1310. return nil, "", false
  1311. }
  1312. // Check that the response type has the next page token.
  1313. s := m.responseType()
  1314. if s == nil || s.typ.Kind != disco.StructKind {
  1315. return nil, "", false
  1316. }
  1317. for _, prop := range s.properties() {
  1318. if isPageTokenName(prop.p.Name) && prop.Type().Type == "string" {
  1319. return ptg, prop.GoName(), true
  1320. }
  1321. }
  1322. return nil, "", false
  1323. }
  1324. type pageTokenGenerator struct {
  1325. isParam bool // is the page token a URL parameter?
  1326. name string // param or request field name
  1327. requestName string // empty for URL param
  1328. }
  1329. func (p *pageTokenGenerator) genGet() string {
  1330. if p.isParam {
  1331. return fmt.Sprintf("c.urlParams_.Get(%q)", p.name)
  1332. }
  1333. return fmt.Sprintf("c.%s.%s", p.requestName, p.name)
  1334. }
  1335. func (p *pageTokenGenerator) genSet(valueExpr string) string {
  1336. if p.isParam {
  1337. return fmt.Sprintf("c.%s(%s)", initialCap(p.name), valueExpr)
  1338. }
  1339. return fmt.Sprintf("c.%s.%s = %s", p.requestName, p.name, valueExpr)
  1340. }
  1341. func (p *pageTokenGenerator) genDeferBody() string {
  1342. if p.isParam {
  1343. return p.genSet(p.genGet())
  1344. }
  1345. return fmt.Sprintf("func (pt string) { %s }(%s)", p.genSet("pt"), p.genGet())
  1346. }
  1347. // pageTokenGenerator returns a pageTokenGenerator that will generate code to
  1348. // get/set the page token for a subsequent page in the context of the generated
  1349. // Pages method. It returns nil if there is no page token.
  1350. func (m *Method) pageTokenGenerator() *pageTokenGenerator {
  1351. matches := m.grepParams(func(p *Param) bool { return isPageTokenName(p.p.Name) })
  1352. switch len(matches) {
  1353. case 1:
  1354. if matches[0].p.Required {
  1355. // The page token is a required parameter (e.g. because there is
  1356. // a separate API call to start an iteration), and so the relevant
  1357. // call factory method takes the page token instead.
  1358. return nil
  1359. }
  1360. n := matches[0].p.Name
  1361. return &pageTokenGenerator{true, n, ""}
  1362. case 0: // No URL parameter, but maybe a request field.
  1363. if m.m.Request == nil {
  1364. return nil
  1365. }
  1366. rs := m.m.Request
  1367. if rs.RefSchema != nil {
  1368. rs = rs.RefSchema
  1369. }
  1370. for _, p := range rs.Properties {
  1371. if isPageTokenName(p.Name) {
  1372. return &pageTokenGenerator{false, initialCap(p.Name), validGoIdentifer(strings.ToLower(rs.Name))}
  1373. }
  1374. }
  1375. return nil
  1376. default:
  1377. panicf("too many page token parameters for method %s", m.m.Name)
  1378. return nil
  1379. }
  1380. }
  1381. func isPageTokenName(s string) bool {
  1382. return s == "pageToken" || s == "nextPageToken"
  1383. }
  1384. func (m *Method) Params() []*Param {
  1385. if m.params == nil {
  1386. for _, p := range m.m.Parameters {
  1387. m.params = append(m.params, &Param{
  1388. method: m,
  1389. p: p,
  1390. })
  1391. }
  1392. }
  1393. return m.params
  1394. }
  1395. func (m *Method) grepParams(f func(*Param) bool) []*Param {
  1396. matches := make([]*Param, 0)
  1397. for _, param := range m.Params() {
  1398. if f(param) {
  1399. matches = append(matches, param)
  1400. }
  1401. }
  1402. return matches
  1403. }
  1404. func (m *Method) NamedParam(name string) *Param {
  1405. matches := m.grepParams(func(p *Param) bool {
  1406. return p.p.Name == name
  1407. })
  1408. if len(matches) < 1 {
  1409. log.Panicf("failed to find named parameter %q", name)
  1410. }
  1411. if len(matches) > 1 {
  1412. log.Panicf("found multiple parameters for parameter name %q", name)
  1413. }
  1414. return matches[0]
  1415. }
  1416. func (m *Method) OptParams() []*Param {
  1417. return m.grepParams(func(p *Param) bool {
  1418. return !p.p.Required
  1419. })
  1420. }
  1421. func (meth *Method) cacheResponseTypes(api *API) {
  1422. if retType := responseType(api, meth.m); retType != "" && strings.HasPrefix(retType, "*") {
  1423. api.responseTypes[retType] = true
  1424. }
  1425. }
  1426. // convertMultiParams builds a []string temp variable from a slice
  1427. // of non-strings and returns the name of the temp variable.
  1428. func convertMultiParams(a *API, param string) string {
  1429. a.pn(" var %v_ []string", param)
  1430. a.pn(" for _, v := range %v {", param)
  1431. a.pn(" %v_ = append(%v_, fmt.Sprint(v))", param, param)
  1432. a.pn(" }")
  1433. return param + "_"
  1434. }
  1435. func (meth *Method) generateCode() {
  1436. res := meth.r // may be nil if a top-level method
  1437. a := meth.api
  1438. p, pn := a.p, a.pn
  1439. pn("\n// method id %q:", meth.Id())
  1440. retType := responseType(a, meth.m)
  1441. retTypeComma := retType
  1442. if retTypeComma != "" {
  1443. retTypeComma += ", "
  1444. }
  1445. args := meth.NewArguments()
  1446. methodName := initialCap(meth.m.Name)
  1447. prefix := ""
  1448. if res != nil {
  1449. prefix = initialCap(res.FullName)
  1450. }
  1451. callName := a.GetName(prefix + methodName + "Call")
  1452. pn("\ntype %s struct {", callName)
  1453. pn(" s *%s", a.ServiceType())
  1454. for _, arg := range args.l {
  1455. if arg.location != "query" {
  1456. pn(" %s %s", arg.goname, arg.gotype)
  1457. }
  1458. }
  1459. pn(" urlParams_ gensupport.URLParams")
  1460. httpMethod := meth.m.HTTPMethod
  1461. if httpMethod == "GET" {
  1462. pn(" ifNoneMatch_ string")
  1463. }
  1464. if meth.supportsMediaUpload() {
  1465. pn(" mediaInfo_ *gensupport.MediaInfo")
  1466. }
  1467. pn(" ctx_ context.Context")
  1468. pn(" header_ http.Header")
  1469. pn("}")
  1470. p("\n%s", asComment("", methodName+": "+meth.m.Description))
  1471. if res != nil {
  1472. if url := canonicalDocsURL[fmt.Sprintf("%v%v/%v", docsLink, res.Name, meth.m.Name)]; url != "" {
  1473. pn("// For details, see %v", url)
  1474. }
  1475. }
  1476. var servicePtr string
  1477. if res == nil {
  1478. pn("func (s *Service) %s(%s) *%s {", methodName, args, callName)
  1479. servicePtr = "s"
  1480. } else {
  1481. pn("func (r *%s) %s(%s) *%s {", resourceGoType(res), methodName, args, callName)
  1482. servicePtr = "r.s"
  1483. }
  1484. pn(" c := &%s{s: %s, urlParams_: make(gensupport.URLParams)}", callName, servicePtr)
  1485. for _, arg := range args.l {
  1486. // TODO(gmlewis): clean up and consolidate this section.
  1487. // See: https://code-review.googlesource.com/#/c/3520/18/google-api-go-generator/gen.go
  1488. if arg.location == "query" {
  1489. switch arg.gotype {
  1490. case "[]string":
  1491. pn(" c.urlParams_.SetMulti(%q, append([]string{}, %v...))", arg.apiname, arg.goname)
  1492. case "string":
  1493. pn(" c.urlParams_.Set(%q, %v)", arg.apiname, arg.goname)
  1494. default:
  1495. if strings.HasPrefix(arg.gotype, "[]") {
  1496. tmpVar := convertMultiParams(a, arg.goname)
  1497. pn(" c.urlParams_.SetMulti(%q, %v)", arg.apiname, tmpVar)
  1498. } else {
  1499. pn(" c.urlParams_.Set(%q, fmt.Sprint(%v))", arg.apiname, arg.goname)
  1500. }
  1501. }
  1502. continue
  1503. }
  1504. if arg.gotype == "[]string" {
  1505. pn(" c.%s = append([]string{}, %s...)", arg.goname, arg.goname) // Make a copy of the []string.
  1506. continue
  1507. }
  1508. pn(" c.%s = %s", arg.goname, arg.goname)
  1509. }
  1510. pn(" return c")
  1511. pn("}")
  1512. for _, opt := range meth.OptParams() {
  1513. if opt.p.Location != "query" {
  1514. panicf("optional parameter has unsupported location %q", opt.p.Location)
  1515. }
  1516. setter := initialCap(opt.p.Name)
  1517. des := opt.p.Description
  1518. des = strings.Replace(des, "Optional.", "", 1)
  1519. des = strings.TrimSpace(des)
  1520. p("\n%s", asComment("", fmt.Sprintf("%s sets the optional parameter %q: %s", setter, opt.p.Name, des)))
  1521. addFieldValueComments(p, opt, "", true)
  1522. np := new(namePool)
  1523. np.Get("c") // take the receiver's name
  1524. paramName := np.Get(validGoIdentifer(opt.p.Name))
  1525. typePrefix := ""
  1526. if opt.p.Repeated {
  1527. typePrefix = "..."
  1528. }
  1529. pn("func (c *%s) %s(%s %s%s) *%s {", callName, setter, paramName, typePrefix, opt.GoType(), callName)
  1530. if opt.p.Repeated {
  1531. if opt.GoType() == "string" {
  1532. pn("c.urlParams_.SetMulti(%q, append([]string{}, %v...))", opt.p.Name, paramName)
  1533. } else {
  1534. tmpVar := convertMultiParams(a, paramName)
  1535. pn(" c.urlParams_.SetMulti(%q, %v)", opt.p.Name, tmpVar)
  1536. }
  1537. } else {
  1538. if opt.GoType() == "string" {
  1539. pn("c.urlParams_.Set(%q, %v)", opt.p.Name, paramName)
  1540. } else {
  1541. pn("c.urlParams_.Set(%q, fmt.Sprint(%v))", opt.p.Name, paramName)
  1542. }
  1543. }
  1544. pn("return c")
  1545. pn("}")
  1546. }
  1547. if meth.supportsMediaUpload() {
  1548. comment := "Media specifies the media to upload in one or more chunks. " +
  1549. "The chunk size may be controlled by supplying a MediaOption generated by googleapi.ChunkSize. " +
  1550. "The chunk size defaults to googleapi.DefaultUploadChunkSize." +
  1551. "The Content-Type header used in the upload request will be determined by sniffing the contents of r, " +
  1552. "unless a MediaOption generated by googleapi.ContentType is supplied." +
  1553. "\nAt most one of Media and ResumableMedia may be set."
  1554. // TODO(mcgreevy): Ensure that r is always closed before Do returns, and document this.
  1555. // See comments on https://code-review.googlesource.com/#/c/3970/
  1556. p("\n%s", asComment("", comment))
  1557. pn("func (c *%s) Media(r io.Reader, options ...googleapi.MediaOption) *%s {", callName, callName)
  1558. // We check if the body arg, if any, has a content type and apply it here.
  1559. // In practice, this only happens for the storage API today.
  1560. // TODO(djd): check if we can cope with the developer setting the body's Content-Type field
  1561. // after they've made this call.
  1562. if ba := args.bodyArg(); ba != nil {
  1563. if ba.schema.HasContentType() {
  1564. pn(" if ct := c.%s.ContentType; ct != \"\" {", ba.goname)
  1565. pn(" options = append([]googleapi.MediaOption{googleapi.ContentType(ct)}, options...)")
  1566. pn(" }")
  1567. }
  1568. }
  1569. pn(" c.mediaInfo_ = gensupport.NewInfoFromMedia(r, options)")
  1570. pn(" return c")
  1571. pn("}")
  1572. comment = "ResumableMedia specifies the media to upload in chunks and can be canceled with ctx. " +
  1573. "\n\nDeprecated: use Media instead." +
  1574. "\n\nAt most one of Media and ResumableMedia may be set. " +
  1575. `mediaType identifies the MIME media type of the upload, such as "image/png". ` +
  1576. `If mediaType is "", it will be auto-detected. ` +
  1577. `The provided ctx will supersede any context previously provided to ` +
  1578. `the Context method.`
  1579. p("\n%s", asComment("", comment))
  1580. pn("func (c *%s) ResumableMedia(ctx context.Context, r io.ReaderAt, size int64, mediaType string) *%s {", callName, callName)
  1581. pn(" c.ctx_ = ctx")
  1582. pn(" c.mediaInfo_ = gensupport.NewInfoFromResumableMedia(r, size, mediaType)")
  1583. pn(" return c")
  1584. pn("}")
  1585. comment = "ProgressUpdater provides a callback function that will be called after every chunk. " +
  1586. "It should be a low-latency function in order to not slow down the upload operation. " +
  1587. "This should only be called when using ResumableMedia (as opposed to Media)."
  1588. p("\n%s", asComment("", comment))
  1589. pn("func (c *%s) ProgressUpdater(pu googleapi.ProgressUpdater) *%s {", callName, callName)
  1590. pn(`c.mediaInfo_.SetProgressUpdater(pu)`)
  1591. pn("return c")
  1592. pn("}")
  1593. }
  1594. comment := "Fields allows partial responses to be retrieved. " +
  1595. "See https://developers.google.com/gdata/docs/2.0/basics#PartialResponse " +
  1596. "for more information."
  1597. p("\n%s", asComment("", comment))
  1598. pn("func (c *%s) Fields(s ...googleapi.Field) *%s {", callName, callName)
  1599. pn(`c.urlParams_.Set("fields", googleapi.CombineFields(s))`)
  1600. pn("return c")
  1601. pn("}")
  1602. if httpMethod == "GET" {
  1603. // Note that non-GET responses are excluded from supporting If-None-Match.
  1604. // See https://github.com/google/google-api-go-client/issues/107 for more info.
  1605. comment := "IfNoneMatch sets the optional parameter which makes the operation fail if " +
  1606. "the object's ETag matches the given value. This is useful for getting updates " +
  1607. "only after the object has changed since the last request. " +
  1608. "Use googleapi.IsNotModified to check whether the response error from Do " +
  1609. "is the result of In-None-Match."
  1610. p("\n%s", asComment("", comment))
  1611. pn("func (c *%s) IfNoneMatch(entityTag string) *%s {", callName, callName)
  1612. pn(" c.ifNoneMatch_ = entityTag")
  1613. pn(" return c")
  1614. pn("}")
  1615. }
  1616. doMethod := "Do method"
  1617. if meth.supportsMediaDownload() {
  1618. doMethod = "Do and Download methods"
  1619. }
  1620. commentFmtStr := "Context sets the context to be used in this call's %s. " +
  1621. "Any pending HTTP request will be aborted if the provided context is canceled."
  1622. comment = fmt.Sprintf(commentFmtStr, doMethod)
  1623. p("\n%s", asComment("", comment))
  1624. if meth.supportsMediaUpload() {
  1625. comment = "This context will supersede any context previously provided to " +
  1626. "the ResumableMedia method."
  1627. p("%s", asComment("", comment))
  1628. }
  1629. pn("func (c *%s) Context(ctx context.Context) *%s {", callName, callName)
  1630. pn(`c.ctx_ = ctx`)
  1631. pn("return c")
  1632. pn("}")
  1633. comment = "Header returns an http.Header that can be modified by the caller to add " +
  1634. "HTTP headers to the request."
  1635. p("\n%s", asComment("", comment))
  1636. pn("func (c *%s) Header() http.Header {", callName)
  1637. pn(" if c.header_ == nil {")
  1638. pn(" c.header_ = make(http.Header)")
  1639. pn(" }")
  1640. pn(" return c.header_")
  1641. pn("}")
  1642. pn("\nfunc (c *%s) doRequest(alt string) (*http.Response, error) {", callName)
  1643. pn(`reqHeaders := make(http.Header)`)
  1644. pn("for k, v := range c.header_ {")
  1645. pn(" reqHeaders[k] = v")
  1646. pn("}")
  1647. pn(`reqHeaders.Set("User-Agent",c.s.userAgent())`)
  1648. if httpMethod == "GET" {
  1649. pn(`if c.ifNoneMatch_ != "" {`)
  1650. pn(` reqHeaders.Set("If-None-Match", c.ifNoneMatch_)`)
  1651. pn("}")
  1652. }
  1653. pn("var body io.Reader = nil")
  1654. if ba := args.bodyArg(); ba != nil && httpMethod != "GET" {
  1655. style := "WithoutDataWrapper"
  1656. if a.needsDataWrapper() {
  1657. style = "WithDataWrapper"
  1658. }
  1659. pn("body, err := googleapi.%s.JSONReader(c.%s)", style, ba.goname)
  1660. pn("if err != nil { return nil, err }")
  1661. pn(`reqHeaders.Set("Content-Type", "application/json")`)
  1662. }
  1663. pn(`c.urlParams_.Set("alt", alt)`)
  1664. pn("urls := googleapi.ResolveRelative(c.s.BasePath, %q)", meth.m.Path)
  1665. if meth.supportsMediaUpload() {
  1666. pn("if c.mediaInfo_ != nil {")
  1667. // Hack guess, since we get a 404 otherwise:
  1668. //pn("urls = googleapi.ResolveRelative(%q, %q)", a.apiBaseURL(), meth.mediaUploadPath())
  1669. // Further hack. Discovery doc is wrong?
  1670. pn(" urls = strings.Replace(urls, %q, %q, 1)", "https://www.googleapis.com/", "https://www.googleapis.com/upload/")
  1671. pn(` c.urlParams_.Set("uploadType", c.mediaInfo_.UploadType())`)
  1672. pn("}")
  1673. pn("if body == nil {")
  1674. pn(" body = new(bytes.Buffer)")
  1675. pn(` reqHeaders.Set("Content-Type", "application/json")`)
  1676. pn("}")
  1677. pn("body, getBody, cleanup := c.mediaInfo_.UploadRequest(reqHeaders, body)")
  1678. pn("defer cleanup()")
  1679. }
  1680. pn("urls += \"?\" + c.urlParams_.Encode()")
  1681. pn("req, _ := http.NewRequest(%q, urls, body)", httpMethod)
  1682. pn("req.Header = reqHeaders")
  1683. if meth.supportsMediaUpload() {
  1684. pn("gensupport.SetGetBody(req, getBody)")
  1685. }
  1686. // Replace param values after NewRequest to avoid reencoding them.
  1687. // E.g. Cloud Storage API requires '%2F' in entity param to be kept, but url.Parse replaces it with '/'.
  1688. argsForLocation := args.forLocation("path")
  1689. if len(argsForLocation) > 0 {
  1690. pn(`googleapi.Expand(req.URL, map[string]string{`)
  1691. for _, arg := range argsForLocation {
  1692. pn(`"%s": %s,`, arg.apiname, arg.exprAsString("c."))
  1693. }
  1694. pn(`})`)
  1695. }
  1696. pn("return gensupport.SendRequest(c.ctx_, c.s.client, req)")
  1697. pn("}")
  1698. if meth.supportsMediaDownload() {
  1699. pn("\n// Download fetches the API endpoint's \"media\" value, instead of the normal")
  1700. pn("// API response value. If the returned error is nil, the Response is guaranteed to")
  1701. pn("// have a 2xx status code. Callers must close the Response.Body as usual.")
  1702. pn("func (c *%s) Download(opts ...googleapi.CallOption) (*http.Response, error) {", callName)
  1703. pn(`gensupport.SetOptions(c.urlParams_, opts...)`)
  1704. pn(`res, err := c.doRequest("media")`)
  1705. pn("if err != nil { return nil, err }")
  1706. pn("if err := googleapi.CheckMediaResponse(res); err != nil {")
  1707. pn("res.Body.Close()")
  1708. pn("return nil, err")
  1709. pn("}")
  1710. pn("return res, nil")
  1711. pn("}")
  1712. }
  1713. mapRetType := strings.HasPrefix(retTypeComma, "map[")
  1714. pn("\n// Do executes the %q call.", meth.m.ID)
  1715. if retTypeComma != "" && !mapRetType {
  1716. commentFmtStr := "Exactly one of %v or error will be non-nil. " +
  1717. "Any non-2xx status code is an error. " +
  1718. "Response headers are in either %v.ServerResponse.Header " +
  1719. "or (if a response was returned at all) in error.(*googleapi.Error).Header. " +
  1720. "Use googleapi.IsNotModified to check whether the returned error was because " +
  1721. "http.StatusNotModified was returned."
  1722. comment := fmt.Sprintf(commentFmtStr, retType, retType)
  1723. p("%s", asComment("", comment))
  1724. }
  1725. pn("func (c *%s) Do(opts ...googleapi.CallOption) (%serror) {", callName, retTypeComma)
  1726. nilRet := ""
  1727. if retTypeComma != "" {
  1728. nilRet = "nil, "
  1729. }
  1730. pn(`gensupport.SetOptions(c.urlParams_, opts...)`)
  1731. pn(`res, err := c.doRequest("json")`)
  1732. if retTypeComma != "" && !mapRetType {
  1733. pn("if res != nil && res.StatusCode == http.StatusNotModified {")
  1734. pn(" if res.Body != nil { res.Body.Close() }")
  1735. pn(" return nil, &googleapi.Error{")
  1736. pn(" Code: res.StatusCode,")
  1737. pn(" Header: res.Header,")
  1738. pn(" }")
  1739. pn("}")
  1740. }
  1741. pn("if err != nil { return %serr }", nilRet)
  1742. pn("defer googleapi.CloseBody(res)")
  1743. pn("if err := googleapi.CheckResponse(res); err != nil { return %serr }", nilRet)
  1744. if meth.supportsMediaUpload() {
  1745. pn(`rx := c.mediaInfo_.ResumableUpload(res.Header.Get("Location"))`)
  1746. pn("if rx != nil {")
  1747. pn(" rx.Client = c.s.client")
  1748. pn(" rx.UserAgent = c.s.userAgent()")
  1749. pn(" ctx := c.ctx_")
  1750. pn(" if ctx == nil {")
  1751. // TODO(mcgreevy): Require context when calling Media, or Do.
  1752. pn(" ctx = context.TODO()")
  1753. pn(" }")
  1754. pn(" res, err = rx.Upload(ctx)")
  1755. pn(" if err != nil { return %serr }", nilRet)
  1756. pn(" defer res.Body.Close()")
  1757. pn(" if err := googleapi.CheckResponse(res); err != nil { return %serr }", nilRet)
  1758. pn("}")
  1759. }
  1760. if retTypeComma == "" {
  1761. pn("return nil")
  1762. } else {
  1763. if mapRetType {
  1764. pn("var ret %s", responseType(a, meth.m))
  1765. } else {
  1766. pn("ret := &%s{", responseTypeLiteral(a, meth.m))
  1767. pn(" ServerResponse: googleapi.ServerResponse{")
  1768. pn(" Header: res.Header,")
  1769. pn(" HTTPStatusCode: res.StatusCode,")
  1770. pn(" },")
  1771. pn("}")
  1772. }
  1773. if a.needsDataWrapper() {
  1774. pn("target := &struct {")
  1775. pn(" Data %s `json:\"data\"`", responseType(a, meth.m))
  1776. pn("}{ret}")
  1777. } else {
  1778. pn("target := &ret")
  1779. }
  1780. pn("if err := gensupport.DecodeResponse(target, res); err != nil { return nil, err }")
  1781. pn("return ret, nil")
  1782. }
  1783. bs, _ := json.MarshalIndent(meth.m.JSONMap, "\t// ", " ")
  1784. pn("// %s\n", string(bs))
  1785. pn("}")
  1786. if ptg, rname, ok := meth.supportsPaging(); ok {
  1787. // We can assume retType is non-empty.
  1788. pn("")
  1789. pn("// Pages invokes f for each page of results.")
  1790. pn("// A non-nil error returned from f will halt the iteration.")
  1791. pn("// The provided context supersedes any context provided to the Context method.")
  1792. pn("func (c *%s) Pages(ctx context.Context, f func(%s) error) error {", callName, retType)
  1793. pn(" c.ctx_ = ctx")
  1794. pn(` defer %s // reset paging to original point`, ptg.genDeferBody())
  1795. pn(" for {")
  1796. pn(" x, err := c.Do()")
  1797. pn(" if err != nil { return err }")
  1798. pn(" if err := f(x); err != nil { return err }")
  1799. pn(` if x.%s == "" { return nil }`, rname)
  1800. pn(ptg.genSet("x." + rname))
  1801. pn(" }")
  1802. pn("}")
  1803. }
  1804. }
  1805. // A Field provides methods that describe the characteristics of a Param or Property.
  1806. type Field interface {
  1807. Default() string
  1808. Enum() ([]string, bool)
  1809. EnumDescriptions() []string
  1810. UnfortunateDefault() bool
  1811. }
  1812. type Param struct {
  1813. method *Method
  1814. p *disco.Parameter
  1815. callFieldName string // empty means to use the default
  1816. }
  1817. func (p *Param) Default() string {
  1818. return p.p.Default
  1819. }
  1820. func (p *Param) Enum() ([]string, bool) {
  1821. if e := p.p.Enums; e != nil {
  1822. return e, true
  1823. }
  1824. return nil, false
  1825. }
  1826. func (p *Param) EnumDescriptions() []string {
  1827. return p.p.EnumDescriptions
  1828. }
  1829. func (p *Param) UnfortunateDefault() bool {
  1830. // We do not do anything special for Params with unfortunate defaults.
  1831. return false
  1832. }
  1833. func (p *Param) GoType() string {
  1834. typ, format := p.p.Type, p.p.Format
  1835. if typ == "string" && strings.Contains(format, "int") && p.p.Location != "query" {
  1836. panic("unexpected int parameter encoded as string, not in query: " + p.p.Name)
  1837. }
  1838. t, ok := simpleTypeConvert(typ, format)
  1839. if !ok {
  1840. panic("failed to convert parameter type " + fmt.Sprintf("type=%q, format=%q", typ, format))
  1841. }
  1842. return t
  1843. }
  1844. // goCallFieldName returns the name of this parameter's field in a
  1845. // method's "Call" struct.
  1846. func (p *Param) goCallFieldName() string {
  1847. if p.callFieldName != "" {
  1848. return p.callFieldName
  1849. }
  1850. return validGoIdentifer(p.p.Name)
  1851. }
  1852. // APIMethods returns top-level ("API-level") methods. They don't have an associated resource.
  1853. func (a *API) APIMethods() []*Method {
  1854. meths := []*Method{}
  1855. for _, m := range a.doc.Methods {
  1856. meths = append(meths, &Method{
  1857. api: a,
  1858. r: nil, // to be explicit
  1859. m: m,
  1860. })
  1861. }
  1862. return meths
  1863. }
  1864. func resolveRelative(basestr, relstr string) string {
  1865. u, err := url.Parse(basestr)
  1866. if err != nil {
  1867. panicf("Error parsing base URL %q: %v", basestr, err)
  1868. }
  1869. rel, err := url.Parse(relstr)
  1870. if err != nil {
  1871. panicf("Error parsing relative URL %q: %v", relstr, err)
  1872. }
  1873. u = u.ResolveReference(rel)
  1874. return u.String()
  1875. }
  1876. func (meth *Method) NewArguments() (args *arguments) {
  1877. args = &arguments{
  1878. method: meth,
  1879. m: make(map[string]*argument),
  1880. }
  1881. po := meth.m.ParameterOrder
  1882. if len(po) > 0 {
  1883. for _, pname := range po {
  1884. arg := meth.NewArg(pname, meth.NamedParam(pname))
  1885. args.AddArg(arg)
  1886. }
  1887. }
  1888. if rs := meth.m.Request; rs != nil {
  1889. args.AddArg(meth.NewBodyArg(rs))
  1890. }
  1891. return
  1892. }
  1893. func (meth *Method) NewBodyArg(ds *disco.Schema) *argument {
  1894. s := meth.api.schemaNamed(ds.RefSchema.Name)
  1895. return &argument{
  1896. goname: validGoIdentifer(strings.ToLower(ds.Ref)),
  1897. apiname: "REQUEST",
  1898. gotype: "*" + s.GoName(),
  1899. apitype: ds.Ref,
  1900. location: "body",
  1901. schema: s,
  1902. }
  1903. }
  1904. func (meth *Method) NewArg(apiname string, p *Param) *argument {
  1905. apitype := p.p.Type
  1906. des := p.p.Description
  1907. goname := validGoIdentifer(apiname) // but might be changed later, if conflicts
  1908. if strings.Contains(des, "identifier") && !strings.HasSuffix(strings.ToLower(goname), "id") {
  1909. goname += "id" // yay
  1910. p.callFieldName = goname
  1911. }
  1912. gotype := mustSimpleTypeConvert(apitype, p.p.Format)
  1913. if p.p.Repeated {
  1914. gotype = "[]" + gotype
  1915. }
  1916. return &argument{
  1917. apiname: apiname,
  1918. apitype: apitype,
  1919. goname: goname,
  1920. gotype: gotype,
  1921. location: p.p.Location,
  1922. }
  1923. }
  1924. type argument struct {
  1925. method *Method
  1926. schema *Schema // Set if location == "body".
  1927. apiname, apitype string
  1928. goname, gotype string
  1929. location string // "path", "query", "body"
  1930. }
  1931. func (a *argument) String() string {
  1932. return a.goname + " " + a.gotype
  1933. }
  1934. func (a *argument) exprAsString(prefix string) string {
  1935. switch a.gotype {
  1936. case "[]string":
  1937. log.Printf("TODO(bradfitz): only including the first parameter in path query.")
  1938. return prefix + a.goname + `[0]`
  1939. case "string":
  1940. return prefix + a.goname
  1941. case "integer", "int64":
  1942. return "strconv.FormatInt(" + prefix + a.goname + ", 10)"
  1943. case "uint64":
  1944. return "strconv.FormatUint(" + prefix + a.goname + ", 10)"
  1945. case "bool":
  1946. return "strconv.FormatBool(" + prefix + a.goname + ")"
  1947. }
  1948. log.Panicf("unknown type: apitype=%q, gotype=%q", a.apitype, a.gotype)
  1949. return ""
  1950. }
  1951. // arguments are the arguments that a method takes
  1952. type arguments struct {
  1953. l []*argument
  1954. m map[string]*argument
  1955. method *Method
  1956. }
  1957. func (args *arguments) forLocation(loc string) []*argument {
  1958. matches := make([]*argument, 0)
  1959. for _, arg := range args.l {
  1960. if arg.location == loc {
  1961. matches = append(matches, arg)
  1962. }
  1963. }
  1964. return matches
  1965. }
  1966. func (args *arguments) bodyArg() *argument {
  1967. for _, arg := range args.l {
  1968. if arg.location == "body" {
  1969. return arg
  1970. }
  1971. }
  1972. return nil
  1973. }
  1974. func (args *arguments) AddArg(arg *argument) {
  1975. n := 1
  1976. oname := arg.goname
  1977. for {
  1978. _, present := args.m[arg.goname]
  1979. if !present {
  1980. args.m[arg.goname] = arg
  1981. args.l = append(args.l, arg)
  1982. return
  1983. }
  1984. n++
  1985. arg.goname = fmt.Sprintf("%s%d", oname, n)
  1986. }
  1987. }
  1988. func (a *arguments) String() string {
  1989. var buf bytes.Buffer
  1990. for i, arg := range a.l {
  1991. if i != 0 {
  1992. buf.Write([]byte(", "))
  1993. }
  1994. buf.Write([]byte(arg.String()))
  1995. }
  1996. return buf.String()
  1997. }
  1998. var urlRE = regexp.MustCompile(`^http\S+$`)
  1999. func asComment(pfx, c string) string {
  2000. var buf bytes.Buffer
  2001. const maxLen = 70
  2002. r := strings.NewReplacer(
  2003. "\n", "\n"+pfx+"// ",
  2004. "`\"", `"`,
  2005. "\"`", `"`,
  2006. )
  2007. for len(c) > 0 {
  2008. line := c
  2009. if len(line) < maxLen {
  2010. fmt.Fprintf(&buf, "%s// %s\n", pfx, r.Replace(line))
  2011. break
  2012. }
  2013. // Don't break URLs.
  2014. if !urlRE.MatchString(line[:maxLen]) {
  2015. line = line[:maxLen]
  2016. }
  2017. si := strings.LastIndex(line, " ")
  2018. if nl := strings.Index(line, "\n"); nl != -1 && nl < si {
  2019. si = nl
  2020. }
  2021. if si != -1 {
  2022. line = line[:si]
  2023. }
  2024. fmt.Fprintf(&buf, "%s// %s\n", pfx, r.Replace(line))
  2025. c = c[len(line):]
  2026. if si != -1 {
  2027. c = c[1:]
  2028. }
  2029. }
  2030. return buf.String()
  2031. }
  2032. func simpleTypeConvert(apiType, format string) (gotype string, ok bool) {
  2033. // From http://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.1
  2034. switch apiType {
  2035. case "boolean":
  2036. gotype = "bool"
  2037. case "string":
  2038. gotype = "string"
  2039. switch format {
  2040. case "int64", "uint64", "int32", "uint32":
  2041. gotype = format
  2042. }
  2043. case "number":
  2044. gotype = "float64"
  2045. case "integer":
  2046. gotype = "int64"
  2047. case "any":
  2048. gotype = "interface{}"
  2049. }
  2050. return gotype, gotype != ""
  2051. }
  2052. func mustSimpleTypeConvert(apiType, format string) string {
  2053. if gotype, ok := simpleTypeConvert(apiType, format); ok {
  2054. return gotype
  2055. }
  2056. panic(fmt.Sprintf("failed to simpleTypeConvert(%q, %q)", apiType, format))
  2057. }
  2058. func responseType(api *API, m *disco.Method) string {
  2059. if m.Response == nil {
  2060. return ""
  2061. }
  2062. ref := m.Response.Ref
  2063. if ref != "" {
  2064. if s := api.schemas[ref]; s != nil {
  2065. return s.GoReturnType()
  2066. }
  2067. return "*" + ref
  2068. }
  2069. return ""
  2070. }
  2071. // Strips the leading '*' from a type name so that it can be used to create a literal.
  2072. func responseTypeLiteral(api *API, m *disco.Method) string {
  2073. v := responseType(api, m)
  2074. if strings.HasPrefix(v, "*") {
  2075. return v[1:]
  2076. }
  2077. return v
  2078. }
  2079. // initialCap returns the identifier with a leading capital letter.
  2080. // it also maps "foo-bar" to "FooBar".
  2081. func initialCap(ident string) string {
  2082. if ident == "" {
  2083. panic("blank identifier")
  2084. }
  2085. return depunct(ident, true)
  2086. }
  2087. func validGoIdentifer(ident string) string {
  2088. id := depunct(ident, false)
  2089. switch id {
  2090. case "break", "default", "func", "interface", "select",
  2091. "case", "defer", "go", "map", "struct",
  2092. "chan", "else", "goto", "package", "switch",
  2093. "const", "fallthrough", "if", "range", "type",
  2094. "continue", "for", "import", "return", "var":
  2095. return id + "_"
  2096. }
  2097. return id
  2098. }
  2099. // depunct removes '-', '.', '$', '/', '_' from identifers, making the
  2100. // following character uppercase. Multiple '_' are preserved.
  2101. func depunct(ident string, needCap bool) string {
  2102. var buf bytes.Buffer
  2103. preserve_ := false
  2104. for i, c := range ident {
  2105. if c == '_' {
  2106. if preserve_ || strings.HasPrefix(ident[i:], "__") {
  2107. preserve_ = true
  2108. } else {
  2109. needCap = true
  2110. continue
  2111. }
  2112. } else {
  2113. preserve_ = false
  2114. }
  2115. if c == '-' || c == '.' || c == '$' || c == '/' {
  2116. needCap = true
  2117. continue
  2118. }
  2119. if needCap {
  2120. c = unicode.ToUpper(c)
  2121. needCap = false
  2122. }
  2123. buf.WriteByte(byte(c))
  2124. }
  2125. return buf.String()
  2126. }
  2127. func addFieldValueComments(p func(format string, args ...interface{}), field Field, indent string, blankLine bool) {
  2128. var lines []string
  2129. if enum, ok := field.Enum(); ok {
  2130. desc := field.EnumDescriptions()
  2131. lines = append(lines, asComment(indent, "Possible values:"))
  2132. defval := field.Default()
  2133. for i, v := range enum {
  2134. more := ""
  2135. if v == defval {
  2136. more = " (default)"
  2137. }
  2138. if len(desc) > i && desc[i] != "" {
  2139. more = more + " - " + desc[i]
  2140. }
  2141. lines = append(lines, asComment(indent, ` "`+v+`"`+more))
  2142. }
  2143. } else if field.UnfortunateDefault() {
  2144. lines = append(lines, asComment("\t", fmt.Sprintf("Default: %s", field.Default())))
  2145. }
  2146. if blankLine && len(lines) > 0 {
  2147. p(indent + "//\n")
  2148. }
  2149. for _, l := range lines {
  2150. p("%s", l)
  2151. }
  2152. }