Skip to content

Commit ddf3533

Browse files
committed
burl: prevent binary output in terminal
1 parent 607439f commit ddf3533

File tree

3 files changed

+51
-2
lines changed

3 files changed

+51
-2
lines changed

example/client/burl/any_iostream.cpp

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,31 @@
99

1010
#include "any_iostream.hpp"
1111

12+
#ifdef _MSC_VER
13+
#include <io.h>
14+
#else
15+
#include <unistd.h>
16+
#endif
17+
18+
namespace
19+
{
20+
bool
21+
is_stdout_tty()
22+
{
23+
#ifdef _MSC_VER
24+
return _isatty(_fileno(stdout));
25+
#else
26+
return isatty(fileno(stdout));
27+
#endif
28+
}
29+
} // namespace
30+
31+
any_ostream::any_ostream()
32+
: stream_{ &std::cout }
33+
, is_tty_{ ::is_stdout_tty() }
34+
{
35+
}
36+
1237
any_ostream::any_ostream(core::string_view path)
1338
{
1439
if(path == "-")
@@ -29,6 +54,12 @@ any_ostream::any_ostream(core::string_view path)
2954
}
3055
}
3156

57+
bool
58+
any_ostream::is_tty() const noexcept
59+
{
60+
return is_tty_;
61+
}
62+
3263
any_ostream::
3364
operator std::ostream&()
3465
{

example/client/burl/any_iostream.hpp

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,16 @@ namespace core = boost::core;
2121
class any_ostream
2222
{
2323
std::variant<std::ofstream, std::ostream*> stream_;
24+
bool is_tty_ = false;
2425

2526
public:
27+
any_ostream();
28+
2629
any_ostream(core::string_view path);
2730

31+
bool
32+
is_tty() const noexcept;
33+
2834
operator std::ostream&();
2935

3036
template<typename T>

example/client/burl/main.cpp

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -504,8 +504,20 @@ request(
504504
{
505505
for(auto cb : parser.pull_body())
506506
{
507-
body_output << core::string_view{
507+
auto chunk = core::string_view{
508508
static_cast<const char*>(cb.data()), cb.size() };
509+
510+
if(body_output.is_tty() &&
511+
chunk.find(char{0}) != core::string_view::npos)
512+
{
513+
std::cerr <<
514+
"Warning: Binary output can mess up your terminal.\n"
515+
"Warning: Use \"--output -\" to tell burl to output it to your terminal anyway, or\n"
516+
"Warning: consider \"--output <FILE>\" to save to a file.\n";
517+
co_return;
518+
}
519+
520+
body_output << chunk;
509521
parser.consume_body(cb.size());
510522
}
511523

@@ -750,7 +762,7 @@ main(int argc, char* argv[])
750762
{
751763
if(vm.count("output"))
752764
return any_ostream{ vm.at("output").as<std::string>() };
753-
return any_ostream{ "-" };
765+
return any_ostream{};
754766
}();
755767

756768
auto header_output = [&]() -> std::optional<any_ostream>

0 commit comments

Comments
 (0)