From 416ab13b14cfae108286121463baaec46aa85738 Mon Sep 17 00:00:00 2001 From: Patrick Shriwise Date: Mon, 29 Oct 2018 23:00:25 -0500 Subject: [PATCH] Adding check for redirect and non-terminal calls. --- src/progress_bar.cpp | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/src/progress_bar.cpp b/src/progress_bar.cpp index 7231b2098..6af9c698f 100644 --- a/src/progress_bar.cpp +++ b/src/progress_bar.cpp @@ -5,8 +5,26 @@ #include #include +#ifdef UNIX +#include +#endif + #define BAR_WIDTH 72 +#ifdef UNIX +int check_isatty(int fd) { + return isatty(fd); +} +#endif + +bool is_terminal() { +#ifdef UNIX + return check_isatty(STDOUT_FILENO) != 0; +#else + return false; +#endif +} + ProgressBar::ProgressBar() { bar = ""; set_value(0.0); @@ -14,6 +32,9 @@ ProgressBar::ProgressBar() { void ProgressBar::set_value(double val) { + + if (!is_terminal()) return; + // set the bar percentage if (val >= 100.0) { bar.append("100"); @@ -28,19 +49,19 @@ ProgressBar::set_value(double val) { bar.append("% |"); // remaining width of the bar - int remain = BAR_WIDTH - bar.size() - 1; + int remain = BAR_WIDTH - bar.size() - 2; // set the bar width if (val >= 100.0) { bar.append(remain, '='); } else { - int width = (int)(65*val/100); + int width = (int)((double)remain*val/100); bar.append(width, '='); bar.append(1, '>'); bar.append(remain-width-1, ' '); } - bar.append("|"); + bar.append("|+"); // write the bar std::cout << '\r' << bar << std::flush;