// all logging functions call this `log` function func (console *Logger) log(d logDetails, colorAttr color.Attribute, isBold bool, format string, args ...interface{}) { // Only print out, logs that are the selected level or higher if console.level >= d.level { newlog := color.Set(colorAttr) defer color.Unset() // if the request is to log bold text if isBold { newlog.Add(color.Bold) } // Check to see if we are to add background color // Alert and Fatal have background colors switch d.level { case 1: // for Fatal color.Set(color.BgRed) break case 2: // for Alerts color.Set(color.BgMagenta) break } // I want it log both into the file and on the console console.LogFile.Printf(format, args...) log.Printf(format, args...) } }
func printDiffYaml(m map[interface{}]interface{}, indent string) { sortedMap := make([]string, len(m)) i := 0 for k, _ := range m { sortedMap[i] = k.(string) i++ } sort.Strings(sortedMap) for _, v := range sortedMap { key := v value := m[key] if reflect.TypeOf(value).Kind() == reflect.Map { println(indent + key + ":") printDiffYaml(m[key].(map[interface{}]interface{}), indent+" ") } else { tmp := value.(Comparer) println(indent + key + ":") color.Set(color.FgRed) printValue(tmp.leftValue, indent+" - ") color.Set(color.FgGreen) printValue(tmp.rightValue, indent+" + ") color.Unset() } } }
func (r Results) print(limit int) { i := 0 if r.ResultType == "exact" { for _, def := range r.List { if limit == -1 || i < limit { // ugly code for windows! color.Set(color.FgBlue) fmt.Printf("%d)\n", i+1) color.Unset() color.Set(color.FgGreen) fmt.Printf("%s\n", "Def:") color.Unset() fmt.Println(def.Definition) color.Set(color.FgGreen) fmt.Printf("%s\n", "Eg:") color.Unset() fmt.Printf("%s\n\n", def.Example) i++ } } } else { color.Red("No definitions.\n") return } }
func showTweets(tweets []Tweet, verbose bool) { if verbose { for i := len(tweets) - 1; i >= 0; i-- { name := tweets[i].User.Name user := tweets[i].User.ScreenName text := tweets[i].Text text = replacer.Replace(text) color.Set(color.FgHiRed) fmt.Println(user + ": " + name) color.Set(color.Reset) fmt.Println(" " + text) fmt.Println(" " + tweets[i].Identifier) fmt.Println(" " + tweets[i].CreatedAt) fmt.Println() } } else { for i := len(tweets) - 1; i >= 0; i-- { user := tweets[i].User.ScreenName text := tweets[i].Text color.Set(color.FgHiRed) fmt.Print(user) color.Set(color.Reset) fmt.Print(": ") fmt.Println(text) } } }
// Attack an enemy during an encounter. func (c *Character) Attack(e Enemy) { // Fight until enemy is dead, or player is below 25%. red := color.New(color.FgRed, color.Bold).SprintFunc() log.Printf("Attacking enemy: %s\n", red(e.Name)) playerHpLimit := int(float64(c.Hp) * 0.25) playerDamage := c.Body.Weapond.Dmg - e.Armor if playerDamage <= 0 { playerDamage = 1 } enemyDamage := e.Damage - (c.Body.Head.Armor + c.Body.Armor.Armor + c.Body.Shield.Armor + c.Body.LRing.Armor + c.Body.RRing.Armor) if enemyDamage <= 0 { enemyDamage = 1 } for c.Hp > playerHpLimit && e.Hp > 0 { e.Hp -= playerDamage c.Hp -= enemyDamage } if e.Hp <= 0 { color.Set(color.FgCyan) log.Println("Player won!") color.Unset() c.CurrentXp += e.Xp displayProgressBar(c.CurrentXp, c.NextLevelXp) c.awardItems(e) mdb.Update(*c) return } color.Set(color.FgHiRed) log.Println("Enemy won. Player has fled with hp: ", c.Hp) color.Unset() mdb.Update(*c) }
func showTweets(tweets []Tweet, verbose bool) { if *asjson { for _, tweet := range tweets { json.NewEncoder(os.Stdout).Encode(tweet) os.Stdout.Sync() } } else if verbose { for i := len(tweets) - 1; i >= 0; i-- { name := tweets[i].User.Name user := tweets[i].User.ScreenName text := tweets[i].Text text = replacer.Replace(text) color.Set(color.FgHiRed) fmt.Println(user + ": " + name) color.Set(color.Reset) fmt.Println(" " + text) fmt.Println(" " + tweets[i].Identifier) fmt.Println(" " + tweets[i].CreatedAt) fmt.Println() } } else { for i := len(tweets) - 1; i >= 0; i-- { user := tweets[i].User.ScreenName text := tweets[i].Text color.Set(color.FgHiRed) fmt.Print(user) color.Set(color.Reset) fmt.Print(": ") fmt.Println(text) } } }
func sendSMS(dev *gsmmodem.Device, message string, phoneNumber string) { defer color.Unset() log.Printf("Отправка сообщения на номер: %s\n", phoneNumber) err := dev.SendLongSMS(message, sms.PhoneNumber(phoneNumber)) if err != nil { color.Set(color.FgHiRed) log.Printf("Ошибка отправки сообщения: %s\n", err.Error()) } else { color.Set(color.FgHiGreen) log.Printf("Сообщение отправлено на номер: " + phoneNumber) } }
func (state *state) printBoard() { board := state.board fmt.Println() fmt.Print(" ") for _, c := range "abcdefgh" { fmt.Print(fmt.Sprintf("%c ", c)) } fmt.Println() for i := 0; i < N; i++ { for k := 0; k < 3; k++ { if k == 1 { fmt.Print(fmt.Sprintf(" %d", N-i)) } else { fmt.Print(" ") } for j := 0; j < N; j++ { cp := colors[boardColors[i][j]] color.Set(cp.bg) fmt.Print(" ") piece := board[i][j] if k == 1 && piece != nil { color.Unset() color.Set(colors[piece.Color].fg) if piece.Player == humanPlayer { fmt.Print("X") } else { fmt.Print("O") } } else { fmt.Print(" ") } color.Set(cp.bg) fmt.Print(" ") } color.Unset() if k == 1 { fmt.Print(N - i) } fmt.Println() } } fmt.Print(" ") for _, c := range "abcdefgh" { fmt.Print(fmt.Sprintf("%c ", c)) } fmt.Println() fmt.Println() }
// Rest will Replenish Health. func (c *Character) Rest() { c.Hp = c.MaxHp color.Set(color.FgBlue) log.Println("Player is fully rested.") color.Unset() mdb.Update(*c) }
func (selector *Selector) Select() (err error) { var choice int var input string retValue := selector.ConfKeeper.Get(bConfList) err = retValue.Error if err != nil { return } lenConfList := len(retValue.Value.([]interface{})) err = fmt.Errorf("") stdin := bufio.NewReader(os.Stdin) for err != nil { err = selector.OutputChoices() if err != nil { return } _, err = fmt.Scanf("%s", &input) stdin.ReadString('\n') if err != nil { Out("Error:", err.Error(), "\n\n") Out("\n", bigseparator, "\n\n") continue } input = strings.TrimSpace(input) var outputColor color.Attribute switch input { case "q", "--": choice = -1 err = nil default: choice, err = strconv.Atoi(input) if err != nil { outputColor = color.FgRed err = fmt.Errorf("Your input is not integer number or code to exit!") } } if err == nil { switch { case choice < -1 || choice >= lenConfList: outputColor = color.FgMagenta err = fmt.Errorf("%d is out of range [ -1, %d ]!", choice, lenConfList-1) default: outputColor = color.FgCyan err = nil } } Out("\nYou selected ") color.Set(outputColor, color.Bold) Out(input) color.Unset() Out(".\n\n") if err != nil { Out(err.Error(), "\n") Out("\n", bigseparator, "\n\n") } } err = selector.ConfKeeper.Set(bSelected, strconv.Itoa(choice)).Error return }
func exec(cmd *cobra.Command, args []string) { if len(args) == 1 { color.Green("Creando nueva aplicacion " + args[0]) gopath := os.Getenv("GOPATHs") if gopath == "" { color.Set(color.FgRed) defer color.Unset() log.Fatalln("GOPATH no found :(") os.Exit(2) } src := fmt.Sprintf("%s\\src", gopath) appName := args[0] appDir := fmt.Sprintf("%s\\%s", src, appName) createAppFolder(appDir, []string{}) fmt.Printf("appDir: %s\n", appDir) createAppFolder(fmt.Sprintf("%s\\%s", appDir, "public"), []string{"assets"}) createAppFolder(fmt.Sprintf("%s\\%s", appDir, "app"), []string{"controllers", "models"}) createSubFolder(fmt.Sprintf("%s\\%s\\%s", appDir, "public", "assets"), []string{"js", "scss", "img", "fonts"}) // creamos la estructura basica } }
func debugResponse(res *http.Response) { if debug { color.Set(color.FgCyan) doDebug(httputil.DumpResponse(res, true)) color.Unset() } }
func debugRequest(req *http.Request) { if debug { color.Set(color.FgMagenta) doDebug(httputil.DumpRequestOut(req, true)) color.Unset() } }
func TestIndentConnects(t *testing.T) { source := readFileToSlice("./tests_data/source_indentConnects.cpp") result := readFileToSlice("./tests_data/result_indentConnects.cpp") indentConnects(source) for i, line := range source { if line != result[i] { color.Set(color.FgYellow) fmt.Printf("\nTheses lines are different: \n%s\n%s\n\n", line, result[i]) color.Set(color.FgRed) t.FailNow() color.Unset() } } }
func printResult(message string, c color.Attribute) { print("[") color.Set(c) print(message) color.Unset() println("]") }
func OutputTests() { for _, test := range tests { fmt.Printf("%s: expected ", test.function) if len(test.attributes) > 0 { color.Set(test.attributes...) } fmt.Print(test.expected) if len(test.attributes) > 0 { color.Unset() } fmt.Print(", actual ") switch test.function { case "Debug": Debug(test.input...) case "Log": Log(test.input...) fmt.Print("\nFor output, look at file ", logFileName) case "Print": Print(test.input...) case "Out": Out(test.input...) fmt.Print("\nFor other output, look at file ", logFileName) } fmt.Println() } }
// Ask the amount of the selected ingredient func (b *bread) askAmount(starter string) int { color.Set(color.FgWhite) fmt.Printf("Enter the amount of %s in grams: ", starter) color.Unset() var amount, _ = b.reader.ReadString('\n') var intAmount, err = strconv.Atoi(strings.TrimSpace(amount)) if err != nil { color.Set(color.FgRed) fmt.Println("Wrong amount. Try again!") color.Unset() return b.askAmount(starter) } return intAmount }
func writeError(format string, err error, a ...interface{}) { color.Set(color.FgRed) fmt.Fprintf(os.Stderr, format+"\n", a...) if err != nil { fmt.Fprintln(os.Stderr, err) } color.Unset() }
func variableMenu() { color.Set(color.FgYellow) print("") print("a - Add") print("D - Delete") print("? - Help") print("b - Back") color.Unset() }
func printDatagram(out *color.Color, d *protocol.Datagram) { re := regexp.MustCompilePOSIX("^00000") out.Printf("FROM: %s\n", d.From) out.Printf("SIZE: %d\n", len(d.Data)) data := strings.TrimLeft(hex.Dump(d.Data), "0") out.Printf("DATA: 000" + re.ReplaceAllString(data, " ")) color.Set(color.Bold) }
func sshKeysHelp() { color.Set(color.FgYellow) print("") print("a - Add") print("D - Delete") print("? - Help") print("b - Back") color.Unset() }
func displayRSS(items []Item) { for i, item := range items { index := i + 1 color.Set(color.FgRed) fmt.Printf("%2d.", index) color.Unset() fmt.Printf(" %s\n", item.Title) } }
func Print(args ...interface{}) { formated := Format(args...) if len(formated.Attributes) > 0 { color.Set(formated.Attributes...) } fmt.Print(formated.Text) if len(formated.Attributes) > 0 { color.Unset() } }
// Ask for the type of bread func (b *bread) askType() int { color.Set(color.FgWhite) fmt.Println("What type of bread are you making?") color.Unset() // Print each type of bread sequentially for i, v := range breadIndex { fmt.Printf("%d. %s\n", i+1, strings.Title(v)) } color.Set(color.FgWhite) fmt.Print("Type the corresponding number (Default: Standard): ") color.Unset() var breadType, _ = b.reader.ReadString('\n') breadType = strings.TrimSpace(breadType) // No input sets the default type of bread if breadType == "" { return 0 } var breadTypeInt, err = strconv.Atoi(breadType) if err != nil { color.Set(color.FgRed) fmt.Println("Wrong input. Try again!") color.Unset() b.askType() } if breadTypeInt == 0 || breadTypeInt > len(breadIndex) { color.Set(color.FgRed) fmt.Println("No bread type with the input number. Try again!") color.Unset() b.askType() } // Convert the input to a 0-based index for // the types of bread slice return breadTypeInt - 1 }
func mainMenu() { color.Set(color.FgYellow) print("") print("a - AWS Key") print("s - SSH Keys") print("v - Variables") print("d - Environment Duration") print("? - Help") print("q - Quit") color.Unset() }
// SellItems will clear the inventory. func (c *Character) SellItems() { for _, v := range c.Inventory.Items { c.Gold += v.Value } yellow := color.New(color.FgYellow).SprintFunc() color.Set(color.FgBlue) log.Printf("Player has sold all items. Current gold is: %s\n", yellow(c.Gold)) color.Unset() c.Inventory.Items = []Item{} mdb.Update(*c) }
// Render table output func (t Table) Render() { if t.border { t.printLine(true) } color.Set(color.BgBlue) color.Set(color.Bold) color.Set(color.CrossedOut) t.printHeading() color.Unset() color.Set(color.BgCyan) color.Set(color.FgBlack) t.printRows() color.Unset() if !t.rowLine && t.border { t.printLine(true) } t.printFooter() }
func (x Cli) Publish(publishMsgs <-chan models.Message, connector models.Connector) { for { message := <-publishMsgs fmt.Print("\n") switch message.Out.Status { case "SUCCESS": color.Set(color.FgGreen) case "WARN": color.Set(color.FgYellow) case "FAIL": color.Set(color.FgRed) } fmt.Println(message.Out.Text) color.Unset() if message.Out.Detail != "" { fmt.Println(message.Out.Detail) } fmt.Print("\n", connector.BotName, "> ") } }
func main() { // Connect to modem and initialize dev := &gsmmodem.Device{ CommandPort: "com6", NotifyPort: "com7", } if err := dev.Open(); err != nil { log.Println(err) return } if err := dev.Init(gsmmodem.DeviceE173()); err != nil { log.Println(err) return } defer dev.Close() fmt.Print("Enter phone number: ") phoneNumber := "" if _, err := fmt.Scanln(&phoneNumber); err != nil { fmt.Println(err) return } fmt.Println("Enter message:") message := "" if _, err := fmt.Scanln(&message); err != nil { fmt.Println(err) return } log.Printf("Send message \"%s\" to phone number %s\n", phoneNumber, message) err := dev.SendLongSMS(message, sms.PhoneNumber(phoneNumber)) if err != nil { color.Set(color.FgHiRed) log.Printf("Ошибка отправки сообщения: %s\n", err.Error()) } else { color.Set(color.FgHiGreen) log.Printf("Сообщение отправлено на номер: " + phoneNumber) } }
func (selector *Selector) OutputChoices() (err error) { var confList []interface{} retValue := selector.ConfKeeper.Get(bConfList) confList, err = retValue.Value.([]interface{}), retValue.Error if err != nil { return } Out("Choose your application:\n\n") var ( curAppName, curConfSrc string appName interface{} ) retValue = selector.ConfKeeper.Get(Key(bCurrent, kApp)) err = retValue.Error if err == nil { curAppName = retValue.Value.(map[string]interface{})[kName].(string) curConfSrc = retValue.Value.(map[string]interface{})[kConfSrc].(string) } color.Set(color.FgGreen, color.Bold) for key, value := range confList { retValue = selector.ConfKeeper.Get(Key(bConfData, key, kApp, kName)) appName, err = retValue.Value, retValue.Error if err != nil { color.Unset() return } if curAppName == appName && curConfSrc == value { color.Set(color.FgYellow, color.Bold) Out("?:Current: %2d. %-30v == %v\n", key, appName, value) color.Set(color.FgGreen, color.Bold) } else { Out("?: %2d. %-30v == %v\n", key, appName, value) } } //Out(bigseparator, "\n\n") color.Unset() Out("\nWrite number of selected application from list printed above\n\nor q, -- or -1 to exit: ") return }