1
0
Fork 0
mirror of https://github.com/restic/restic.git synced 2024-12-21 23:33:03 +00:00

termstatus: Fix panic for non-terminal runs

Closes #1803
This commit is contained in:
Alexander Neumann 2018-05-27 12:51:42 +02:00
parent 4bf07a74a0
commit 7d9642523b
2 changed files with 48 additions and 6 deletions

View file

@ -290,6 +290,20 @@ func (t *Terminal) Errorf(msg string, args ...interface{}) {
t.Error(s)
}
// truncate returns a string that has at most maxlen characters. If maxlen is
// negative, the empty string is returned.
func truncate(s string, maxlen int) string {
if maxlen < 0 {
return ""
}
if len(s) < maxlen {
return s
}
return s[:maxlen]
}
// SetStatus updates the status lines.
func (t *Terminal) SetStatus(lines []string) {
if len(lines) == 0 {
@ -297,7 +311,7 @@ func (t *Terminal) SetStatus(lines []string) {
}
width, _, err := getTermSize(t.fd)
if err != nil || width < 0 {
if err != nil || width <= 0 {
// use 80 columns by default
width = 80
}
@ -305,11 +319,7 @@ func (t *Terminal) SetStatus(lines []string) {
// make sure that all lines have a line break and are not too long
for i, line := range lines {
line = strings.TrimRight(line, "\n")
if len(line) >= width-2 {
line = line[:width-2]
}
line += "\n"
line = truncate(line, width-2) + "\n"
lines[i] = line
}

View file

@ -0,0 +1,32 @@
package termstatus
import "testing"
func TestTruncate(t *testing.T) {
var tests = []struct {
input string
maxlen int
output string
}{
{"", 80, ""},
{"", 0, ""},
{"", -1, ""},
{"foo", 80, "foo"},
{"foo", 4, "foo"},
{"foo", 3, "foo"},
{"foo", 2, "fo"},
{"foo", 1, "f"},
{"foo", 0, ""},
{"foo", -1, ""},
}
for _, test := range tests {
t.Run("", func(t *testing.T) {
out := truncate(test.input, test.maxlen)
if out != test.output {
t.Fatalf("wrong output for input %v, maxlen %d: want %q, got %q",
test.input, test.maxlen, test.output, out)
}
})
}
}