load.go 1.5 KB

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