Beispiel #1
0
func (h *HTTPLogger) ServeHTTP(w http.ResponseWriter, r *http.Request) {

	//Colors to be used on the logger
	red := ansi.ColorCode("red+bh")
	white := ansi.ColorCode("white+bh")
	greenUnderline := ansi.ColorCode("green+buh")
	blackOnWhite := ansi.ColorCode("black+b:white+h")
	//Reset the color
	reset := ansi.ColorCode("reset")

	//Log data
	fmt.Println(red,
		time.Now(),
		reset,
		":",
		white,
		r.RemoteAddr,
		reset, "requested page",
		greenUnderline,
		r.URL.String(),
		reset,
		"with method",
		blackOnWhite,
		r.Method,
		reset)
}
Beispiel #2
0
// thanks to IonicaBizau/image-to-ascii for algorithm
func Convert(img image.Image) (str string) {
	var buffer bytes.Buffer
	size := img.Bounds().Max
	pixels := ".,:;i1tfLCG08@"
	precision := (255 * 4) / (len(pixels) - 1)

	// ansi color end constant
	reset := ansi.ColorCode("reset")

	for y := 0; y < size.Y; y += 1 {
		for x := 0; x < size.X; x += 1 {
			r, g, b, a := img.At(x, y).RGBA()
			sum := r>>8 + g>>8 + b>>8 + a>>8
			pixel := pixels[int(sum)/precision]
			// find the closest ansi color code
			code := x256.ClosestCode(uint8(r>>8), uint8(g>>8), uint8(b>>8))
			/// get the ansi color code
			color := ansi.ColorCode(strconv.Itoa(code))

			// write the pixel
			buffer.WriteString(color)
			buffer.WriteString(string(pixel))
			buffer.WriteString(reset)
		}
		buffer.WriteString("\n")
	}

	return buffer.String()
}
Beispiel #3
0
func showBlockedList(successBlock []anaconda.User, failedBlock []User) (err error) {

	red := ansi.ColorCode("red")
	blue := ansi.ColorCode("blue")
	reset := ansi.ColorCode("reset")

	if len(successBlock) > 0 {
		fmt.Println(red, "Blocked", reset)
		for idx, user := range successBlock {
			fmt.Println(idx+1, ":", user.Name, "(@", user.ScreenName, ")")
		}
	}

	if len(failedBlock) > 0 {
		fmt.Println(blue, "Failed Block", reset)
		for idx, user := range failedBlock {
			if user.id == 0 {
				fmt.Println(idx+1, ":", user.screenName)
			} else {
				fmt.Println(idx+1, ":", user.id)
			}
		}
	}

	return
}
Beispiel #4
0
func (g *githubPackage) DisplayResult() {
	localTime, lerr := g.LocalLastCommitDate()
	githubTime, gerr := g.GithubLastCommitDate()

	fmt.Println("Package:", g.ImportName)
	if lerr != nil {
		fmt.Println("Local:  Error")
	} else {
		fmt.Println("Local:  ", localTime)
	}

	if gerr != nil {
		fmt.Println("Github:  Error")
	} else {
		fmt.Println("Github: ", githubTime)
	}

	if lerr == nil && gerr == nil {
		delta := localTime.Sub(githubTime)
		if delta.Minutes() == 0 {
			green := ansi.ColorCode("green")
			reset := ansi.ColorCode("reset")
			fmt.Println("Status:", green, "OK", reset)
		} else {
			green := ansi.ColorCode("red")
			reset := ansi.ColorCode("reset")
			fmt.Println("Status:", green, "Outdated", reset)
		}
	}
	fmt.Println(strings.Repeat("-", len(g.ImportName)))
}
Beispiel #5
0
func AssertJSONBody(tb testing.TB, exp, act interface{}) {
	red := ansi.ColorCode("red+h:black")
	green := ansi.ColorCode("green+h:black")
	yellow := ansi.ColorFunc("yellow+h")
	reset := ansi.ColorCode("reset")

	var actBuf bytes.Buffer
	err := json.Indent(&actBuf, []byte(act.(string)), "", " ")
	if err != nil {
		fmt.Println(red, "Invalid json: ", act, reset)
	}
	act = string(actBuf.Bytes())

	var expBuf bytes.Buffer
	err = json.Indent(&expBuf, []byte(exp.(string)), "", " ")
	if err != nil {
		fmt.Println(red, "Invalid json: ", exp, reset)
	}
	exp = string(expBuf.Bytes())

	if !reflect.DeepEqual(exp, act) {
		_, file, line, _ := runtime.Caller(1)

		fmt.Println(yellow(fmt.Sprintf("%s:%d", filepath.Base(file), line)))
		fmt.Println(green, "Expected: ", exp, reset)
		fmt.Println(red, "     Got: ", act, reset)

		tb.FailNow()
	}
}
Beispiel #6
0
func Config(c *cli.Context) {
	_, err := ioutil.ReadFile(utils.Home() + "/.asana.yml")
	if err != nil || config.Load().Api_key == "" {
		println("visit: http://app.asana.com/-/account_api")
		print("paste your api_key: ")
		var s string
		fmt.Scanf("%s", &s)

		f, _ := os.Create(utils.Home() + "/.asana.yml")
		defer f.Close()
		f.WriteString("api_key: " + s + "\n")
	}

	ws := api.Me().Workspaces
	index := 0

	cyan := ansi.ColorCode("cyan")
	reset := ansi.ColorCode("reset")
	if len(ws) > 1 {
		fmt.Println("\n" + strconv.Itoa(len(ws)) + " workspaces found.")
		for i, w := range ws {
			fmt.Printf("%s[%d]%s %s\n", cyan, i, reset, w.Name)
		}
		index = utils.EndlessSelect(len(ws)-1, index)
	}
	apiKey := config.Load().Api_key
	f, _ := os.Create(utils.Home() + "/.asana.yml")
	f.WriteString("api_key: " + apiKey + "\n")
	f.WriteString("workspace: " + strconv.Itoa(ws[index].Id) + "\n")
}
Beispiel #7
0
func colorizeMessage(color, prefix, message string, args ...interface{}) string {
	prefResult := ""
	if prefix != "" {
		prefResult = ansi.Color(prefix, color+"+b") + " " + ansi.ColorCode("reset")
	}
	return prefResult + ansi.Color(fmt.Sprintf(message, args...), color) + ansi.ColorCode("reset")
}
Beispiel #8
0
func (r *Row) Print(c bool) {
	if c {
		color := ansi.ColorCode(r.Color)
		reset := ansi.ColorCode("reset")
		fmt.Println(color, r.Message, reset)
		return
	}
	fmt.Println(r.Message)
}
Beispiel #9
0
func main() {
	flag.Parse()

	u, err := url.Parse(flag.Arg(0))
	if err != nil {
		panic(err)
	}
	h := http.Header{"Origin": {"http://" + u.Host}}
	conn, _, err := websocket.DefaultDialer.Dial(u.String(), h)

	if err != nil {
		panic(err)
	}

	go func() {
		for {
			t, buf, err := conn.ReadMessage()
			if *flagDebug {
				log.Println("type:", t, len(buf), err)
				continue
			}
			if *flagPretty {
				color := ansi.ColorCode("green")
				reset := ansi.ColorCode("reset")
				fmt.Fprintf(os.Stdout, "%s%s%s\n", color, strings.Repeat("<", 10), reset)
				var v interface{}
				if err := json.Unmarshal(buf, &v); err != nil {
					os.Stdout.Write(buf)
				} else {
					buf, err = json.MarshalIndent(v, "", "  ")
					if err != nil {
						panic(err)
					}
					os.Stdout.Write(buf)
					fmt.Fprintln(os.Stdout)
				}
			} else {
				os.Stdout.Write(buf)
			}
		}
	}()

	b := bufio.NewReader(os.Stdin)
	for {
		line, err := b.ReadString('\n')
		if err != nil {
			log.Println(err)
			break
		}
		if err := conn.WriteMessage(websocket.TextMessage, []byte(line)); err != nil {
			break
		}
	}

	conn.Close()
}
Beispiel #10
0
func (f *fullDBInfo) MaintenanceString() string {
	valstr, _ := f.DBInfo.Info.GetString("Maintenance")
	if valstr != "" && valstr != "not required" {
		return " " + ansi.Color("!!", "red+b") + ansi.ColorCode("reset")
	}
	return ""
}
Beispiel #11
0
func SetColor(colors bool) {
	config.Colors = colors
	logger.SetPrefix("")
	if config.Colors {
		logger.SetPrefix(ansi.ColorCode("white"))
	}
}
Beispiel #12
0
func main() {
	reset := ansi.ColorCode("reset")
	msg := ansi.Color("red+b", "red+b:white")
	fmt.Println(msg, reset)
	msg = ansi.Color("green", "green")
	fmt.Println(msg, reset)
	msg = ansi.Color("background white", "black:white")
	fmt.Println(msg, reset)

	warn := ansi.ColorFunc("yellow:black")
	fmt.Println(warn("this is warning!"), reset)

	lime := ansi.ColorCode("green+h:black")

	fmt.Println(lime, "Lime message.", reset)
}
Beispiel #13
0
Datei: cmd.go Projekt: THEY/godo
func (gcmd *command) toExecCmd() (cmd *exec.Cmd, err error) {
	cmd = exec.Command(gcmd.executable, gcmd.argv...)
	if gcmd.wd != "" {
		cmd.Dir = gcmd.wd
	}

	cmd.Env = effectiveEnv(gcmd.env)
	cmd.Stdin = os.Stdin

	if gcmd.captureOutput {
		outWrapper := newFileWrapper(os.Stdout, &gcmd.recorder, "")
		errWrapper := newFileWrapper(os.Stderr, &gcmd.recorder, ansi.ColorCode("red+b"))
		cmd.Stdout = outWrapper
		cmd.Stderr = errWrapper
	} else {
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
	}

	if verbose {
		if Env != "" {
			util.Debug("#", "Env: %s\n", Env)
		}
		util.Debug("#", "%s\n", gcmd.commandstr)
	}

	return cmd, nil
}
Beispiel #14
0
func AssertEqual(tb testing.TB, exp, act interface{}) {
	if !reflect.DeepEqual(exp, act) {
		yellow := ansi.ColorFunc("yellow+h")
		green := ansi.ColorCode("green+h:black")
		red := ansi.ColorCode("red+h:black")
		reset := ansi.ColorCode("reset")

		_, file, line, _ := runtime.Caller(1)

		fmt.Println(yellow(fmt.Sprintf("%s:%d", filepath.Base(file), line)))
		fmt.Println(green, "Expected: ", exp, reset)
		fmt.Println(red, "     Got: ", act, reset)

		tb.FailNow()
	}
}
Beispiel #15
0
Datei: log.go Projekt: kr/hk-1
func (c *colorizer) Writeln(p string) (n int, err error) {
	if c.filter.MatchString(p) {
		submatches := c.filter.FindStringSubmatch(p)
		return fmt.Fprintln(c.writer, ansi.Color(submatches[1], c.resolve(submatches[2]))+ansi.ColorCode("reset")+submatches[3])
	}

	return fmt.Fprintln(c.writer, p)
}
Beispiel #16
0
// Demo demo
func Demo() {
	// colorize a string, slowest method
	msg := ansi.Color("foo", "red+b:white")
	fmt.Print(msg)

	// create a closure to avoid escape code compilation
	phosphorize := ansi.ColorFunc("green+h:black")
	msg = phosphorize("Bring back the 80s!")
	fmt.Print(msg)

	// cache escape codes and build strings manually, faster than closure
	lime := ansi.ColorCode("green+h:black")
	reset := ansi.ColorCode("reset")

	msg = lime + "Bring back the 80s!" + reset
	fmt.Print(msg)

}
Beispiel #17
0
func format(line string) {
	green := ansi.ColorCode("green")
	bold := ansi.ColorCode("white")
	red := ansi.ColorCode("red")
	reset := ansi.ColorCode("reset")
	dateRegexp := "[0-9]{4}-[0-9]{2}-[0-9]{2}"

	index := regexp.MustCompile("^[0-9]*").FindString(line)
	line = regexp.MustCompile("^[0-9]*:").ReplaceAllString(line, "") // remove index
	line = regexp.MustCompile("^[0-9]*:").ReplaceAllString(line, "") // remove task_id

	date := regexp.MustCompile("^" + dateRegexp).FindString(line)
	line = regexp.MustCompile("^("+dateRegexp+")?:").ReplaceAllString(line, "") // remove date

	assignee := regexp.MustCompile("^[a-zA-Z]*:").FindString(line)
	line = regexp.MustCompile("^.*:").ReplaceAllString(line, "") // remove assignee

	fmt.Printf("%s%2s%s [ %s%10s%s ] %s@%s%s %s\n", bold, index, reset, red, date, reset, green, assignee, reset, line)
}
Beispiel #18
0
func newFileWrapper(file *os.File, recorder *bytes.Buffer, color string) *fileWrapper {
	streamer := &fileWrapper{
		file:       file,
		buf:        bytes.NewBuffer([]byte("")),
		recorder:   recorder,
		colorReset: ansi.ColorCode("reset"),
		colorStart: color,
	}

	return streamer
}
Beispiel #19
0
func Print(color string, args ...interface{}) {
	if config.Quiet {
		return
	}

	if config.Colors {
		colorStart := ansi.ColorCode(color)
		colorFinish := ansi.ColorCode("reset")
		args = append([]interface{}{colorStart}, args...)
		args = append(args, colorFinish)
	} else {
		args = append([]interface{}{""}, args...)
	}

	if config.Prefix != "" && len(args) > 0 {
		args[0] = args[0].(string) + "[" + config.Prefix + "]"
	}

	logger.Println(args...)
}
Beispiel #20
0
func fromAPI(saveCache bool, withProject bool) {
	tasks := api.Tasks(url.Values{}, false, withProject)
	if saveCache {
		cache(tasks)
	}
	red := ansi.ColorCode("red")
	blue := ansi.ColorCode("blue")
	green := ansi.ColorCode("green")
	reset := ansi.ColorCode("reset")
	for i, t := range tasks {
		fmt.Printf("%2d [ %s%10s%s ] %s@%s%s: ", i, red, t.Due_on, reset, green, t.Assignee.Name, reset)
		for _, p := range t.Projects {
			fmt.Printf("%s#%s%s ", blue, p.Name, reset)
		}

		for _, ta := range t.Tags {
			fmt.Printf("%s#%s%s ", blue, ta.Name, reset)
		}
		fmt.Printf("%s\n", t.Name)
	}
}
Beispiel #21
0
func Projects(c *cli.Context) {
	projects := api.Projects()
	index := 0
	cyan := ansi.ColorCode("cyan")
	reset := ansi.ColorCode("reset")
	if len(projects) > 0 {
		fmt.Println("\n" + strconv.Itoa(len(projects)) + " projects found.")
		for i, p := range projects {
			fmt.Printf("%s[%2d]%s %s\n", cyan, i, reset, p.Name)
		}
		index = utils.EndlessSelect(len(projects)-1, index)
	}

	workspace := config.Load().Workspace
	apiKey := config.Load().Api_key
	proj := strconv.Itoa(projects[index].Id)

	f, _ := os.Create(utils.Home() + "/.asana.yml")
	f.WriteString("api_key: " + apiKey + "\n")
	f.WriteString("workspace: " + strconv.Itoa(workspace) + "\n")
	f.WriteString("project: " + proj + "\n")
}
Beispiel #22
0
func NewColorTheme(c *ColorTheme) (theme *ColorTheme) {
	color_theme := &ColorTheme{
		Verified: ansi.ColorCode(c.Verified),
		Bad:      ansi.ColorCode(c.Bad),
		Plus:     ansi.ColorCode(c.Plus),
		OK:       ansi.ColorCode(c.OK),
		Absent:   ansi.ColorCode(c.Absent),
		Title:    ansi.ColorCode(c.Title),
		Reset:    ansi.ColorCode("reset"),
	}
	return color_theme
}
Beispiel #23
0
func cache(tasks []api.Task_t) {
	f, _ := os.Create(utils.CacheFile())
	defer f.Close()

	blue := ansi.ColorCode("blue")
	reset := ansi.ColorCode("reset")

	for i, t := range tasks {
		f.WriteString(strconv.Itoa(i) + ":")
		f.WriteString(strconv.Itoa(t.Id) + ":")
		f.WriteString(t.Due_on + ":")
		f.WriteString(t.Assignee.Name + ":")
		for _, p := range t.Projects {
			f.WriteString(blue + "#" + p.Name + " " + reset)
		}

		for _, ta := range t.Tags {
			f.WriteString(blue + "#" + ta.Name + " " + reset)
		}
		f.WriteString(t.Name + " ")
		f.WriteString("\n")
	}
}
func GetExecutionOutput(executionid string) {
	client := NewClientFromEnv()
	data, err := client.GetExecutionOutput(executionid)
	red := ansi.ColorCode("red")
	green := ansi.ColorCode("green")
	cyan := ansi.ColorCode("cyan")
	reset := ansi.ColorCode("reset")

	if err != nil {
		fmt.Printf("%s\n", err)
		return
	}
	for _, e := range data.Entries.Entry {
		fmt.Printf("%s %s", e.Time, e.Node)
		if e.Level == "ERROR" {
			fmt.Println(red, e.Level, e.Log, reset)
		} else if e.Level == "VERBOSE" {
			fmt.Println(cyan, e.Level, e.Log, reset)
		} else {
			fmt.Println(green, e.Level, e.Log, reset)
		}
	}
}
Beispiel #25
0
func parseTheme(theme string) *colorScheme {
	m := parseKVList(theme, ",")
	cs := &colorScheme{}
	var wildcard string

	var color = func(key string) string {
		if disableColors {
			return ""
		}
		style := m[key]
		c := ansi.ColorCode(style)
		if c == "" {
			c = wildcard
		}
		//fmt.Printf("plain=%b [%s] %s=%q\n", ansi.DefaultFG, key, style, c)

		return c
	}
	wildcard = color("*")

	if wildcard != ansi.Reset {
		cs.Key = wildcard
		cs.Value = wildcard
		cs.Misc = wildcard
		cs.Source = wildcard
		cs.Message = wildcard

		cs.Trace = wildcard
		cs.Debug = wildcard
		cs.Warn = wildcard
		cs.Info = wildcard
		cs.Error = wildcard
	}

	cs.Key = color("key")
	cs.Value = color("value")
	cs.Misc = color("misc")
	cs.Source = color("source")
	cs.Message = color("message")

	cs.Trace = color("TRC")
	cs.Debug = color("DBG")
	cs.Warn = color("WRN")
	cs.Info = color("INF")
	cs.Error = color("ERR")
	return cs
}
Beispiel #26
0
func Task(c *cli.Context, withProject bool) {
	t, stories := api.Task(api.FindTaskId(c.Args().First(), true, withProject), c.Bool("verbose"))
	red := ansi.ColorCode("red")
	blue := ansi.ColorCode("blue")
	green := ansi.ColorCode("green")
	reset := ansi.ColorCode("reset")
	bold := ansi.ColorCode("white")
	yellow := ansi.ColorCode("yellow")

	fmt.Printf("[ %s%s%s ] %s%s%s\n", red, t.Due_on, reset, bold, t.Name, reset)

	showTags(t.Tags)

	fmt.Printf("\n%s\n", t.Notes)

	if stories != nil {
		fmt.Println("\n----------------------------------------\n")
		for _, s := range stories {
			color := ""

			if strings.HasPrefix(s.String(), "*") {
				color = blue
			}
			match, _ := regexp.MatchString("\\* .* attached", s.String())
			if match {
				color = yellow
			}

			if strings.HasPrefix(s.String(), ">") {
				color = green
			}

			fmt.Printf("%s%s%s\n", color, s, reset)
		}
	}
}
Beispiel #27
0
	"fmt"
	"io/ioutil"
	"os"
	"regexp"
	"strings"

	"github.com/hashicorp/go-version"
	"github.com/mgutz/ansi"
)

