Skip to content

Commit

Permalink
Remove deep references to GOPATH
Browse files Browse the repository at this point in the history
With this change, GOPATH is still used, but only at the top level (main.go) where it's used to
determine the absolute path for output.
  • Loading branch information
taylor-sutton committed Apr 21, 2022
1 parent e1e9b5b commit 6436a44
Show file tree
Hide file tree
Showing 7 changed files with 53 additions and 69 deletions.
15 changes: 7 additions & 8 deletions clients/go/gengo.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@ import (
)

// Generate generates a client
func Generate(packageName, packagePath string, s spec.Swagger) error {
if err := generateClient(packageName, packagePath, s); err != nil {
func Generate(packageName, basePath string, s spec.Swagger) error {
if err := generateClient(packageName, basePath, s); err != nil {
return err
}
return generateInterface(packageName, packagePath, &s, s.Info.InfoProps.Title, s.Paths)
return generateInterface(packageName, basePath, &s, s.Info.InfoProps.Title, s.Paths)
}

type clientCodeTemplate struct {
Expand Down Expand Up @@ -197,8 +197,7 @@ func shortHash(s string) string {
}
`

func generateClient(packageName, packagePath string, s spec.Swagger) error {

func generateClient(packageName, basePath string, s spec.Swagger) error {
codeTemplate := clientCodeTemplate{
PackageName: packageName,
ServiceName: s.Info.InfoProps.Title,
Expand Down Expand Up @@ -227,7 +226,7 @@ func generateClient(packageName, packagePath string, s spec.Swagger) error {
return err
}

g := swagger.Generator{PackagePath: packagePath}
g := swagger.Generator{BasePath: basePath}
g.Printf(clientCode)
return g.WriteFile("client/client.go")
}
Expand All @@ -248,8 +247,8 @@ func IsBinaryParam(param spec.Parameter, definitions map[string]spec.Schema) boo
return definitions[definitionName].Format == "binary"
}

func generateInterface(packageName, packagePath string, s *spec.Swagger, serviceName string, paths *spec.Paths) error {
g := swagger.Generator{PackagePath: packagePath}
func generateInterface(packageName, basePath string, s *spec.Swagger, serviceName string, paths *spec.Paths) error {
g := swagger.Generator{BasePath: basePath}
g.Printf("package client\n\n")
g.Printf(swagger.ImportStatements([]string{"context", packageName + "/models"}))
g.Printf("//go:generate mockgen -source=$GOFILE -destination=mock_client.go -package=client\n\n")
Expand Down
55 changes: 22 additions & 33 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,9 @@ type config struct {
goPackageName *string

dynamoPath string
goAbsolutePackagePath string
goClientPath string
goPackagePath string
goAbsolutePackagePath string
jsClientPath string
modelsPath string
serverPath string
tracingPath string

generateDynamo bool
generateGoClient bool
Expand Down Expand Up @@ -95,31 +91,31 @@ func main() {
}

if conf.generateGoModels {
if err := generateGoModels(conf.modelsPath, conf.goPackagePath, swaggerSpec); err != nil {
if err := generateGoModels(conf.goAbsolutePackagePath, swaggerSpec); err != nil {
log.Fatal(err.Error())
}
}

if conf.generateServer {
if err := generateServer(conf.serverPath, *conf.goPackageName, conf.goPackagePath, swaggerSpec); err != nil {
if err := generateServer(*conf.goPackageName, conf.goAbsolutePackagePath, swaggerSpec); err != nil {
log.Fatal(err.Error())
}
}

if conf.generateTracing {
if err := generateTracing(conf.tracingPath, conf.goPackagePath); err != nil {
if err := generateTracing(conf.goAbsolutePackagePath); err != nil {
log.Fatal(err.Error())
}
}

if conf.generateDynamo {
if err := generateDynamo(conf.dynamoPath, *conf.goPackageName, conf.goPackagePath, *conf.relativeDynamoPath, swaggerSpec); err != nil {
if err := generateDynamo(conf.dynamoPath, *conf.goPackageName, conf.goAbsolutePackagePath, *conf.relativeDynamoPath, swaggerSpec); err != nil {
log.Fatal(err.Error())
}
}

if conf.generateGoClient {
if err := generateGoClient(conf.goClientPath, *conf.goPackageName, conf.goPackagePath, swaggerSpec); err != nil {
if err := generateGoClient(*conf.goPackageName, conf.goAbsolutePackagePath, swaggerSpec); err != nil {
log.Fatal(err.Error())
}
}
Expand All @@ -131,24 +127,24 @@ func main() {
}
}

func generateGoModels(modelsPath, goPackagePath string, swaggerSpec spec.Swagger) error {
if err := prepareDir(modelsPath); err != nil {
func generateGoModels(basePath string, swaggerSpec spec.Swagger) error {
if err := prepareDir(filepath.Join(basePath, "models")); err != nil {
return err
}
if err := models.Generate(goPackagePath, swaggerSpec); err != nil {
if err := models.Generate(basePath, swaggerSpec); err != nil {
return fmt.Errorf("Error generating models: %s", err)
}
return nil
}

func generateServer(serverPath, goPackageName, goPackagePath string, swaggerSpec spec.Swagger) error {
if err := prepareDir(serverPath); err != nil {
func generateServer(goPackageName, basePath string, swaggerSpec spec.Swagger) error {
if err := prepareDir(filepath.Join(basePath, "server")); err != nil {
return err
}
if err := server.Generate(goPackageName, goPackagePath, swaggerSpec); err != nil {
if err := server.Generate(goPackageName, basePath, swaggerSpec); err != nil {
return fmt.Errorf("Failed to generate server: %s", err)
}
middlewareGenerator := swagger.Generator{PackagePath: goPackagePath}
middlewareGenerator := swagger.Generator{BasePath: basePath}
middlewareGenerator.Write(hardcoded.MustAsset("../_hardcoded/middleware.go"))
if err := middlewareGenerator.WriteFile("server/middleware.go"); err != nil {
return fmt.Errorf("Failed to copy middleware.go: %s", err)
Expand All @@ -157,12 +153,12 @@ func generateServer(serverPath, goPackageName, goPackagePath string, swaggerSpec
return nil
}

func generateTracing(tracingPath, goPackagePath string) error {
if err := prepareDir(tracingPath); err != nil {
func generateTracing(basePath string) error {
if err := prepareDir(filepath.Join(basePath, "tracing")); err != nil {
return err
}

tracingGenerator := swagger.Generator{PackagePath: goPackagePath}
tracingGenerator := swagger.Generator{BasePath: basePath}
tracingGenerator.Write(hardcoded.MustAsset("../_hardcoded/tracing.go"))
if err := tracingGenerator.WriteFile("tracing/tracing.go"); err != nil {
log.Fatalf("Failed to copy tracing.go: %s", err)
Expand All @@ -171,24 +167,24 @@ func generateTracing(tracingPath, goPackagePath string) error {
return nil
}

func generateDynamo(dynamoPath, goPackageName, goPackagePath, outputPath string, swaggerSpec spec.Swagger) error {
func generateDynamo(dynamoPath, goPackageName, basePath, outputPath string, swaggerSpec spec.Swagger) error {
if err := prepareDir(dynamoPath); err != nil {
return err
}
if err := gendb.GenerateDB(goPackageName, goPackagePath, &swaggerSpec, outputPath); err != nil {
if err := gendb.GenerateDB(goPackageName, basePath, &swaggerSpec, outputPath); err != nil {
return fmt.Errorf("Failed to generate database: %s", err)
}
return nil
}

func generateGoClient(goClientPath, goPackageName, goPackagePath string, swaggerSpec spec.Swagger) error {
if err := prepareDir(goClientPath); err != nil {
func generateGoClient(goPackageName, basePath string, swaggerSpec spec.Swagger) error {
if err := prepareDir(filepath.Join(basePath, "client")); err != nil {
return err
}
if err := goclient.Generate(goPackageName, goPackagePath, swaggerSpec); err != nil {
if err := goclient.Generate(goPackageName, basePath, swaggerSpec); err != nil {
return fmt.Errorf("Failed generating go client %s", err)
}
doerGenerator := swagger.Generator{PackagePath: goPackagePath}
doerGenerator := swagger.Generator{BasePath: basePath}
doerGenerator.Write(hardcoded.MustAsset("../_hardcoded/doer.go"))
if err := doerGenerator.WriteFile("client/doer.go"); err != nil {
return fmt.Errorf("Failed to copy doer.go: %s", err)
Expand Down Expand Up @@ -322,15 +318,8 @@ func (c *config) setClientLanguage(clientLanguage, jsModulePath string) error {
// setGeneratedFilePaths determines where to output the generated files.
func (c *config) setGeneratedFilePaths() {
const serverDir = "server"
const tracingDir = "tracing"

// determine paths for generated files
c.goAbsolutePackagePath = filepath.Join(os.Getenv("GOPATH"), "src", c.goPackagePath)
c.modelsPath = filepath.Join(c.goAbsolutePackagePath, "models")
c.serverPath = filepath.Join(c.goAbsolutePackagePath, serverDir)
c.tracingPath = filepath.Join(c.goAbsolutePackagePath, tracingDir)
c.goClientPath = filepath.Join(c.goAbsolutePackagePath, "client")

if c.generateDynamo {
// set path of generated dynamo code if none specified
if swag.StringValue(c.relativeDynamoPath) == "" {
Expand Down
4 changes: 0 additions & 4 deletions main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -217,10 +217,6 @@ func Test_config_validate(t *testing.T) {
t.Errorf("config.validate() error = %v, wantErr %v", err, tt.wantErr)
} else if !tt.wantErr {
// clear paths so they are not diffed
tt.input.modelsPath = ""
tt.input.serverPath = ""
tt.input.tracingPath = ""
tt.input.goClientPath = ""
tt.input.jsClientPath = ""
tt.input.dynamoPath = ""
tt.input.goAbsolutePackagePath = ""
Expand Down
16 changes: 8 additions & 8 deletions models/genmodels.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import (
)

// Generate writes the files to the client directories
func Generate(packagePath string, s spec.Swagger) error {
func Generate(basePath string, s spec.Swagger) error {

tmpFile, err := swagger.WriteToFile(&s)
if err != nil {
Expand All @@ -29,7 +29,7 @@ func Generate(packagePath string, s spec.Swagger) error {
genopts := generator.GenOpts{
Spec: tmpFile,
ModelPackage: "models",
Target: fmt.Sprintf("%s/src/%s/", os.Getenv("GOPATH"), packagePath),
Target: basePath,
IncludeModel: true,
IncludeHandler: false,
IncludeSupport: false,
Expand All @@ -45,18 +45,18 @@ func Generate(packagePath string, s spec.Swagger) error {
return fmt.Errorf("error generating go-swagger models: %s", err)
}

if err := generateOutputs(packagePath, s); err != nil {
if err := generateOutputs(basePath, s); err != nil {
return fmt.Errorf("error generating outputs: %s", err)
}
if err := generateInputs(packagePath, s); err != nil {
if err := generateInputs(basePath, s); err != nil {
return fmt.Errorf("error generating inputs: %s", err)
}
return nil
}

func generateInputs(packagePath string, s spec.Swagger) error {
func generateInputs(basePath string, s spec.Swagger) error {

g := swagger.Generator{PackagePath: packagePath}
g := swagger.Generator{BasePath: basePath}

g.Printf(`
package models
Expand Down Expand Up @@ -305,8 +305,8 @@ var queryParamStr = `
{{end}}
`

func generateOutputs(packagePath string, s spec.Swagger) error {
g := swagger.Generator{PackagePath: packagePath}
func generateOutputs(basePath string, s spec.Swagger) error {
g := swagger.Generator{BasePath: basePath}

g.Printf("package models\n\n")

Expand Down
4 changes: 2 additions & 2 deletions server/gendb/gendb.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ func findCompositeAttribute(config XDBConfig, attributeName string) *CompositeAt
}

// GenerateDB generates DB code for schemas annotated with the x-db extension.
func GenerateDB(packageName, packagePath string, s *spec.Swagger, outputPath string) error {
func GenerateDB(packageName, basePath string, s *spec.Swagger, outputPath string) error {
var schemaNames []string
for schemaName := range s.Definitions {
schemaNames = append(schemaNames, schemaName)
Expand Down Expand Up @@ -175,7 +175,7 @@ func GenerateDB(packageName, packagePath string, s *spec.Swagger, outputPath str
return err
}

g := swagger.Generator{PackagePath: packagePath}
g := swagger.Generator{BasePath: basePath}
g.Printf(tmpBuf.String())
return g.WriteFile(outputFilename)
}
Expand Down
20 changes: 10 additions & 10 deletions server/genserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,15 @@ import (
)

// Generate server package for a swagger spec.
func Generate(packageName, packagePath string, s spec.Swagger) error {
func Generate(packageName, basePath string, s spec.Swagger) error {

if err := generateRouter(packageName, packagePath, s, s.Paths); err != nil {
if err := generateRouter(packageName, basePath, s, s.Paths); err != nil {
return err
}
if err := generateInterface(packageName, packagePath, &s, s.Info.InfoProps.Title, s.Paths); err != nil {
if err := generateInterface(packageName, basePath, &s, s.Info.InfoProps.Title, s.Paths); err != nil {
return err
}
if err := generateHandlers(packageName, packagePath, &s, s.Paths); err != nil {
if err := generateHandlers(packageName, basePath, &s, s.Paths); err != nil {
return err
}
return nil
Expand All @@ -41,7 +41,7 @@ type routerTemplate struct {
Functions []routerFunction
}

func generateRouter(packageName, packagePath string, s spec.Swagger, paths *spec.Paths) error {
func generateRouter(packageName, basePath string, s spec.Swagger, paths *spec.Paths) error {

var template routerTemplate
template.Title = s.Info.Title
Expand Down Expand Up @@ -82,7 +82,7 @@ func generateRouter(packageName, packagePath string, s spec.Swagger, paths *spec
if err != nil {
return err
}
g := swagger.Generator{PackagePath: packagePath}
g := swagger.Generator{BasePath: basePath}
g.Printf(routerCode)
return g.WriteFile("server/router.go")
}
Expand Down Expand Up @@ -115,7 +115,7 @@ type Controller interface {
}
`

func generateInterface(packageName, packagePath string, s *spec.Swagger, serviceName string, paths *spec.Paths) error {
func generateInterface(packageName, basePath string, s *spec.Swagger, serviceName string, paths *spec.Paths) error {

tmpl := interfaceFileTemplate{
ImportStatements: swagger.ImportStatements([]string{"context", packageName + "/models"}),
Expand All @@ -141,7 +141,7 @@ func generateInterface(packageName, packagePath string, s *spec.Swagger, service
if err != nil {
return err
}
g := swagger.Generator{PackagePath: packagePath}
g := swagger.Generator{BasePath: basePath}
g.Printf(interfaceCode)
return g.WriteFile("server/interface.go")
}
Expand Down Expand Up @@ -186,7 +186,7 @@ func jsonMarshalNoError(i interface{}) string {
{{end}}
`

func generateHandlers(packageName, packagePath string, s *spec.Swagger, paths *spec.Paths) error {
func generateHandlers(packageName, basePath string, s *spec.Swagger, paths *spec.Paths) error {
tmpl := handlerFileTemplate{
ImportStatements: swagger.ImportStatements([]string{"context", "github.com/gorilla/mux",
"gopkg.in/Clever/kayvee-go.v6/logger",
Expand Down Expand Up @@ -215,7 +215,7 @@ func generateHandlers(packageName, packagePath string, s *spec.Swagger, paths *s
if err != nil {
return err
}
g := swagger.Generator{PackagePath: packagePath}
g := swagger.Generator{BasePath: basePath}
g.Printf(handlerCode)
return g.WriteFile("server/handlers.go")
}
Expand Down
8 changes: 4 additions & 4 deletions swagger/swagger.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ import (

// Generator handles common code generation operations when generating a file in a Go package.
type Generator struct {
PackagePath string
buf bytes.Buffer
BasePath string
buf bytes.Buffer
}

// Printf writes a formatted string to the buffer.
Expand All @@ -30,7 +30,7 @@ func (g *Generator) Write(p []byte) (n int, err error) {
}

// WriteFile writes the buffer to a gofmt-ed file.
// The file will be located at $GOPATH/src/{PackagePath}/{path}.
// The file will be located at {(Generator).BasePath}/{path}.
func (g *Generator) WriteFile(path string) error {
if len(path) == 0 || path[0] == '/' {
return fmt.Errorf("path must be relative")
Expand All @@ -52,7 +52,7 @@ func (g *Generator) WriteFile(path string) error {
}
fileBytes = formattedFileBytes
}
absPath := filepath.Join(os.Getenv("GOPATH"), "src", g.PackagePath, path)
absPath := filepath.Join(g.BasePath, path)
dir := filepath.Dir(absPath)
if err := os.MkdirAll(dir, 0755); err != nil {
return err
Expand Down

0 comments on commit 6436a44

Please sign in to comment.