load.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. json.NewDecoder(f).Decode(a)
  32. }
  33. // AttachString will unmarshal a raw JSON string, and setup the
  34. // API if not already done so.
  35. func (a *API) AttachString(str string) {
  36. json.Unmarshal([]byte(str), a)
  37. if !a.initialized {
  38. a.Setup()
  39. }
  40. }
  41. // Setup initializes the API.
  42. func (a *API) Setup() {
  43. a.unrecognizedNames = map[string]string{}
  44. a.writeShapeNames()
  45. a.resolveReferences()
  46. a.fixStutterNames()
  47. a.renameExportable()
  48. a.renameToplevelShapes()
  49. a.updateTopLevelShapeReferences()
  50. a.createInputOutputShapes()
  51. a.customizationPasses()
  52. if !a.NoRemoveUnusedShapes {
  53. a.removeUnusedShapes()
  54. }
  55. if len(a.unrecognizedNames) > 0 {
  56. msg := []string{
  57. "Unrecognized inflections for the following export names:",
  58. "(Add these to inflections.csv with any inflections added after the ':')",
  59. }
  60. fmt.Fprintf(os.Stderr, "%s\n%s\n\n", msg[0], msg[1])
  61. for n, m := range a.unrecognizedNames {
  62. if n == m {
  63. m = ""
  64. }
  65. fmt.Fprintf(os.Stderr, "%s:%s\n", n, m)
  66. }
  67. os.Stderr.WriteString("\n\n")
  68. panic("Found unrecognized exported names in API " + a.PackageName())
  69. }
  70. a.initialized = true
  71. }