var (
	procfileRegex = regexp.MustCompile("^([A-Za-z0-9_]+):\\s*(.+)$")
	envVarPattern = "\\$([A-Z_]+[A-Z0-9_]*)"
	envVarRegex   = regexp.MustCompile(envVarPattern)

	MsgReset string = ansi.ColorCode("reset")

	PrintTitle, PrintlnTitle     = printers(" ", ansi.ColorCode("green+h"))
	PrintL0, PrintlnL0           = printers(" ", ansi.ColorCode("magenta"))
	PrintL1, PrintlnL1           = printers(" ", ansi.ColorCode("white"))
	PrintL2, PrintlnL2           = printers(" ----> ", ansi.ColorCode("black+h"))
	PrintError, PrintlnError     = printers(" ", ansi.ColorCode("red"))
	PrintWarning, PrintlnWarning = printers(" ", ansi.ColorCode("yellow"))
)

func printers(prefix string, color string) (print func(format string, a ...interface{}), println func(format string, a ...interface{})) {
	print = func(format string, a ...interface{}) {
		fmt.Printf(color+prefix+format+MsgReset, a...)
	}
	println = func(format string, a ...interface{}) {
		print(format+"\n", a...)
Beispiel #28
0
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/docker/docker/pkg/mflag"
	"github.com/mgutz/ansi"
)

const (
	schedulerHost = "positive-cocoa-90213.appspot.com"
	JSON          = "application/json"
)

var (
	start = ansi.ColorCode("black+ub")
	fail  = ansi.ColorCode("red+b")
	succ  = ansi.ColorCode("green+b")
	reset = ansi.ColorCode("reset")

	useScheduler = false
	runParallel  = false

	consoleLock = sync.Mutex{}
)

type test struct {
	name  string
	hosts int
}
Beispiel #29
0
	defer DbOnFlagsLock.Unlock()
	if x, o := DbOnFlags[db]; o && x {
		fmt.Printf(format, args...)
	}
}

