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

Merge branch 'master' of github.com:Unknwon/bee

This commit is contained in:
Unknown 2013-08-19 23:56:06 +08:00
commit 3d3b109b8a
5 changed files with 123 additions and 34 deletions

4
.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
.DS_Store
bee
*.exe
*.exe~

16
new.go
View File

@ -40,15 +40,15 @@ func init() {
func createApp(cmd *Command, args []string) {
curpath, _ := os.Getwd()
if len(args) != 1 {
fmt.Println("[ERRO] Argument [appname] is missing")
colorLog("[ERRO] Argument [appname] is missing\n")
os.Exit(2)
}
gopath := os.Getenv("GOPATH")
Debugf("gopath:%s", gopath)
if gopath == "" {
fmt.Printf("[ERRO] $GOPATH not found\n")
fmt.Printf("[HINT] Set $GOPATH in your environment vairables\n")
colorLog("[ERRO] $GOPATH not found\n")
colorLog("[HINT] Set $GOPATH in your environment vairables\n")
os.Exit(2)
}
haspath := false
@ -56,9 +56,9 @@ func createApp(cmd *Command, args []string) {
wgopath := path.SplitList(gopath)
for _, wg := range wgopath {
wg = path.Join(wg, "src")
wg, _ = path.EvalSymlinks(path.Join(wg, "src"))
if path.HasPrefix(strings.ToLower(curpath), strings.ToLower(wg)) {
if strings.HasPrefix(strings.ToLower(curpath), strings.ToLower(wg)) {
haspath = true
appsrcpath = wg
break
@ -66,8 +66,8 @@ func createApp(cmd *Command, args []string) {
}
if !haspath {
fmt.Printf("[ERRO] Unable to create an application outside of $GOPATH(%s)\n", gopath)
fmt.Printf("[HINT] Change your work directory by `cd $GOPATH%ssrc`\n", string(path.Separator))
colorLog("[ERRO] Unable to create an application outside of $GOPATH(%s)\n", gopath)
colorLog("[HINT] Change your work directory by `cd ($GOPATH%ssrc)`\n", string(path.Separator))
os.Exit(2)
}
@ -110,7 +110,7 @@ func createApp(cmd *Command, args []string) {
fmt.Println(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)), string(path.Separator)), -1))
fmt.Println("[SUCC] New application successfully created!")
colorLog("[SUCC] New application successfully created!\n")
}
var appconf = `appname = {{.Appname}}

8
run.go
View File

@ -2,7 +2,6 @@ package main
import (
"encoding/json"
"fmt"
"os"
path "path/filepath"
"runtime"
@ -69,7 +68,8 @@ var conf struct {
func runApp(cmd *Command, args []string) {
exit := make(chan bool)
if len(args) != 1 {
fmt.Println("[ERRO] Argument [appname] is missing")
colorLog("[ERRO] Cannot start running[ %s ]\n",
"argument 'appname' is missing")
os.Exit(2)
}
crupath, _ := os.Getwd()
@ -77,7 +77,7 @@ func runApp(cmd *Command, args []string) {
err := loadConfig()
if err != nil {
fmt.Println("[ERRO] Fail to parse bee.json:", err)
colorLog("[ERRO] Fail to parse bee.json[ %s ]", err)
}
var paths []string
paths = append(paths,
@ -111,7 +111,7 @@ func loadConfig() error {
}
} else {
defer f.Close()
fmt.Println("[INFO] Detected bee.json")
colorLog("[INFO] Detected bee.json\n")
d := json.NewDecoder(f)
err = d.Decode(&conf)
if err != nil {

75
util.go
View File

@ -1,9 +1,12 @@
package main
import "fmt"
import "os"
import "runtime"
import "path/filepath"
import (
"fmt"
"os"
"path/filepath"
"runtime"
"strings"
)
// 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.
@ -28,3 +31,67 @@ func Debugf(format string, a ...interface{}) {
fmt.Fprintf(os.Stderr, fmt.Sprintf("[debug] %s:%d %s\n", file, line, format), a...)
}
}
const (
Gray = uint8(iota + 90)
Red
Green
Yellow
Blue
Magenta
//NRed = uint8(31) // Normal
EndColor = "\033[0m"
)
// colorLog colors log and print to stdout.
// Log format: [<level>] <content [path]> [ error ].
// Level: ERRO -> red; WARN -> Magenta; SUCC -> green; others -> default.
// Content: default; path: yellow; error -> red.
// Errors have to surrounded by "[ " and " ]"(space).
func colorLog(format string, a ...interface{}) {
log := fmt.Sprintf(format, a...)
if runtime.GOOS != "windows" {
var clog string
// Level.
i := strings.Index(log, "]")
if log[0] == '[' && i > -1 {
clog += "[" + getColorLevel(log[1:i]) + "]"
}
log = log[i+1:]
// Error.
log = strings.Replace(log, "[ ", fmt.Sprintf("[\033[%dm", Red), -1)
log = strings.Replace(log, " ]", EndColor+"]", -1)
// Path.
log = strings.Replace(log, "( ", fmt.Sprintf("(\033[%dm", Yellow), -1)
log = strings.Replace(log, " )", EndColor+")", -1)
// Highlights.
log = strings.Replace(log, "# ", fmt.Sprintf("\033[%dm", Gray), -1)
log = strings.Replace(log, " #", EndColor, -1)
log = clog + log
}
fmt.Print(log)
}
// getColorLevel returns colored level string by given level.
func getColorLevel(level string) string {
level = strings.ToUpper(level)
switch level {
case "TRAC":
return fmt.Sprintf("\033[%dm%s\033[0m", Blue, level)
case "ERRO":
return fmt.Sprintf("\033[%dm%s\033[0m", Red, level)
case "WARN":
return fmt.Sprintf("\033[%dm%s\033[0m", Magenta, level)
case "SUCC":
return fmt.Sprintf("\033[%dm%s\033[0m", Green, level)
default:
return level
}
}

View File

@ -14,13 +14,14 @@ import (
var (
cmd *exec.Cmd
state sync.Mutex
eventTime = make(map[string]time.Time)
eventTime = make(map[string]int64)
)
func NewWatcher(paths []string) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
colorLog("[ERRO] Fail to create new Watcher[ %s ]\n", err)
os.Exit(2)
}
go func() {
@ -37,18 +38,16 @@ func NewWatcher(paths []string) {
continue
}
if t, ok := eventTime[e.Name]; ok {
// if 500ms change many times, then ignore it.
// for liteide often gofmt code after save.
if t.Add(time.Millisecond * 500).After(time.Now()) {
fmt.Println("[SKIP]", e.String())
isbuild = false
}
mt := getFileModTime(e.Name)
if t := eventTime[e.Name]; mt == t {
colorLog("[SKIP] # %s #\n", e.String())
isbuild = false
}
eventTime[e.Name] = time.Now()
eventTime[e.Name] = mt
if isbuild {
fmt.Println("[EVEN]", e)
colorLog("[EVEN] %s\n", e)
go Autobuild()
}
case err := <-watcher.Error:
@ -57,22 +56,41 @@ func NewWatcher(paths []string) {
}
}()
fmt.Println("[INFO] Initializing watcher...")
colorLog("[INFO] Initializing watcher...\n")
for _, path := range paths {
fmt.Println(path)
colorLog("[TRAC] Directory( %s )\n", path)
err = watcher.Watch(path)
if err != nil {
log.Fatal(err)
colorLog("[ERRO] Fail to watch directory[ %s ]\n", err)
os.Exit(2)
}
}
}
// getFileModTime retuens unix timestamp of `os.File.ModTime` by given path.
func getFileModTime(path string) int64 {
f, err := os.Open(path)
if err != nil {
colorLog("[ERRO] Fail to open file[ %s ]", err)
return time.Now().Unix()
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
colorLog("[ERRO] Fail to get file information[ %s ]", err)
return time.Now().Unix()
}
return fi.ModTime().Unix()
}
func Autobuild() {
state.Lock()
defer state.Unlock()
fmt.Println("[INFO] Start building...")
colorLog("[INFO] Start building...\n")
path, _ := os.Getwd()
os.Chdir(path)
@ -94,10 +112,10 @@ func Autobuild() {
}
if err != nil {
fmt.Println("[ERRO] ============== Build failed ===================")
colorLog("[ERRO] ============== Build failed ===================\n")
return
}
fmt.Println("[SUCC] Build was successful")
colorLog("[SUCC] Build was successful\n")
Restart(appname)
}
@ -119,7 +137,7 @@ func Restart(appname string) {
}
func Start(appname string) {
fmt.Println("[INFO] Restarting", appname)
colorLog("[INFO] Restarting %s ...\n", appname)
if strings.Index(appname, "./") == -1 {
appname = "./" + appname
}