main.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. // +build codegen
  2. // Command aws-gen-gocli parses a JSON description of an AWS API and generates a
  3. // Go file containing a client for the API.
  4. //
  5. // aws-gen-gocli apis/s3/2006-03-03/api-2.json
  6. package main
  7. import (
  8. "flag"
  9. "fmt"
  10. "io/ioutil"
  11. "os"
  12. "path/filepath"
  13. "runtime/debug"
  14. "strings"
  15. "sync"
  16. "github.com/aws/aws-sdk-go/private/model/api"
  17. "github.com/aws/aws-sdk-go/private/util"
  18. )
  19. func usage() {
  20. fmt.Fprintln(os.Stderr, `Usage: api-gen <options> [model path | file path]
  21. Loads API models from file and generates SDK clients from the models.
  22. The model path arguments can be globs, or paths to individual files. The
  23. utiliity requires that the API model files follow the following pattern:
  24. <root>/<servicename>/<api-version>/<model json files>
  25. e.g:
  26. ./models/apis/s3/2006-03-01/*.json
  27. Flags:`)
  28. flag.PrintDefaults()
  29. }
  30. // Generates service api, examples, and interface from api json definition files.
  31. //
  32. // Flags:
  33. // -path alternative service path to write generated files to for each service.
  34. //
  35. // Env:
  36. // SERVICES comma separated list of services to generate.
  37. func main() {
  38. var svcPath, svcImportPath string
  39. flag.StringVar(&svcPath, "path", "service",
  40. "The `path` to generate service clients in to.",
  41. )
  42. flag.StringVar(&svcImportPath, "svc-import-path",
  43. "github.com/aws/aws-sdk-go/service",
  44. "The Go `import path` to generate client to be under.",
  45. )
  46. flag.Usage = usage
  47. flag.Parse()
  48. if len(os.Getenv("AWS_SDK_CODEGEN_DEBUG")) != 0 {
  49. api.LogDebug(os.Stdout)
  50. }
  51. // Make sure all paths are based on platform's pathing not Unix
  52. globs := flag.Args()
  53. for i, g := range globs {
  54. globs[i] = filepath.FromSlash(g)
  55. }
  56. svcPath = filepath.FromSlash(svcPath)
  57. modelPaths, err := api.ExpandModelGlobPath(globs...)
  58. if err != nil {
  59. fmt.Fprintln(os.Stderr, "failed to glob file pattern", err)
  60. os.Exit(1)
  61. }
  62. modelPaths, _ = api.TrimModelServiceVersions(modelPaths)
  63. apis, err := api.LoadAPIs(modelPaths, svcImportPath)
  64. if err != nil {
  65. fmt.Fprintln(os.Stderr, "failed to load API models", err)
  66. os.Exit(1)
  67. }
  68. if len(apis) == 0 {
  69. fmt.Fprintf(os.Stderr, "expected to load models, but found none")
  70. os.Exit(1)
  71. }
  72. if v := os.Getenv("SERVICES"); len(v) != 0 {
  73. svcs := strings.Split(v, ",")
  74. for pkgName, a := range apis {
  75. var found bool
  76. for _, include := range svcs {
  77. if a.PackageName() == include {
  78. found = true
  79. break
  80. }
  81. }
  82. if !found {
  83. delete(apis, pkgName)
  84. }
  85. }
  86. }
  87. var wg sync.WaitGroup
  88. servicePaths := map[string]struct{}{}
  89. for _, a := range apis {
  90. if _, ok := excludeServices[a.PackageName()]; ok {
  91. continue
  92. }
  93. // Create the output path for the model.
  94. pkgDir := filepath.Join(svcPath, a.PackageName())
  95. os.MkdirAll(filepath.Join(pkgDir, a.InterfacePackageName()), 0775)
  96. if _, ok := servicePaths[pkgDir]; ok {
  97. fmt.Fprintf(os.Stderr,
  98. "attempted to generate a client into %s twice. Second model package, %v\n",
  99. pkgDir, a.PackageName())
  100. os.Exit(1)
  101. }
  102. servicePaths[pkgDir] = struct{}{}
  103. g := &generateInfo{
  104. API: a,
  105. PackageDir: pkgDir,
  106. }
  107. wg.Add(1)
  108. go func() {
  109. defer wg.Done()
  110. writeServiceFiles(g, pkgDir)
  111. }()
  112. }
  113. wg.Wait()
  114. }
  115. type generateInfo struct {
  116. *api.API
  117. PackageDir string
  118. }
  119. var excludeServices = map[string]struct{}{
  120. "importexport": {},
  121. }
  122. func writeServiceFiles(g *generateInfo, pkgDir string) {
  123. defer func() {
  124. if r := recover(); r != nil {
  125. fmt.Fprintf(os.Stderr, "Error generating %s\n%s\n%s\n",
  126. pkgDir, r, debug.Stack())
  127. os.Exit(1)
  128. }
  129. }()
  130. fmt.Printf("Generating %s (%s)...\n",
  131. g.API.PackageName(), g.API.Metadata.APIVersion)
  132. // write files for service client and API
  133. Must(writeServiceDocFile(g))
  134. Must(writeAPIFile(g))
  135. Must(writeServiceFile(g))
  136. Must(writeInterfaceFile(g))
  137. Must(writeWaitersFile(g))
  138. Must(writeAPIErrorsFile(g))
  139. Must(writeExamplesFile(g))
  140. if g.API.HasEventStream {
  141. Must(writeAPIEventStreamTestFile(g))
  142. }
  143. if g.API.PackageName() == "s3" {
  144. Must(writeS3ManagerUploadInputFile(g))
  145. }
  146. if len(g.API.SmokeTests.TestCases) > 0 {
  147. Must(writeAPISmokeTestsFile(g))
  148. }
  149. }
  150. // Must will panic if the error passed in is not nil.
  151. func Must(err error) {
  152. if err != nil {
  153. panic(err)
  154. }
  155. }
  156. const codeLayout = `// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
  157. %s
  158. package %s
  159. %s
  160. `
  161. func writeGoFile(file string, layout string, args ...interface{}) error {
  162. return ioutil.WriteFile(file, []byte(util.GoFmt(fmt.Sprintf(layout, args...))), 0664)
  163. }
  164. // writeServiceDocFile generates the documentation for service package.
  165. func writeServiceDocFile(g *generateInfo) error {
  166. return writeGoFile(filepath.Join(g.PackageDir, "doc.go"),
  167. codeLayout,
  168. strings.TrimSpace(g.API.ServicePackageDoc()),
  169. g.API.PackageName(),
  170. "",
  171. )
  172. }
  173. // writeExamplesFile writes out the service example file.
  174. func writeExamplesFile(g *generateInfo) error {
  175. code := g.API.ExamplesGoCode()
  176. if len(code) > 0 {
  177. return writeGoFile(filepath.Join(g.PackageDir, "examples_test.go"),
  178. codeLayout,
  179. "",
  180. g.API.PackageName()+"_test",
  181. code,
  182. )
  183. }
  184. return nil
  185. }
  186. // writeServiceFile writes out the service initialization file.
  187. func writeServiceFile(g *generateInfo) error {
  188. return writeGoFile(filepath.Join(g.PackageDir, "service.go"),
  189. codeLayout,
  190. "",
  191. g.API.PackageName(),
  192. g.API.ServiceGoCode(),
  193. )
  194. }
  195. // writeInterfaceFile writes out the service interface file.
  196. func writeInterfaceFile(g *generateInfo) error {
  197. const pkgDoc = `
  198. // Package %s provides an interface to enable mocking the %s service client
  199. // for testing your code.
  200. //
  201. // It is important to note that this interface will have breaking changes
  202. // when the service model is updated and adds new API operations, paginators,
  203. // and waiters.`
  204. return writeGoFile(filepath.Join(g.PackageDir, g.API.InterfacePackageName(), "interface.go"),
  205. codeLayout,
  206. fmt.Sprintf(pkgDoc, g.API.InterfacePackageName(), g.API.Metadata.ServiceFullName),
  207. g.API.InterfacePackageName(),
  208. g.API.InterfaceGoCode(),
  209. )
  210. }
  211. func writeWaitersFile(g *generateInfo) error {
  212. if len(g.API.Waiters) == 0 {
  213. return nil
  214. }
  215. return writeGoFile(filepath.Join(g.PackageDir, "waiters.go"),
  216. codeLayout,
  217. "",
  218. g.API.PackageName(),
  219. g.API.WaitersGoCode(),
  220. )
  221. }
  222. // writeAPIFile writes out the service API file.
  223. func writeAPIFile(g *generateInfo) error {
  224. return writeGoFile(filepath.Join(g.PackageDir, "api.go"),
  225. codeLayout,
  226. "",
  227. g.API.PackageName(),
  228. g.API.APIGoCode(),
  229. )
  230. }
  231. // writeAPIErrorsFile writes out the service API errors file.
  232. func writeAPIErrorsFile(g *generateInfo) error {
  233. return writeGoFile(filepath.Join(g.PackageDir, "errors.go"),
  234. codeLayout,
  235. "",
  236. g.API.PackageName(),
  237. g.API.APIErrorsGoCode(),
  238. )
  239. }
  240. func writeAPIEventStreamTestFile(g *generateInfo) error {
  241. return writeGoFile(filepath.Join(g.PackageDir, "eventstream_test.go"),
  242. codeLayout,
  243. "// +build go1.6\n",
  244. g.API.PackageName(),
  245. g.API.APIEventStreamTestGoCode(),
  246. )
  247. }
  248. func writeS3ManagerUploadInputFile(g *generateInfo) error {
  249. return writeGoFile(filepath.Join(g.PackageDir, "s3manager", "upload_input.go"),
  250. codeLayout,
  251. "",
  252. "s3manager",
  253. api.S3ManagerUploadInputGoCode(g.API),
  254. )
  255. }
  256. func writeAPISmokeTestsFile(g *generateInfo) error {
  257. return writeGoFile(filepath.Join(g.PackageDir, "integ_test.go"),
  258. codeLayout,
  259. "// +build go1.10,integration\n",
  260. g.API.PackageName()+"_test",
  261. g.API.APISmokeTestsGoCode(),
  262. )
  263. }