1
0
mirror of https://github.com/beego/bee.git synced 2024-12-22 10:00:50 +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:
- go vet $(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/)
- unused $(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
// License for the specific language governing permissions and limitations
// under the License.
package bale
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
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
import (

View File

@ -11,7 +11,6 @@
// 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 run
import (

View File

@ -11,7 +11,6 @@
// 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 config
import (
@ -27,93 +26,106 @@ import (
const confVer = 0
var defaultConf = `{
"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
// gopm support
Gopm struct {
Enable bool
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"`
Envs []string
Bale struct {
Import string
Dirs []string
IngExt []string `json:"ignore_ext" yaml:"ignore_ext"`
}
Database struct {
Driver string
Conn string
}
var Conf = struct {
Version int
Gopm gopm
GoInstall bool `json:"go_install" yaml:"go_install"` // Indicates whether execute "go install" before "go build".
DirStruct dirStruct `json:"dir_structure" yaml:"dir_structure"`
CmdArgs []string `json:"cmd_args" yaml:"cmd_args"`
Envs []string
Bale bale
Database database
EnableReload bool `json:"enable_reload" yaml:"enable_reload"`
EnableNotification bool `json:"enable_notification" yaml:"enable_notification"`
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() {
loadConfig()
// gopm support
type gopm struct {
Enable bool
Install bool
}
// loadConfig loads customized configuration.
func loadConfig() {
beeLogger.Log.Info("Loading default configuration...")
err := json.Unmarshal([]byte(defaultConf), &Conf)
// dirStruct describes the application's directory structure
type dirStruct struct {
WatchAll bool `json:"watch_all" yaml:"watch_all"`
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 {
beeLogger.Log.Errorf(err.Error())
beeLogger.Log.Error(err.Error())
}
err = filepath.Walk(".", func(path string, fileInfo os.FileInfo, err error) error {
if err != nil {
return nil
}
if fileInfo.IsDir() {
return nil
}
switch fileInfo.Name() {
dir, err := os.Open(currentPath)
if err != nil {
beeLogger.Log.Error(err.Error())
}
defer dir.Close()
files, err := dir.Readdir(-1)
if err != nil {
beeLogger.Log.Error(err.Error())
}
for _, file := range files {
switch file.Name() {
case "bee.json":
beeLogger.Log.Info("Loading configuration from 'bee.json'...")
return parseJSON(path, &Conf)
{
beeLogger.Log.Info("Loading configuration from 'bee.json'...")
err = parseJSON(filepath.Join(currentPath, file.Name()), &Conf)
if err != nil {
beeLogger.Log.Errorf("Failed to parse JSON file: %s", err)
}
break
}
case "Beefile":
beeLogger.Log.Info("Loading configuration from 'Beefile'...")
return parseYAML(path, &Conf)
{
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
}
}
return nil
})
if err != nil {
beeLogger.Log.Errorf("Failed to parse config file: %s", err)
}
// Check format version
if Conf.Version != confVer {
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 {
Conf.DirStruct.Controllers = "controllers"
}
if len(Conf.DirStruct.Models) == 0 {
Conf.DirStruct.Models = "models"
}
// Append watch exts
//watchExts = append(watchExts, Conf.WatchExt...)
return
}
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)
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{}
@ -352,7 +352,7 @@ func analyseControllerPkg(localName, pkgpath string) {
}
gopath := os.Getenv("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 := ""
@ -370,7 +370,7 @@ func analyseControllerPkg(localName, pkgpath string) {
}
pkgCache[pkgpath] = struct{}{}
} 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()
@ -379,7 +379,7 @@ func analyseControllerPkg(localName, pkgpath string) {
return !info.IsDir() && !strings.HasPrefix(name, ".") && strings.HasSuffix(name, ".go")
}, parser.ParseComments)
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 _, fl := range pkg.Files {
@ -417,7 +417,7 @@ func isSystemPackage(pkgpath string) bool {
goroot = runtime.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))
@ -481,7 +481,7 @@ func parserComments(comments *ast.CommentGroup, funcName, controllerName, pkgpat
ss = strings.TrimSpace(ss[pos:])
schemaName, pos := peekNextSplitString(ss)
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, "[]") {
schemaName = schemaName[2:]
@ -518,7 +518,7 @@ func parserComments(comments *ast.CommentGroup, funcName, controllerName, pkgpat
para := swagger.Parameter{}
p := getparams(strings.TrimSpace(t[len("@Param "):]))
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]
switch p[1] {
@ -533,7 +533,7 @@ func parserComments(comments *ast.CommentGroup, funcName, controllerName, pkgpat
case "body":
break
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]
pp := strings.Split(p[2], ".")
@ -564,7 +564,7 @@ func parserComments(comments *ast.CommentGroup, funcName, controllerName, pkgpat
paraType = typeFormat[0]
paraFormat = typeFormat[1]
} 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 {
para.Type = "array"
@ -717,7 +717,7 @@ func getModel(str string) (objectname string, m swagger.Schema, realTypes []stri
}
}
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
//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)
} 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 {
// beeLogger.Log.Warnf("Invalid default value type '%s': %s", typ, s)
beeLogger.Log.Warnf("Invalid default value type '%s': %s", typ, 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
import (
@ -8,6 +21,7 @@ import (
"github.com/beego/bee/cmd"
"github.com/beego/bee/cmd/commands"
"github.com/beego/bee/config"
"github.com/beego/bee/generate/swaggergen"
"github.com/beego/bee/utils"
)
@ -46,6 +60,8 @@ func main() {
c.PreRun(c, args)
}
config.LoadConfig()
// Check if current directory is inside the GOPATH,
// if so parse the packages inside it.
if strings.Contains(currentpath, utils.GetGOPATHs()[0]+"/src") && cmd.IfGenerateDocs(c.Name(), args) {