Skip to content

Commit df7df27

Browse files
committed
color: take care of handling --[no-]color options
1 parent 44c88ab commit df7df27

File tree

2 files changed

+37
-12
lines changed

2 files changed

+37
-12
lines changed

color.hh

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,4 +46,32 @@ class ColorWriter {
4646
bool enabled_;
4747
};
4848

49+
template <class TOptDesc>
50+
void addColorOptions(TOptDesc *desc) {
51+
desc->add_options()
52+
("color",
53+
"use colorized console output (default if connected to a terminal)")
54+
("no-color",
55+
"do not use colorized console output");
56+
}
57+
58+
template <class TValMap>
59+
bool readColorOptions(EColorMode *pDst, const char **pErr, const TValMap &vm) {
60+
const bool colorAlways = vm.count("color");
61+
const bool colorNever = vm.count("no-color");
62+
if (colorAlways && colorNever) {
63+
*pErr = "options --color and --no-color are mutually exclusive";
64+
return false;
65+
}
66+
67+
if (colorAlways)
68+
*pDst = CM_ALWAYS;
69+
else if (colorNever)
70+
*pDst = CM_NEVER;
71+
else
72+
*pDst = CM_AUTO;
73+
74+
return true;
75+
}
76+
4977
#endif /* H_GUARD_COLOR_H */

csgrep.cc

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -503,10 +503,10 @@ int main(int argc, char *argv[])
503503

504504
("ignore-case,i", "ignore case when matching regular expressions")
505505
("invert-match,v", "select defects that do not match the selected criteria")
506-
("invert-regex,n", "invert regular expressions in all predicates")
506+
("invert-regex,n", "invert regular expressions in all predicates");
507507

508-
("color", "use colorized console output (default if connected to a terminal)")
509-
("no-color", "do not use colorized console output")
508+
addColorOptions(&desc);
509+
desc.add_options()
510510
("quiet,q", "do not report any parsing errors")
511511

512512
("mode", po::value<string>(&mode)
@@ -547,17 +547,14 @@ int main(int argc, char *argv[])
547547
}
548548

549549
// handle --[no-]color options
550-
const bool color_always = vm.count("color");
551-
const bool color_never = vm.count("no-color");
552-
if (color_always && color_never) {
553-
std::cerr << name << ": error: "
554-
"options --color and --no-color are mutually exclusive\n";
550+
EColorMode cm;
551+
const char *err;
552+
if (readColorOptions(&cm, &err, vm))
553+
WriterFactory::setColorMode(cm);
554+
else {
555+
std::cerr << name << ": error: " << err << std::endl;
555556
return 1;
556557
}
557-
if (color_always)
558-
WriterFactory::setColorMode(CM_ALWAYS);
559-
if (color_never)
560-
WriterFactory::setColorMode(CM_NEVER);
561558

562559
// create a writer according to the selected mode
563560
WriterFactory factory;

0 commit comments

Comments
 (0)