Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@ require (
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51
github.com/mattn/go-colorable v0.1.6 // indirect
github.com/mattn/go-isatty v0.0.12
github.com/mattn/go-runewidth v0.0.9 // indirect
github.com/mattn/go-runewidth v0.0.9
github.com/neelance/parallel v0.0.0-20160708114440-4de9ce63d14c
github.com/nsf/termbox-go v0.0.0-20200418040025-38ba6e5628f1
github.com/olekukonko/tablewriter v0.0.4 // indirect
github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4
github.com/pkg/errors v0.9.1
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/Qd
github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
github.com/neelance/parallel v0.0.0-20160708114440-4de9ce63d14c h1:NZOii9TDGRAfCS5VM16XnF4K7afoLQmIiZX8EkKnxtE=
github.com/neelance/parallel v0.0.0-20160708114440-4de9ce63d14c/go.mod h1:eTBvSIlRgLo+CNFFQRQTwUGTZOEdvXIKeZS/xG+D2yU=
github.com/nsf/termbox-go v0.0.0-20200418040025-38ba6e5628f1 h1:lh3PyZvY+B9nFliSGTn5uFuqQQJGuNrD0MLCokv09ag=
github.com/nsf/termbox-go v0.0.0-20200418040025-38ba6e5628f1/go.mod h1:IuKpRQcYE1Tfu+oAQqaLisqDeXgjyyltCfsaoYN18NQ=
github.com/olekukonko/tablewriter v0.0.4 h1:vHD/YYe1Wolo78koG299f7V/VAS08c6IpCLn+Ejf/w8=
github.com/olekukonko/tablewriter v0.0.4/go.mod h1:zq6QwlOf5SlnkVbMSr5EoBv3636FWnp+qbPhuoO21uA=
github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4 h1:49lOXmGaUpV9Fz3gd7TFZY106KVlPVa5jcYD1gaQf98=
Expand Down
97 changes: 97 additions & 0 deletions internal/output/_examples/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
package main

import (
"flag"
"strings"
"sync"
"time"

"github.com/sourcegraph/src-cli/internal/output"
)

var (
duration time.Duration
verbose bool
)

func init() {
flag.DurationVar(&duration, "progress", 5*time.Second, "time to take in the progress bar and pending samples")
flag.BoolVar(&verbose, "verbose", false, "enable verbose mode")
}

func main() {
flag.Parse()

out := output.NewOutput(flag.CommandLine.Output(), output.OutputOpts{
Verbose: verbose,
})

var wg sync.WaitGroup
progress := out.Progress([]output.ProgressBar{
{Label: "A", Max: 1.0},
{Label: "BB", Max: 1.0, Value: 0.5},
{Label: strings.Repeat("X", 200), Max: 1.0},
}, nil)

wg.Add(1)
go func() {
ticker := time.NewTicker(duration / 20)
defer ticker.Stop()
defer wg.Done()

i := 0
for _ = range ticker.C {
i += 1
if i > 20 {
return
}

progress.Verbosef("%slog line %d", output.StyleWarning, i)
}
}()

wg.Add(1)
go func() {
ticker := time.NewTicker(10 * time.Millisecond)
defer ticker.Stop()
defer wg.Done()

start := time.Now()
until := start.Add(duration)
for _ = range ticker.C {
now := time.Now()
if now.After(until) {
return
}

progress.SetValue(0, float64(now.Sub(start))/float64(duration))
progress.SetValue(1, 0.5+float64(now.Sub(start))/float64(duration)/2)
progress.SetValue(2, 2*float64(now.Sub(start))/float64(duration))
}
}()

wg.Wait()
progress.Complete()

func() {
ticker := time.NewTicker(10 * time.Millisecond)
defer ticker.Stop()

pending := out.Pending(output.Linef("", output.StylePending, "Starting pending ticker"))
defer pending.Complete(output.Line(output.EmojiSuccess, output.StyleSuccess, "Ticker done!"))

until := time.Now().Add(duration)
for _ = range ticker.C {
now := time.Now()
if now.After(until) {
return
}

pending.Updatef("Waiting for another %s", until.Sub(time.Now()))
}
}()

out.Write("")
block := out.Block(output.Line(output.EmojiSuccess, output.StyleSuccess, "Done!"))
block.Write("Here is some additional information.\nIt even line wraps.")
}
45 changes: 45 additions & 0 deletions internal/output/block.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package output

import "bytes"

// Block represents a block of output with one status line, and then zero or
// more lines of output nested under the status line.
type Block struct {
*Output
}

func newBlock(indent int, o *Output) *Block {
// Block uses Output's implementation, but with a wrapped writer that
// indents all output lines. (Note, however, that o's lock mutex is still
// used.)
return &Block{
&Output{
w: &indentedWriter{
o: o,
indent: bytes.Repeat([]byte(" "), indent),
},
caps: o.caps,
opts: o.opts,
},
}
}

type indentedWriter struct {
o *Output
indent []byte
}

func (w *indentedWriter) Write(p []byte) (int, error) {
w.o.lock.Lock()
defer w.o.lock.Unlock()

// This is a little tricky: output from Writer methods includes a trailing
// newline, so we need to trim that so we don't output extra blank lines.
for _, line := range bytes.Split(bytes.TrimRight(p, "\n"), []byte("\n")) {
w.o.w.Write(w.indent)
w.o.w.Write(line)
w.o.w.Write([]byte("\n"))
}

return len(p), nil
}
69 changes: 69 additions & 0 deletions internal/output/capabilities.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package output

import (
"os"
"strconv"

"github.com/mattn/go-isatty"
"github.com/nsf/termbox-go"
)

type capabilities struct {
Color bool
Isatty bool
Height int
Width int
}

func detectCapabilities() capabilities {
// There's a pretty obvious flaw here in that we only check the terminal
// size once. We may want to consider adding a background goroutine that
// updates the capabilities struct every second or two.
//
// Pulling in termbox is probably overkill, but finding a pure Go library
// that could just provide terminfo was surprisingly hard. At least termbox
// is widely used.
if err := termbox.Init(); err != nil {
panic(err)
}
w, h := termbox.Size()
termbox.Close()

atty := isatty.IsTerminal(os.Stdout.Fd())

return capabilities{
Color: detectColor(atty),
Isatty: atty,
Height: h,
Width: w,
}
}

func detectColor(atty bool) bool {
if os.Getenv("NO_COLOR") != "" {
return false
}

if color := os.Getenv("COLOR"); color != "" {
enabled, _ := strconv.ParseBool(color)
return enabled
}

if !atty {
return false
}

return true
}

func (c *capabilities) formatArgs(args []interface{}) []interface{} {
out := make([]interface{}, len(args))
for i, arg := range args {
if _, ok := arg.(Style); ok && !c.Color {
out[i] = ""
} else {
out[i] = arg
}
}
return out
}
7 changes: 7 additions & 0 deletions internal/output/emoji.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package output

// Standard emoji for use in output.
const (
EmojiFailure = "❌"
EmojiSuccess = "✅"
)
49 changes: 49 additions & 0 deletions internal/output/line.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package output

import (
"fmt"
"io"
)

// FancyLine is a formatted output line with an optional emoji and style.
type FancyLine struct {
emoji string
style Style
format string
args []interface{}
}

// Line creates a new FancyLine without a format string.
func Line(emoji string, style Style, s string) FancyLine {
return FancyLine{
emoji: emoji,
style: style,
format: "%s",
args: []interface{}{s},
}
}

// Line creates a new FancyLine with a format string. As with Writer, the
// arguments may include Style instances with the %s specifier.
func Linef(emoji string, style Style, format string, a ...interface{}) FancyLine {
args := make([]interface{}, len(a))
for i := range a {
args[i] = a[i]
}

return FancyLine{
emoji: emoji,
style: style,
format: format,
args: args,
}
}

func (ol FancyLine) write(w io.Writer, caps capabilities) {
if ol.emoji != "" {
fmt.Fprint(w, ol.emoji+" ")
}

fmt.Fprintf(w, "%s"+ol.format+"%s", caps.formatArgs(append(append([]interface{}{ol.style}, ol.args...), StyleReset))...)
w.Write([]byte("\n"))
}
Loading