Skip to content

Commit

Permalink
color: take care of handling --[no-]color options
Browse files Browse the repository at this point in the history
  • Loading branch information
kdudka committed Dec 18, 2014
1 parent 44c88ab commit df7df27
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 12 deletions.
28 changes: 28 additions & 0 deletions color.hh
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,32 @@ class ColorWriter {
bool enabled_;
};

template <class TOptDesc>
void addColorOptions(TOptDesc *desc) {
desc->add_options()
("color",
"use colorized console output (default if connected to a terminal)")
("no-color",
"do not use colorized console output");
}

template <class TValMap>
bool readColorOptions(EColorMode *pDst, const char **pErr, const TValMap &vm) {
const bool colorAlways = vm.count("color");
const bool colorNever = vm.count("no-color");
if (colorAlways && colorNever) {
*pErr = "options --color and --no-color are mutually exclusive";
return false;
}

if (colorAlways)
*pDst = CM_ALWAYS;
else if (colorNever)
*pDst = CM_NEVER;
else
*pDst = CM_AUTO;

return true;
}

#endif /* H_GUARD_COLOR_H */
21 changes: 9 additions & 12 deletions csgrep.cc
Original file line number Diff line number Diff line change
Expand Up @@ -503,10 +503,10 @@ int main(int argc, char *argv[])

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

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

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

// handle --[no-]color options
const bool color_always = vm.count("color");
const bool color_never = vm.count("no-color");
if (color_always && color_never) {
std::cerr << name << ": error: "
"options --color and --no-color are mutually exclusive\n";
EColorMode cm;
const char *err;
if (readColorOptions(&cm, &err, vm))
WriterFactory::setColorMode(cm);
else {
std::cerr << name << ": error: " << err << std::endl;
return 1;
}
if (color_always)
WriterFactory::setColorMode(CM_ALWAYS);
if (color_never)
WriterFactory::setColorMode(CM_NEVER);

// create a writer according to the selected mode
WriterFactory factory;
Expand Down

0 comments on commit df7df27

Please sign in to comment.