lib/terminal: factor from cmd/progress, swap Azure/go-ansiterm for mattn/go-colorable

This commit is contained in:
Nick Craig-Wood 2019-09-26 21:14:47 +01:00
parent c78d1dd18b
commit 593de059be
4 changed files with 120 additions and 106 deletions

View file

@ -5,7 +5,6 @@ package cmd
import (
"bytes"
"fmt"
"os"
"strings"
"sync"
"time"
@ -13,7 +12,7 @@ import (
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/accounting"
"github.com/rclone/rclone/fs/log"
"golang.org/x/crypto/ssh/terminal"
"github.com/rclone/rclone/lib/terminal"
)
const (
@ -23,34 +22,10 @@ const (
logTimeFormat = "2006-01-02 15:04:05"
)
var (
initTerminal func() error
writeToTerminal func([]byte)
)
// Initialise the VT100 terminal
func initTerminalVT100() error {
return nil
}
// Write to the VT100 terminal
func writeToTerminalVT100(b []byte) {
_, _ = os.Stdout.Write(b)
}
// startProgress starts the progress bar printing
//
// It returns a func which should be called to stop the stats.
func startProgress() func() {
if os.Getenv("TERM") != "" {
initTerminal = initTerminalVT100
writeToTerminal = writeToTerminalVT100
}
err := initTerminal()
if err != nil {
fs.Errorf(nil, "Failed to start progress: %v", err)
return func() {}
}
stopStats := make(chan struct{})
oldLogPrint := fs.LogPrint
if !log.Redirected() {
@ -88,13 +63,6 @@ func startProgress() func() {
}
}
// VT100 codes
const (
eraseLine = "\x1b[2K"
moveToStartOfLine = "\x1b[0G"
moveUp = "\x1b[A"
)
// state for the progress printing
var (
nlines = 0 // number of lines in the previous stats block
@ -107,11 +75,7 @@ func printProgress(logMessage string) {
defer progressMu.Unlock()
var buf bytes.Buffer
w, h, err := terminal.GetSize(int(os.Stdout.Fd()))
if err != nil {
w, h = 80, 25
}
_ = h
w, _ := terminal.GetSize()
stats := strings.TrimSpace(accounting.GlobalStats().String())
logMessage = strings.TrimSpace(logMessage)
@ -121,17 +85,17 @@ func printProgress(logMessage string) {
if logMessage != "" {
out("\n")
out(moveUp)
out(terminal.MoveUp)
}
// Move to the start of the block we wrote erasing all the previous lines
for i := 0; i < nlines-1; i++ {
out(eraseLine)
out(moveUp)
out(terminal.EraseLine)
out(terminal.MoveUp)
}
out(eraseLine)
out(moveToStartOfLine)
out(terminal.EraseLine)
out(terminal.MoveToStartOfLine)
if logMessage != "" {
out(eraseLine)
out(terminal.EraseLine)
out(logMessage + "\n")
}
fixedLines := strings.Split(stats, "\n")
@ -145,5 +109,5 @@ func printProgress(logMessage string) {
out("\n")
}
}
writeToTerminal(buf.Bytes())
terminal.Write(buf.Bytes())
}