func (ConsolePlugin) Log(text string, skipChevron bool) { if skipChevron { fmt.Printf("%v", colorstring.Color("[light_gray]"+text)) return } fmt.Printf("%v %v", colorstring.Color("[blue]>"), colorstring.Color("[light_gray]"+text)) }
func main() { movie, err := movies.GetMovieByID(randomID()) if err != nil { fmt.Println(colorstring.Color("[red]" + err.Error())) } textColor := getColorForRating(movie.ImdbRating) fmt.Println(colorstring.Color(textColor + movie.Title)) }
// BuildSession build a session based on Session structure func BuildSession(s *Session, tmux string, args []string, attach bool) error { if s.Name == "" { s.Name = "tmass-session-" + strconv.Itoa(rand.Int()) } // Wow this code is creepy :/ if IsSessionExists(s.Name) { if !attach { return fmt.Errorf("session with name %s already exists, use the --attach switch to attach to it or use --target for overwrite name", s.Name) } s.Attach = true } for i := range s.Windows { if !s.Attach && i == 0 { // First window is created when new session is started, if its not an attach session cmd := Command{} if !s.Attach { cmd.Add("new-session", "-d", "-s") } cmd.Add(s.Name) cmd.Add("-n", s.Windows[i].Name, "-c", s.Windows[i].RealPane[0].Root) if _, err := cmd.Execute(tmux, args); err != nil { return err } // tmux -P switch for new window return data for window not the first pane //TODO: Default is zero, if default is changed by user? s.Windows[i].RealPane[0].identifier = s.Name + ":0.0" } else { c := Command{} c.Add("new-window", "-P", "-t", s.Name, "-n", s.Windows[i].Name, "-c", s.Windows[i].RealPane[0].Root) n, err := c.Execute(tmux, args) if err != nil { return err } s.Windows[i].RealPane[0].identifier = n } cf, err := BuildPane(&s.Windows[i], tmux, args, s) if err != nil { return err } // The problem is, layout may contain the focus. so for setting focus, we need to call it after setting layout c := Command{[]string{"select-layout", s.Windows[i].Layout}} if _, err := c.Execute(tmux, args); err != nil { log.Println(colorstring.Color("[yellow] Failed to apply layout. ignored")) } if cf != nil { if _, err := cf.Execute(tmux, args); err != nil { log.Println(colorstring.Color("[yellow] Failed to select pane. ignored")) } } } return nil }
// A simple fallback, Sometime the split-window fails with `create pane failed: pane too small` // In that case, print a warning and then try to use new-window func newWindowFallback(w *Window, tmux string, args []string, s *Session, p *Pane) (string, error) { log.Println(colorstring.Color("[yellow] Failed to split window. try to create new window.")) // First try to set layout for old window c := Command{[]string{"select-layout", w.Layout}} if _, err := c.Execute(tmux, args); err != nil { log.Println(colorstring.Color("[yellow] Failed to apply layout. ignored")) } c.Clear() c.Add("new-window", "-P", "-t", s.Name, "-n", w.Name, "-c", p.Root) return c.Execute(tmux, args) }
func printCurrentWeather(forecast Forecast, geolocation GeoLocation, ignoreAlerts bool) { unitsFormat := UnitFormats[forecast.Flags.Units] icon, err := getIcon(forecast.Currently.Icon) if err != nil { printError(err) } else { fmt.Println(icon) } location := colorstring.Color(fmt.Sprintf("[green]%s in %s", geolocation.City, geolocation.Region)) fmt.Printf("\nCurrent weather is %s in %s for %s\n", colorstring.Color("[cyan]"+forecast.Currently.Summary), location, colorstring.Color("[cyan]"+epochFormat(forecast.Currently.Time))) temp := colorstring.Color(fmt.Sprintf("[magenta]%v%s", forecast.Currently.Temperature, unitsFormat.Degrees)) feelslike := colorstring.Color(fmt.Sprintf("[magenta]%v%s", forecast.Currently.ApparentTemperature, unitsFormat.Degrees)) fmt.Printf("The temperature is %s, but it feels like %s\n\n", temp, feelslike) if !ignoreAlerts { for _, alert := range forecast.Alerts { if alert.Title != "" { fmt.Println(colorstring.Color("[red]" + alert.Title)) } if alert.Description != "" { fmt.Print(colorstring.Color("[red]" + alert.Description)) } fmt.Println("\t\t\t" + colorstring.Color("[red]Created: "+epochFormat(alert.Time))) fmt.Println("\t\t\t" + colorstring.Color("[red]Expires: "+epochFormat(alert.Expires)) + "\n") } } printWeather(forecast.Currently, unitsFormat) }
// LoadSessionFromTmux fill session structure from a running instance of tmux func LoadSessionFromTmux(tmux string, args []string, session string) (*Session, error) { sess := Session{Name: session} sess.Windows = make([]Window, 0) cmd := Command{} cmd.Add("list-window", "-t", session, "-F", "#S:#I|#{window_name}|#{window_layout}") out, err := cmd.Execute(tmux, args) if err != nil { return nil, err } for _, s := range strings.Split(out, "\n") { parts := strings.Split(s, "|") if len(parts) != 3 { log.Println(colorstring.Color("[red][_yellow_]Invalid count! ignoring this window!")) continue } w, err := LoadWindowFromTmux(tmux, args, parts[0], parts[1], parts[2]) if err != nil { return nil, err } sess.Windows = append(sess.Windows, *w) } return &sess, nil }
func renderSummary() { printHR() printCentered(fmt.Sprintf(c.Color("[white]lsp \"[red]%s[white]\""), presentPath(mode.targetPath)) + fmt.Sprintf(c.Color(", [red]%v[white] files, [red]%v[white] directories"), len(FileList), len(Trie.Ch["dirs"].Fls))) for _, cm := range mode.comments { printCentered(cm) } }
func main() { var filepath string var isVersion bool flag.StringVar(&filepath, "f", "", "keepalived.conf file path") flag.BoolVar(&isVersion, "v", false, "print the version") flag.Parse() if isVersion { log.Infof("gokc version %s", Version) os.Exit(0) } if filepath == "" { log.Error("filepath required") } file, err := os.Open(filepath) if err != nil { log.Error(err) } defer file.Close() if err := parser.Parse(file, filepath); err != nil { if e, ok := err.(*parser.Error); ok { msg := colorstring.Color(fmt.Sprintf("[white]%s:%d:%d: [red]%s[reset]", e.Filename, e.Line, e.Column, e.Message)) log.Error(msg) } else { log.Error(err) } } log.Infof("gokc: the configuration file %s syntax is ok", filepath) }
// LoadWindowFromTmux loads window from a tmux session func LoadWindowFromTmux(tmux string, args []string, window, name, layout string) (*Window, error) { // The real pane is not used here. ignore it w := Window{Name: name, Layout: layout, Panes: make([]interface{}, 0)} cmd := Command{} cmd.Add("list-pane", "-t", window, "-F", "#{pane_current_path}|#{pane_current_command}|#{pane_active}") out, err := cmd.Execute(tmux, args) if err != nil { return nil, err } for _, s := range strings.Split(out, "\n") { parts := strings.Split(s, "|") if len(parts) != 3 { log.Println(colorstring.Color("[red][_yellow_]Invalid count! ignoring this pane!")) continue } for _, v := range IgnoredCmd { if v == parts[1] { parts[1] = DefaultCmd break } } p := Pane{Commands: []string{parts[1]}, Root: parts[0], Focus: parts[2] == "1"} w.Panes = append(w.Panes, p) } return &w, nil }
// Colorize color msg. func Colorize(msg string, color string) (out string) { // If color is blank return plain text if color == "" { return msg } return colorstring.Color(fmt.Sprintf("[%s]%s[reset]", color, msg)) }
func printHeader(o string) { length := utf8.RuneCountInString(o) sideburns := (6+2*columnSize-length)/2 - dashesNumber if sideburns < 0 { sideburns = 0 } fmt.Printf(strings.Repeat(" ", sideburns)) fmt.Printf(c.Color("[yellow]" + strings.Repeat("-", dashesNumber) + o + strings.Repeat("-", dashesNumber) + "[white]\n")) }
func printCentered(o string) { length := utf8.RuneCountInString(o) sideburns := (6 + 2*columnSize - length) / 2 if sideburns < 0 { sideburns = 0 } fmt.Printf(strings.Repeat(" ", sideburns)) fmt.Printf(c.Color("[yellow]" + o + "[white]\n")) }
func (t *IssueDetailTemplate) Print() error { var buf bytes.Buffer if err := t.Execute(&buf, t); err != nil { return err } fmt.Println(color.Color(buf.String())) return nil }
func printTotals(totals map[string]string) { if len(totals) > 0 { header := []string{"Totals"} row := []string{"-"} fmt.Println("") w := tabwriter.NewWriter(os.Stdout, 20, 1, 3, ' ', 0) for k, v := range totals { header = append(header, stripColon(k)) row = append(row, v) } fmt.Fprintln(w, colorstring.Color("[cyan]"+strings.Join(header, "\t"))) fmt.Fprintln(w, colorstring.Color("[blue]"+strings.Join(row, "\t"))) w.Flush() } return }
func catchUserInterruption(start time.Time) { c := make(chan os.Signal, 2) signal.Notify(c, os.Interrupt) go func() { for sig := range c { fmt.Printf(colorstring.Color("Awww, your total pomodoro time was: %v, [red]%v\n"), elapsedTime(start), sig) os.Exit(2) } }() }
// PrintColumns prints two-column table row, nicely formatted and shortened if needed func PrintColumns(filename, description string) { indentSize := columnSize - utf8.RuneCountInString(filename) if indentSize < 0 { indentSize = 0 } if utf8.RuneCountInString(filename) > maxFileNameSize { filename = string([]rune(filename)[0:maxFileNameSize]) + "[magenta][...]" } if mode.pyramid { fmt.Printf(c.Color(commonPrefix + fmt.Sprintf("[white]%s[blue]", filename))) fmt.Printf(strings.Repeat(" ", indentSize)) } else { fmt.Printf(strings.Repeat(" ", indentSize)) fmt.Printf(c.Color(commonPrefix + fmt.Sprintf("[white]%s[blue]", filename))) } // central dividing space fmt.Printf(" ") fmt.Printf(c.Color(fmt.Sprintf("[red]%s[white]\n", description))) }
func printCommon(weather Weather, unitsFormat UnitMeasures) error { if weather.Humidity > 0 { humidity := colorstring.Color(fmt.Sprintf("[white]%v%s", weather.Humidity*100, "%")) if weather.Humidity > 0.20 { fmt.Printf("Ick! The humidity is %s\n", humidity) } else { fmt.Printf("The humidity is %s\n", humidity) } } if weather.PrecipIntensity > 0 { precInt := colorstring.Color(fmt.Sprintf("[white]%v %s", weather.PrecipIntensity, unitsFormat.Precipitation)) fmt.Printf("The precipitation intensity of %s is %s\n", colorstring.Color("[white]"+weather.PrecipType), precInt) } if weather.PrecipProbability > 0 { prec := colorstring.Color(fmt.Sprintf("[white]%v%s", weather.PrecipProbability*100, "%")) fmt.Printf("The precipitation probability is %s\n", prec) } if weather.NearestStormDistance > 0 { dist := colorstring.Color(fmt.Sprintf("[white]%v %s %v", weather.NearestStormDistance, unitsFormat.Length, getBearingDetails(weather.NearestStormBearing))) fmt.Printf("The nearest storm is %s away\n", dist) } if weather.WindSpeed > 0 { wind := colorstring.Color(fmt.Sprintf("[white]%v %s %v", weather.WindSpeed, unitsFormat.Speed, getBearingDetails(weather.WindBearing))) fmt.Printf("The wind speed is %s\n", wind) } if weather.CloudCover > 0 { cloudCover := colorstring.Color(fmt.Sprintf("[white]%v%s", weather.CloudCover*100, "%")) fmt.Printf("The cloud coverage is %s\n", cloudCover) } if weather.Visibility < 10 { visibility := colorstring.Color(fmt.Sprintf("[white]%v %s", weather.Visibility, unitsFormat.Length)) fmt.Printf("The visibility is %s\n", visibility) } if weather.Pressure > 0 { pressure := colorstring.Color(fmt.Sprintf("[white]%v %s", weather.Pressure, "mbar")) fmt.Printf("The pressure is %s\n", pressure) } return nil }
func getIcon(iconStr string) (icon string, err error) { color := "blue" // steralize the icon string name iconStr = strings.Replace(strings.Replace(iconStr, "-", "", -1), "_", "", -1) switch iconStr { case "clear": icon = icons.Clear case "clearday": color = "yellow" icon = icons.Clearday case "clearnight": color = "light_yellow" icon = icons.Clearnight case "clouds": icon = icons.Clouds case "cloudy": icon = icons.Cloudy case "cloudsnight": color = "light_yellow" icon = icons.Cloudsnight case "fog": icon = icons.Fog case "haze": icon = icons.Haze case "hazenight": color = "light_yellow" icon = icons.Hazenight case "partlycloudyday": color = "yellow" icon = icons.Partlycloudyday case "partlycloudynight": color = "light_yellow" icon = icons.Partlycloudynight case "rain": icon = icons.Rain case "sleet": icon = icons.Sleet case "snow": color = "white" icon = icons.Snow case "thunderstorm": color = "black" icon = icons.Thunderstorm case "tornado": color = "black" icon = icons.Tornado case "wind": color = "black" icon = icons.Wind } return colorstring.Color("[" + color + "]" + icon), nil }
func deliverIfDone(client tracker.ProjectClient, story tracker.Story, sources string, repos []string) { sayf(colorstring.Color("Checking for finished story: [blue]#%d\n"), story.ID) for _, repo := range repos { dir := filepath.Join(sources, repo) sayf(colorstring.Color(" [white][bold]%s[default]...%s"), repo, strings.Repeat(" ", 80-2-3-10-len(repo))) outputFixes := checkGitLog("fixes", story, dir) outputFinishes := checkGitLog("finishes", story, dir) if len(outputFixes) > 0 || len(outputFinishes) > 0 { sayf(colorstring.Color("[green]DELIVERING\n")) client.DeliverStoryWithComment(story.ID, "Delivered by Concourse") } else { sayf(colorstring.Color(" [yellow]SKIPPING\n")) } } sayf("\n") }
// PrintDaily pretty prints the daily forecast data. func PrintDaily(forecast Forecast, days int) error { unitsFormat := UnitFormats[forecast.Flags.Units] fmt.Println(colorstring.Color("\n[white]" + fmt.Sprintf("%v Day Forecast", days))) // Ignore the current day as it's printed before for index, daily := range forecast.Daily.Data[1:] { // only do the amount of days they request if index == days { break } fmt.Println(colorstring.Color("\n[magenta]" + epochFormatDate(daily.Time))) tempMax := colorstring.Color(fmt.Sprintf("[blue]%v%s", daily.TemperatureMax, unitsFormat.Degrees)) tempMin := colorstring.Color(fmt.Sprintf("[blue]%v%s", daily.TemperatureMin, unitsFormat.Degrees)) feelsLikeMax := colorstring.Color(fmt.Sprintf("[cyan]%v%s", daily.ApparentTemperatureMax, unitsFormat.Degrees)) feelsLikeMin := colorstring.Color(fmt.Sprintf("[cyan]%v%s", daily.ApparentTemperatureMin, unitsFormat.Degrees)) fmt.Printf("The temperature high is %s, feels like %s around %s, and low is %s, feels like %s around %s\n\n", tempMax, feelsLikeMax, epochFormatTime(daily.TemperatureMaxTime), tempMin, feelsLikeMin, epochFormatTime(daily.TemperatureMinTime)) printCommon(daily, unitsFormat) } return nil }
func (fi FileInfo) investigateDir(i int, updated chan FileListUpdate) { files, err := ioutil.ReadDir(mode.targetPath + "/" + fi.f.Name()) if err != nil { updated <- FileListUpdate{i, &fi, true} return } fi.description = fmt.Sprintf(c.Color("[red]%v[white] files inside"), len(files)) isgit := investigateGit(mode.targetPath + "/" + fi.f.Name()) if isgit != "" { fi.description = isgit } updated <- FileListUpdate{i, &fi, true} }
// Prompt will prompt for input from the shell and return a trimmed response func Prompt(p string, v ...interface{}) string { reader := bufio.NewReader(os.Stdin) // fmt.Print(colorstring.Color(fmt.Sprintf(p, v...))) input, err := reader.ReadString('\n') if err != nil { config.Fatal("[util/print] reader.ReadString() failed - ", err.Error()) } return strings.TrimSpace(input) }
func (gitLab *gitLabCli) PrintIssue(projectID int, state string) { c := make(chan []*gogitlab.Issue) go gitLab.findIssueState(c, projectID, func(issues []*gogitlab.Issue) bool { if state != "" && issues[len(issues)-1].State != state { return true } return false }) for { issues, ok := <-c if !ok { break } for _, issue := range issues { if state != "" && issue.State != state { continue } title := issue.Title if checkTrim(title) { title = trimPrefixIndex(title) } name := issue.Assignee.Name if checkTrim(name) { name = trimPrefixIndex(name) } labels := fmt.Sprint(issue.Labels) if checkTrim(name) { labels = trimPrefixIndex(labels) } titleCount := titleCount + ((utf8.RuneCountInString(title) - len(title)) / 2) nameCount := nameCount + ((utf8.RuneCountInString(name) - len(name)) / 2) labelCount := labelCount + ((utf8.RuneCountInString(labels) - len(labels)) / 2) t := fmt.Sprintf("[blue]#%%-4d %%-7s [white]%%-%ds [green]%%-%ds [red]%%-%ds [white]%%-33s / %%-33s", titleCount, nameCount, labelCount) fmt.Println(color.Color(fmt.Sprintf(t, issue.LocalID, issue.State, title, name, labels, issue.CreatedAt, issue.UpdatedAt))) } } }
func getIcon(icon string) (iconTxt string, err error) { color := "blue" switch icon { case "clear-day": color = "yellow" case "clear-night": color = "light_yellow" case "snow": color = "white" case "wind": color = "black" case "partly-cloudy-day": color = "yellow" case "partly-cloudy-night": color = "light_yellow" case "thunderstorm": color = "black" case "tornado": color = "black" } uri := "https://s3.j3ss.co/weather/icons/" + icon + ".txt" resp, err := http.Get(uri) if err != nil { return iconTxt, fmt.Errorf("Requesting icon (%s) failed: %s", icon, err) } defer resp.Body.Close() // decode the body out, err := ioutil.ReadAll(resp.Body) if err != nil { return iconTxt, fmt.Errorf("Reading response body for icon (%s) failed: %s", icon, err) } iconTxt = string(out) if strings.Contains(iconTxt, "<?xml") { return "", fmt.Errorf("No icon found for %s.", icon) } return colorstring.Color("[" + color + "]" + iconTxt), nil }
func printDiff(diffs []diffmatchpatch.Diff) { for _, d := range diffs { lines := strings.Split(strings.TrimRight(d.Text, "\n"), "\n") var prefix string switch d.Type { case diffmatchpatch.DiffDelete: prefix = "[red]- " case diffmatchpatch.DiffInsert: prefix = "[green]+ " case diffmatchpatch.DiffEqual: prefix = " " } for _, l := range lines { s := fmt.Sprintf("%s %s", prefix, l) fmt.Println(colorstring.Color(s)) } } }
// BuildPane build a pane from a window func BuildPane(w *Window, tmux string, args []string, s *Session) (*Command, error) { cf := Command{} var basePane string for i, p := range w.RealPane { c := Command{[]string{"select-layout", w.Layout}} if _, err := c.Execute(tmux, args); err != nil { log.Println(colorstring.Color("[yellow] Failed to apply layout. ignored")) } if i == 0 { basePane = p.identifier // I don't know a good way to find the bigger pane, so just split the first pane // TODO do I need to re-apply the layout each time??? } else { // The first pane is created when the window is created c0 := Command{[]string{"split-window", "-P", "-c", p.Root, "-t", basePane}} n, err := c0.Execute(tmux, args) if err != nil { if n, err = newWindowFallback(w, tmux, args, s, &p); err != nil { return nil, err } } p.identifier = n } c1 := Command{[]string{"send-keys", "-t", p.identifier, strings.Join(p.Commands, ";")}} c2 := Command{[]string{"send-keys", "-t", p.identifier, "Enter"}} if _, err := c1.Execute(tmux, args); err != nil { return nil, err } if _, err := c2.Execute(tmux, args); err != nil { return nil, err } if p.Focus { cf.Clear() cf.Add("select-pane", "-t", p.identifier) } } if cf.String() != "" { return &cf, nil } return nil, nil }
func main() { if len(os.Args) != 2 { fmt.Fprintf(os.Stderr, "usage: go-pkg sql\n") os.Exit(1) } resp, err := search(os.Args[1]) if err != nil { log.Fatal(err) } for _, element := range resp.Results { str := colorstring.Color(fmt.Sprintf("[red]Name:[blue]\t\t%s \n[red]Package:[blue]\t%s \n[red]Author:[blue]\t\t%s \n[red]ProjectURL:[blue]\t%s", element.Name, element.Package, element.Author, element.ProjectURL)) colorstring.Println(str) fmt.Println(" ") } }
func main() { flag.Usage = showUsage flag.Parse() catchUserInterruption(start) fmt.Println(colorstring.Color("[green]Start time:"), start.Format(time.RFC3339)) for i := 1; i <= pomodoriRun; i++ { fmt.Printf("Run #%v\n", i) sleepTimer(pomodori, PomodoriMessage) if i%4 == 0 || i == (pomodoriRun) { sleepTimer(largeBreak, LargeMessage) } else { sleepTimer(shortBreak, ShortMessage) } } fmt.Println("Well done, your total pomodoro time was:", elapsedTime(start)) }
func main() { fullPath, err := homedir.Expand("~/.ghprs") if err != nil { log.Fatalf("Failed to expand home directory: %v", err) } vars, err := loadVarFile(fullPath) if err != nil { log.Fatalf("Failed to load configuration file: %v", err) } fmt.Println(colorstring.Color("[green]Connecting to GitHub...")) organization, ok := vars["organization"] if !ok { log.Fatalf("Configuration file is missing organization") } token, ok := vars["token"] if !ok { log.Fatalf("Configuration file is missing token") } m := NewPullRequestLister(organization, token) err = m.Run(os.Args[1:]...) if err != nil { fmt.Println(err) os.Exit(1) } }
func Fatal(doing string, err error) { Sayf(colorstring.Color("[red]error %s: %s\n"), doing, err) os.Exit(1) }