1. new,api,hprose 命令增加两个参数 [-module=true] [-beego=v1.12.1] 用于生成go module项目

2. generate,migrate命令不再打印GOPATH.
3. pack命令排除。
4. run命令支持传递ldflags参数
5. fix watch file bug.ignoredFilesRegExps数组对每个文件增加$,防止目录存在tmp的情况
6. getPackagePath函数被调用时如果找不到GOPATH,则看看工程有没有go.mod 有就当做go module项目处理。
7. .travis.yml检查时排除/pkg/mod/目录
This commit is contained in:
qiantao 2020-06-25 22:29:27 +08:00
parent 1334a99810
commit 9433a7b66f
13 changed files with 237 additions and 72 deletions

View File

@ -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 .

View File

@ -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")

View File

@ -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":

View File

@ -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")

View File

@ -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:])

View File

@ -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")

View File

@ -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 {

View File

@ -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.")

View File

@ -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...)

View File

@ -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 {

View File

@ -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)

View File

@ -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,
}
}

View File

@ -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()