1
0
mirror of https://github.com/beego/bee.git synced 2024-11-25 20:10:55 +00:00

Merge pull request #2 from beego/develop

Develop update
This commit is contained in:
Sergey Lanzman 2016-07-07 15:18:05 +03:00 committed by GitHub
commit c9bcadf026
20 changed files with 300 additions and 220 deletions

View File

@ -7,7 +7,7 @@ Bee is a command line tool facilitating development with beego framework.
## Requirements ## Requirements
- Go version >= 1.1. - Go version >= 1.3.
## Installation ## Installation

115
apiapp.go
View File

@ -546,14 +546,17 @@ func init() {
} }
func createapi(cmd *Command, args []string) int { func createapi(cmd *Command, args []string) int {
curpath, _ := os.Getwd() ShowShortVersionBanner()
if len(args) < 1 { if len(args) < 1 {
ColorLog("[ERRO] Argument [appname] is missing\n") ColorLog("[ERRO] Argument [appname] is missing\n")
os.Exit(2) os.Exit(2)
} }
if len(args) > 1 { if len(args) > 1 {
cmd.Flag.Parse(args[1:]) cmd.Flag.Parse(args[1:])
} }
apppath, packpath, err := checkEnv(args[0]) apppath, packpath, err := checkEnv(args[0])
if err != nil { if err != nil {
fmt.Println(err) fmt.Println(err)
@ -564,23 +567,25 @@ func createapi(cmd *Command, args []string) int {
} }
if conn == "" { if conn == "" {
} }
os.MkdirAll(apppath, 0755)
fmt.Println("create app folder:", apppath)
os.Mkdir(path.Join(apppath, "conf"), 0755)
fmt.Println("create conf:", path.Join(apppath, "conf"))
os.Mkdir(path.Join(apppath, "controllers"), 0755)
fmt.Println("create controllers:", path.Join(apppath, "controllers"))
os.Mkdir(path.Join(apppath, "docs"), 0755)
fmt.Println("create docs:", path.Join(apppath, "docs"))
os.Mkdir(path.Join(apppath, "tests"), 0755)
fmt.Println("create tests:", path.Join(apppath, "tests"))
fmt.Println("create conf app.conf:", path.Join(apppath, "conf", "app.conf")) ColorLog("[INFO] Creating API...\n")
writetofile(path.Join(apppath, "conf", "app.conf"),
strings.Replace(apiconf, "{{.Appname}}", args[0], -1)) os.MkdirAll(apppath, 0755)
fmt.Println("\tcreate\t", apppath)
os.Mkdir(path.Join(apppath, "conf"), 0755)
fmt.Println("\tcreate\t", path.Join(apppath, "conf"))
os.Mkdir(path.Join(apppath, "controllers"), 0755)
fmt.Println("\tcreate\t", path.Join(apppath, "controllers"))
os.Mkdir(path.Join(apppath, "docs"), 0755)
fmt.Println("\tcreate\t", path.Join(apppath, "docs"))
os.Mkdir(path.Join(apppath, "tests"), 0755)
fmt.Println("\tcreate\t", path.Join(apppath, "tests"))
fmt.Println("\tcreate\t", path.Join(apppath, "conf", "app.conf"))
WriteToFile(path.Join(apppath, "conf", "app.conf"),
strings.Replace(apiconf, "{{.Appname}}", path.Base(args[0]), -1))
if conn != "" { if conn != "" {
fmt.Println("create main.go:", path.Join(apppath, "main.go")) fmt.Println("\tcreate\t", path.Join(apppath, "main.go"))
maingoContent := strings.Replace(apiMainconngo, "{{.Appname}}", packpath, -1) maingoContent := strings.Replace(apiMainconngo, "{{.Appname}}", packpath, -1)
maingoContent = strings.Replace(maingoContent, "{{.DriverName}}", string(driver), -1) maingoContent = strings.Replace(maingoContent, "{{.DriverName}}", string(driver), -1)
if driver == "mysql" { if driver == "mysql" {
@ -588,7 +593,7 @@ func createapi(cmd *Command, args []string) int {
} else if driver == "postgres" { } else if driver == "postgres" {
maingoContent = strings.Replace(maingoContent, "{{.DriverPkg}}", `_ "github.com/lib/pq"`, -1) maingoContent = strings.Replace(maingoContent, "{{.DriverPkg}}", `_ "github.com/lib/pq"`, -1)
} }
writetofile(path.Join(apppath, "main.go"), WriteToFile(path.Join(apppath, "main.go"),
strings.Replace( strings.Replace(
maingoContent, maingoContent,
"{{.conn}}", "{{.conn}}",
@ -599,51 +604,47 @@ func createapi(cmd *Command, args []string) int {
ColorLog("[INFO] Using '%s' as 'driver'\n", driver) ColorLog("[INFO] Using '%s' as 'driver'\n", driver)
ColorLog("[INFO] Using '%s' as 'conn'\n", conn) ColorLog("[INFO] Using '%s' as 'conn'\n", conn)
ColorLog("[INFO] Using '%s' as 'tables'\n", tables) ColorLog("[INFO] Using '%s' as 'tables'\n", tables)
generateAppcode(string(driver), string(conn), "3", string(tables), path.Join(curpath, args[0])) generateAppcode(string(driver), string(conn), "3", string(tables), path.Join(apppath, args[0]))
} else { } else {
os.Mkdir(path.Join(apppath, "models"), 0755) os.Mkdir(path.Join(apppath, "models"), 0755)
fmt.Println("create models:", path.Join(apppath, "models")) fmt.Println("\tcreate\t", path.Join(apppath, "models"))
os.Mkdir(path.Join(apppath, "routers"), 0755) os.Mkdir(path.Join(apppath, "routers"), 0755)
fmt.Println(path.Join(apppath, "routers") + string(path.Separator)) fmt.Println("\tcreate\t", path.Join(apppath, "routers") + string(path.Separator))
fmt.Println("create controllers object.go:", path.Join(apppath, "controllers", "object.go")) fmt.Println("\tcreate\t", path.Join(apppath, "controllers", "object.go"))
writetofile(path.Join(apppath, "controllers", "object.go"), WriteToFile(path.Join(apppath, "controllers", "object.go"),
strings.Replace(apiControllers, "{{.Appname}}", packpath, -1)) strings.Replace(apiControllers, "{{.Appname}}", packpath, -1))
fmt.Println("create controllers user.go:", path.Join(apppath, "controllers", "user.go")) fmt.Println("\tcreate\t", path.Join(apppath, "controllers", "user.go"))
writetofile(path.Join(apppath, "controllers", "user.go"), WriteToFile(path.Join(apppath, "controllers", "user.go"),
strings.Replace(apiControllers2, "{{.Appname}}", packpath, -1)) strings.Replace(apiControllers2, "{{.Appname}}", packpath, -1))
fmt.Println("create tests default.go:", path.Join(apppath, "tests", "default_test.go")) fmt.Println("\tcreate\t", path.Join(apppath, "tests", "default_test.go"))
writetofile(path.Join(apppath, "tests", "default_test.go"), WriteToFile(path.Join(apppath, "tests", "default_test.go"),
strings.Replace(apiTests, "{{.Appname}}", packpath, -1)) strings.Replace(apiTests, "{{.Appname}}", packpath, -1))
fmt.Println("create routers router.go:", path.Join(apppath, "routers", "router.go")) fmt.Println("\tcreate\t", path.Join(apppath, "routers", "router.go"))
writetofile(path.Join(apppath, "routers", "router.go"), WriteToFile(path.Join(apppath, "routers", "router.go"),
strings.Replace(apirouter, "{{.Appname}}", packpath, -1)) strings.Replace(apirouter, "{{.Appname}}", packpath, -1))
fmt.Println("create models object.go:", path.Join(apppath, "models", "object.go")) fmt.Println("\tcreate\t", path.Join(apppath, "models", "object.go"))
writetofile(path.Join(apppath, "models", "object.go"), apiModels) WriteToFile(path.Join(apppath, "models", "object.go"), apiModels)
fmt.Println("create models user.go:", path.Join(apppath, "models", "user.go")) fmt.Println("\tcreate\t", path.Join(apppath, "models", "user.go"))
writetofile(path.Join(apppath, "models", "user.go"), apiModels2) WriteToFile(path.Join(apppath, "models", "user.go"), apiModels2)
fmt.Println("create docs doc.go:", path.Join(apppath, "docs", "doc.go")) fmt.Println("\tcreate\t", path.Join(apppath, "docs", "doc.go"))
writetofile(path.Join(apppath, "docs", "doc.go"), "package docs") WriteToFile(path.Join(apppath, "docs", "doc.go"), "package docs")
fmt.Println("create main.go:", path.Join(apppath, "main.go")) fmt.Println("\tcreate\t", path.Join(apppath, "main.go"))
writetofile(path.Join(apppath, "main.go"), WriteToFile(path.Join(apppath, "main.go"),
strings.Replace(apiMaingo, "{{.Appname}}", packpath, -1)) strings.Replace(apiMaingo, "{{.Appname}}", packpath, -1))
} }
ColorLog("[SUCC] New API successfully created!\n")
return 0 return 0
} }
func checkEnv(appname string) (apppath, packpath string, err error) { func checkEnv(appname string) (apppath, packpath string, err error) {
curpath, err := os.Getwd()
if err != nil {
return
}
gopath := os.Getenv("GOPATH") gopath := os.Getenv("GOPATH")
Debugf("gopath:%s", gopath) Debugf("gopath:%s", gopath)
if gopath == "" { if gopath == "" {
@ -651,38 +652,14 @@ func checkEnv(appname string) (apppath, packpath string, err error) {
return return
} }
appsrcpath := "" gosrcpath := path.Join(gopath, "src")
haspath := false apppath = path.Join(gosrcpath, appname)
wgopath := path.SplitList(gopath)
for _, wg := range wgopath {
wg = path.Join(wg, "src")
if strings.HasPrefix(strings.ToLower(curpath), strings.ToLower(wg)) {
haspath = true
appsrcpath = wg
break
}
wg, _ = path.EvalSymlinks(wg)
if strings.HasPrefix(strings.ToLower(curpath), strings.ToLower(wg)) {
haspath = true
appsrcpath = wg
break
}
}
if !haspath {
err = fmt.Errorf("can't create application outside of GOPATH `%s`\n"+
"you first should `cd $GOPATH%ssrc` then use create\n", gopath, string(path.Separator))
return
}
apppath = path.Join(curpath, appname)
if _, e := os.Stat(apppath); os.IsNotExist(e) == false { if _, e := os.Stat(apppath); os.IsNotExist(e) == false {
err = fmt.Errorf("path `%s` exists, can not create app without remove it\n", apppath) err = fmt.Errorf("Cannot create application without removing `%s` first.", apppath)
ColorLog("[ERRO] Path `%s` already exists\n", apppath)
return return
} }
packpath = strings.Join(strings.Split(apppath[len(appsrcpath)+1:], string(path.Separator)), "/") packpath = strings.Join(strings.Split(apppath[len(gosrcpath)+1:], string(path.Separator)), "/")
return return
} }

View File

@ -46,6 +46,8 @@ func init() {
} }
func runBale(cmd *Command, args []string) int { func runBale(cmd *Command, args []string) int {
ShowShortVersionBanner()
err := loadConfig() err := loadConfig()
if err != nil { if err != nil {
ColorLog("[ERRO] Fail to parse bee.json[ %s ]\n", err) ColorLog("[ERRO] Fail to parse bee.json[ %s ]\n", err)
@ -60,7 +62,7 @@ func runBale(cmd *Command, args []string) int {
ColorLog("[WARN] Skipped directory( %s )\n", p) ColorLog("[WARN] Skipped directory( %s )\n", p)
continue continue
} }
ColorLog("[INFO] Packing directory( %s )\n", p) ColorLog("[INFO] Packaging directory( %s )\n", p)
filepath.Walk(p, walkFn) filepath.Walk(p, walkFn)
} }

69
banner.go Normal file
View File

@ -0,0 +1,69 @@
package main
import (
"io"
"io/ioutil"
"os"
"runtime"
"text/template"
"time"
)
type vars struct {
GoVersion string
GOOS string
GOARCH string
NumCPU int
GOPATH string
GOROOT string
Compiler string
BeeVersion string
BeegoVersion string
}
func Now(layout string) string {
return time.Now().Format(layout)
}
// Init load the banner and prints it to output
// All errors are ignored, the application will not
// print the banner in case of error.
func InitBanner(out io.Writer, in io.Reader) {
if in == nil {
ColorLog("[ERRO] The input is nil\n")
os.Exit(2)
}
banner, err := ioutil.ReadAll(in)
if err != nil {
ColorLog("[ERRO] Error trying to read the banner\n")
ColorLog("[HINT] %v\n", err)
os.Exit(2)
}
show(out, string(banner))
}
func show(out io.Writer, content string) {
t, err := template.New("banner").
Funcs(template.FuncMap{"Now": Now}).
Parse(content)
if err != nil {
ColorLog("[ERRO] Cannot parse the banner template\n")
ColorLog("[HINT] %v\n", err)
os.Exit(2)
}
t.Execute(out, vars{
runtime.Version(),
runtime.GOOS,
runtime.GOARCH,
runtime.NumCPU(),
os.Getenv("GOPATH"),
runtime.GOROOT(),
runtime.Compiler,
version,
getBeegoVersion(),
})
}

13
fix.go
View File

@ -8,11 +8,12 @@ import (
"path/filepath" "path/filepath"
"regexp" "regexp"
"strings" "strings"
"fmt"
) )
var cmdFix = &Command{ var cmdFix = &Command{
UsageLine: "fix", UsageLine: "fix",
Short: "fix the beego application to compatibel with beego 1.6", Short: "fix the beego application to make it compatible with beego 1.6",
Long: ` Long: `
As from beego1.6, there's some incompatible code with the old version. As from beego1.6, there's some incompatible code with the old version.
@ -25,9 +26,12 @@ func init() {
} }
func runFix(cmd *Command, args []string) int { func runFix(cmd *Command, args []string) int {
ShowShortVersionBanner()
ColorLog("[INFO] Upgrading the application...\n")
dir, err := os.Getwd() dir, err := os.Getwd()
if err != nil { if err != nil {
ColorLog("GetCurrent Path:%s\n", err) ColorLog("[ERRO] GetCurrent Path:%s\n", err)
} }
filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if info.IsDir() { if info.IsDir() {
@ -42,13 +46,14 @@ func runFix(cmd *Command, args []string) int {
if strings.HasSuffix(info.Name(), ".exe") { if strings.HasSuffix(info.Name(), ".exe") {
return nil return nil
} }
ColorLog("%s\n", path)
err = fixFile(path) err = fixFile(path)
fmt.Println("\tfix\t", path)
if err != nil { if err != nil {
ColorLog("fixFile:%s\n", err) ColorLog("[ERRO] Could not fix file: %s\n", err)
} }
return err return err
}) })
ColorLog("[INFO] Upgrade done!\n")
return 0 return 0
} }

11
g.go
View File

@ -14,7 +14,10 @@
package main package main
import "os" import (
"os"
"strings"
)
var cmdGenerate = &Command{ var cmdGenerate = &Command{
UsageLine: "generate [Command]", UsageLine: "generate [Command]",
@ -74,6 +77,8 @@ func init() {
} }
func generateCode(cmd *Command, args []string) int { func generateCode(cmd *Command, args []string) int {
ShowShortVersionBanner()
curpath, _ := os.Getwd() curpath, _ := os.Getwd()
if len(args) < 1 { if len(args) < 1 {
ColorLog("[ERRO] command is missing\n") ColorLog("[ERRO] command is missing\n")
@ -119,7 +124,6 @@ func generateCode(cmd *Command, args []string) int {
os.Exit(2) os.Exit(2)
} }
sname := args[1] sname := args[1]
ColorLog("[INFO] Using '%s' as scaffold name\n", sname)
generateScaffold(sname, fields.String(), curpath, driver.String(), conn.String()) generateScaffold(sname, fields.String(), curpath, driver.String(), conn.String())
case "docs": case "docs":
generateDocs(curpath) generateDocs(curpath)
@ -192,7 +196,6 @@ func generateCode(cmd *Command, args []string) int {
os.Exit(2) os.Exit(2)
} }
sname := args[1] sname := args[1]
ColorLog("[INFO] Using '%s' as model name\n", sname)
generateModel(sname, fields.String(), curpath) generateModel(sname, fields.String(), curpath)
case "view": case "view":
if len(args) == 2 { if len(args) == 2 {
@ -206,6 +209,6 @@ func generateCode(cmd *Command, args []string) int {
default: default:
ColorLog("[ERRO] command is missing\n") ColorLog("[ERRO] command is missing\n")
} }
ColorLog("[SUCC] generate successfully created!\n") ColorLog("[SUCC] %s successfully generated!\n", strings.Title(gcmd))
return 0 return 0
} }

View File

@ -292,7 +292,7 @@ func generateAppcode(driver, connStr, level, tables, currpath string) {
// Generate takes table, column and foreign key information from database connection // Generate takes table, column and foreign key information from database connection
// and generate corresponding golang source files // and generate corresponding golang source files
func gen(dbms, connStr string, mode byte, selectedTableNames map[string]bool, currpath string) { func gen(dbms, connStr string, mode byte, selectedTableNames map[string]bool, apppath string) {
db, err := sql.Open(dbms, connStr) db, err := sql.Open(dbms, connStr)
if err != nil { if err != nil {
ColorLog("[ERRO] Could not connect to %s database: %s, %s\n", dbms, connStr, err) ColorLog("[ERRO] Could not connect to %s database: %s, %s\n", dbms, connStr, err)
@ -304,11 +304,11 @@ func gen(dbms, connStr string, mode byte, selectedTableNames map[string]bool, cu
tableNames := trans.GetTableNames(db) tableNames := trans.GetTableNames(db)
tables := getTableObjects(tableNames, db, trans) tables := getTableObjects(tableNames, db, trans)
mvcPath := new(MvcPath) mvcPath := new(MvcPath)
mvcPath.ModelPath = path.Join(currpath, "models") mvcPath.ModelPath = path.Join(apppath, "models")
mvcPath.ControllerPath = path.Join(currpath, "controllers") mvcPath.ControllerPath = path.Join(apppath, "controllers")
mvcPath.RouterPath = path.Join(currpath, "routers") mvcPath.RouterPath = path.Join(apppath, "routers")
createPaths(mode, mvcPath) createPaths(mode, mvcPath)
pkgPath := getPackagePath(currpath) pkgPath := getPackagePath(apppath)
writeSourceFiles(pkgPath, tables, mode, mvcPath, selectedTableNames) writeSourceFiles(pkgPath, tables, mode, mvcPath, selectedTableNames)
} else { } else {
ColorLog("[ERRO] Generating app code from %s database is not supported yet.\n", dbms) ColorLog("[ERRO] Generating app code from %s database is not supported yet.\n", dbms)
@ -516,7 +516,9 @@ func (*MysqlDB) GetGoDataType(sqlType string) (goType string) {
func (*PostgresDB) GetTableNames(db *sql.DB) (tables []string) { func (*PostgresDB) GetTableNames(db *sql.DB) (tables []string) {
rows, err := db.Query(` rows, err := db.Query(`
SELECT table_name FROM information_schema.tables SELECT table_name FROM information_schema.tables
WHERE table_catalog = current_database() and table_schema = 'public'`) WHERE table_catalog = current_database() AND
table_type = 'BASE TABLE' AND
table_schema NOT IN ('pg_catalog', 'information_schema')`)
if err != nil { if err != nil {
ColorLog("[ERRO] Could not show tables: %s\n", err) ColorLog("[ERRO] Could not show tables: %s\n", err)
ColorLog("[HINT] Check your connection string\n") ColorLog("[HINT] Check your connection string\n")
@ -551,8 +553,10 @@ func (*PostgresDB) GetConstraints(db *sql.DB, table *Table, blackList map[string
INNER JOIN INNER JOIN
information_schema.constraint_column_usage cu ON cu.constraint_name = c.constraint_name information_schema.constraint_column_usage cu ON cu.constraint_name = c.constraint_name
WHERE WHERE
c.table_catalog = current_database() AND c.table_schema = 'public' AND c.table_name = $1 c.table_catalog = current_database() AND c.table_schema NOT IN ('pg_catalog', 'information_schema')
AND u.table_catalog = current_database() AND u.table_schema = 'public' AND u.table_name = $2`, AND c.table_name = $1
AND u.table_catalog = current_database() AND u.table_schema NOT IN ('pg_catalog', 'information_schema')
AND u.table_name = $2`,
table.Name, table.Name) // u.position_in_unique_constraint, table.Name, table.Name) // u.position_in_unique_constraint,
if err != nil { if err != nil {
ColorLog("[ERRO] Could not query INFORMATION_SCHEMA for PK/UK/FK information: %s\n", err) ColorLog("[ERRO] Could not query INFORMATION_SCHEMA for PK/UK/FK information: %s\n", err)
@ -608,7 +612,8 @@ func (postgresDB *PostgresDB) GetColumns(db *sql.DB, table *Table, blackList map
FROM FROM
information_schema.columns information_schema.columns
WHERE WHERE
table_catalog = current_database() AND table_schema = 'public' AND table_name = $1`, table_catalog = current_database() AND table_schema NOT IN ('pg_catalog', 'information_schema')
AND table_name = $1`,
table.Name) table.Name)
defer colDefRows.Close() defer colDefRows.Close()
for colDefRows.Next() { for colDefRows.Next() {
@ -985,12 +990,12 @@ func getPackagePath(curpath string) (packpath string) {
ColorLog("[ERRO] Can't generate application code outside of GOPATH '%s'\n", gopath) ColorLog("[ERRO] Can't generate application code outside of GOPATH '%s'\n", gopath)
os.Exit(2) os.Exit(2)
} }
if curpath == appsrcpath { if curpath == appsrcpath {
ColorLog("[ERRO] Can't generate application code outside of application PATH \n") ColorLog("[ERRO] Can't generate application code outside of application PATH \n")
os.Exit(2) os.Exit(2)
} }
packpath = strings.Join(strings.Split(curpath[len(appsrcpath)+1:], string(filepath.Separator)), "/") packpath = strings.Join(strings.Split(curpath[len(appsrcpath)+1:], string(filepath.Separator)), "/")
return return
} }

View File

@ -18,6 +18,7 @@ import (
"os" "os"
"path" "path"
"strings" "strings"
"fmt"
) )
// article // article
@ -58,7 +59,7 @@ func generateController(cname, crupath string) {
f.WriteString(content) f.WriteString(content)
// gofmt generated source code // gofmt generated source code
formatSourceCode(fpath) formatSourceCode(fpath)
ColorLog("[INFO] controller file generated: %s\n", fpath) fmt.Println("\tcreate\t", fpath)
} else { } else {
// error creating file // error creating file
ColorLog("[ERRO] Could not create controller file: %s\n", err) ColorLog("[ERRO] Could not create controller file: %s\n", err)

View File

@ -395,10 +395,13 @@ func parserComments(comments *ast.CommentGroup, funcName, controllerName, pkgpat
tmp = make([]rune, 0) tmp = make([]rune, 0)
j += 1 j += 1
start = false start = false
continue if j == 1 {
} else { continue
st[j] = strings.TrimSpace(ss[i+1:]) } else {
break st[j] = strings.TrimSpace(ss[i+1:])
break
}
} }
} else { } else {
start = true start = true

View File

@ -51,7 +51,7 @@ func generateMigration(mname, upsql, downsql, curpath string) {
f.WriteString(content) f.WriteString(content)
// gofmt generated source code // gofmt generated source code
formatSourceCode(fpath) formatSourceCode(fpath)
ColorLog("[INFO] Migration file generated: %s\n", fpath) fmt.Println("\tcreate\t", fpath)
} else { } else {
// error creating file // error creating file
ColorLog("[ERRO] Could not create migration file: %s\n", err) ColorLog("[ERRO] Could not create migration file: %s\n", err)

View File

@ -5,6 +5,7 @@ import (
"os" "os"
"path" "path"
"strings" "strings"
"fmt"
) )
func generateModel(mname, fields, crupath string) { func generateModel(mname, fields, crupath string) {
@ -44,7 +45,7 @@ func generateModel(mname, fields, crupath string) {
f.WriteString(content) f.WriteString(content)
// gofmt generated source code // gofmt generated source code
formatSourceCode(fpath) formatSourceCode(fpath)
ColorLog("[INFO] model file generated: %s\n", fpath) fmt.Println("\tcreate\t", fpath)
} else { } else {
// error creating file // error creating file
ColorLog("[ERRO] Could not create model file: %s\n", err) ColorLog("[ERRO] Could not create model file: %s\n", err)

View File

@ -7,23 +7,23 @@ import (
func generateScaffold(sname, fields, crupath, driver, conn string) { func generateScaffold(sname, fields, crupath, driver, conn string) {
// generate model // generate model
ColorLog("[INFO] Do you want me to create a %v model? [yes|no]] ", sname) ColorLog("[INFO] Do you want to create a %v model? [yes|no]] ", sname)
if askForConfirmation() { if askForConfirmation() {
generateModel(sname, fields, crupath) generateModel(sname, fields, crupath)
} }
// generate controller // generate controller
ColorLog("[INFO] Do you want me to create a %v controller? [yes|no]] ", sname) ColorLog("[INFO] Do you want to create a %v controller? [yes|no]] ", sname)
if askForConfirmation() { if askForConfirmation() {
generateController(sname, crupath) generateController(sname, crupath)
} }
// generate view // generate view
ColorLog("[INFO] Do you want me to create views for this %v resource? [yes|no]] ", sname) ColorLog("[INFO] Do you want to create views for this %v resource? [yes|no]] ", sname)
if askForConfirmation() { if askForConfirmation() {
generateView(sname, crupath) generateView(sname, crupath)
} }
// generate migration // generate migration
ColorLog("[INFO] Do you want me to create a %v migration and schema for this resource? [yes|no]] ", sname) ColorLog("[INFO] Do you want to create a %v migration and schema for this resource? [yes|no]] ", sname)
if askForConfirmation() { if askForConfirmation() {
upsql := "" upsql := ""
downsql := "" downsql := ""
@ -34,7 +34,7 @@ func generateScaffold(sname, fields, crupath, driver, conn string) {
generateMigration(sname, upsql, downsql, crupath) generateMigration(sname, upsql, downsql, crupath)
} }
// run migration // run migration
ColorLog("[INFO] Do you want to go ahead and migrate the database? [yes|no]] ") ColorLog("[INFO] Do you want to migrate the database? [yes|no]] ")
if askForConfirmation() { if askForConfirmation() {
migrateUpdate(crupath, driver, conn) migrateUpdate(crupath, driver, conn)
} }
@ -48,12 +48,12 @@ func generateSQLFromFields(fields string) string {
for i, v := range fds { for i, v := range fds {
kv := strings.SplitN(v, ":", 2) kv := strings.SplitN(v, ":", 2)
if len(kv) != 2 { if len(kv) != 2 {
ColorLog("[ERRO] the fields format is wrong. should key:type,key:type " + v + "\n") ColorLog("[ERRO] Fields format is wrong. Should be: key:type,key:type " + v + "\n")
return "" return ""
} }
typ, tag := getSqlType(kv[1]) typ, tag := getSqlType(kv[1])
if typ == "" { if typ == "" {
ColorLog("[ERRO] the fields format is wrong. should key:type,key:type " + v + "\n") ColorLog("[ERRO] Fields format is wrong. Should be: key:type,key:type " + v + "\n")
return "" return ""
} }
if i == 0 && strings.ToLower(kv[0]) != "id" { if i == 0 && strings.ToLower(kv[0]) != "id" {

View File

@ -3,18 +3,20 @@ package main
import ( import (
"os" "os"
"path" "path"
"fmt"
) )
// recipe // recipe
// admin/recipe // admin/recipe
func generateView(vpath, crupath string) { func generateView(vpath, crupath string) {
ColorLog("[INFO] Generating view...\n")
absvpath := path.Join(crupath, "views", vpath) absvpath := path.Join(crupath, "views", vpath)
os.MkdirAll(absvpath, os.ModePerm) os.MkdirAll(absvpath, os.ModePerm)
cfile := path.Join(absvpath, "index.tpl") cfile := path.Join(absvpath, "index.tpl")
if f, err := os.OpenFile(cfile, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0666); err == nil { if f, err := os.OpenFile(cfile, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0666); err == nil {
defer f.Close() defer f.Close()
f.WriteString(cfile) f.WriteString(cfile)
ColorLog("[INFO] Created: %v\n", cfile) fmt.Println("\tcreate\t", cfile)
} else { } else {
ColorLog("[ERRO] Could not create view file: %s\n", err) ColorLog("[ERRO] Could not create view file: %s\n", err)
os.Exit(2) os.Exit(2)
@ -23,7 +25,7 @@ func generateView(vpath, crupath string) {
if f, err := os.OpenFile(cfile, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0666); err == nil { if f, err := os.OpenFile(cfile, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0666); err == nil {
defer f.Close() defer f.Close()
f.WriteString(cfile) f.WriteString(cfile)
ColorLog("[INFO] Created: %v\n", cfile) fmt.Println("\tcreate\t", cfile)
} else { } else {
ColorLog("[ERRO] Could not create view file: %s\n", err) ColorLog("[ERRO] Could not create view file: %s\n", err)
os.Exit(2) os.Exit(2)
@ -32,7 +34,7 @@ func generateView(vpath, crupath string) {
if f, err := os.OpenFile(cfile, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0666); err == nil { if f, err := os.OpenFile(cfile, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0666); err == nil {
defer f.Close() defer f.Close()
f.WriteString(cfile) f.WriteString(cfile)
ColorLog("[INFO] Created: %v\n", cfile) fmt.Println("\tcreate\t", cfile)
} else { } else {
ColorLog("[ERRO] Could not create view file: %s\n", err) ColorLog("[ERRO] Could not create view file: %s\n", err)
os.Exit(2) os.Exit(2)
@ -41,7 +43,7 @@ func generateView(vpath, crupath string) {
if f, err := os.OpenFile(cfile, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0666); err == nil { if f, err := os.OpenFile(cfile, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0666); err == nil {
defer f.Close() defer f.Close()
f.WriteString(cfile) f.WriteString(cfile)
ColorLog("[INFO] Created: %v\n", cfile) fmt.Println("\tcreate\t", cfile)
} else { } else {
ColorLog("[ERRO] Could not create view file: %s\n", err) ColorLog("[ERRO] Could not create view file: %s\n", err)
os.Exit(2) os.Exit(2)

View File

@ -255,6 +255,8 @@ func init() {
} }
func createhprose(cmd *Command, args []string) int { func createhprose(cmd *Command, args []string) int {
ShowShortVersionBanner()
curpath, _ := os.Getwd() curpath, _ := os.Getwd()
if len(args) > 1 { if len(args) > 1 {
cmd.Flag.Parse(args[1:]) cmd.Flag.Parse(args[1:])
@ -269,12 +271,15 @@ func createhprose(cmd *Command, args []string) int {
} }
if conn == "" { if conn == "" {
} }
ColorLog("[INFO] Creating Hprose application...\n")
os.MkdirAll(apppath, 0755) os.MkdirAll(apppath, 0755)
fmt.Println("create app folder:", apppath) fmt.Println("\tcreate\t", apppath)
os.Mkdir(path.Join(apppath, "conf"), 0755) os.Mkdir(path.Join(apppath, "conf"), 0755)
fmt.Println("create conf:", path.Join(apppath, "conf")) fmt.Println("\tcreate\t", path.Join(apppath, "conf"))
fmt.Println("create conf app.conf:", path.Join(apppath, "conf", "app.conf")) fmt.Println("\tcreate\t", path.Join(apppath, "conf", "app.conf"))
writetofile(path.Join(apppath, "conf", "app.conf"), WriteToFile(path.Join(apppath, "conf", "app.conf"),
strings.Replace(hproseconf, "{{.Appname}}", args[0], -1)) strings.Replace(hproseconf, "{{.Appname}}", args[0], -1))
if conn != "" { if conn != "" {
@ -282,7 +287,7 @@ func createhprose(cmd *Command, args []string) int {
ColorLog("[INFO] Using '%s' as 'conn'\n", conn) ColorLog("[INFO] Using '%s' as 'conn'\n", conn)
ColorLog("[INFO] Using '%s' as 'tables'\n", tables) ColorLog("[INFO] Using '%s' as 'tables'\n", tables)
generateHproseAppcode(string(driver), string(conn), "1", string(tables), path.Join(curpath, args[0])) generateHproseAppcode(string(driver), string(conn), "1", string(tables), path.Join(curpath, args[0]))
fmt.Println("create main.go:", path.Join(apppath, "main.go")) fmt.Println("\tcreate\t", path.Join(apppath, "main.go"))
maingoContent := strings.Replace(hproseMainconngo, "{{.Appname}}", packpath, -1) maingoContent := strings.Replace(hproseMainconngo, "{{.Appname}}", packpath, -1)
maingoContent = strings.Replace(maingoContent, "{{.DriverName}}", string(driver), -1) maingoContent = strings.Replace(maingoContent, "{{.DriverName}}", string(driver), -1)
maingoContent = strings.Replace(maingoContent, "{{HproseFunctionList}}", strings.Join(hproseAddFunctions, ""), -1) maingoContent = strings.Replace(maingoContent, "{{HproseFunctionList}}", strings.Join(hproseAddFunctions, ""), -1)
@ -291,7 +296,7 @@ func createhprose(cmd *Command, args []string) int {
} else if driver == "postgres" { } else if driver == "postgres" {
maingoContent = strings.Replace(maingoContent, "{{.DriverPkg}}", `_ "github.com/lib/pq"`, -1) maingoContent = strings.Replace(maingoContent, "{{.DriverPkg}}", `_ "github.com/lib/pq"`, -1)
} }
writetofile(path.Join(apppath, "main.go"), WriteToFile(path.Join(apppath, "main.go"),
strings.Replace( strings.Replace(
maingoContent, maingoContent,
"{{.conn}}", "{{.conn}}",
@ -301,17 +306,18 @@ func createhprose(cmd *Command, args []string) int {
) )
} else { } else {
os.Mkdir(path.Join(apppath, "models"), 0755) os.Mkdir(path.Join(apppath, "models"), 0755)
fmt.Println("create models:", path.Join(apppath, "models")) fmt.Println("\tcreate\t", path.Join(apppath, "models"))
fmt.Println("create models object.go:", path.Join(apppath, "models", "object.go")) fmt.Println("\tcreate\t", path.Join(apppath, "models", "object.go"))
writetofile(path.Join(apppath, "models", "object.go"), apiModels) WriteToFile(path.Join(apppath, "models", "object.go"), apiModels)
fmt.Println("create models user.go:", path.Join(apppath, "models", "user.go")) fmt.Println("\tcreate\t", path.Join(apppath, "models", "user.go"))
writetofile(path.Join(apppath, "models", "user.go"), apiModels2) WriteToFile(path.Join(apppath, "models", "user.go"), apiModels2)
fmt.Println("create main.go:", path.Join(apppath, "main.go")) fmt.Println("\tcreate\t", path.Join(apppath, "main.go"))
writetofile(path.Join(apppath, "main.go"), WriteToFile(path.Join(apppath, "main.go"),
strings.Replace(hproseMaingo, "{{.Appname}}", packpath, -1)) strings.Replace(hproseMaingo, "{{.Appname}}", packpath, -1))
} }
ColorLog("[SUCC] New Hprose application successfully created!\n")
return 0 return 0
} }

View File

@ -62,6 +62,8 @@ func init() {
// runMigration is the entry point for starting a migration // runMigration is the entry point for starting a migration
func runMigration(cmd *Command, args []string) int { func runMigration(cmd *Command, args []string) int {
ShowShortVersionBanner()
crupath, _ := os.Getwd() crupath, _ := os.Getwd()
gopath := os.Getenv("GOPATH") gopath := os.Getenv("GOPATH")

89
new.go
View File

@ -55,7 +55,8 @@ func init() {
} }
func createApp(cmd *Command, args []string) int { func createApp(cmd *Command, args []string) int {
curpath, _ := os.Getwd() ShowShortVersionBanner()
if len(args) != 1 { if len(args) != 1 {
ColorLog("[ERRO] Argument [appname] is missing\n") ColorLog("[ERRO] Argument [appname] is missing\n")
os.Exit(2) os.Exit(2)
@ -65,40 +66,12 @@ func createApp(cmd *Command, args []string) int {
Debugf("gopath:%s", gopath) Debugf("gopath:%s", gopath)
if gopath == "" { if gopath == "" {
ColorLog("[ERRO] $GOPATH not found\n") ColorLog("[ERRO] $GOPATH not found\n")
ColorLog("[HINT] Set $GOPATH in your environment vairables\n") ColorLog("[HINT] Set $GOPATH in your environment variables\n")
os.Exit(2)
}
haspath := false
appsrcpath := ""
wgopath := path.SplitList(gopath)
for _, wg := range wgopath {
wg = path.Join(wg, "src")
if strings.HasPrefix(strings.ToLower(curpath), strings.ToLower(wg)) {
haspath = true
appsrcpath = wg
break
}
wg, _ = path.EvalSymlinks(wg)
if strings.HasPrefix(strings.ToLower(curpath), strings.ToLower(wg)) {
haspath = true
appsrcpath = wg
break
}
}
if !haspath {
ColorLog("[ERRO] Unable to create an application outside of $GOPATH%ssrc(%s%ssrc)\n", string(path.Separator), gopath, string(path.Separator))
ColorLog("[HINT] Change your work directory by `cd ($GOPATH%ssrc)`\n", string(path.Separator))
os.Exit(2) os.Exit(2)
} }
apppath := path.Join(curpath, args[0]) gosrcpath := path.Join(gopath, "src") // User's workspace
apppath := path.Join(gosrcpath, args[0])
if isExist(apppath) { if isExist(apppath) {
ColorLog("[ERRO] Path (%s) already exists\n", apppath) ColorLog("[ERRO] Path (%s) already exists\n", apppath)
@ -108,47 +81,47 @@ func createApp(cmd *Command, args []string) int {
} }
} }
fmt.Println("[INFO] Creating application...") ColorLog("[INFO] Creating application...\n")
os.MkdirAll(apppath, 0755) os.MkdirAll(apppath, 0755)
fmt.Println(apppath + string(path.Separator)) fmt.Println("\tcreate\t", apppath + string(path.Separator))
os.Mkdir(path.Join(apppath, "conf"), 0755) os.Mkdir(path.Join(apppath, "conf"), 0755)
fmt.Println(path.Join(apppath, "conf") + string(path.Separator)) fmt.Println("\tcreate\t", path.Join(apppath, "conf") + string(path.Separator))
os.Mkdir(path.Join(apppath, "controllers"), 0755) os.Mkdir(path.Join(apppath, "controllers"), 0755)
fmt.Println(path.Join(apppath, "controllers") + string(path.Separator)) fmt.Println("\tcreate\t", path.Join(apppath, "controllers") + string(path.Separator))
os.Mkdir(path.Join(apppath, "models"), 0755) os.Mkdir(path.Join(apppath, "models"), 0755)
fmt.Println(path.Join(apppath, "models") + string(path.Separator)) fmt.Println("\tcreate\t", path.Join(apppath, "models") + string(path.Separator))
os.Mkdir(path.Join(apppath, "routers"), 0755) os.Mkdir(path.Join(apppath, "routers"), 0755)
fmt.Println(path.Join(apppath, "routers") + string(path.Separator)) fmt.Println("\tcreate\t", path.Join(apppath, "routers") + string(path.Separator))
os.Mkdir(path.Join(apppath, "tests"), 0755) os.Mkdir(path.Join(apppath, "tests"), 0755)
fmt.Println(path.Join(apppath, "tests") + string(path.Separator)) fmt.Println("\tcreate\t", path.Join(apppath, "tests") + string(path.Separator))
os.Mkdir(path.Join(apppath, "static"), 0755) os.Mkdir(path.Join(apppath, "static"), 0755)
fmt.Println(path.Join(apppath, "static") + string(path.Separator)) fmt.Println("\tcreate\t", path.Join(apppath, "static") + string(path.Separator))
os.Mkdir(path.Join(apppath, "static", "js"), 0755) os.Mkdir(path.Join(apppath, "static", "js"), 0755)
fmt.Println(path.Join(apppath, "static", "js") + string(path.Separator)) fmt.Println("\tcreate\t", path.Join(apppath, "static", "js") + string(path.Separator))
os.Mkdir(path.Join(apppath, "static", "css"), 0755) os.Mkdir(path.Join(apppath, "static", "css"), 0755)
fmt.Println(path.Join(apppath, "static", "css") + string(path.Separator)) fmt.Println("\tcreate\t", path.Join(apppath, "static", "css") + string(path.Separator))
os.Mkdir(path.Join(apppath, "static", "img"), 0755) os.Mkdir(path.Join(apppath, "static", "img"), 0755)
fmt.Println(path.Join(apppath, "static", "img") + string(path.Separator)) fmt.Println("\tcreate\t", path.Join(apppath, "static", "img") + string(path.Separator))
fmt.Println(path.Join(apppath, "views") + string(path.Separator)) fmt.Println("\tcreate\t", path.Join(apppath, "views") + string(path.Separator))
os.Mkdir(path.Join(apppath, "views"), 0755) os.Mkdir(path.Join(apppath, "views"), 0755)
fmt.Println(path.Join(apppath, "conf", "app.conf")) fmt.Println("\tcreate\t", path.Join(apppath, "conf", "app.conf"))
writetofile(path.Join(apppath, "conf", "app.conf"), strings.Replace(appconf, "{{.Appname}}", args[0], -1)) WriteToFile(path.Join(apppath, "conf", "app.conf"), strings.Replace(appconf, "{{.Appname}}", path.Base(args[0]), -1))
fmt.Println(path.Join(apppath, "controllers", "default.go")) fmt.Println("\tcreate\t", path.Join(apppath, "controllers", "default.go"))
writetofile(path.Join(apppath, "controllers", "default.go"), controllers) WriteToFile(path.Join(apppath, "controllers", "default.go"), controllers)
fmt.Println(path.Join(apppath, "views", "index.tpl")) fmt.Println("\tcreate\t", path.Join(apppath, "views", "index.tpl"))
writetofile(path.Join(apppath, "views", "index.tpl"), indextpl) WriteToFile(path.Join(apppath, "views", "index.tpl"), indextpl)
fmt.Println(path.Join(apppath, "routers", "router.go")) fmt.Println("\tcreate\t", path.Join(apppath, "routers", "router.go"))
writetofile(path.Join(apppath, "routers", "router.go"), strings.Replace(router, "{{.Appname}}", strings.Join(strings.Split(apppath[len(appsrcpath)+1:], string(path.Separator)), "/"), -1)) WriteToFile(path.Join(apppath, "routers", "router.go"), strings.Replace(router, "{{.Appname}}", strings.Join(strings.Split(apppath[len(gosrcpath)+1:], string(path.Separator)), "/"), -1))
fmt.Println(path.Join(apppath, "tests", "default_test.go")) fmt.Println("\tcreate\t", path.Join(apppath, "tests", "default_test.go"))
writetofile(path.Join(apppath, "tests", "default_test.go"), strings.Replace(test, "{{.Appname}}", strings.Join(strings.Split(apppath[len(appsrcpath)+1:], string(path.Separator)), "/"), -1)) WriteToFile(path.Join(apppath, "tests", "default_test.go"), strings.Replace(test, "{{.Appname}}", strings.Join(strings.Split(apppath[len(gosrcpath)+1:], string(path.Separator)), "/"), -1))
fmt.Println(path.Join(apppath, "main.go")) fmt.Println("\tcreate\t", path.Join(apppath, "main.go"))
writetofile(path.Join(apppath, "main.go"), strings.Replace(maingo, "{{.Appname}}", strings.Join(strings.Split(apppath[len(appsrcpath)+1:], string(path.Separator)), "/"), -1)) WriteToFile(path.Join(apppath, "main.go"), strings.Replace(maingo, "{{.Appname}}", strings.Join(strings.Split(apppath[len(gosrcpath)+1:], string(path.Separator)), "/"), -1))
ColorLog("[SUCC] New application successfully created!\n") ColorLog("[SUCC] New application successfully created!\n")
return 0 return 0
@ -336,11 +309,11 @@ var indextpl = `<!DOCTYPE html>
</html> </html>
` `
func writetofile(filename, content string) { func WriteToFile(filename, content string) {
f, err := os.Create(filename) f, err := os.Create(filename)
defer f.Close()
if err != nil { if err != nil {
panic(err) panic(err)
} }
defer f.Close()
f.WriteString(content) f.WriteString(content)
} }

29
pack.go
View File

@ -242,7 +242,7 @@ func (wft *walkFileTree) walkLeaf(fpath string, fi os.FileInfo, err error) error
if added, err := wft.wak.compress(name, fpath, fi); added { if added, err := wft.wak.compress(name, fpath, fi); added {
if verbose { if verbose {
fmt.Printf("Compressed: %s\n", name) fmt.Printf("\t+ Compressed: %s\n", name)
} }
wft.allfiles[name] = true wft.allfiles[name] = true
return err return err
@ -397,10 +397,10 @@ func (wft *zipWalk) compress(name, fpath string, fi os.FileInfo) (bool, error) {
func packDirectory(excludePrefix []string, excludeSuffix []string, func packDirectory(excludePrefix []string, excludeSuffix []string,
excludeRegexp []*regexp.Regexp, includePath ...string) (err error) { excludeRegexp []*regexp.Regexp, includePath ...string) (err error) {
fmt.Printf("exclude relpath prefix: %s\n", strings.Join(excludePrefix, ":")) ColorLog("Excluding relpath prefix: %s\n", strings.Join(excludePrefix, ":"))
fmt.Printf("exclude relpath suffix: %s\n", strings.Join(excludeSuffix, ":")) ColorLog("Excluding relpath suffix: %s\n", strings.Join(excludeSuffix, ":"))
if len(excludeRegexp) > 0 { if len(excludeRegexp) > 0 {
fmt.Printf("exclude filename regex: `%s`\n", strings.Join(excludeR, "`, `")) ColorLog("Excluding filename regex: `%s`\n", strings.Join(excludeR, "`, `"))
} }
w, err := os.OpenFile(outputP, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644) w, err := os.OpenFile(outputP, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
@ -472,6 +472,8 @@ func isBeegoProject(thePath string) bool {
} }
func packApp(cmd *Command, args []string) int { func packApp(cmd *Command, args []string) int {
ShowShortVersionBanner()
curPath, _ := os.Getwd() curPath, _ := os.Getwd()
thePath := "" thePath := ""
@ -493,17 +495,17 @@ func packApp(cmd *Command, args []string) int {
thePath, err := path.Abs(appPath) thePath, err := path.Abs(appPath)
if err != nil { if err != nil {
exitPrint(fmt.Sprintf("wrong app path: %s", thePath)) exitPrint(fmt.Sprintf("Wrong app path: %s", thePath))
} }
if stat, err := os.Stat(thePath); os.IsNotExist(err) || stat.IsDir() == false { if stat, err := os.Stat(thePath); os.IsNotExist(err) || stat.IsDir() == false {
exitPrint(fmt.Sprintf("not exist app path: %s", thePath)) exitPrint(fmt.Sprintf("App path does not exist: %s", thePath))
} }
if isBeegoProject(thePath) == false { if isBeegoProject(thePath) == false {
exitPrint(fmt.Sprintf("not support non beego project")) exitPrint(fmt.Sprintf("Bee does not support non Beego project"))
} }
fmt.Printf("app path: %s\n", thePath) ColorLog("Packaging application: %s\n", thePath)
appName := path.Base(thePath) appName := path.Base(thePath)
@ -523,8 +525,7 @@ func packApp(cmd *Command, args []string) int {
os.Mkdir(tmpdir, 0700) os.Mkdir(tmpdir, 0700)
if build { if build {
fmt.Println("build", appName) ColorLog("Building application...\n")
var envs []string var envs []string
for _, env := range buildEnvs { for _, env := range buildEnvs {
parts := strings.SplitN(env, "=", 2) parts := strings.SplitN(env, "=", 2)
@ -546,7 +547,7 @@ func packApp(cmd *Command, args []string) int {
os.Setenv("GOOS", goos) os.Setenv("GOOS", goos)
os.Setenv("GOARCH", goarch) os.Setenv("GOARCH", goarch)
fmt.Println("GOOS", goos, "GOARCH", goarch) ColorLog("Env: GOOS=%s GOARCH=%s\n", goos, goarch)
binPath := path.Join(tmpdir, appName) binPath := path.Join(tmpdir, appName)
if goos == "windows" { if goos == "windows" {
@ -559,7 +560,7 @@ func packApp(cmd *Command, args []string) int {
} }
if verbose { if verbose {
fmt.Println("go ", strings.Join(args, " ")) fmt.Println("\t+ go", strings.Join(args, " "))
} }
execmd := exec.Command("go", args...) execmd := exec.Command("go", args...)
@ -572,7 +573,7 @@ func packApp(cmd *Command, args []string) int {
exitPrint(err.Error()) exitPrint(err.Error())
} }
fmt.Println("build success") ColorLog("Build successful\n")
} }
switch format { switch format {
@ -624,6 +625,6 @@ func packApp(cmd *Command, args []string) int {
exitPrint(err.Error()) exitPrint(err.Error())
} }
fmt.Printf("file write to `%s`\n", outputP) ColorLog("Writing to output: `%s`\n", outputP)
return 0 return 0
} }

19
run.go
View File

@ -15,18 +15,15 @@
package main package main
import ( import (
"fmt"
"io/ioutil" "io/ioutil"
"log"
"os" "os"
"os/exec"
path "path/filepath" path "path/filepath"
"runtime" "runtime"
"strings" "strings"
) )
var cmdRun = &Command{ var cmdRun = &Command{
UsageLine: "run [appname] [watchall] [-main=*.go] [-downdoc=true] [-gendoc=true] [-e=Godeps -e=folderToExclude]", UsageLine: "run [appname] [watchall] [-main=*.go] [-downdoc=true] [-gendoc=true] [-e=Godeps -e=folderToExclude] [-tags=goBuildTags]",
Short: "run the app and start a Web server for development", Short: "run the app and start a Web server for development",
Long: ` Long: `
Run command will supervise the file system of the beego project using inotify, Run command will supervise the file system of the beego project using inotify,
@ -43,24 +40,22 @@ var gendoc docValue
// The flags list of the paths excluded from watching // The flags list of the paths excluded from watching
var excludedPaths strFlags var excludedPaths strFlags
// Pass through to -tags arg of "go build"
var buildTags string
func init() { func init() {
cmdRun.Run = runApp cmdRun.Run = runApp
cmdRun.Flag.Var(&mainFiles, "main", "specify main go files") cmdRun.Flag.Var(&mainFiles, "main", "specify main go files")
cmdRun.Flag.Var(&gendoc, "gendoc", "auto generate the docs") cmdRun.Flag.Var(&gendoc, "gendoc", "auto generate the docs")
cmdRun.Flag.Var(&downdoc, "downdoc", "auto download swagger file when not exist") cmdRun.Flag.Var(&downdoc, "downdoc", "auto download swagger file when not exist")
cmdRun.Flag.Var(&excludedPaths, "e", "Excluded paths[].") cmdRun.Flag.Var(&excludedPaths, "e", "Excluded paths[].")
cmdRun.Flag.StringVar(&buildTags, "tags", "", "Build tags (https://golang.org/pkg/go/build/)")
} }
var appname string var appname string
func runApp(cmd *Command, args []string) int { func runApp(cmd *Command, args []string) int {
fmt.Println("bee :" + version) ShowShortVersionBanner()
fmt.Println("beego :" + getbeegoVersion())
goversion, err := exec.Command("go", "version").Output()
if err != nil {
log.Fatal(err)
}
fmt.Println("Go :" + string(goversion))
exit := make(chan bool) exit := make(chan bool)
crupath, _ := os.Getwd() crupath, _ := os.Getwd()
@ -81,7 +76,7 @@ func runApp(cmd *Command, args []string) int {
} }
Debugf("current path:%s\n", crupath) Debugf("current path:%s\n", crupath)
err = loadConfig() err := loadConfig()
if err != nil { if err != nil {
ColorLog("[ERRO] Fail to parse bee.json[ %s ]\n", err) ColorLog("[ERRO] Fail to parse bee.json[ %s ]\n", err)
} }

View File

@ -4,11 +4,10 @@ import (
"bufio" "bufio"
"fmt" "fmt"
"io" "io"
"log"
"os" "os"
"os/exec"
path "path/filepath" path "path/filepath"
"regexp" "regexp"
"bytes"
) )
var cmdVersion = &Command{ var cmdVersion = &Command{
@ -25,30 +24,59 @@ bee version
`, `,
} }
const verboseVersionBanner =
`______
| ___ \
| |_/ / ___ ___
| ___ \ / _ \ / _ \
| |_/ /| __/| __/
\____/ \___| \___| v{{ .BeeVersion }}
Beego : {{ .BeegoVersion }}
GoVersion : {{ .GoVersion }}
GOOS : {{ .GOOS }}
GOARCH : {{ .GOARCH }}
NumCPU : {{ .NumCPU }}
GOPATH : {{ .GOPATH }}
GOROOT : {{ .GOROOT }}
Compiler : {{ .Compiler }}
Date : {{ Now "Monday, 2 Jan 2006" }}
`
const shortVersionBanner =
`______
| ___ \
| |_/ / ___ ___
| ___ \ / _ \ / _ \
| |_/ /| __/| __/
\____/ \___| \___| v{{ .BeeVersion }}
`
func init() { func init() {
cmdVersion.Run = versionCmd cmdVersion.Run = versionCmd
} }
func versionCmd(cmd *Command, args []string) int { func versionCmd(cmd *Command, args []string) int {
fmt.Println("bee :" + version) ShowVerboseVersionBanner()
fmt.Println("beego :" + getbeegoVersion())
//fmt.Println("Go :" + runtime.Version())
goversion, err := exec.Command("go", "version").Output()
if err != nil {
log.Fatal(err)
}
fmt.Println("Go :" + string(goversion))
return 0 return 0
} }
func getbeegoVersion() string { func ShowVerboseVersionBanner() {
InitBanner(os.Stdout, bytes.NewBufferString(verboseVersionBanner))
}
func ShowShortVersionBanner() {
InitBanner(os.Stdout, bytes.NewBufferString(shortVersionBanner))
}
func getBeegoVersion() string {
gopath := os.Getenv("GOPATH") gopath := os.Getenv("GOPATH")
re, err := regexp.Compile(`VERSION = "([0-9.]+)"`) re, err := regexp.Compile(`VERSION = "([0-9.]+)"`)
if err != nil { if err != nil {
return "" return ""
} }
if gopath == "" { if gopath == "" {
err = fmt.Errorf("you should set GOPATH in the env") err = fmt.Errorf("You should set GOPATH env variable")
return "" return ""
} }
wgopath := path.SplitList(gopath) wgopath := path.SplitList(gopath)
@ -60,11 +88,11 @@ func getbeegoVersion() string {
if os.IsNotExist(err) { if os.IsNotExist(err) {
continue continue
} }
ColorLog("[ERRO] get beego.go has error\n") ColorLog("[ERRO] Get `beego.go` has error\n")
} }
fd, err := os.Open(filename) fd, err := os.Open(filename)
if err != nil { if err != nil {
ColorLog("[ERRO] open beego.go has error\n") ColorLog("[ERRO] Open `beego.go` has error\n")
continue continue
} }
reader := bufio.NewReader(fd) reader := bufio.NewReader(fd)
@ -84,5 +112,5 @@ func getbeegoVersion() string {
} }
} }
return "you don't install beego,install first: github.com/astaxie/beego" return "Beego not installed. Please install it first: https://github.com/astaxie/beego"
} }

View File

@ -136,6 +136,7 @@ func Autobuild(files []string, isgenerate bool) {
icmd := exec.Command("go", "list", "./...") icmd := exec.Command("go", "list", "./...")
buf := bytes.NewBuffer([]byte("")) buf := bytes.NewBuffer([]byte(""))
icmd.Stdout = buf icmd.Stdout = buf
icmd.Env = append(os.Environ(), "GOGC=off")
err = icmd.Run() err = icmd.Run()
if err == nil { if err == nil {
list := strings.Split(buf.String(), "\n")[1:] list := strings.Split(buf.String(), "\n")[1:]
@ -146,6 +147,7 @@ func Autobuild(files []string, isgenerate bool) {
icmd = exec.Command(cmdName, "install", pkg) icmd = exec.Command(cmdName, "install", pkg)
icmd.Stdout = os.Stdout icmd.Stdout = os.Stdout
icmd.Stderr = os.Stderr icmd.Stderr = os.Stderr
icmd.Env = append(os.Environ(), "GOGC=off")
err = icmd.Run() err = icmd.Run()
if err != nil { if err != nil {
break break
@ -156,6 +158,7 @@ func Autobuild(files []string, isgenerate bool) {
if isgenerate { if isgenerate {
icmd := exec.Command("bee", "generate", "docs") icmd := exec.Command("bee", "generate", "docs")
icmd.Env = append(os.Environ(), "GOGC=off")
icmd.Stdout = os.Stdout icmd.Stdout = os.Stdout
icmd.Stderr = os.Stderr icmd.Stderr = os.Stderr
icmd.Run() icmd.Run()
@ -170,9 +173,13 @@ func Autobuild(files []string, isgenerate bool) {
args := []string{"build"} args := []string{"build"}
args = append(args, "-o", appName) args = append(args, "-o", appName)
if buildTags != "" {
args = append(args, "-tags", buildTags)
}
args = append(args, files...) args = append(args, files...)
bcmd := exec.Command(cmdName, args...) bcmd := exec.Command(cmdName, args...)
bcmd.Env = append(os.Environ(), "GOGC=off")
bcmd.Stdout = os.Stdout bcmd.Stdout = os.Stdout
bcmd.Stderr = os.Stderr bcmd.Stderr = os.Stderr
err = bcmd.Run() err = bcmd.Run()