From 9433a7b66f3f3edd28d3417916b6c4f5095f9492 Mon Sep 17 00:00:00 2001 From: qiantao Date: Thu, 25 Jun 2020 22:29:27 +0800 Subject: [PATCH] =?UTF-8?q?1.=20new,api,hprose=20=E5=91=BD=E4=BB=A4?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E4=B8=A4=E4=B8=AA=E5=8F=82=E6=95=B0=20[-modu?= =?UTF-8?q?le=3Dtrue]=20[-beego=3Dv1.12.1]=20=E7=94=A8=E4=BA=8E=E7=94=9F?= =?UTF-8?q?=E6=88=90go=20module=E9=A1=B9=E7=9B=AE=202.=20generate,migrate?= =?UTF-8?q?=E5=91=BD=E4=BB=A4=E4=B8=8D=E5=86=8D=E6=89=93=E5=8D=B0GOPATH.?= =?UTF-8?q?=203.=20pack=E5=91=BD=E4=BB=A4=E6=8E=92=E9=99=A4=E3=80=82=204.?= =?UTF-8?q?=20run=E5=91=BD=E4=BB=A4=E6=94=AF=E6=8C=81=E4=BC=A0=E9=80=92ldf?= =?UTF-8?q?lags=E5=8F=82=E6=95=B0=205.=20fix=20watch=20file=20bug.ignoredF?= =?UTF-8?q?ilesRegExps=E6=95=B0=E7=BB=84=E5=AF=B9=E6=AF=8F=E4=B8=AA?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E5=A2=9E=E5=8A=A0$,=E9=98=B2=E6=AD=A2?= =?UTF-8?q?=E7=9B=AE=E5=BD=95=E5=AD=98=E5=9C=A8tmp=E7=9A=84=E6=83=85?= =?UTF-8?q?=E5=86=B5=206.=20getPackagePath=E5=87=BD=E6=95=B0=E8=A2=AB?= =?UTF-8?q?=E8=B0=83=E7=94=A8=E6=97=B6=E5=A6=82=E6=9E=9C=E6=89=BE=E4=B8=8D?= =?UTF-8?q?=E5=88=B0GOPATH=EF=BC=8C=E5=88=99=E7=9C=8B=E7=9C=8B=E5=B7=A5?= =?UTF-8?q?=E7=A8=8B=E6=9C=89=E6=B2=A1=E6=9C=89go.mod=20=E6=9C=89=E5=B0=B1?= =?UTF-8?q?=E5=BD=93=E5=81=9Ago=20module=E9=A1=B9=E7=9B=AE=E5=A4=84?= =?UTF-8?q?=E7=90=86=E3=80=82=207.=20.travis.yml=E6=A3=80=E6=9F=A5?= =?UTF-8?q?=E6=97=B6=E6=8E=92=E9=99=A4/pkg/mod/=E7=9B=AE=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .travis.yml | 19 ++++++----- cmd/commands/api/apiapp.go | 53 +++++++++++++++++++++++++--- cmd/commands/generate/generate.go | 9 ----- cmd/commands/hprose/hprose.go | 57 +++++++++++++++++++++++++++---- cmd/commands/migrate/migrate.go | 9 ----- cmd/commands/new/new.go | 53 +++++++++++++++++++++++----- cmd/commands/pack/pack.go | 11 ++++-- cmd/commands/run/run.go | 3 ++ cmd/commands/run/watch.go | 13 ++++--- cmd/commands/version/version.go | 2 +- generate/g_appcode.go | 37 ++++++++++++++++++-- generate/swaggergen/g_docs.go | 34 ++++++++++-------- utils/utils.go | 9 +++++ 13 files changed, 237 insertions(+), 72 deletions(-) diff --git a/.travis.yml b/.travis.yml index 0480311..eaad43e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,20 +1,21 @@ language: go go: - - 1.10.3 + - 1.12.17 install: - export PATH=$PATH:$HOME/gopath/bin - go get -u github.com/opennota/check/cmd/structcheck - - go get -u honnef.co/go/tools/cmd/gosimple - go get -u honnef.co/go/tools/cmd/staticcheck - - go get -u honnef.co/go/tools/cmd/unused - go get -u github.com/mdempsky/unconvert - go get -u github.com/gordonklaus/ineffassign script: + - pwd + - cd $(dirname `dirname $(pwd)`)/beego/bee + - export GO111MODULE="on" + - go mod download - find . ! \( -path './vendor' -prune \) -type f -name '*.go' -print0 | xargs -0 gofmt -l -s - - go vet $(go list ./... | grep -v /vendor/) - - structcheck $(go list ./... | grep -v /vendor/) - - gosimple -ignore "$(cat gosimple.ignore)" $(go list ./... | grep -v /vendor/) - - staticcheck -ignore "$(cat staticcheck.ignore)" $(go list ./... | grep -v /vendor/) - - unused $(go list ./... | grep -v /vendor/) - - unconvert $(go list ./... | grep -v /vendor/) + - go list ./... | grep -v /vendor/ | grep -v /pkg/mod/ + - go vet $(go list ./... | grep -v /vendor/ | grep -v /pkg/mod/ ) + - structcheck $(go list ./... | grep -v /vendor/ | grep -v /pkg/mod/ ) + - staticcheck $(go list ./... | grep -v /vendor/ | grep -v /pkg/mod/ ) + - unconvert $(go list ./... | grep -v /vendor/ | grep -v /pkg/mod/ ) - ineffassign . diff --git a/cmd/commands/api/apiapp.go b/cmd/commands/api/apiapp.go index 8f9865f..1265329 100644 --- a/cmd/commands/api/apiapp.go +++ b/cmd/commands/api/apiapp.go @@ -16,8 +16,10 @@ package apiapp import ( "fmt" + "github.com/beego/bee/logger/colors" "os" path "path/filepath" + "runtime" "strings" "github.com/beego/bee/cmd/commands" @@ -35,7 +37,7 @@ var CmdApiapp = &commands.Command{ The command 'api' creates a Beego API application. {{"Example:"|bold}} - $ bee api [appname] [-tables=""] [-driver=mysql] [-conn="root:@tcp(127.0.0.1:3306)/test"] + $ bee api [appname] [-tables=""] [-driver=mysql] [-conn="root:@tcp(127.0.0.1:3306)/test"] [-module=true] [-beego=v1.12.1] If 'conn' argument is empty, the command will generate an example API application. Otherwise the command will connect to your database and generate models based on the existing tables. @@ -43,6 +45,7 @@ var CmdApiapp = &commands.Command{ The command 'api' creates a folder named [appname] with the following structure: ├── main.go + ├── go.mod ├── {{"conf"|foldername}} │ └── app.conf ├── {{"controllers"|foldername}} @@ -103,6 +106,14 @@ func main() { beego.Run() } +` +var goMod = ` +module %s + +go %s + +require github.com/astaxie/beego %s +require github.com/smartystreets/goconvey v1.6.4 ` var apirouter = `// @APIVersion 1.0.0 @@ -533,11 +544,15 @@ func TestGet(t *testing.T) { } ` +var module utils.DocValue +var beegoVersion utils.DocValue func init() { CmdApiapp.Flag.Var(&generate.Tables, "tables", "List of table names separated by a comma.") CmdApiapp.Flag.Var(&generate.SQLDriver, "driver", "Database driver. Either mysql, postgres or sqlite.") CmdApiapp.Flag.Var(&generate.SQLConn, "conn", "Connection string used by the driver to connect to a database instance.") + CmdApiapp.Flag.Var(&module, "module", "Support go modules") + CmdApiapp.Flag.Var(&beegoVersion, "beego", "set beego version,only take effect by -module=true") commands.AvailableCommands = append(commands.AvailableCommands, CmdApiapp) } @@ -548,14 +563,38 @@ func createAPI(cmd *commands.Command, args []string) int { beeLogger.Log.Fatal("Argument [appname] is missing") } - if len(args) > 1 { - err := cmd.Flag.Parse(args[1:]) + if len(args) >= 2 { + cmd.Flag.Parse(args[1:]) + } else { + module = "false" + } + var appPath string + var packPath string + var err error + if module != `true` { + beeLogger.Log.Info("generate api project support GOPATH") + version.ShowShortVersionBanner() + appPath, packPath, err = utils.CheckEnv(args[0]) if err != nil { - beeLogger.Log.Error(err.Error()) + beeLogger.Log.Fatalf("%s", err) + } + } else { + beeLogger.Log.Info("generate api project support go modules.") + appPath = path.Join(utils.GetBeeWorkPath(), args[0]) + packPath = args[0] + if beegoVersion.String() == `` { + beegoVersion.Set(`v1.12.1`) + } + } + + if utils.IsExist(appPath) { + beeLogger.Log.Errorf(colors.Bold("Application '%s' already exists"), appPath) + beeLogger.Log.Warn(colors.Bold("Do you want to overwrite it? [Yes|No] ")) + if !utils.AskForConfirmation() { + os.Exit(2) } } - appPath, packPath, err := utils.CheckEnv(args[0]) appName := path.Base(args[0]) if err != nil { beeLogger.Log.Fatalf("%s", err) @@ -567,6 +606,10 @@ func createAPI(cmd *commands.Command, args []string) int { beeLogger.Log.Info("Creating API...") os.MkdirAll(appPath, 0755) + if module == `true` { //generate first for calc model name + fmt.Fprintf(output, "\t%s%screate%s\t %s%s\n", "\x1b[32m", "\x1b[1m", "\x1b[21m", path.Join(appPath, "go.mod"), "\x1b[0m") + utils.WriteToFile(path.Join(appPath, "go.mod"), fmt.Sprintf(goMod, packPath, runtime.Version()[2:], beegoVersion.String())) + } fmt.Fprintf(output, "\t%s%screate%s\t %s%s\n", "\x1b[32m", "\x1b[1m", "\x1b[21m", appPath, "\x1b[0m") os.Mkdir(path.Join(appPath, "conf"), 0755) fmt.Fprintf(output, "\t%s%screate%s\t %s%s\n", "\x1b[32m", "\x1b[1m", "\x1b[21m", path.Join(appPath, "conf"), "\x1b[0m") diff --git a/cmd/commands/generate/generate.go b/cmd/commands/generate/generate.go index 993ff3f..d8bee28 100644 --- a/cmd/commands/generate/generate.go +++ b/cmd/commands/generate/generate.go @@ -81,15 +81,6 @@ func GenerateCode(cmd *commands.Command, args []string) int { beeLogger.Log.Fatal("Command is missing") } - gps := utils.GetGOPATHs() - if len(gps) == 0 { - beeLogger.Log.Fatal("GOPATH environment variable is not set or empty") - } - - gopath := gps[0] - - beeLogger.Log.Debugf("GOPATH: %s", utils.FILE(), utils.LINE(), gopath) - gcmd := args[0] switch gcmd { case "scaffold": diff --git a/cmd/commands/hprose/hprose.go b/cmd/commands/hprose/hprose.go index 1d50581..f926c53 100644 --- a/cmd/commands/hprose/hprose.go +++ b/cmd/commands/hprose/hprose.go @@ -1,7 +1,9 @@ package hprose import ( + "github.com/beego/bee/logger/colors" "os" + "runtime" "fmt" "path" @@ -24,7 +26,7 @@ var CmdHproseapp = &commands.Command{ {{"To scaffold out your application, use:"|bold}} - $ bee hprose [appname] [-tables=""] [-driver=mysql] [-conn="root:@tcp(127.0.0.1:3306)/test"] + $ bee hprose [appname] [-tables=""] [-driver=mysql] [-conn="root:@tcp(127.0.0.1:3306)/test"] [-module=true] [-beego=v1.12.1] If 'conn' is empty, the command will generate a sample application. Otherwise the command will connect to your database and generate models based on the existing tables. @@ -32,6 +34,7 @@ var CmdHproseapp = &commands.Command{ The command 'hprose' creates a folder named [appname] with the following structure: ├── main.go + ├── go.mod ├── {{"conf"|foldername}} │ └── app.conf └── {{"models"|foldername}} @@ -42,34 +45,76 @@ var CmdHproseapp = &commands.Command{ Run: createhprose, } +var goMod = ` +module %s + +go %s + +require github.com/astaxie/beego %s +require github.com/smartystreets/goconvey v1.6.4 +` + +var module utils.DocValue +var beegoVersion utils.DocValue + func init() { CmdHproseapp.Flag.Var(&generate.Tables, "tables", "List of table names separated by a comma.") CmdHproseapp.Flag.Var(&generate.SQLDriver, "driver", "Database driver. Either mysql, postgres or sqlite.") CmdHproseapp.Flag.Var(&generate.SQLConn, "conn", "Connection string used by the driver to connect to a database instance.") + CmdHproseapp.Flag.Var(&module, "module", "Support go modules") + CmdHproseapp.Flag.Var(&beegoVersion, "beego", "set beego version,only take effect by -module=true") commands.AvailableCommands = append(commands.AvailableCommands, CmdHproseapp) } func createhprose(cmd *commands.Command, args []string) int { output := cmd.Out() - - if len(args) != 1 { + if len(args) == 0 { beeLogger.Log.Fatal("Argument [appname] is missing") } curpath, _ := os.Getwd() if len(args) > 1 { cmd.Flag.Parse(args[1:]) + } else { + module = "false" } - apppath, packpath, err := utils.CheckEnv(args[0]) - if err != nil { - beeLogger.Log.Fatalf("%s", err) + var apppath string + var packpath string + var err error + if module != `true` { + beeLogger.Log.Info("generate api project support GOPATH") + version.ShowShortVersionBanner() + apppath, packpath, err = utils.CheckEnv(args[0]) + if err != nil { + beeLogger.Log.Fatalf("%s", err) + } + } else { + beeLogger.Log.Info("generate api project support go modules.") + apppath = path.Join(utils.GetBeeWorkPath(), args[0]) + packpath = args[0] + if beegoVersion.String() == `` { + beegoVersion.Set(`v1.12.1`) + } } + + if utils.IsExist(apppath) { + beeLogger.Log.Errorf(colors.Bold("Application '%s' already exists"), apppath) + beeLogger.Log.Warn(colors.Bold("Do you want to overwrite it? [Yes|No] ")) + if !utils.AskForConfirmation() { + os.Exit(2) + } + } + if generate.SQLDriver == "" { generate.SQLDriver = "mysql" } beeLogger.Log.Info("Creating Hprose application...") os.MkdirAll(apppath, 0755) + if module == `true` { //generate first for calc model name + fmt.Fprintf(output, "\t%s%screate%s\t %s%s\n", "\x1b[32m", "\x1b[1m", "\x1b[21m", path.Join(apppath, "go.mod"), "\x1b[0m") + utils.WriteToFile(path.Join(apppath, "go.mod"), fmt.Sprintf(goMod, packpath, runtime.Version()[2:], beegoVersion.String())) + } fmt.Fprintf(output, "\t%s%screate%s\t %s%s\n", "\x1b[32m", "\x1b[1m", "\x1b[21m", apppath, "\x1b[0m") os.Mkdir(path.Join(apppath, "conf"), 0755) fmt.Fprintf(output, "\t%s%screate%s\t %s%s\n", "\x1b[32m", "\x1b[1m", "\x1b[21m", path.Join(apppath, "conf"), "\x1b[0m") diff --git a/cmd/commands/migrate/migrate.go b/cmd/commands/migrate/migrate.go index 71e93cd..edf6bbb 100644 --- a/cmd/commands/migrate/migrate.go +++ b/cmd/commands/migrate/migrate.go @@ -71,15 +71,6 @@ func init() { func RunMigration(cmd *commands.Command, args []string) int { currpath, _ := os.Getwd() - gps := utils.GetGOPATHs() - if len(gps) == 0 { - beeLogger.Log.Fatal("GOPATH environment variable is not set or empty") - } - - gopath := gps[0] - - beeLogger.Log.Debugf("GOPATH: %s", utils.FILE(), utils.LINE(), gopath) - // Getting command line arguments if len(args) != 0 { cmd.Flag.Parse(args[1:]) diff --git a/cmd/commands/new/new.go b/cmd/commands/new/new.go index 3cb1cc7..98c1aed 100644 --- a/cmd/commands/new/new.go +++ b/cmd/commands/new/new.go @@ -18,6 +18,7 @@ import ( "fmt" "os" path "path/filepath" + "runtime" "strings" "github.com/beego/bee/cmd/commands" @@ -27,15 +28,19 @@ import ( "github.com/beego/bee/utils" ) +var module utils.DocValue +var beegoVersion utils.DocValue + var CmdNew = &commands.Command{ - UsageLine: "new [appname]", + UsageLine: "new [appname] [-module=true] [-beego=v1.12.1]", Short: "Creates a Beego application", Long: ` Creates a Beego application for the given app name in the current directory. - - The command 'new' creates a folder named [appname] and generates the following structure: + now supoort generate a go modules project + The command 'new' creates a folder named [appname] [-module=true] [-beego=v1.12.1] and generates the following structure: ├── main.go + ├── go.mod ├── {{"conf"|foldername}} │ └── app.conf ├── {{"controllers"|foldername}} @@ -53,7 +58,7 @@ Creates a Beego application for the given app name in the current directory. └── index.tpl `, - PreRun: func(cmd *commands.Command, args []string) { version.ShowShortVersionBanner() }, + PreRun: nil, Run: CreateApp, } @@ -85,7 +90,14 @@ func init() { beego.Router("/", &controllers.MainController{}) } ` +var goMod = ` +module %s +go %s + +require github.com/astaxie/beego %s +require github.com/smartystreets/goconvey v1.6.4 +` var test = `package test import ( @@ -245,18 +257,39 @@ var reloadJsClient = `function b(a){var c=new WebSocket(a);c.onclose=function(){ ` func init() { + CmdNew.Flag.Var(&module, "module", "Support go modules") + CmdNew.Flag.Var(&beegoVersion, "beego", "set beego version,only take effect by -module=true") commands.AvailableCommands = append(commands.AvailableCommands, CmdNew) } func CreateApp(cmd *commands.Command, args []string) int { output := cmd.Out() - if len(args) != 1 { + if len(args) == 0 { beeLogger.Log.Fatal("Argument [appname] is missing") } - appPath, packPath, err := utils.CheckEnv(args[0]) - if err != nil { - beeLogger.Log.Fatalf("%s", err) + if len(args) >= 2 { + cmd.Flag.Parse(args[1:]) + } else { + module = "false" + } + var appPath string + var packPath string + var err error + if module != `true` { + beeLogger.Log.Info("generate new project support GOPATH") + version.ShowShortVersionBanner() + appPath, packPath, err = utils.CheckEnv(args[0]) + if err != nil { + beeLogger.Log.Fatalf("%s", err) + } + } else { + beeLogger.Log.Info("generate new project support go modules.") + appPath = path.Join(utils.GetBeeWorkPath(), args[0]) + packPath = args[0] + if beegoVersion.String() == `` { + beegoVersion.Set(`v1.12.1`) + } } if utils.IsExist(appPath) { @@ -270,6 +303,10 @@ func CreateApp(cmd *commands.Command, args []string) int { beeLogger.Log.Info("Creating application...") os.MkdirAll(appPath, 0755) + if module == `true` { + fmt.Fprintf(output, "\t%s%screate%s\t %s%s\n", "\x1b[32m", "\x1b[1m", "\x1b[21m", path.Join(appPath, "go.mod"), "\x1b[0m") + utils.WriteToFile(path.Join(appPath, "go.mod"), fmt.Sprintf(goMod, packPath, runtime.Version()[2:], beegoVersion.String())) + } fmt.Fprintf(output, "\t%s%screate%s\t %s%s\n", "\x1b[32m", "\x1b[1m", "\x1b[21m", appPath+string(path.Separator), "\x1b[0m") os.Mkdir(path.Join(appPath, "conf"), 0755) fmt.Fprintf(output, "\t%s%screate%s\t %s%s\n", "\x1b[32m", "\x1b[1m", "\x1b[21m", path.Join(appPath, "conf")+string(path.Separator), "\x1b[0m") diff --git a/cmd/commands/pack/pack.go b/cmd/commands/pack/pack.go index becddcc..36540ea 100644 --- a/cmd/commands/pack/pack.go +++ b/cmd/commands/pack/pack.go @@ -40,6 +40,7 @@ var CmdPack = &commands.Command{ var ( appPath string + appName string excludeP string excludeS string outputP string @@ -57,6 +58,7 @@ func init() { fs := flag.NewFlagSet("pack", flag.ContinueOnError) fs.StringVar(&appPath, "p", "", "Set the application path. Defaults to the current path.") fs.BoolVar(&build, "b", true, "Tell the command to do a build for the current platform. Defaults to true.") + fs.StringVar(&appName, "a", "", "Set the application name. Defaults to the dir name.") fs.StringVar(&buildArgs, "ba", "", "Specify additional args for Go build.") fs.Var(&buildEnvs, "be", "Specify additional env variables for Go build. e.g. GOARCH=arm.") fs.StringVar(&outputP, "o", "", "Set the compressed file output path. Defaults to the current path.") @@ -445,7 +447,9 @@ func packApp(cmd *commands.Command, args []string) int { beeLogger.Log.Infof("Packaging application on '%s'...", thePath) - appName := path.Base(thePath) + if len(appName) == 0 { + appName = path.Base(thePath) + } goos := runtime.GOOS if v, found := syscall.Getenv("GOOS"); found { @@ -470,7 +474,7 @@ func packApp(cmd *commands.Command, args []string) int { }() if build { - beeLogger.Log.Info("Building application...") + beeLogger.Log.Infof("Building application (%v)...", appName) var envs []string for _, env := range buildEnvs { parts := strings.SplitN(env, "=", 2) @@ -553,7 +557,8 @@ func packApp(cmd *commands.Command, args []string) int { exs = append(exs, p) } } - + exs = append(exs, `go.mod`) + exs = append(exs, `go.sum`) var exr []*regexp.Regexp for _, r := range excludeR { if len(r) > 0 { diff --git a/cmd/commands/run/run.go b/cmd/commands/run/run.go index bcd6251..9eec587 100644 --- a/cmd/commands/run/run.go +++ b/cmd/commands/run/run.go @@ -46,6 +46,8 @@ var ( excludedPaths utils.StrFlags // Pass through to -tags arg of "go build" buildTags string + // Pass through to -ldflags arg of "go build" + buildLDFlags string // Application path currpath string // Application name @@ -72,6 +74,7 @@ func init() { CmdRun.Flag.Var(&excludedPaths, "e", "List of paths to exclude.") CmdRun.Flag.BoolVar(&vendorWatch, "vendor", false, "Enable watch vendor folder.") CmdRun.Flag.StringVar(&buildTags, "tags", "", "Set the build tags. See: https://golang.org/pkg/go/build/") + CmdRun.Flag.StringVar(&buildLDFlags, "ldflags", "", "Set the build ldflags. See: https://golang.org/pkg/go/build/") CmdRun.Flag.StringVar(&runmode, "runmode", "", "Set the Beego run mode.") CmdRun.Flag.StringVar(&runargs, "runargs", "", "Extra args to run application") CmdRun.Flag.Var(&extraPackages, "ex", "List of extra package to watch.") diff --git a/cmd/commands/run/watch.go b/cmd/commands/run/watch.go index 5e6b493..5aae690 100644 --- a/cmd/commands/run/watch.go +++ b/cmd/commands/run/watch.go @@ -39,11 +39,11 @@ var ( watchExts = config.Conf.WatchExts watchExtsStatic = config.Conf.WatchExtsStatic ignoredFilesRegExps = []string{ - `.#(\w+).go`, - `.(\w+).go.swp`, - `(\w+).go~`, - `(\w+).tmp`, - `commentsRouter_controllers.go`, + `.#(\w+).go$`, + `.(\w+).go.swp$`, + `(\w+).go~$`, + `(\w+).tmp$`, + `commentsRouter_controllers.go$`, } ) @@ -158,6 +158,9 @@ func AutoBuild(files []string, isgenerate bool) { if buildTags != "" { args = append(args, "-tags", buildTags) } + if buildLDFlags != "" { + args = append(args, "-ldflags", buildLDFlags) + } args = append(args, files...) bcmd := exec.Command(cmdName, args...) diff --git a/cmd/commands/version/version.go b/cmd/commands/version/version.go index b30128a..4eebd9f 100644 --- a/cmd/commands/version/version.go +++ b/cmd/commands/version/version.go @@ -124,7 +124,7 @@ func GetBeegoVersion() string { } wgopath := utils.GetGOPATHs() if len(wgopath) == 0 { - beeLogger.Log.Error("You need to set GOPATH environment variable") + beeLogger.Log.Error("GOPATH environment is empty,may be you use `go module`") return "" } for _, wg := range wgopath { diff --git a/generate/g_appcode.go b/generate/g_appcode.go index 260472a..014d3a5 100644 --- a/generate/g_appcode.go +++ b/generate/g_appcode.go @@ -15,8 +15,10 @@ package generate import ( + "bufio" "database/sql" "fmt" + "io" "os" "path" "path/filepath" @@ -948,11 +950,40 @@ func getFileName(tbName string) (filename string) { func getPackagePath(curpath string) (packpath string) { gopath := os.Getenv("GOPATH") if gopath == "" { - beeLogger.Log.Fatal("GOPATH environment variable is not set or empty") + info := "GOPATH environment variable is not set or empty" + gomodpath := filepath.Join(curpath, `go.mod`) + re, err := regexp.Compile(`^module\s+(.+)$`) + if err != nil { + beeLogger.Log.Error(info) + beeLogger.Log.Fatalf("try `go.mod` generate regexp error:%s", err) + return "" + } + fd, err := os.Open(gomodpath) + if err != nil { + beeLogger.Log.Error(info) + beeLogger.Log.Fatalf("try `go.mod` Error while reading 'go.mod',%s", gomodpath) + } + reader := bufio.NewReader(fd) + for { + byteLine, _, er := reader.ReadLine() + if er != nil && er != io.EOF { + return "" + } + if er == io.EOF { + break + } + line := string(byteLine) + s := re.FindStringSubmatch(line) + if len(s) >= 2 { + return s[1] + } + } + beeLogger.Log.Error(info) + beeLogger.Log.Fatalf("try `go.mod` Error while parse 'go.mod',%s", gomodpath) + } else { + beeLogger.Log.Debugf("GOPATH: %s", utils.FILE(), utils.LINE(), gopath) } - beeLogger.Log.Debugf("GOPATH: %s", utils.FILE(), utils.LINE(), gopath) - appsrcpath := "" haspath := false wgopath := filepath.SplitList(gopath) diff --git a/generate/swaggergen/g_docs.go b/generate/swaggergen/g_docs.go index 512e01c..69fcfe8 100644 --- a/generate/swaggergen/g_docs.go +++ b/generate/swaggergen/g_docs.go @@ -432,22 +432,27 @@ func analyseControllerPkg(vendorPath, localName, pkgpath string) { pps := strings.Split(pkgpath, "/") importlist[pps[len(pps)-1]] = pkgpath } - gopaths := bu.GetGOPATHs() - if len(gopaths) == 0 { - beeLogger.Log.Fatal("GOPATH environment variable is not set or empty") - } + pkgRealpath := "" - wg, _ := filepath.EvalSymlinks(filepath.Join(vendorPath, pkgpath)) - if utils.FileExists(wg) { - pkgRealpath = wg + if os.Getenv(`GO111MODULE`) == `on` { + pkgRealpath = filepath.Join(bu.GetBeeWorkPath(), "..", pkgpath) } else { - wgopath := gopaths - for _, wg := range wgopath { - wg, _ = filepath.EvalSymlinks(filepath.Join(wg, "src", pkgpath)) - if utils.FileExists(wg) { - pkgRealpath = wg - break + gopaths := bu.GetGOPATHs() + if len(gopaths) == 0 { + beeLogger.Log.Fatal("GOPATH environment variable is not set or empty") + } + wg, _ := filepath.EvalSymlinks(filepath.Join(vendorPath, pkgpath)) + if utils.FileExists(wg) { + pkgRealpath = wg + } else { + wgopath := gopaths + for _, wg := range wgopath { + wg, _ = filepath.EvalSymlinks(filepath.Join(wg, "src", pkgpath)) + if utils.FileExists(wg) { + pkgRealpath = wg + break + } } } } @@ -468,6 +473,7 @@ func analyseControllerPkg(vendorPath, localName, pkgpath string) { if err != nil { beeLogger.Log.Fatalf("Error while parsing dir at '%s': %s", pkgpath, err) } + for _, pkg := range astPkgs { for _, fl := range pkg.Files { for _, d := range fl.Decls { @@ -802,7 +808,7 @@ func setParamType(para *swagger.Parameter, typ string, pkgpath, controllerName s paraFormat = typeFormat[1] if para.In == "body" { para.Schema = &swagger.Schema{ - Type: paraType, + Type: paraType, Format: paraFormat, } } diff --git a/utils/utils.go b/utils/utils.go index 75b6898..ce62421 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -33,6 +33,14 @@ import ( "github.com/beego/bee/logger/colors" ) +func GetBeeWorkPath() string { + beePath, err := filepath.Abs(filepath.Dir(os.Args[0])) + if err != nil { + panic(err) + } + return beePath +} + // Go is a basic promise implementation: it wraps calls a function in a goroutine // and returns a channel which will later return the function's return value. func Go(f func() error) chan error { @@ -305,6 +313,7 @@ func Tmpl(text string, data interface{}) { func CheckEnv(appname string) (apppath, packpath string, err error) { gps := GetGOPATHs() if len(gps) == 0 { + beeLogger.Log.Error("if you want new a go module project,please add param `-module=true` and set env `G111MODULE=on`") beeLogger.Log.Fatal("GOPATH environment variable is not set or empty") } currpath, _ := os.Getwd()