Пример #1
0
func init() {
	errCol = ansi.ColorFunc("white+b:red")
	warnCol = ansi.ColorFunc("208+b")
	infoCol = ansi.ColorFunc("white+b")
	debugCol = ansi.ColorFunc("white")
	bold = ansi.ColorFunc("white+b")
}
Пример #2
0
// RemoveFormat removes the current format
func RemoveFormat() {
	LInfo = "info"
	LWarn = "warn"
	LErr = "error"
	LStart = "start"
	LDone = "done"
	STime = ansi.ColorFunc("")
	SFail = ansi.ColorFunc("")
	SKey = ansi.ColorFunc("")
	SVal = ansi.ColorFunc("")
}
Пример #3
0
// Status implements the `got status` command.
func Status(c *cli.Context) {
	// Open the database
	db := util.OpenDB()
	defer db.Close()

	// Colored output
	yellow := ansi.ColorFunc("yellow+h:black")
	green := ansi.ColorFunc("green+h:black")
	red := ansi.ColorFunc("red+h:black")

	// Perform operations in a read-only lock
	err := db.View(func(tx *bolt.Tx) error {
		// Get the current commit sha
		info := tx.Bucket(util.INFO)
		objects := tx.Bucket(util.OBJECTS)
		current := info.Get(util.CURRENT)

		// Find the differences between the working directory and the tree of the current commit.
		differences := []Difference{}
		if current != nil {
			// Load commit object
			commit := types.DeserializeCommitObject(objects.Get(current))
			util.DebugLog("Comparing working directory to commit '" + commit.Message + "'.")
			differences = TreeDiff(objects, commit.Tree, ".")
		} else {
			// Compare directory to the empty hash
			util.DebugLog("Comparing working directory to empty tree.")
			differences = TreeDiff(objects, types.EMPTY, ".")
		}

		// Print out the found differences
		for _, difference := range differences {
			line := fmt.Sprintf("%s %s", difference.Type, difference.FilePath)
			if difference.Type == "A" {
				fmt.Println(green(line))
			}
			if difference.Type == "R" {
				fmt.Println(red(line))
			}
			if difference.Type == "M" {
				fmt.Println(yellow(line))
			}
		}

		return nil
	})

	if err != nil {
		log.Fatal("Error reading from the database.")
	}
}
Пример #4
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()
	}
}
Пример #5
0
// Prints the information for one commit in the log, including ascii graph on left side of commits if
// -graph arg is true.
func printCommit(node LogNode, db datas.Database) (err error) {
	lineno := 0
	doColor := func(s string) string { return s }
	if useColor {
		doColor = ansi.ColorFunc("red+h")
	}

	fmt.Printf("%s%s\n", genGraph(node, lineno), doColor(node.commit.Hash().String()))
	parents := commitRefsFromSet(node.commit.Get(datas.ParentsField).(types.Set))
	lineno++
	if len(parents) > 1 {
		pstrings := []string{}
		for _, cr := range parents {
			pstrings = append(pstrings, cr.TargetHash().String())
		}
		fmt.Printf("%sMerge: %s\n", genGraph(node, lineno), strings.Join(pstrings, " "))
	} else if len(parents) == 1 {
		fmt.Printf("%sParent: %s\n", genGraph(node, lineno), parents[0].TargetHash().String())
	} else {
		fmt.Printf("%sParent: None\n", genGraph(node, lineno))
	}
	if *maxLines != 0 {
		var n int
		if *showValue {
			n, err = writeCommitLines(node, *maxLines, lineno, os.Stdout)
		} else {
			n, err = writeDiffLines(node, db, *maxLines, lineno, os.Stdout)
		}
		lineno += n
	}
	return
}
Пример #6
0
func (self *Context) PrintUsage() {
	if self.App.Usage != "" {
		self.Print(self.App.Usage)
		return
	}

	boldUnderline := ansi.ColorFunc("white+bu")
	self.Print("\n%s", boldUnderline("COMMANDS"))

	maxLength1 := getMaxLength(self.App.Commands)
	maxLength2 := getMaxLength(self.App.Flags) + 2
	maxLength := maxLength1
	if maxLength2 > maxLength1 {
		maxLength = maxLength2
	}

	for _, k := range self.App.CommandKeys {
		command := padRight(k, " ", maxLength+3)
		self.Print(command + self.App.Commands[k])
	}

	if len(self.App.FlagKeys) > 0 {
		self.Print("\n%s", boldUnderline("FLAGS"))
		for _, k := range self.App.FlagKeys {
			flag := padRight("--"+k, " ", maxLength+3)
			desc := self.App.Flags[k]

			if self.App.FlagDefaults[k] != "" {
				desc += " (default: " + self.App.FlagDefaults[k] + ")"
			}

			self.Print(flag + desc)
		}
	}
}
Пример #7
0
func handleMessage(msg wray.Message) {
	redColor := ansi.ColorFunc("red+h")
	capColor := ansi.ColorFunc("yellow")
	infoColor := ansi.ColorFunc("white")

	s, err := strconv.Unquote(msg.Data)
	if err != nil {
		fmt.Println("Error: ", err)
	}
	var m logMessage
	err = json.Unmarshal([]byte(s), &m)
	if err != nil {
		fmt.Println("Error:", err)
	}

	var level string
	var colorFunc func(string) string

	switch m.Severity {
	case 0:
		level = "TRACE"
		colorFunc = infoColor
	case 1:
		level = "DEBUG"
		colorFunc = infoColor
	case 2:
		level = "INFO"
		colorFunc = infoColor
	case 3:
		level = "WARN"
		colorFunc = capColor
	case 4:
		level = "ERROR"
		colorFunc = redColor
	case 5:
		level = "IMPORTANT"
		colorFunc = redColor
	case 6:
		level = "FATAL"
		colorFunc = redColor
	}

	fmt.Println(colorFunc(fmt.Sprintf("%s [%s] - %s", m.Time, level, m.Message)))

}
Пример #8
0
func cmdList(c *cli.Context) error {
	conf, err := config.Open(c.GlobalString("config"))
	if err != nil {
		Logger.Fatalf("Cannot load configuration: %v", err)
		return nil
	}

	// ansi coloring
	greenColorize := func(input string) string { return input }
	redColorize := func(input string) string { return input }
	yellowColorize := func(input string) string { return input }
	if terminal.IsTerminal(int(os.Stdout.Fd())) {
		greenColorize = ansi.ColorFunc("green+b+h")
		redColorize = ansi.ColorFunc("red")
		yellowColorize = ansi.ColorFunc("yellow")
	}

	fmt.Printf("Listing entries\n\n")

	for _, host := range conf.Hosts.SortedList() {
		options := host.Options()
		options.Remove("User")
		options.Remove("Port")
		host.ApplyDefaults(&conf.Defaults)
		fmt.Printf("    %s -> %s\n", greenColorize(host.Name()), host.Prototype())
		if len(options) > 0 {
			fmt.Printf("        %s %s\n", yellowColorize("[custom options]"), strings.Join(options.ToStringList(), " "))
		}
		fmt.Println()
	}

	generalOptions := conf.Defaults.Options()
	if len(generalOptions) > 0 {
		fmt.Println(greenColorize("    (*) General options:"))
		for _, opt := range conf.Defaults.Options() {
			fmt.Printf("        %s: %s\n", redColorize(opt.Name), opt.Value)
		}
		fmt.Println()
	}

	return nil
}
Пример #9
0
func init() {
	flag.Usage = func() {
		fmt.Printf("Usage: ./colorize -color 'red:green' -alt=false\n")
		flag.PrintDefaults()
	}

	flag.Parse()
	if *colorFlag != "" {
		color = ansi.ColorFunc(*colorFlag)
	}
}
Пример #10
0
func (m *Map) String() string {
	var b bytes.Buffer

	// Nice colors for debugging.
	r := ansi.ColorFunc("red")
	g := ansi.ColorFunc("green")

	for y := 0; y < m.size; y++ {
		for x := 0; x < m.size; x++ {
			v := m.get(x, y)

			if v > 0 {
				fmt.Fprint(&b, r(fmt.Sprintf("%.2f ", v)))
			} else {
				fmt.Fprint(&b, g(fmt.Sprintf("%.2f ", v)))
			}
		}

		fmt.Fprint(&b, "\n")
	}

	return b.String()
}
Пример #11
0
func getColorFunction(code string) ColorizeFunc {
	var (
		colorFunc ColorizeFunc
		ok        bool
	)

	if colorFunc, ok = colorFuncMap[code]; ok {
		return colorFunc
	}

	colorFunc = ColorizeFunc(ansi.ColorFunc(code))
	colorFuncMap[code] = colorFunc

	return colorFunc
}
Пример #12
0
func Log(c *cli.Context) {
	db := util.OpenDB()
	defer db.Close()

	yellow := ansi.ColorFunc("yellow+h:black")

	// Perform operations in a read-only lock
	db.View(func(tx *bolt.Tx) error {
		info := tx.Bucket(util.INFO)
		objects := tx.Bucket(util.OBJECTS)
		headsBytes := info.Get(util.HEADS)

		if headsBytes != nil {
			queue := types.DeserializeHashes(headsBytes)

			// TODO: Keep a visited set, so we don't repeat commits

			for len(queue) > 0 {
				i := GetNewestCommit(objects, queue)

				// Get commit and remove it from the priority queue
				commitSha := queue[i]
				commit := types.DeserializeCommitObject(objects.Get(commitSha))
				queue = append(queue[:i], queue[i+1:]...)

				fmt.Printf(yellow("commit %s\n"), commitSha)
				fmt.Printf("Message: %s\n", commit.Message)
				fmt.Printf("Author: %s\n", commit.Author)
				fmt.Printf("Date: %s\n", commit.Time)

				if len(commit.Parents) > 0 {
					fmt.Printf("Parents: %s\n", commit.Parents)
				}

				fmt.Printf("Tree: %s\n", commit.Tree)
				fmt.Println()

				// Append parents of this commit to the queue
				queue = append(queue, commit.Parents...)
			}

			return nil
		}

		fmt.Println("There are no commits in this repository...")
		return nil
	})
}
Пример #13
0
func init() {
	ansi.DisableColors(false)
	cyan = ansi.ColorFunc("cyan")
	red = ansi.ColorFunc("red+b")
	yellow = ansi.ColorFunc("yellow+b")
	redInverse = ansi.ColorFunc("white:red")
	gray = ansi.ColorFunc("black+h")
	magenta = ansi.ColorFunc("magenta+h")
	writer = colorable.NewColorableStdout()
}
Пример #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()
	}
}
Пример #15
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)
}
Пример #16
0
func (current *CurrentColor) Set(value string) error {
	if current.color != value {
		if !strings.Contains(value, ":") { // foreground:background
			if value == "black" {
				value += ":white"
			} else {
				value += ":black"
			}
		}

		current.color = value
		current.colorfunc = ansi.ColorFunc(current.color)
	}

	return nil
}
Пример #17
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)

}
Пример #18
0
func init() {
	failMsg = ansi.ColorFunc("red+b")
	changedMsg = ansi.ColorFunc("yellow")
	okMsg = ansi.ColorFunc("green")
}
Пример #19
0
// Copyright 2015 Dominique Feyer <*****@*****.**>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package logger

