|
| 1 | +package pretty |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "log" |
| 6 | + "os" |
| 7 | + "strings" |
| 8 | + |
| 9 | + "github.com/mohanson/daze/lib/doa" |
| 10 | +) |
| 11 | + |
| 12 | +// PrintProgress draw a progress bar in the terminal. The percent takes values from 0 to 1. |
| 13 | +func PrintProgress(percent float64) { |
| 14 | + doa.Doa(0 <= percent && percent <= 1) |
| 15 | + out, _ := os.Stdout.Stat() |
| 16 | + // Identify if we are displaying to a terminal or through a pipe or redirect. |
| 17 | + if out.Mode()&os.ModeCharDevice == os.ModeCharDevice { |
| 18 | + // Save or restore cursor position. |
| 19 | + if percent == 0 { |
| 20 | + log.Writer().Write([]byte{0x1b, 0x37}) |
| 21 | + } |
| 22 | + if percent != 0 { |
| 23 | + log.Writer().Write([]byte{0x1b, 0x38}) |
| 24 | + } |
| 25 | + } |
| 26 | + cap := int(percent * 44) |
| 27 | + buf := []byte("[ ] 000%") |
| 28 | + for i := 1; i < cap+1; i++ { |
| 29 | + buf[i] = '=' |
| 30 | + } |
| 31 | + buf[1+cap] = '>' |
| 32 | + num := fmt.Sprintf("%3d", int(percent*100)) |
| 33 | + buf[48] = num[0] |
| 34 | + buf[49] = num[1] |
| 35 | + buf[50] = num[2] |
| 36 | + log.Println("pretty:", string(buf)) |
| 37 | +} |
| 38 | + |
| 39 | +// PrintTable easily draw tables in terminal/console applications from a list of lists of strings. |
| 40 | +func PrintTable(data [][]string) { |
| 41 | + size := make([]int, len(data[0])) |
| 42 | + for _, r := range data { |
| 43 | + for j, c := range r { |
| 44 | + size[j] = max(size[j], len(c)) |
| 45 | + } |
| 46 | + } |
| 47 | + line := make([]string, len(data[0])) |
| 48 | + for j, c := range data[0] { |
| 49 | + l := size[j] |
| 50 | + line[j] = strings.Repeat(" ", l-len(c)) + c |
| 51 | + } |
| 52 | + log.Println("pretty:", strings.Join(line, " ")) |
| 53 | + for i, c := range size { |
| 54 | + line[i] = strings.Repeat("-", c) |
| 55 | + } |
| 56 | + log.Println("pretty:", strings.Join(line, "-")) |
| 57 | + for _, r := range data[1:] { |
| 58 | + for j, c := range r { |
| 59 | + l := size[j] |
| 60 | + line[j] = strings.Repeat(" ", l-len(c)) + c |
| 61 | + } |
| 62 | + log.Println("pretty:", strings.Join(line, " ")) |
| 63 | + } |
| 64 | +} |
0 commit comments