[lxc-devel] [lxd/master] lxc/progress: Add terminal detection
stgraber on Github
lxc-bot at linuxcontainers.org
Tue Oct 9 17:24:00 UTC 2018
A non-text attachment was scrubbed...
Name: not available
Type: text/x-mailbox
Size: 404 bytes
Desc: not available
URL: <http://lists.linuxcontainers.org/pipermail/lxc-devel/attachments/20181009/19363af2/attachment.bin>
-------------- next part --------------
From 35366b7413d37a6118a0fc3d23f90ed94866db78 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Graber?= <stgraber at ubuntu.com>
Date: Tue, 9 Oct 2018 13:21:24 -0400
Subject: [PATCH] lxc/progress: Add terminal detection
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Closes: https://github.com/lxc/lxc/issues/2683
Signed-off-by: Stéphane Graber <stgraber at ubuntu.com>
---
lxc/utils/progress.go | 40 ++++++++++++++++++++++++++++++++++++++++
1 file changed, 40 insertions(+)
diff --git a/lxc/utils/progress.go b/lxc/utils/progress.go
index 3b5ebcf48d..13f1eef689 100644
--- a/lxc/utils/progress.go
+++ b/lxc/utils/progress.go
@@ -2,12 +2,14 @@ package utils
import (
"fmt"
+ "os"
"strings"
"sync"
"time"
"github.com/lxc/lxd/shared/api"
"github.com/lxc/lxd/shared/ioprogress"
+ "github.com/lxc/lxd/shared/termios"
)
// ProgressRenderer tracks the progress information
@@ -19,6 +21,22 @@ type ProgressRenderer struct {
wait time.Time
done bool
lock sync.Mutex
+ terminal int
+}
+
+func (p *ProgressRenderer) truncate(msg string) string {
+ width, _, err := termios.GetSize(int(os.Stdout.Fd()))
+ if err != nil {
+ return msg
+ }
+
+ newSize := len(msg)
+ if width < newSize {
+ newSize = width
+ }
+
+ msg = msg[0:newSize]
+ return msg
}
// Done prints the final status and prevents any update
@@ -45,6 +63,9 @@ func (p *ProgressRenderer) Done(msg string) {
return
}
+ // Truncate msg to terminal length
+ msg = p.truncate(msg)
+
// Print the new message
if msg != "" {
msg += "\n"
@@ -82,6 +103,19 @@ func (p *ProgressRenderer) Update(status string) {
return
}
+ // Skip status updates when not dealing with a terminal
+ if p.terminal == 0 {
+ if !termios.IsTerminal(int(os.Stdout.Fd())) {
+ p.terminal = -1
+ }
+
+ p.terminal = 1
+ }
+
+ if p.terminal != 1 {
+ return
+ }
+
// Print the new message
msg := "%s"
if p.Format != "" {
@@ -90,6 +124,9 @@ func (p *ProgressRenderer) Update(status string) {
msg = fmt.Sprintf("\r"+msg, status)
+ // Truncate msg to terminal length
+ msg = p.truncate(msg)
+
if len(msg) > p.maxLength {
p.maxLength = len(msg)
} else {
@@ -114,6 +151,9 @@ func (p *ProgressRenderer) Warn(status string, timeout time.Duration) {
p.wait = time.Now().Add(timeout)
msg := fmt.Sprintf("\r%s", status)
+ // Truncate msg to terminal length
+ msg = p.truncate(msg)
+
if len(msg) > p.maxLength {
p.maxLength = len(msg)
} else {
More information about the lxc-devel
mailing list