func DbFprintf(db string, w io.Writer, format string, args ...interface{}) {
	DbOnFlagsLock.Lock()
	defer DbOnFlagsLock.Unlock()
	if x, o := DbOnFlags[db]; o && x {
		fmt.Fprintf(w, format, args...)
	}
}

var (
	Red    = ansi.ColorCode("red")
	Yellow = ansi.ColorCode("yellow")
	Green  = ansi.ColorCode("green")
	Reset  = ansi.ColorCode("reset")
)

func DbOn(db string) (ok bool) {
	ok = false
	DbOnFlagsLock.Lock()
	defer DbOnFlagsLock.Unlock()
	if x, o := DbOnFlags[db]; o {
		ok = x
	}
	return
}
Beispiel #30
0
	YELLOW
	MAGENTA
	CYAN
	WHITE
	LIGHTBLACK
	LIGHTRED
	LIGHTGREEN
	LIGHTYELLOW
	LIGHTBLUE
	LIGHTMAGENTA
	LIGHTCYAN
	LIGHTWHITE
)

var coloursMap = map[Colour]string{
	BLACK:        ansi.ColorCode("black"),
	RED:          ansi.ColorCode("red"),
	GREEN:        ansi.ColorCode("green"),
	GREY:         string([]byte{'\033', '[', '3', '2', ';', '1', 'm'}),
	YELLOW:       ansi.ColorCode("yellow"),
	BLUE:         ansi.ColorCode("blue"),
	MAGENTA:      ansi.ColorCode("magenta"),
	CYAN:         ansi.ColorCode("cyan"),
	WHITE:        ansi.ColorCode("white"),
	LIGHTBLACK:   ansi.ColorCode("black+h"),
	LIGHTRED:     ansi.ColorCode("red+h"),
	LIGHTGREEN:   ansi.ColorCode("green+h"),
	LIGHTYELLOW:  ansi.ColorCode("yellow+h"),
	LIGHTBLUE:    ansi.ColorCode("blue+h"),
	LIGHTMAGENTA: ansi.ColorCode("magenta+h"),
	LIGHTCYAN:    ansi.ColorCode("cyan+h"),