Colorful log print

This commit is contained in:
Unknown 2013-08-09 22:40:46 +08:00
parent 89acd00955
commit ea43654872
4 changed files with 81 additions and 21 deletions

12
new.go
View File

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

7
run.go
View File

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

69
util.go
View File

@ -1,9 +1,12 @@
package main package main
import "fmt" import (
import "os" "fmt"
import "runtime" "os"
import "path/filepath" "path/filepath"
"runtime"
"strings"
)
// Go is a basic promise implementation: it wraps calls a function in a goroutine // 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. // and returns a channel which will later return the function's return value.
@ -28,3 +31,61 @@ func Debugf(format string, a ...interface{}) {
fmt.Fprintf(os.Stderr, fmt.Sprintf("[debug] %s:%d %s\n", file, line, format), a...) 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)
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 "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

@ -41,14 +41,14 @@ func NewWatcher(paths []string) {
// if 500ms change many times, then ignore it. // if 500ms change many times, then ignore it.
// for liteide often gofmt code after save. // for liteide often gofmt code after save.
if t.Add(time.Millisecond * 500).After(time.Now()) { if t.Add(time.Millisecond * 500).After(time.Now()) {
fmt.Println("[SKIP]", e.String()) colorLog("[SKIP] %s\n", e.String())
isbuild = false isbuild = false
} }
} }
eventTime[e.Name] = time.Now() eventTime[e.Name] = time.Now()
if isbuild { if isbuild {
fmt.Println("[EVEN]", e) colorLog("[EVEN] %s\n", e)
go Autobuild() go Autobuild()
} }
case err := <-watcher.Error: case err := <-watcher.Error:
@ -57,7 +57,7 @@ func NewWatcher(paths []string) {
} }
}() }()
fmt.Println("[INFO] Initializing watcher...") colorLog("[INFO] Initializing watcher...\n")
for _, path := range paths { for _, path := range paths {
fmt.Println(path) fmt.Println(path)
err = watcher.Watch(path) err = watcher.Watch(path)
@ -72,7 +72,7 @@ func Autobuild() {
state.Lock() state.Lock()
defer state.Unlock() defer state.Unlock()
fmt.Println("[INFO] Start building...") colorLog("[INFO] Start building...\n")
path, _ := os.Getwd() path, _ := os.Getwd()
os.Chdir(path) os.Chdir(path)
@ -94,10 +94,10 @@ func Autobuild() {
} }
if err != nil { if err != nil {
fmt.Println("[ERRO] ============== Build failed ===================") colorLog("[ERRO] ============== Build failed ===================\n")
return return
} }
fmt.Println("[SUCC] Build was successful") colorLog("[SUCC] Build was successful\n")
Restart(appname) Restart(appname)
} }
@ -119,7 +119,7 @@ func Restart(appname string) {
} }
func Start(appname string) { func Start(appname string) {
fmt.Println("[INFO] Restarting", appname) colorLog("[INFO] Restarting %s ...\n", appname)
if strings.Index(appname, "./") == -1 { if strings.Index(appname, "./") == -1 {
appname = "./" + appname appname = "./" + appname
} }