load.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // +build codegen
  2. package api
  3. import (
  4. "encoding/json"
  5. "fmt"
  6. "os"
  7. "path/filepath"
  8. )
  9. // Load takes a set of files for each filetype and returns an API pointer.
  10. // The API will be initialized once all files have been loaded and parsed.
  11. //
  12. // Will panic if any failure opening the definition JSON files, or there
  13. // are unrecognized exported names.
  14. func Load(api, docs, paginators, waiters string) *API {
  15. a := API{}
  16. a.Attach(api)
  17. a.Attach(docs)
  18. a.Attach(paginators)
  19. a.Attach(waiters)
  20. a.Setup()
  21. return &a
  22. }
  23. // Attach opens a file by name, and unmarshal its JSON data.
  24. // Will proceed to setup the API if not already done so.
  25. func (a *API) Attach(filename string) {
  26. a.path = filepath.Dir(filename)
  27. f, err := os.Open(filename)
  28. defer f.Close()
  29. if err != nil {
  30. panic(err)
  31. }
  32. if err := json.NewDecoder(f).Decode(a); err != nil {
  33. panic(fmt.Errorf("failed to decode %s, err: %v", filename, err))
  34. }
  35. }
  36. // AttachString will unmarshal a raw JSON string, and setup the
  37. // API if not already done so.
  38. func (a *API) AttachString(str string) {
  39. json.Unmarshal([]byte(str), a)
  40. if !a.initialized {
  41. a.Setup()
  42. }
  43. }
  44. // Setup initializes the API.
  45. func (a *API) Setup() {
  46. a.writeShapeNames()
  47. a.resolveReferences()
  48. a.fixStutterNames()
  49. a.renameExportable()
  50. if !a.NoRenameToplevelShapes {
  51. a.renameToplevelShapes()
  52. }
  53. a.updateTopLevelShapeReferences()
  54. a.createInputOutputShapes()
  55. a.customizationPasses()
  56. if !a.NoRemoveUnusedShapes {
  57. a.removeUnusedShapes()
  58. }
  59. if !a.NoValidataShapeMethods {
  60. a.addShapeValidations()
  61. }
  62. a.initialized = true
  63. }