import (
	"github.com/dfeyer/flow-debugproxy/config"

	"bytes"
	"fmt"
	"github.com/mgutz/ansi"
)

var (
	debugize = ansi.ColorFunc("green+h:black")
	greenize = ansi.ColorFunc("green")
	redize   = ansi.ColorFunc("red")
)

// Logger handle log message
type Logger struct {
	Config *config.Config
}

//Debug output a debug text
func (l *Logger) Debug(f string, args ...interface{}) {
	if l.Config.Debug {
		fmt.Printf(debugize("[DEBUG] "+f)+"\n", args...)
	}
}
Пример #20
0
	LInfo = ansi.Color("info", "green")

	// LWarn shows warning messages
	LWarn = ansi.Color("warn", "yellow")

	// LErr shows error messages
	LErr = ansi.Color("error", "red")

	// LStart shows start messages
	LStart = ansi.Color("start", "blue+h")

	// LDone shows done messages
	LDone = ansi.Color("done", "blue+h")

	// STime is style for time
	STime = ansi.ColorFunc("magenta+h")

	// SFail is style for faillures
	SFail = ansi.ColorFunc("red+h")

	// SKey is style for keys
	SKey = ansi.ColorFunc("cyan")

	// SVal is style for values
	SVal = ansi.ColorFunc("white+b")
)

