From 7d52ed25beb2c368cfc2f0977f06a5c4e70ece1e Mon Sep 17 00:00:00 2001 From: Peter Date: Sun, 5 Jun 2011 20:35:15 +0200 Subject: [PATCH] disable colorization on !tty devices, add option to force colorization --- tools/osmpbf-outline.cpp | 44 +++++++++++++++++++++++++++++++++++----- 1 file changed, 39 insertions(+), 5 deletions(-) diff --git a/tools/osmpbf-outline.cpp b/tools/osmpbf-outline.cpp index 4094e73..4fe50dc 100644 --- a/tools/osmpbf-outline.cpp +++ b/tools/osmpbf-outline.cpp @@ -4,6 +4,9 @@ // file io lib #include +// getopt is used to check for the --color-flag +#include + // zlib compression is used inside the pbf blobs #include @@ -13,6 +16,9 @@ // this is the header to pbf format #include +// should the output use color? +bool usecolor = false; + // buffer for reading a compressed blob from file char buffer[OSMPBF::max_uncompressed_blob_size]; @@ -33,9 +39,15 @@ OSMPBF::PrimitiveBlock primblock; // prints a formatted message to stdout, optionally color coded void msg(const char* format, int color, va_list args) { - fprintf(stdout, "\x1b[0;%dm", color); + if(usecolor) { + fprintf(stdout, "\x1b[0;%dm", color); + } vfprintf(stdout, format, args); - fprintf(stdout, "\x1b[0m\n"); + if(usecolor) { + fprintf(stdout, "\x1b[0m\n"); + } else { + fprintf(stdout, "\n"); + } } // prints a formatted message to stderr, color coded to red @@ -73,12 +85,34 @@ void debug(const char* format, ...) { // application main method int main(int argc, char *argv[]) { + // check if the output is a tty so we can use colors + usecolor = isatty(1); + + static struct option long_options[] = { + {"color", no_argument, 0, 'c'}, + }; + + while (1) { + int c = getopt_long(argc, argv, "c", long_options, 0); + + if (c == -1) + break; + + switch (c) { + case 'c': + usecolor = true; + break; + default: + exit(1); + } + } + // check for proper command line args - if(argc != 2) - err("usage: %s file.osm.pbf", argv[0]); + if(optind != argc-1) + err("usage: %s [--color] file.osm.pbf", argv[0]); // open specified file - FILE *fp = fopen(argv[1], "r"); + FILE *fp = fopen(argv[optind], "r"); // read while the file has not reached its end while(!feof(fp)) {