diff --git a/bale.go b/bale.go index 673353a..03f8b7f 100644 --- a/bale.go +++ b/bale.go @@ -24,8 +24,6 @@ import ( "path/filepath" "runtime" "strings" - - "github.com/Unknwon/com" ) var cmdBale = &Command{ @@ -48,7 +46,7 @@ func init() { func runBale(cmd *Command, args []string) { err := loadConfig() if err != nil { - com.ColorLog("[ERRO] Fail to parse bee.json[ %s ]\n", err) + ColorLog("[ERRO] Fail to parse bee.json[ %s ]\n", err) } os.RemoveAll("bale") @@ -56,11 +54,11 @@ func runBale(cmd *Command, args []string) { // Pack and compress data. for _, p := range conf.Bale.Dirs { - if !com.IsExist(p) { - com.ColorLog("[WARN] Skipped directory( %s )\n", p) + if !IsExist(p) { + ColorLog("[WARN] Skipped directory( %s )\n", p) continue } - com.ColorLog("[INFO] Packing directory( %s )\n", p) + ColorLog("[INFO] Packing directory( %s )\n", p) filepath.Walk(p, walkFn) } @@ -72,18 +70,18 @@ func runBale(cmd *Command, args []string) { fw, err := os.Create("bale.go") if err != nil { - com.ColorLog("[ERRO] Fail to create file[ %s ]\n", err) + ColorLog("[ERRO] Fail to create file[ %s ]\n", err) os.Exit(2) } defer fw.Close() _, err = fw.Write(buf.Bytes()) if err != nil { - com.ColorLog("[ERRO] Fail to write data[ %s ]\n", err) + ColorLog("[ERRO] Fail to write data[ %s ]\n", err) os.Exit(2) } - com.ColorLog("[SUCC] Baled resources successfully!\n") + ColorLog("[SUCC] Baled resources successfully!\n") } const ( @@ -150,7 +148,7 @@ func walkFn(resPath string, info os.FileInfo, err error) error { // Open resource files. fr, err := os.Open(resPath) if err != nil { - com.ColorLog("[ERRO] Fail to read file[ %s ]\n", err) + ColorLog("[ERRO] Fail to read file[ %s ]\n", err) os.Exit(2) } @@ -169,7 +167,7 @@ func walkFn(resPath string, info os.FileInfo, err error) error { os.MkdirAll(path.Dir(resPath), os.ModePerm) fw, err := os.Create("bale/" + resPath + ".go") if err != nil { - com.ColorLog("[ERRO] Fail to create file[ %s ]\n", err) + ColorLog("[ERRO] Fail to create file[ %s ]\n", err) os.Exit(2) } defer fw.Close() diff --git a/new.go b/new.go index 31375b8..65d4263 100644 --- a/new.go +++ b/new.go @@ -19,8 +19,6 @@ import ( "os" path "path/filepath" "strings" - - "github.com/Unknwon/com" ) var cmdNew = &Command{ @@ -56,15 +54,15 @@ func init() { func createApp(cmd *Command, args []string) { curpath, _ := os.Getwd() if len(args) != 1 { - com.ColorLog("[ERRO] Argument [appname] is missing\n") + ColorLog("[ERRO] Argument [appname] is missing\n") os.Exit(2) } gopath := os.Getenv("GOPATH") Debugf("gopath:%s", gopath) if gopath == "" { - com.ColorLog("[ERRO] $GOPATH not found\n") - com.ColorLog("[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 @@ -82,8 +80,8 @@ func createApp(cmd *Command, args []string) { } if !haspath { - com.ColorLog("[ERRO] Unable to create an application outside of $GOPATH(%s)\n", gopath) - com.ColorLog("[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) } @@ -126,7 +124,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)) - com.ColorLog("[SUCC] New application successfully created!\n") + ColorLog("[SUCC] New application successfully created!\n") } var appconf = `appname = {{.Appname}} diff --git a/run.go b/run.go index 92bf3fa..3749234 100644 --- a/run.go +++ b/run.go @@ -20,8 +20,6 @@ import ( path "path/filepath" "runtime" "strings" - - "github.com/Unknwon/com" ) var cmdRun = &Command{ @@ -88,7 +86,7 @@ func runApp(cmd *Command, args []string) { crupath, _ := os.Getwd() if len(args) != 1 { appname = path.Base(crupath) - com.ColorLog("[INFO] Uses '%s' as 'appname'\n", appname) + ColorLog("[INFO] Uses '%s' as 'appname'\n", appname) } else { appname = args[0] } @@ -96,7 +94,7 @@ func runApp(cmd *Command, args []string) { err := loadConfig() if err != nil { - com.ColorLog("[ERRO] Fail to parse bee.json[ %s ]\n", err) + ColorLog("[ERRO] Fail to parse bee.json[ %s ]\n", err) } var paths []string paths = append(paths, @@ -105,9 +103,9 @@ func runApp(cmd *Command, args []string) { path.Join(crupath, "./")) // Current path. // Because monitor files has some issues, we watch current directory // and ignore non-go files. - gps := com.GetGOPATHs() + gps := GetGOPATHs() if len(gps) == 0 { - com.ColorLog("[ERRO] Fail to start[ %s ]\n", "$GOPATH is not set or empty") + ColorLog("[ERRO] Fail to start[ %s ]\n", "$GOPATH is not set or empty") os.Exit(2) } gopath := gps[0] @@ -136,7 +134,7 @@ func loadConfig() error { } } else { defer f.Close() - com.ColorLog("[INFO] Detected bee.json\n") + ColorLog("[INFO] Detected bee.json\n") d := json.NewDecoder(f) err = d.Decode(&conf) if err != nil { diff --git a/test.go b/test.go index 978edd8..2fd4019 100644 --- a/test.go +++ b/test.go @@ -20,8 +20,6 @@ import ( "os/exec" path "path/filepath" "time" - - "github.com/Unknwon/com" ) var cmdTest = &Command{ @@ -38,7 +36,7 @@ var started = make(chan bool) func testApp(cmd *Command, args []string) { if len(args) != 1 { - com.ColorLog("[ERRO] Cannot start running[ %s ]\n", + ColorLog("[ERRO] Cannot start running[ %s ]\n", "argument 'appname' is missing") os.Exit(2) } @@ -47,7 +45,7 @@ func testApp(cmd *Command, args []string) { err := loadConfig() if err != nil { - com.ColorLog("[ERRO] Fail to parse bee.json[ %s ]\n", err) + ColorLog("[ERRO] Fail to parse bee.json[ %s ]\n", err) } var paths []string paths = append(paths, @@ -72,7 +70,7 @@ func testApp(cmd *Command, args []string) { } func runTest() { - com.ColorLog("[INFO] Start testing...\n") + ColorLog("[INFO] Start testing...\n") time.Sleep(time.Second * 5) path, _ := os.Getwd() os.Chdir(path + "/tests") @@ -82,16 +80,16 @@ func runTest() { var out, errbuffer bytes.Buffer icmd.Stdout = &out icmd.Stderr = &errbuffer - com.ColorLog("[INFO] ============== Test Begin ===================\n") + ColorLog("[INFO] ============== Test Begin ===================\n") err = icmd.Run() - com.ColorLog(out.String()) - com.ColorLog(errbuffer.String()) - com.ColorLog("[INFO] ============== Test End ===================\n") + ColorLog(out.String()) + ColorLog(errbuffer.String()) + ColorLog("[INFO] ============== Test End ===================\n") if err != nil { - com.ColorLog("[ERRO] ============== Test failed ===================\n") - com.ColorLog("[ERRO] ", err) + ColorLog("[ERRO] ============== Test failed ===================\n") + ColorLog("[ERRO] ", err) return } - com.ColorLog("[SUCC] Test finish\n") + ColorLog("[SUCC] Test finish\n") } diff --git a/util.go b/util.go index 080e336..05d8544 100644 --- a/util.go +++ b/util.go @@ -19,6 +19,7 @@ import ( "os" "path/filepath" "runtime" + "strings" ) // Go is a basic promise implementation: it wraps calls a function in a goroutine @@ -44,3 +45,122 @@ 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. +// See color rules in function 'ColorLogS'. +func ColorLog(format string, a ...interface{}) { + fmt.Print(ColorLogS(format, a...)) +} + +// ColorLogS colors log and return colored content. +// Log format: [ error ]. +// Level: TRAC -> blue; ERRO -> red; WARN -> Magenta; SUCC -> green; others -> default. +// Content: default; path: yellow; error -> red. +// Level has to be surrounded by "[" and "]". +// Highlights have to be surrounded by "# " and " #"(space), "#" will be deleted. +// Paths have to be surrounded by "( " and " )"(space). +// Errors have to be surrounded by "[ " and " ]"(space). +// Note: it hasn't support windows yet, contribute is welcome. +func ColorLogS(format string, a ...interface{}) string { + log := fmt.Sprintf(format, a...) + + var clog string + + if runtime.GOOS != "windows" { + + // 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 + + } else { + // Level. + i := strings.Index(log, "]") + if log[0] == '[' && i > -1 { + clog += "[" + log[1:i] + "]" + } + + log = log[i+1:] + + // Error. + log = strings.Replace(log, "[ ", "[", -1) + log = strings.Replace(log, " ]", "]", -1) + + // Path. + log = strings.Replace(log, "( ", "(", -1) + log = strings.Replace(log, " )", ")", -1) + + // Highlights. + log = strings.Replace(log, "# ", "", -1) + log = strings.Replace(log, " #", "", -1) + + log = clog + log + } + + return 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 + } + return level +} + +// IsExist returns whether a file or directory exists. +func IsExist(path string) bool { + _, err := os.Stat(path) + return err == nil || os.IsExist(err) +} + +// GetGOPATHs returns all paths in GOPATH variable. +func GetGOPATHs() []string { + gopath := os.Getenv("GOPATH") + var paths []string + if runtime.GOOS == "windows" { + gopath = strings.Replace(gopath, "\\", "/", -1) + paths = strings.Split(gopath, ";") + } else { + paths = strings.Split(gopath, ":") + } + return paths +} diff --git a/watch.go b/watch.go index a10b013..b252afa 100644 --- a/watch.go +++ b/watch.go @@ -23,7 +23,6 @@ import ( "sync" "time" - "github.com/Unknwon/com" "github.com/howeyc/fsnotify" ) @@ -36,7 +35,7 @@ var ( func NewWatcher(paths []string) { watcher, err := fsnotify.NewWatcher() if err != nil { - com.ColorLog("[ERRO] Fail to create new Watcher[ %s ]\n", err) + ColorLog("[ERRO] Fail to create new Watcher[ %s ]\n", err) os.Exit(2) } @@ -56,14 +55,14 @@ func NewWatcher(paths []string) { mt := getFileModTime(e.Name) if t := eventTime[e.Name]; mt == t { - com.ColorLog("[SKIP] # %s #\n", e.String()) + ColorLog("[SKIP] # %s #\n", e.String()) isbuild = false } eventTime[e.Name] = mt if isbuild { - com.ColorLog("[EVEN] %s\n", e) + ColorLog("[EVEN] %s\n", e) go Autobuild() } case err := <-watcher.Error: @@ -74,12 +73,12 @@ func NewWatcher(paths []string) { time.Sleep(500 * time.Millisecond) }() - com.ColorLog("[INFO] Initializing watcher...\n") + ColorLog("[INFO] Initializing watcher...\n") for _, path := range paths { - com.ColorLog("[TRAC] Directory( %s )\n", path) + ColorLog("[TRAC] Directory( %s )\n", path) err = watcher.Watch(path) if err != nil { - com.ColorLog("[ERRO] Fail to watch directory[ %s ]\n", err) + ColorLog("[ERRO] Fail to watch directory[ %s ]\n", err) os.Exit(2) } } @@ -91,14 +90,14 @@ func getFileModTime(path string) int64 { path = strings.Replace(path, "\\", "/", -1) f, err := os.Open(path) if err != nil { - com.ColorLog("[ERRO] Fail to open file[ %s ]\n", err) + ColorLog("[ERRO] Fail to open file[ %s ]\n", err) return time.Now().Unix() } defer f.Close() fi, err := f.Stat() if err != nil { - com.ColorLog("[ERRO] Fail to get file information[ %s ]\n", err) + ColorLog("[ERRO] Fail to get file information[ %s ]\n", err) return time.Now().Unix() } @@ -109,7 +108,7 @@ func Autobuild() { state.Lock() defer state.Unlock() - com.ColorLog("[INFO] Start building...\n") + ColorLog("[INFO] Start building...\n") path, _ := os.Getwd() os.Chdir(path) @@ -131,10 +130,10 @@ func Autobuild() { } if err != nil { - com.ColorLog("[ERRO] ============== Build failed ===================\n") + ColorLog("[ERRO] ============== Build failed ===================\n") return } - com.ColorLog("[SUCC] Build was successful\n") + ColorLog("[SUCC] Build was successful\n") Restart(appname) } @@ -156,7 +155,7 @@ func Restart(appname string) { } func Start(appname string) { - com.ColorLog("[INFO] Restarting %s ...\n", appname) + ColorLog("[INFO] Restarting %s ...\n", appname) if strings.Index(appname, "./") == -1 { appname = "./" + appname } @@ -166,7 +165,7 @@ func Start(appname string) { cmd.Stderr = os.Stderr go cmd.Run() - com.ColorLog("[INFO] %s is running...\n", appname) + ColorLog("[INFO] %s is running...\n", appname) started <- true }