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

Merge pull request #375 from amrfaissal/fix-load-config

Fixes configuration loading since last changes
This commit is contained in:
astaxie 2017-03-17 11:50:23 +08:00 committed by GitHub
commit 20c6a26952
8 changed files with 143 additions and 94 deletions

View File

@ -13,7 +13,7 @@ install:
script: script:
- go vet $(go list ./... | grep -v /vendor/) - go vet $(go list ./... | grep -v /vendor/)
- structcheck $(go list ./... | grep -v /vendor/) - structcheck $(go list ./... | grep -v /vendor/)
- gosimple $(go list ./... | grep -v /vendor/) - gosimple -ignore "github.com/beego/bee/cmd/commands/run/*.go:S1024" $(go list ./... | grep -v /vendor/)
- staticcheck $(go list ./... | grep -v /vendor/) - staticcheck $(go list ./... | grep -v /vendor/)
- unused $(go list ./... | grep -v /vendor/) - unused $(go list ./... | grep -v /vendor/)
- unconvert $(go list ./... | grep -v /vendor/) - unconvert $(go list ./... | grep -v /vendor/)

View File

@ -11,7 +11,6 @@
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations // License for the specific language governing permissions and limitations
// under the License. // under the License.
package bale package bale
import ( import (

View File

@ -1,3 +1,16 @@
// Copyright 2013 bee authors
//
// Licensed under the Apache License, Version 2.0 (the "License"): you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
package generate package generate
import ( import (

View File

@ -1,3 +1,16 @@
// Copyright 2013 bee authors
//
// Licensed under the Apache License, Version 2.0 (the "License"): you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
package migrate package migrate
import ( import (

View File

@ -11,7 +11,6 @@
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations // License for the specific language governing permissions and limitations
// under the License. // under the License.
package run package run
import ( import (

View File

@ -11,7 +11,6 @@
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations // License for the specific language governing permissions and limitations
// under the License. // under the License.
package config package config
import ( import (
@ -27,93 +26,106 @@ import (
const confVer = 0 const confVer = 0
var defaultConf = `{ var Conf = struct {
"version": 0,
"gopm": {
"enable": false,
"install": false
},
"go_install": true,
"watch_ext": [],
"dir_structure": {
"watch_all": false,
"controllers": "",
"models": "",
"others": []
},
"cmd_args": [],
"envs": [],
"database": {
"driver": "mysql"
},
"enable_reload": false,
"enable_notification": true
}
`
var Conf struct {
Version int Version int
// gopm support Gopm gopm
Gopm struct { GoInstall bool `json:"go_install" yaml:"go_install"` // Indicates whether execute "go install" before "go build".
Enable bool DirStruct dirStruct `json:"dir_structure" yaml:"dir_structure"`
Install bool
}
// Indicates whether execute "go install" before "go build".
GoInstall bool `json:"go_install" yaml:"go_install"`
WatchExt []string `json:"watch_ext" yaml:"watch_ext"`
DirStruct struct {
WatchAll bool `json:"watch_all" yaml:"watch_all"`
Controllers string
Models string
Others []string // Other directories.
} `json:"dir_structure" yaml:"dir_structure"`
CmdArgs []string `json:"cmd_args" yaml:"cmd_args"` CmdArgs []string `json:"cmd_args" yaml:"cmd_args"`
Envs []string Envs []string
Bale struct { Bale bale
Import string Database database
Dirs []string
IngExt []string `json:"ignore_ext" yaml:"ignore_ext"`
}
Database struct {
Driver string
Conn string
}
EnableReload bool `json:"enable_reload" yaml:"enable_reload"` EnableReload bool `json:"enable_reload" yaml:"enable_reload"`
EnableNotification bool `json:"enable_notification" yaml:"enable_notification"` EnableNotification bool `json:"enable_notification" yaml:"enable_notification"`
Scripts map[string]string `json:"scripts" yaml:"scripts"` Scripts map[string]string `json:"scripts" yaml:"scripts"`
}{
GoInstall: true,
DirStruct: dirStruct{
Others: []string{},
},
CmdArgs: []string{},
Envs: []string{},
Bale: bale{
Dirs: []string{},
IngExt: []string{},
},
Database: database{
Driver: "mysql",
},
EnableNotification: true,
Scripts: map[string]string{},
} }
func init() { // gopm support
loadConfig() type gopm struct {
Enable bool
Install bool
} }
// loadConfig loads customized configuration. // dirStruct describes the application's directory structure
func loadConfig() { type dirStruct struct {
beeLogger.Log.Info("Loading default configuration...") WatchAll bool `json:"watch_all" yaml:"watch_all"`
err := json.Unmarshal([]byte(defaultConf), &Conf) Controllers string
Models string
Others []string // Other directories
}
// bale
type bale struct {
Import string
Dirs []string
IngExt []string `json:"ignore_ext" yaml:"ignore_ext"`
}
// database holds the database connection information
type database struct {
Driver string
Conn string
}
// LoadConfig loads the bee tool configuration.
// It looks for Beefile or bee.json in the current path,
// and falls back to default configuration in case not found.
func LoadConfig() {
currentPath, err := os.Getwd()
if err != nil { if err != nil {
beeLogger.Log.Errorf(err.Error()) beeLogger.Log.Error(err.Error())
} }
err = filepath.Walk(".", func(path string, fileInfo os.FileInfo, err error) error {
dir, err := os.Open(currentPath)
if err != nil { if err != nil {
return nil beeLogger.Log.Error(err.Error())
} }
if fileInfo.IsDir() { defer dir.Close()
return nil
files, err := dir.Readdir(-1)
if err != nil {
beeLogger.Log.Error(err.Error())
} }
switch fileInfo.Name() {
for _, file := range files {
switch file.Name() {
case "bee.json": case "bee.json":
{
beeLogger.Log.Info("Loading configuration from 'bee.json'...") beeLogger.Log.Info("Loading configuration from 'bee.json'...")
return parseJSON(path, &Conf) err = parseJSON(filepath.Join(currentPath, file.Name()), &Conf)
case "Beefile":
beeLogger.Log.Info("Loading configuration from 'Beefile'...")
return parseYAML(path, &Conf)
}
return nil
})
if err != nil { if err != nil {
beeLogger.Log.Errorf("Failed to parse config file: %s", err) beeLogger.Log.Errorf("Failed to parse JSON file: %s", err)
} }
break
}
case "Beefile":
{
beeLogger.Log.Info("Loading configuration from 'Beefile'...")
err = parseYAML(filepath.Join(currentPath, file.Name()), &Conf)
if err != nil {
beeLogger.Log.Errorf("Failed to parse YAML file: %s", err)
}
break
}
}
}
// Check format version // Check format version
if Conf.Version != confVer { if Conf.Version != confVer {
beeLogger.Log.Warn("Your configuration file is outdated. Please do consider updating it.") beeLogger.Log.Warn("Your configuration file is outdated. Please do consider updating it.")
@ -124,13 +136,10 @@ func loadConfig() {
if len(Conf.DirStruct.Controllers) == 0 { if len(Conf.DirStruct.Controllers) == 0 {
Conf.DirStruct.Controllers = "controllers" Conf.DirStruct.Controllers = "controllers"
} }
if len(Conf.DirStruct.Models) == 0 { if len(Conf.DirStruct.Models) == 0 {
Conf.DirStruct.Models = "models" Conf.DirStruct.Models = "models"
} }
// Append watch exts
//watchExts = append(watchExts, Conf.WatchExt...)
return
} }
func parseJSON(path string, v interface{}) error { func parseJSON(path string, v interface{}) error {

View File

@ -143,7 +143,7 @@ func GenerateDocs(curpath string) {
f, err := parser.ParseFile(fset, path.Join(curpath, "routers", "router.go"), nil, parser.ParseComments) f, err := parser.ParseFile(fset, path.Join(curpath, "routers", "router.go"), nil, parser.ParseComments)
if err != nil { if err != nil {
// beeLogger.Log.Fatalf("Error while parsing router.go: %s", err) beeLogger.Log.Fatalf("Error while parsing router.go: %s", err)
} }
rootapi.Infos = swagger.Information{} rootapi.Infos = swagger.Information{}
@ -352,7 +352,7 @@ func analyseControllerPkg(localName, pkgpath string) {
} }
gopath := os.Getenv("GOPATH") gopath := os.Getenv("GOPATH")
if gopath == "" { if gopath == "" {
// beeLogger.Log.Fatal("GOPATH environment variable is not set or empty") beeLogger.Log.Fatal("GOPATH environment variable is not set or empty")
} }
pkgRealpath := "" pkgRealpath := ""
@ -370,7 +370,7 @@ func analyseControllerPkg(localName, pkgpath string) {
} }
pkgCache[pkgpath] = struct{}{} pkgCache[pkgpath] = struct{}{}
} else { } else {
// beeLogger.Log.Fatalf("Package '%s' does not exist in the GOPATH", pkgpath) beeLogger.Log.Fatalf("Package '%s' does not exist in the GOPATH", pkgpath)
} }
fileSet := token.NewFileSet() fileSet := token.NewFileSet()
@ -379,7 +379,7 @@ func analyseControllerPkg(localName, pkgpath string) {
return !info.IsDir() && !strings.HasPrefix(name, ".") && strings.HasSuffix(name, ".go") return !info.IsDir() && !strings.HasPrefix(name, ".") && strings.HasSuffix(name, ".go")
}, parser.ParseComments) }, parser.ParseComments)
if err != nil { if err != nil {
// beeLogger.Log.Fatalf("Error while parsing dir at '%s': %s", pkgpath, err) beeLogger.Log.Fatalf("Error while parsing dir at '%s': %s", pkgpath, err)
} }
for _, pkg := range astPkgs { for _, pkg := range astPkgs {
for _, fl := range pkg.Files { for _, fl := range pkg.Files {
@ -417,7 +417,7 @@ func isSystemPackage(pkgpath string) bool {
goroot = runtime.GOROOT() goroot = runtime.GOROOT()
} }
if goroot == "" { if goroot == "" {
// beeLogger.Log.Fatalf("GOROOT environment variable is not set or empty") beeLogger.Log.Fatalf("GOROOT environment variable is not set or empty")
} }
wg, _ := filepath.EvalSymlinks(filepath.Join(goroot, "src", "pkg", pkgpath)) wg, _ := filepath.EvalSymlinks(filepath.Join(goroot, "src", "pkg", pkgpath))
@ -481,7 +481,7 @@ func parserComments(comments *ast.CommentGroup, funcName, controllerName, pkgpat
ss = strings.TrimSpace(ss[pos:]) ss = strings.TrimSpace(ss[pos:])
schemaName, pos := peekNextSplitString(ss) schemaName, pos := peekNextSplitString(ss)
if schemaName == "" { if schemaName == "" {
// beeLogger.Log.Fatalf("[%s.%s] Schema must follow {object} or {array}", controllerName, funcName) beeLogger.Log.Fatalf("[%s.%s] Schema must follow {object} or {array}", controllerName, funcName)
} }
if strings.HasPrefix(schemaName, "[]") { if strings.HasPrefix(schemaName, "[]") {
schemaName = schemaName[2:] schemaName = schemaName[2:]
@ -518,7 +518,7 @@ func parserComments(comments *ast.CommentGroup, funcName, controllerName, pkgpat
para := swagger.Parameter{} para := swagger.Parameter{}
p := getparams(strings.TrimSpace(t[len("@Param "):])) p := getparams(strings.TrimSpace(t[len("@Param "):]))
if len(p) < 4 { if len(p) < 4 {
// beeLogger.Log.Fatal(controllerName + "_" + funcName + "'s comments @Param should have at least 4 params") beeLogger.Log.Fatal(controllerName + "_" + funcName + "'s comments @Param should have at least 4 params")
} }
para.Name = p[0] para.Name = p[0]
switch p[1] { switch p[1] {
@ -533,7 +533,7 @@ func parserComments(comments *ast.CommentGroup, funcName, controllerName, pkgpat
case "body": case "body":
break break
default: default:
// beeLogger.Log.Warnf("[%s.%s] Unknown param location: %s. Possible values are `query`, `header`, `path`, `formData` or `body`.\n", controllerName, funcName, p[1]) beeLogger.Log.Warnf("[%s.%s] Unknown param location: %s. Possible values are `query`, `header`, `path`, `formData` or `body`.\n", controllerName, funcName, p[1])
} }
para.In = p[1] para.In = p[1]
pp := strings.Split(p[2], ".") pp := strings.Split(p[2], ".")
@ -564,7 +564,7 @@ func parserComments(comments *ast.CommentGroup, funcName, controllerName, pkgpat
paraType = typeFormat[0] paraType = typeFormat[0]
paraFormat = typeFormat[1] paraFormat = typeFormat[1]
} else { } else {
// beeLogger.Log.Warnf("[%s.%s] Unknown param type: %s\n", controllerName, funcName, typ) beeLogger.Log.Warnf("[%s.%s] Unknown param type: %s\n", controllerName, funcName, typ)
} }
if isArray { if isArray {
para.Type = "array" para.Type = "array"
@ -717,7 +717,7 @@ func getModel(str string) (objectname string, m swagger.Schema, realTypes []stri
} }
} }
if m.Title == "" { if m.Title == "" {
// beeLogger.Log.Warnf("Cannot find the object: %s", str) beeLogger.Log.Warnf("Cannot find the object: %s", str)
// TODO remove when all type have been supported // TODO remove when all type have been supported
//os.Exit(1) //os.Exit(1)
} }
@ -808,7 +808,7 @@ func parseObject(d *ast.Object, k string, m *swagger.Schema, realTypes *[]string
mp.Default = str2RealType(res[1], realType) mp.Default = str2RealType(res[1], realType)
} else { } else {
// beeLogger.Log.Warnf("Invalid default value: %s", defaultValue) beeLogger.Log.Warnf("Invalid default value: %s", defaultValue)
} }
} }
@ -946,7 +946,7 @@ func str2RealType(s string, typ string) interface{} {
} }
if err != nil { if err != nil {
// beeLogger.Log.Warnf("Invalid default value type '%s': %s", typ, s) beeLogger.Log.Warnf("Invalid default value type '%s': %s", typ, s)
return s return s
} }

16
main.go
View File

@ -1,3 +1,16 @@
// Copyright 2013 bee authors
//
// Licensed under the Apache License, Version 2.0 (the "License"): you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
package main package main
import ( import (
@ -8,6 +21,7 @@ import (
"github.com/beego/bee/cmd" "github.com/beego/bee/cmd"
"github.com/beego/bee/cmd/commands" "github.com/beego/bee/cmd/commands"
"github.com/beego/bee/config"
"github.com/beego/bee/generate/swaggergen" "github.com/beego/bee/generate/swaggergen"
"github.com/beego/bee/utils" "github.com/beego/bee/utils"
) )
@ -46,6 +60,8 @@ func main() {
c.PreRun(c, args) c.PreRun(c, args)
} }
config.LoadConfig()
// Check if current directory is inside the GOPATH, // Check if current directory is inside the GOPATH,
// if so parse the packages inside it. // if so parse the packages inside it.
if strings.Contains(currentpath, utils.GetGOPATHs()[0]+"/src") && cmd.IfGenerateDocs(c.Name(), args) { if strings.Contains(currentpath, utils.GetGOPATHs()[0]+"/src") && cmd.IfGenerateDocs(c.Name(), args) {