func funcName(d int) string {
	pc, _, _, _ := runtime.Caller(d + 1)
	return runtime.FuncForPC(pc).Name()
}
Пример #21
0
package main

import (
	"bytes"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"
	"regexp"
	"strings"

	"github.com/jessevdk/go-flags"
	"github.com/mgutz/ansi"
)

var styleRed = ansi.ColorFunc("red")
var styleRedUnderline = ansi.ColorFunc("red+u")
var styleGreen = ansi.ColorFunc("green")
var styleGreenUnderline = ansi.ColorFunc("green+u")
var styleHeader = ansi.ColorFunc("white+b:black")
var styleBold = ansi.ColorFunc("+b")

func main() {
	dir, _ := os.Getwd()
	exitCode := mainSub(dir, os.Stdout, os.Stdin, os.Args[1:])
	if exitCode != 0 {
		os.Exit(exitCode)
	}
}

type options struct {
Пример #22
0
package main

import (
	"fmt"
	"io/ioutil"
	"os"
	"strings"

	"github.com/codegangsta/cli"
	"github.com/mgutz/ansi"
)

var green = ansi.ColorFunc("green")
var red = ansi.ColorFunc("red")
var yellow = ansi.ColorFunc("yellow")

func main() {
	app := cli.NewApp()
	app.Name = "ply"
	app.Usage = "Deployment made simple"
	app.Flags = []cli.Flag{
		cli.StringFlag{
			Name:  "config, c",
			Usage: "The path to your ply config",
		},
		cli.StringFlag{
			Name:  "environment, e",
			Usage: "The environment to execute the task",
		},
		cli.StringFlag{
			Name:  "vars, variables",
Пример #23
0
func (self *Context) FailWithCode(msg string, code int) {
	error := ansi.ColorFunc("88")
	self.PrintError("%s", error(msg))
	os.Exit(code)
}
Пример #24
0
package gondorcli

import (
	"fmt"
	"os"

	"github.com/mgutz/ansi"
)

var successize = ansi.ColorFunc("green+b")
var errize = ansi.ColorFunc("red+b")
var heyYou = ansi.ColorFunc("yellow+b")

func success(s string) {
	fmt.Fprintf(os.Stderr, "%s %s\n", successize("Success:"), s)
}

func failure(s string) {
	fmt.Fprintf(os.Stderr, "%s %s\n", errize("ERROR:"), s)
}

func fatal(s string) {
	failure(s)
	os.Exit(1)
}
Пример #25
0
package client

import (
	"bufio"
	"net"

	"github.com/mgutz/ansi"
)

var phosphorize = ansi.ColorFunc("green+h:black")

// Client represents a client connected to the chat
type Client struct {
	Conn      net.Conn
	Receiving chan *Message
	Outgoing  chan *Message
	Name      string
	Input     *bufio.Reader
}

// Message is what is sent by a client
type Message struct {
	Client  *Client
	Content string
}

// NewClient is a constructor for Client
func NewClient(conn net.Conn, onInit chan *Client) *Client {
	client := Client{
		conn,
		make(chan *Message),
Пример #26
0
				}
			}

			duration := time.Since(start)
			logObjectPopulate(name, duration)
		}(injectObject.Name, injectObject.Value)
	}

	wg.Wait()
	log.Info("Done!")

	return nil
}

var (
	microColor   = ansi.ColorFunc("cyan")
	milliColor   = ansi.ColorFunc("yellow")
	secondsColor = ansi.ColorFunc("red")
)

func logObjectPopulate(name string, duration time.Duration) {
	var (
		value     string
		unit      string
		colorFunc func(string) string

		message string
	)

	s := duration.Seconds()
	ms := duration.Nanoseconds() / 1000000
Пример #27
0
func (self *Context) ShowUsageWithMessage(m string) {
	self.PrintIntro()
	error := ansi.ColorFunc("88")
	self.PrintError("\n%s", error(m))
	self.PrintUsage()
}
Пример #28
0
	"github.com/mgutz/str"
	"github.com/syreclabs/dat"
	"github.com/syreclabs/dat/sqlx-runner"
	. "gopkg.in/godo.v2"
	"gopkg.in/godo.v2/util"
)

func mapBytesToString(m map[string]interface{}) {
	for k, v := range m {
		if b, ok := v.([]byte); ok {
			m[k] = string(b)
		}
	}
}

var lightGreen = ansi.ColorFunc("green+h")
var cyan = ansi.ColorFunc("cyan")

func printMap(m map[string]interface{}) {
	first := true

	fmt.Print(lightGreen("{"))
	for k, v := range m {
		if !first {
			fmt.Print(" ")
		}
		fmt.Printf("%s=%v", cyan(k), v)
		first = false
	}
	fmt.Print(lightGreen("}"))
	fmt.Print("\n")
Пример #29
0
)

var (
	logToConsol = false // should log to consol
	logToFile   = false // should log to file
	logDir      = ""    // directory in which to store logfiles
	maxDays     = -1    // total number of logfiles at any time
	// if exeeded will delete oldest

	//log queue
	logChan     = make(chan logItem, 100)
	logNameChan = make(chan string, 2)
	killChan    = make(chan bool, 1)

	//colour functions
	startupColourFunc = ansi.ColorFunc("green+b")
	fatalColourFunc   = ansi.ColorFunc("red+b")
	generalColourFunc = ansi.ColorFunc("blue+b")
	warningColourFunc = ansi.ColorFunc("yellow+b")
)

// The colour type enumerator
const (
	startupColour int = iota
	fatalColour
	generalColour
	warningColour
)

// Init initialises the srvlog package. if either consoleLog or fileLog
// is true it will start the logger in another gorutine ready to log
Пример #30
0
func (self *Context) Fail(msg string) {
	error := ansi.ColorFunc("88")
	self.PrintError("%s", error(msg))
	os.Exit(1)
}