Пример #1
0
// PrintMissingEnv ...
func PrintMissingEnv(name string, path string, err error) {
	if err != nil {
		errLine := ansi.Color(
			fmt.Sprintf(
				"%s",
				err,
			),
			"red",
		)

		fmt.Fprintln(
			os.Stderr,
			errLine,
		)
	}

	helpLine := ansi.Color(
		fmt.Sprintf(
			"missing %s in %s",
			name,
			path,
		),
		"yellow",
	)

	fmt.Fprintln(
		os.Stderr,
		helpLine,
	)
}
Пример #2
0
func main() {

	log.Fatalln("@todo refactor")

	if err := checkEnv(); err != nil {
		log.Fatal(err)
	}

	for _, cmd := range getCommands() {
		out, err := exec.Command(cmd.name, cmd.args...).CombinedOutput()
		if cmd.rm {
			defer os.Remove(cmd.name)
		}
		args := strings.Join(cmd.args, " ")
		if err != nil {
			log.Fatalf(ansi.Color("Failed:\n%s %s => %s\n%s", "red"), cmd.name, args, err, out)
		}

		log.Printf("%s %s", cmd.name, args)
		if nil != out && len(out) > 0 {
			log.Printf("%s", out)
		}
	}
	log.Println(ansi.Color("Done", "green"))
}
Пример #3
0
func newFileRecord(path string) *FileRecord {
	fr := FileRecord{}
	fr.input.path = path

	fr.debug = log.New(ioutil.Discard, "@@ ", 0)
	fr.info = log.New(&fr.logBuf, ":: ", 0)
	fr.plain = log.New(&fr.logBuf, "", 0)
	fr.section = log.New(&fr.logBuf, "==> ", 0)
	fr.warning = log.New(&fr.logBuf, ":: Warning: ", 0)
	fr.error = log.New(&fr.logBuf, ":: Error: ", 0)

	if options.Debug {
		fr.debug.SetOutput(&fr.logBuf)
	}

	if options.Color {
		fr.debug.SetPrefix(ansi.Color(fr.debug.Prefix(), "cyan+b"))
		fr.info.SetPrefix(ansi.Color(fr.info.Prefix(), "magenta+b"))
		fr.section.SetPrefix(ansi.Color(fr.section.Prefix(), "green+b"))
		fr.warning.SetPrefix(ansi.Color(fr.warning.Prefix(), "yellow+b"))
		fr.error.SetPrefix(ansi.Color(fr.error.Prefix(), "red+b"))
	}

	return &fr
}
Пример #4
0
// The format is:
//   [input] | attr | [output]
func prettyPrint(fr *FileRecord, attr, input, output string, attrMaxlen, valueMaxlen int) {
	colorIn := ""
	colorOut := ""
	if options.Color && input != output &&
		(attr != "parameters" || output != "[-c:a copy]") &&
		((attr != "embedded" && attr != "external") || (len(output) >= 3 && output[len(output)-3:] != " ''")) {
		colorIn = "red"
		colorOut = "green"
	}

	// Replace control characters to avoid mangling the output.
	input = rePrintable.ReplaceAllString(input, " / ")
	output = rePrintable.ReplaceAllString(output, " / ")

	in := []rune(input)
	out := []rune(output)

	min := func(a, b int) int {
		if a < b {
			return a
		}
		return b
	}

	// Print first line with title.
	fr.plain.Printf(
		"%*v["+ansi.Color("%.*s", colorIn)+"] | %-*v | ["+ansi.Color("%.*s", colorOut)+"]\n",
		valueMaxlen-min(valueMaxlen, len(in)), "",
		valueMaxlen, input,
		attrMaxlen, attr,
		valueMaxlen, output)

	// Print the rest that does not fit on first line.
	for i := valueMaxlen; i < len(in) || i < len(out); i += valueMaxlen {
		inLo := min(i, len(in))
		inHi := min(i+valueMaxlen, len(in))
		outLo := min(i, len(out))
		outHi := min(i+valueMaxlen, len(out))

		inDelimLeft, inDelimRight := "[", "]"
		outDelimLeft, outDelimRight := "[", "]"
		if i >= len(in) {
			inDelimLeft, inDelimRight = " ", " "
		}
		if i >= len(out) {
			outDelimLeft, outDelimRight = "", ""
		}

		fr.plain.Printf(
			"%s"+ansi.Color("%s", colorIn)+"%s%*v | %*v | %s"+ansi.Color("%s", colorOut)+"%s\n",
			inDelimLeft,
			string(in[inLo:inHi]),
			inDelimRight,
			valueMaxlen-inHi+inLo, "",
			attrMaxlen, "",
			outDelimLeft,
			string(out[outLo:outHi]),
			outDelimRight)
	}
}
Пример #5
0
func (node Node) StartInstance(instance Instance) {
	stolen := node.hesitate(instance)
	if stolen {
		fmt.Println(ansi.Color("yoinked", "yellow"), instance.Index)
		return
	}

	ok := node.volunteer(instance)
	if !ok {
		fmt.Println(ansi.Color("dropped", "red"), instance.Index)
		return
	}

	fmt.Println(ansi.Color("started", "green"), instance.Index)

	// make 25% of them crash after a random amount of time
	//
	// because that's more interesting
	if rand.Intn(4) == 0 {
		instance.MarkedForDeath = true

		go func() {
			time.Sleep(time.Duration(5+rand.Intn(10)) * time.Second)
			node.StopInstance(instance)
		}()
	}

	node.registry.Register(instance)
}
Пример #6
0
// PrintMissingCurrentEnv ...
func PrintMissingCurrentEnv(err error) {
	if err != nil {
		errLine := ansi.Color(
			fmt.Sprintf(
				"%s",
				err,
			),
			"red",
		)

		fmt.Fprintln(
			os.Stderr,
			errLine,
		)
	}

	helpLine := ansi.Color(
		fmt.Sprintf(
			"%s",
			"did you create a .env?",
		),
		"yellow",
	)

	fmt.Fprintln(
		os.Stderr,
		helpLine,
	)
}
Пример #7
0
Файл: util.go Проект: knobnot/hk
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")
}
Пример #8
0
func colorStatus(word string) string {
	if word == "running" {
		return ansi.Color("running", "green+b")
	} else if word == "stopped" {
		return ansi.Color("stopped", "red+b")
	}
	return word
}
Пример #9
0
func (self *ProgressBar) GetLineForPercent(i int, displayPercent float64) string {
	line := ansi.Color("[", self.BackgroundColor)
	line += ansi.Color(strings.Repeat(self.FillShape, i), self.FillColor)
	line += ansi.Color(strings.Repeat(self.EmptyShape, self.Width-i), self.BackgroundColor)
	line += ansi.Color("] ", self.BackgroundColor) + strings.Replace(fmt.Sprintf("%.01f", displayPercent), ".0", "", -1)
	line += "%% "
	return line
}
Пример #10
0
func TestColorize(t *testing.T) {
	for i := 0; i < 256; i++ {
		f := fmt.Sprintf("%d:default", i)
		b := fmt.Sprintf("default:%d", i)
		fmt.Println(ansi.Color(f, f), ansi.Color(b, b))
	}

}
Пример #11
0
func (s *Sapin) Colorize() {
	s.compute()

	s.output = strings.Replace(s.output, "@", ansi.Color("@", fmt.Sprintf("red+%s", s.ColorOpts)), -1)
	s.output = strings.Replace(s.output, "*", ansi.Color("*", fmt.Sprintf("green+%s", s.ColorOpts)), -1)
	s.output = strings.Replace(s.output, "|", ansi.Color("|", fmt.Sprintf("90+%s", s.ColorOpts)), -1)
	s.output = strings.Replace(s.output, "#", ansi.Color("#", fmt.Sprintf("yellow+%s", s.ColorOpts)), -1)
	s.output = strings.Replace(s.output, "~", ansi.Color("~", fmt.Sprintf("yellow+%s", s.ColorOpts)), -1)
}
Пример #12
0
func Init() {
	debugFormat = strings.Join([]string{
		ansi.Color("[", Styles["debugPunct"]),
		ansi.Color("%v", Styles["debugInfo"]),
		ansi.Color(":", Styles["debugPunct"]),
		ansi.Color("%v", Styles["debugInfo"]),
		ansi.Color("]", Styles["debugPunct"]),
	}, "")
}
Пример #13
0
func isProcessOK(err error) {
	var msg string

	if err != nil {
		msg = ansi.Color("     [FAIL]", "red+b")
		fmt.Println(msg)
	} else {
		msg = ansi.Color("     [OK]", "green+b")
		fmt.Println(msg)
	}
}
Пример #14
0
func uiFormat(color, kind, id string) string {
	if id == "" {
		return fmt.Sprintf("%v %v %%v",
			ansi.Color("%v", Styles["timestamp"]),
			ansi.Color(kind, color))
	} else {
		return fmt.Sprintf("%v %v%v %%v",
			ansi.Color("%v", Styles["timestamp"]),
			ansi.Color(kind+":", color),
			ansi.Color(id, color+"+h"))
	}
}
Пример #15
0
func buildTestingTGomegaFailHandler(t testingT) types.GomegaFailHandler {
	return func(message string, callerSkip ...int) {
		skip := 2 // initial runtime/debug.Stack frame + gomega-matchers.buildTestingTGomegaFailHandler frame
		if len(callerSkip) > 0 {
			skip += callerSkip[0]
		}
		stackTrace := pruneStack(string(debug.Stack()), skip)
		stackTrace = strings.TrimSpace(stackTrace)
		stackTrace = ansi.Color(stackTrace, StacktraceColor)

		t.Errorf("\n%s\n%s", stackTrace, ansi.Color(message, "red"))
	}
}
Пример #16
0
func main() {
	var verbose = flag.Bool("v", false, "get verbose output")
	flag.Parse()

	cmd := exec.Command("./a.sh")
	stdout, stderr, exitCode, err := runCommand(cmd, *verbose)
	fmt.Printf("stdout result:%s\n", ansi.Color(stdout, stdoutColor))
	fmt.Printf("stderr result:%s\n", ansi.Color(stderr, stderrColor))
	fmt.Printf("exitCode:%d\n", exitCode)
	if err != nil {
		log.Fatal(err)
	}
}
Пример #17
0
func (s *Starter) dispatchStarts(app string, pipeline chan executor.Instance) {
	for {
		select {
		case instanceToStart := <-pipeline:
			fmt.Println(ansi.Color("dispatching start", "cyan"), app, instanceToStart.Index)
			s.node.StartInstance(instanceToStart)

		case <-time.After(10 * time.Second):
			fmt.Println(ansi.Color("pipeline expired", "red"), app)
			s.closePipe(app)
			return
		}
	}
}
Пример #18
0
func (node Node) LogRegistry() {
	instances := node.registry.AllInstances()

	bar := []string{}

	for _, inst := range instances {
		if inst.MarkedForDeath {
			bar = append(bar, ansi.Color("▇", "red"))
		} else {
			bar = append(bar, "▇")
		}
	}

	fmt.Printf("%s %d: %3d %s\n", ansi.Color("running", "blue"), os.Getpid(), len(instances), strings.Join(bar, ""))
}
Пример #19
0
// SaveEnv ...
func SaveEnv(env string) {
	path := filepath.Join(
		ChenvPath,
		env+".env",
	)

	_, err := os.Stat(CurrentEnvPath)

	if os.IsNotExist(err) {
		PrintMissingCurrentEnv(err)
		ExitOn(err)
	}

	ErrExit(err)

	err = Copy(
		CurrentEnvPath,
		path,
	)

	ErrExit(err)

	msg := ansi.Color(
		fmt.Sprintf(
			"saved current .env to %s",
			path,
		),
		"green",
	)

	fmt.Println(
		msg,
	)

	msg = ansi.Color(
		fmt.Sprintf(
			"  %s saved!",
			env,
		),
		"cyan",
	)

	fmt.Println(
		msg,
	)

	fmt.Println()
}
Пример #20
0
func (a *analyzer) Init() {
	// Script log output must be set for each FileRecord when calling the scripts.
	a.scriptLog = log.New(nil, "@@ ", 0)
	if options.Color {
		a.scriptLog.SetPrefix(ansi.Color(a.scriptLog.Prefix(), "cyan+b"))
	}

	// Compile scripts.
	var err error
	luaDebug := a.scriptLog.Println
	if !options.Debug {
		luaDebug = nil
	}
	a.L, err = MakeSandbox(luaDebug)
	if err != nil {
		log.Fatal(err)
	}

	for _, script := range cache.scripts {
		SandboxCompileScript(a.L, script.name, script.buf)
	}

	for name, action := range cache.actions {
		SandboxCompileAction(a.L, name, action)
	}
}
Пример #21
0
func (verification *Verification) Run() error {
	utils.PrintMessage("Sending approval request to your device... ")
	request, err := verification.SendOneTouchRequest()
	if err != nil {
		utils.PrintMessage(err.Error())
		return ErrInvalidVerification
	}

	utils.PrintMessage(ansi.Color("[sent]\n", "green+h"))
	status, err := verification.api.WaitForApprovalRequest(request.UUID, ApprovalTimeout, url.Values{})
	if err != nil {
		utils.PrintMessage(err.Error())
		return ErrInvalidVerification
	}

	if status == authy.OneTouchStatusApproved {
		runShell()
		return nil
	}

	if status == authy.OneTouchStatusExpired && utils.IsInteractiveConnection() {
		utils.PrintMessage("You didn't confirm the request. ")

		code := verification.askTOTPCode()
		if verification.verifyCode(code) {
			runShell()
			return nil
		}
	}

	return ErrInvalidVerification
}
Пример #22
0
func renderDiff(to io.Writer, a, b string) {
	diffs := difflib.Diff(strings.Split(a, "\n"), strings.Split(b, "\n"))

	for _, diff := range diffs {
		text := diff.Payload

		switch diff.Delta {
		case difflib.RightOnly:
			fmt.Fprintf(to, "%s\n", ansi.Color(text, "green"))
		case difflib.LeftOnly:
			fmt.Fprintf(to, "%s\n", ansi.Color(text, "red"))
		case difflib.Common:
			fmt.Fprintf(to, "%s\n", text)
		}
	}
}
Пример #23
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, w io.Writer, db datas.Database) (err error) {
	maxMetaFieldNameLength := func(commit types.Struct) int {
		maxLen := 0
		if m, ok := commit.MaybeGet(datas.MetaField); ok {
			meta := m.(types.Struct)
			meta.Type().Desc.(types.StructDesc).IterFields(func(name string, t *types.Type) {
				maxLen = max(maxLen, len(name))
			})
		}
		return maxLen
	}

	hashStr := node.commit.Hash().String()
	if useColor {
		hashStr = ansi.Color("commit "+hashStr, "red+h")
	}

	maxFieldNameLen := maxMetaFieldNameLength(node.commit)

	parentLabel := "Parent"
	parentValue := "None"
	parents := commitRefsFromSet(node.commit.Get(datas.ParentsField).(types.Set))
	if len(parents) > 1 {
		pstrings := make([]string, len(parents))
		for i, p := range parents {
			pstrings[i] = p.TargetHash().String()
		}
		parentLabel = "Merge"
		parentValue = strings.Join(pstrings, " ")
	} else if len(parents) == 1 {
		parentValue = parents[0].TargetHash().String()
	}

	if oneline {
		parentStr := fmt.Sprintf("%s %s", parentLabel+":", parentValue)
		fmt.Fprintf(w, "%s (%s)\n", hashStr, parentStr)
		return
	}

	maxFieldNameLen = max(maxFieldNameLen, len(parentLabel))
	parentStr := fmt.Sprintf("%-*s %s", maxFieldNameLen+1, parentLabel+":", parentValue)
	fmt.Fprintf(w, "%s%s\n", genGraph(node, 0), hashStr)
	fmt.Fprintf(w, "%s%s\n", genGraph(node, 1), parentStr)
	lineno := 1

	if maxLines != 0 {
		lineno, err = writeMetaLines(node, maxLines, lineno, maxFieldNameLen, w)
		if err != nil && err != MaxLinesErr {
			fmt.Fprintf(w, "error: %s\n", err)
			return
		}

		if showValue {
			_, err = writeCommitLines(node, maxLines, lineno, w)
		} else {
			_, err = writeDiffLines(node, db, maxLines, lineno, w)
		}
	}
	return
}
Пример #24
0
func (h *Hijacker) handleOutput(conn *websocket.Conn, pio ProcessIO) int {
	var exitStatus int
	for {
		var output atc.HijackOutput
		err := conn.ReadJSON(&output)
		if err != nil {
			if !websocket.IsCloseError(err) && !websocket.IsUnexpectedCloseError(err) {
				fmt.Println(err)
			}
			break
		}

		if output.ExitStatus != nil {
			exitStatus = *output.ExitStatus
		} else if len(output.Error) > 0 {
			fmt.Fprintf(os.Stderr, "%s\n", ansi.Color(output.Error, "red+b"))
			exitStatus = 255
		} else if len(output.Stdout) > 0 {
			pio.Out.Write(output.Stdout)
		} else if len(output.Stderr) > 0 {
			pio.Err.Write(output.Stderr)
		}
	}

	return exitStatus
}
Пример #25
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 ""
}
Пример #26
0
func highlightQuery(line string, query string) {
	// Split query into multiple parts for regex
	q := strings.Split(query, " ")
	// Match the string
	match, err := regexp.Compile(q[0])
	if err != nil {
		panic(err)
	}

	// Split our line into an ary
	lineAry := strings.Split(line, " ")
	// Iterate the ary, finding the string match
	for i, s := range lineAry {
		if match.MatchString(s) {
			// Color just the string which matches
			hlQuery := ansi.Color(s, "yellow:black")
			// Thren break down into three parts
			lpt1 := lineAry[:i]
			lpt2 := lineAry[i:]
			lpt2 = append(lpt2[:0], lpt2[1:]...)
			// Contatenate back together
			part1 := strings.Join(lpt1, " ")
			part2 := strings.Join(lpt2, " ")
			final := []string{part1, hlQuery, part2}
			finalHl := strings.Join(final, " ")
			// Print the final output
			//log.Info(finalHl)
			fmt.Println(finalHl)
		}
	}
}
Пример #27
0
func padColor(s string, styles []string) string {
	buffer := ""
	for _, style := range styles {
		buffer += ansi.Color(pad(s+style, 20), s+style)
	}
	return buffer
}
Пример #28
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)
}
Пример #29
0
func beforeCommand(c *cli.Context) error {
	// set the env vars from global options
	if c.GlobalString("runenv") != "production" {
		tokenFile = "cx_" + c.GlobalString("runenv") + ".json"
		fmt.Printf(ansi.Color(fmt.Sprintf("Running against %s environment\n", c.GlobalString("runenv")), "grey"))
		honeybadger.Environment = c.GlobalString("runenv")
	} else {
		honeybadger.Environment = "production"
	}

	if c.GlobalString("fayeEndpoint") != "" {
		fayeEndpoint = c.GlobalString("fayeEndpoint")
	}

	debugMode = c.GlobalBool("debug")

	var command string
	if len(c.Args()) >= 1 {
		command = c.Args().First()
	}

	if (command != "version") && (command != "help") && (command != "update") {
		initClients(c)
	}

	if (command != "update") && (VERSION != "dev") {
		defer backgroundRun()
	}

	return nil
}
Пример #30
0
// prints all the info you see at program finish
func PrintCompletionInfo(start time.Time, onWindows bool) {
	// let user know if any files were inaccessible
	if len(failedDownloads) == 1 {
		fmt.Println("")
		fmt.Println(len(failedDownloads), "file or directory was not downloaded (permissions issue or corrupt):")
		PrintSlice(failedDownloads)
	} else if len(failedDownloads) > 1 {
		fmt.Println("")
		fmt.Println(len(failedDownloads), "files or directories were not downloaded (permissions issue or corrupt):")
		PrintSlice(failedDownloads)
	}

	if len(failedDownloads) > 100 {
		fmt.Println("\nYou had over 100 failed downloads, we highly recommend you omit the failed file'sopen parent directories using the omit flag.\n")
	}

	// display runtime
	elapsed := time.Since(start)
	elapsedString := strings.Split(elapsed.String(), ".")[0]
	elapsedString = strings.TrimSuffix(elapsedString, ".") + "s"
	fmt.Println("\nDownload time: " + elapsedString)

	msg := ansi.Color(appName+" Successfully Downloaded!", "green+b")
	if onWindows == true {
		msg = "Successfully Downloaded!"
	}
	fmt.Println(msg)
}