main.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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. "sort"
  15. "strings"
  16. "sync"
  17. "github.com/aws/aws-sdk-go/private/model/api"
  18. "github.com/aws/aws-sdk-go/private/util"
  19. )
  20. type generateInfo struct {
  21. *api.API
  22. PackageDir string
  23. }
  24. var excludeServices = map[string]struct{}{
  25. "importexport": {},
  26. }
  27. // newGenerateInfo initializes the service API's folder structure for a specific service.
  28. // If the SERVICES environment variable is set, and this service is not apart of the list
  29. // this service will be skipped.
  30. func newGenerateInfo(modelFile, svcPath, svcImportPath string) *generateInfo {
  31. g := &generateInfo{API: &api.API{SvcClientImportPath: svcImportPath, BaseCrosslinkURL: "https://docs.aws.amazon.com"}}
  32. g.API.Attach(modelFile)
  33. if _, ok := excludeServices[g.API.PackageName()]; ok {
  34. return nil
  35. }
  36. paginatorsFile := strings.Replace(modelFile, "api-2.json", "paginators-1.json", -1)
  37. if _, err := os.Stat(paginatorsFile); err == nil {
  38. g.API.AttachPaginators(paginatorsFile)
  39. } else if !os.IsNotExist(err) {
  40. fmt.Println("api-2.json error:", err)
  41. }
  42. docsFile := strings.Replace(modelFile, "api-2.json", "docs-2.json", -1)
  43. if _, err := os.Stat(docsFile); err == nil {
  44. g.API.AttachDocs(docsFile)
  45. } else {
  46. fmt.Println("docs-2.json error:", err)
  47. }
  48. waitersFile := strings.Replace(modelFile, "api-2.json", "waiters-2.json", -1)
  49. if _, err := os.Stat(waitersFile); err == nil {
  50. g.API.AttachWaiters(waitersFile)
  51. } else if !os.IsNotExist(err) {
  52. fmt.Println("waiters-2.json error:", err)
  53. }
  54. g.API.Setup()
  55. if svc := os.Getenv("SERVICES"); svc != "" {
  56. svcs := strings.Split(svc, ",")
  57. included := false
  58. for _, s := range svcs {
  59. if s == g.API.PackageName() {
  60. included = true
  61. break
  62. }
  63. }
  64. if !included {
  65. // skip this non-included service
  66. return nil
  67. }
  68. }
  69. // ensure the directory exists
  70. pkgDir := filepath.Join(svcPath, g.API.PackageName())
  71. os.MkdirAll(pkgDir, 0775)
  72. os.MkdirAll(filepath.Join(pkgDir, g.API.InterfacePackageName()), 0775)
  73. g.PackageDir = pkgDir
  74. return g
  75. }
  76. // Generates service api, examples, and interface from api json definition files.
  77. //
  78. // Flags:
  79. // -path alternative service path to write generated files to for each service.
  80. //
  81. // Env:
  82. // SERVICES comma separated list of services to generate.
  83. func main() {
  84. var svcPath, sessionPath, svcImportPath string
  85. flag.StringVar(&svcPath, "path", "service", "directory to generate service clients in")
  86. flag.StringVar(&sessionPath, "sessionPath", filepath.Join("aws", "session"), "generate session service client factories")
  87. flag.StringVar(&svcImportPath, "svc-import-path", "github.com/aws/aws-sdk-go/service", "namespace to generate service client Go code import path under")
  88. flag.Parse()
  89. api.Bootstrap()
  90. files := []string{}
  91. for i := 0; i < flag.NArg(); i++ {
  92. file := flag.Arg(i)
  93. if strings.Contains(file, "*") {
  94. paths, _ := filepath.Glob(file)
  95. files = append(files, paths...)
  96. } else {
  97. files = append(files, file)
  98. }
  99. }
  100. for svcName := range excludeServices {
  101. if strings.Contains(os.Getenv("SERVICES"), svcName) {
  102. fmt.Printf("Service %s is not supported\n", svcName)
  103. os.Exit(1)
  104. }
  105. }
  106. sort.Strings(files)
  107. // Remove old API versions from list
  108. m := map[string]bool{}
  109. for i := range files {
  110. idx := len(files) - 1 - i
  111. parts := strings.Split(files[idx], string(filepath.Separator))
  112. svc := parts[len(parts)-3] // service name is 2nd-to-last component
  113. if m[svc] {
  114. files[idx] = "" // wipe this one out if we already saw the service
  115. }
  116. m[svc] = true
  117. }
  118. wg := sync.WaitGroup{}
  119. for i := range files {
  120. filename := files[i]
  121. if filename == "" { // empty file
  122. continue
  123. }
  124. genInfo := newGenerateInfo(filename, svcPath, svcImportPath)
  125. if genInfo == nil {
  126. continue
  127. }
  128. if _, ok := excludeServices[genInfo.API.PackageName()]; ok {
  129. // Skip services not yet supported.
  130. continue
  131. }
  132. wg.Add(1)
  133. go func(g *generateInfo, filename string) {
  134. defer wg.Done()
  135. writeServiceFiles(g, filename)
  136. }(genInfo, filename)
  137. }
  138. wg.Wait()
  139. }
  140. func writeServiceFiles(g *generateInfo, filename string) {
  141. defer func() {
  142. if r := recover(); r != nil {
  143. fmt.Fprintf(os.Stderr, "Error generating %s\n%s\n%s\n",
  144. filename, r, debug.Stack())
  145. }
  146. }()
  147. fmt.Printf("Generating %s (%s)...\n",
  148. g.API.PackageName(), g.API.Metadata.APIVersion)
  149. // write api.go and service.go files
  150. Must(writeAPIFile(g))
  151. Must(writeExamplesFile(g))
  152. Must(writeServiceFile(g))
  153. Must(writeInterfaceFile(g))
  154. Must(writeWaitersFile(g))
  155. Must(writeAPIErrorsFile(g))
  156. }
  157. // Must will panic if the error passed in is not nil.
  158. func Must(err error) {
  159. if err != nil {
  160. panic(err)
  161. }
  162. }
  163. const codeLayout = `// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
  164. %s
  165. package %s
  166. %s
  167. `
  168. func writeGoFile(file string, layout string, args ...interface{}) error {
  169. return ioutil.WriteFile(file, []byte(util.GoFmt(fmt.Sprintf(layout, args...))), 0664)
  170. }
  171. // writeExamplesFile writes out the service example file.
  172. func writeExamplesFile(g *generateInfo) error {
  173. return writeGoFile(filepath.Join(g.PackageDir, "examples_test.go"),
  174. codeLayout,
  175. "",
  176. g.API.PackageName()+"_test",
  177. g.API.ExampleGoCode(),
  178. )
  179. }
  180. // writeServiceFile writes out the service initialization file.
  181. func writeServiceFile(g *generateInfo) error {
  182. return writeGoFile(filepath.Join(g.PackageDir, "service.go"),
  183. codeLayout,
  184. "",
  185. g.API.PackageName(),
  186. g.API.ServiceGoCode(),
  187. )
  188. }
  189. // writeInterfaceFile writes out the service interface file.
  190. func writeInterfaceFile(g *generateInfo) error {
  191. const pkgDoc = `
  192. // Package %s provides an interface to enable mocking the %s service client
  193. // for testing your code.
  194. //
  195. // It is important to note that this interface will have breaking changes
  196. // when the service model is updated and adds new API operations, paginators,
  197. // and waiters.`
  198. return writeGoFile(filepath.Join(g.PackageDir, g.API.InterfacePackageName(), "interface.go"),
  199. codeLayout,
  200. fmt.Sprintf(pkgDoc, g.API.InterfacePackageName(), g.API.Metadata.ServiceFullName),
  201. g.API.InterfacePackageName(),
  202. g.API.InterfaceGoCode(),
  203. )
  204. }
  205. func writeWaitersFile(g *generateInfo) error {
  206. if len(g.API.Waiters) == 0 {
  207. return nil
  208. }
  209. return writeGoFile(filepath.Join(g.PackageDir, "waiters.go"),
  210. codeLayout,
  211. "",
  212. g.API.PackageName(),
  213. g.API.WaitersGoCode(),
  214. )
  215. }
  216. // writeAPIFile writes out the service api file.
  217. func writeAPIFile(g *generateInfo) error {
  218. return writeGoFile(filepath.Join(g.PackageDir, "api.go"),
  219. codeLayout,
  220. fmt.Sprintf("\n// Package %s provides a client for %s.",
  221. g.API.PackageName(), g.API.Metadata.ServiceFullName),
  222. g.API.PackageName(),
  223. g.API.APIGoCode(),
  224. )
  225. }
  226. // writeAPIErrorsFile writes out the service api errors file.
  227. func writeAPIErrorsFile(g *generateInfo) error {
  228. return writeGoFile(filepath.Join(g.PackageDir, "errors.go"),
  229. codeLayout,
  230. "",
  231. g.API.PackageName(),
  232. g.API.APIErrorsGoCode(),
  233. )
  234. }