Skip to content

Commit 3328e1f

Browse files
fix: Handle non-TTY output for progress bar (#405)
1 parent e842090 commit 3328e1f

File tree

2 files changed

+20
-5
lines changed

2 files changed

+20
-5
lines changed

indexer/ProgressReporter.cc

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#include <cmath>
22
#include <cstdint>
3+
#include <filesystem>
34
#include <iostream>
45
#include <ostream>
56
#include <string_view>
@@ -12,12 +13,20 @@ namespace scip_clang {
1213

1314
ProgressReporter::ProgressReporter(bool active, std::string_view msg,
1415
size_t totalCount)
15-
: message(msg), totalCount(totalCount), countWidth(), active(active) {
16+
: message(msg), totalCount(totalCount), countWidth(), active(active),
17+
isTty(false) {
1618
if (this->totalCount == 0) {
1719
countWidth = 1;
1820
} else {
1921
countWidth = std::log10(double(this->totalCount)) + 1;
2022
}
23+
#if __linux__ || __APPLE__
24+
std::error_code ec;
25+
auto status = std::filesystem::status("/dev/stdout", ec);
26+
if (!ec) {
27+
this->isTty = (status.type() == std::filesystem::file_type::character);
28+
}
29+
#endif
2130
}
2231

2332
void ProgressReporter::report(size_t count, std::string_view extraData) const {
@@ -26,14 +35,19 @@ void ProgressReporter::report(size_t count, std::string_view extraData) const {
2635
}
2736
int maxExtraWidth = 256;
2837
auto backspaceCount = std::max(maxExtraWidth - int(extraData.size()), 0);
29-
fmt::print("\r[{1:>{0}}/{2:>{0}}] {3} {4:<{5}}{6:\b<{7}}", countWidth, count,
30-
this->totalCount, this->message, extraData, maxExtraWidth, "",
31-
backspaceCount);
38+
if (this->isTty) {
39+
fmt::print("\r[{1:>{0}}/{2:>{0}}] {3} {4:<{5}}{6:\b<{7}}", countWidth,
40+
count, this->totalCount, this->message, extraData, maxExtraWidth,
41+
"", backspaceCount);
42+
} else {
43+
fmt::print("[{1:>{0}}/{2:>{0}}] {3} {4}\n", countWidth, count,
44+
this->totalCount, this->message, extraData);
45+
}
3246
std::flush(std::cout);
3347
}
3448

3549
ProgressReporter::~ProgressReporter() {
36-
if (this->active) {
50+
if (this->active && this->isTty) {
3751
fmt::print("\n");
3852
}
3953
}

indexer/ProgressReporter.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ class ProgressReporter {
1111
size_t totalCount;
1212
size_t countWidth;
1313
bool active;
14+
bool isTty;
1415

1516
public:
1617
ProgressReporter(bool active, std::string_view msg, size_t totalCount);

0 commit comments

Comments
 (0)