disable colorization on !tty devices, add option to force colorization

This commit is contained in:
Peter 2011-06-05 20:35:15 +02:00
parent c2d7f27220
commit 7d52ed25be
1 changed files with 39 additions and 5 deletions

View File

@ -4,6 +4,9 @@
// file io lib
#include <stdio.h>
// getopt is used to check for the --color-flag
#include <getopt.h>
// zlib compression is used inside the pbf blobs
#include <zlib.h>
@ -13,6 +16,9 @@
// this is the header to pbf format
#include <osmpbf/osmpbf.h>
// 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)) {