Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226package cli
import ( "errors" "fmt" "io" "os" "os/exec" "path/filepath" "regexp" "runtime" "strings" "time" "unicode/utf8"
"github.com/charmbracelet/huh" "github.com/spf13/cobra")
// table prints rows aligned on a terminal and tab-separated otherwise, so// output stays easy to pipe into cut or awk.type table struct { app *App rows [][]string}
func (a *App) newTable() *table { return &table{app: a} }
func (t *table) row(cells ...string) { t.rows = append(t.rows, cells) }
func (t *table) render() { if !t.app.OutTTY { for _, r := range t.rows { fmt.Fprintln(t.app.Out, strings.Join(r, "\t")) } return } widths := map[int]int{} for _, r := range t.rows { for i, c := range r { widths[i] = max(widths[i], visibleWidth(c)) } } for _, r := range t.rows { var b strings.Builder for i, c := range r { b.WriteString(c) if i < len(r)-1 { b.WriteString(strings.Repeat(" ", widths[i]-visibleWidth(c)+2)) } } fmt.Fprintln(t.app.Out, b.String()) }}
var ansiRe = regexp.MustCompile("\x1b\\[[0-9;]*m")
func visibleWidth(s string) int { return utf8.RuneCountInString(ansiRe.ReplaceAllString(s, ""))}
// truncate shortens s to n runes on a terminal.func (a *App) truncate(s string, n int) string { s = strings.ReplaceAll(s, "\n", " ") if !a.OutTTY { return s } r := []rune(s) if len(r) <= n { return s } return string(r[:n-1]) + "…"}
// timeAgo renders an RFC 3339 timestamp as a relative time on a terminal and// leaves it as is otherwise.func (a *App) timeAgo(ts string) string { if !a.OutTTY { return ts } t, err := time.Parse(time.RFC3339Nano, ts) if err != nil { return ts } d := time.Since(t) switch { case d < time.Minute: return "less than a minute ago" case d < time.Hour: return plural(int(d.Minutes()), "minute") + " ago" case d < 24*time.Hour: return plural(int(d.Hours()), "hour") + " ago" case d < 30*24*time.Hour: return plural(int(d.Hours()/24), "day") + " ago" case d < 365*24*time.Hour: return plural(int(d.Hours()/24/30), "month") + " ago" } return plural(int(d.Hours()/24/365), "year") + " ago"}
func plural(n int, unit string) string { if n == 1 { return "about 1 " + unit } return fmt.Sprintf("about %d %ss", n, unit)}
// editor returns the command used to edit text.func (a *App) editor() string { for _, e := range []string{a.Config.Get("editor"), os.Getenv("VISUAL"), os.Getenv("EDITOR")} { if e != "" { return e } } for _, e := range []string{"nvim", "vim", "nano"} { if _, err := exec.LookPath(e); err == nil { return e } } return "vi"}
// editText opens initial in the user's editor and returns the saved text.func (a *App) editText(initial, name string) (string, error) { dir, err := os.MkdirTemp("", "knit-") if err != nil { return "", err } defer os.RemoveAll(dir) path := filepath.Join(dir, name) if err := os.WriteFile(path, []byte(initial), 0o600); err != nil { return "", err } // run through the shell so editors configured with arguments work cmd := exec.Command("sh", "-c", a.editor()+` "$1"`, "sh", path) cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if err := cmd.Run(); err != nil { return "", fmt.Errorf("running editor: %w", err) } data, err := os.ReadFile(path) if err != nil { return "", err } return string(data), nil}
// openBrowser opens url in the user's browser.func (a *App) openBrowser(url string) error { browser := a.Config.Get("browser") if browser == "" { browser = os.Getenv("BROWSER") } var cmd *exec.Cmd switch { case browser != "": cmd = exec.Command("sh", "-c", browser+` "$1"`, "sh", url) case runtime.GOOS == "darwin": cmd = exec.Command("open", url) case runtime.GOOS == "windows": cmd = exec.Command("rundll32", "url.dll,FileProtocolHandler", url) default: cmd = exec.Command("xdg-open", url) } cmd.Stdout = io.Discard cmd.Stderr = io.Discard return cmd.Start()}
// browse opens url, or prints it when stdout isn't a terminal.func (a *App) browse(url string) error { if !a.OutTTY { a.Printf("%s\n", url) return nil } a.Infof("Opening %s in your browser.\n", url) return a.openBrowser(url)}
var errNoTTY = errors.New("this command needs flags when not run interactively")
func (a *App) interactive() bool { return a.InTTY && a.OutTTY }
func (a *App) promptInput(title, placeholder string, value *string) error { return huh.NewInput().Title(title).Placeholder(placeholder).Value(value).Run()}
func (a *App) promptConfirm(title string) (bool, error) { ok := false err := huh.NewConfirm().Title(title).Value(&ok).Run() return ok, err}
// readBody resolves a body from --body or --body-file ("-" reads stdin), and// reports whether either flag was given.func (a *App) readBody(cmd *cobra.Command, body, bodyFile string) (string, bool, error) { if bodyFile == "" { return body, cmd.Flags().Changed("body"), nil } var data []byte var err error if bodyFile == "-" { data, err = io.ReadAll(a.In) } else { data, err = os.ReadFile(bodyFile) } return string(data), true, err}
// stateLabel renders a ticket state the way the web interface names it.func (a *App) stateLabel(state string, pull bool) string { switch state { case "open": return a.Green("open") case "completed": if pull { return a.Magenta("merged") } return a.Magenta("completed") case "closed": return a.Red("closed") } return state}