]> git.refcnt.org Git - colorize.git/blob - colorize.c
update copyright year and increase version
[colorize.git] / colorize.c
1 /*
2 * colorize - Read text from standard input stream or file and print
3 * it colorized through use of ANSI escape sequences
4 *
5 * Copyright (c) 2011-2013 Steven Schubiger
6 *
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 *
20 */
21
22 #define _POSIX_SOURCE
23 #include <assert.h>
24 #include <ctype.h>
25 #include <errno.h>
26 #include <getopt.h>
27 #include <stdarg.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <sys/time.h>
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <time.h>
35 #include <unistd.h>
36
37 #define DEBUG 0
38
39 #define str(arg) #arg
40 #define to_str(arg) str(arg)
41
42 #define streq(s1, s2) (strcmp (s1, s2) == 0)
43
44 #define xmalloc(size) malloc_wrap(size, __FILE__, __LINE__)
45 #define xrealloc(ptr, size) realloc_wrap(ptr, size, __FILE__, __LINE__)
46 #define xstrdup(str) strdup_wrap(str, __FILE__, __LINE__)
47
48 #if !defined BUF_SIZE || BUF_SIZE <= 0
49 # undef BUF_SIZE
50 # define BUF_SIZE 4096 + 1
51 #endif
52
53 #define LF 0x01
54 #define CR 0x02
55
56 #define SKIP_LINE_ENDINGS(flags) (((flags) & CR) && ((flags) & LF) ? 2 : 1)
57
58 #define STACK_VAR(ptr) do { \
59 stack_var (&vars_list, &stacked_vars, stacked_vars, ptr); \
60 } while (false);
61
62 #define RELEASE_VAR(ptr) do { \
63 release_var (vars_list, stacked_vars, (void **)&ptr); \
64 } while (false);
65
66 #if DEBUG
67 # define MEM_ALLOC_FAIL(file, line) do { \
68 fprintf (stderr, "memory allocation failure in source file %s, line %d\n", file, line); \
69 exit (2); \
70 } while (false);
71 #else
72 # define MEM_ALLOC_FAIL(file, line) do { \
73 fprintf (stderr, "%s: memory allocation failure\n", program_name); \
74 exit (2); \
75 } while (false);
76 #endif
77
78 #define ABORT_TRACE() \
79 fprintf (stderr, "aborting in source file %s, line %d\n", __FILE__, __LINE__); \
80 abort (); \
81
82 #define CHECK_COLORS_RANDOM(color1, color2) \
83 streq (color_names[color1]->name, "random") \
84 && (streq (color_names[color2]->name, "none") \
85 || streq (color_names[color2]->name, "default")) \
86
87 #define VERSION "0.48"
88
89 typedef unsigned short bool;
90
91 enum { false, true };
92
93 struct color_name {
94 char *name;
95 char *orig;
96 };
97
98 static struct color_name *color_names[3] = { NULL, NULL, NULL };
99
100 struct color {
101 const char *name;
102 const char *code;
103 };
104
105 static const struct color fg_colors[] = {
106 { "none", NULL },
107 { "black", "30m" },
108 { "red", "31m" },
109 { "green", "32m" },
110 { "yellow", "33m" },
111 { "blue", "34m" },
112 { "cyan", "35m" },
113 { "magenta", "36m" },
114 { "white", "37m" },
115 { "default", "39m" },
116 };
117 static const struct color bg_colors[] = {
118 { "none", NULL },
119 { "black", "40m" },
120 { "red", "41m" },
121 { "green", "42m" },
122 { "yellow", "43m" },
123 { "blue", "44m" },
124 { "cyan", "45m" },
125 { "magenta", "46m" },
126 { "white", "47m" },
127 { "default", "49m" },
128 };
129
130 enum fmts {
131 FMT_GENERIC,
132 FMT_COLOR,
133 FMT_RANDOM,
134 FMT_ERROR,
135 FMT_FILE
136 };
137 static const char *formats[] = {
138 "%s", /* generic */
139 "%s color '%s' %s", /* color */
140 "%s color '%s' %s '%s'", /* random */
141 "less than %d bytes %s", /* error */
142 "%s: %s", /* file */
143 };
144
145 enum { FOREGROUND, BACKGROUND };
146
147 static const struct {
148 struct color const *entries;
149 unsigned int count;
150 const char *desc;
151 } tables[] = {
152 { fg_colors, sizeof (fg_colors) / sizeof (struct color), "foreground" },
153 { bg_colors, sizeof (bg_colors) / sizeof (struct color), "background" },
154 };
155
156 enum stream_mode { SCAN_FIRST = 1, SCAN_ALWAYS };
157
158 struct ending {
159 unsigned int flags;
160 const char newline[3];
161 };
162
163 static const struct ending endings[] = {
164 { CR & LF, "\r\n" },
165 { CR, "\r" },
166 { LF, "\n" },
167 };
168
169 static FILE *stream = NULL;
170
171 static unsigned int stacked_vars = 0;
172 static void **vars_list = NULL;
173
174 static char *exclude = NULL;
175
176 static const char *program_name;
177
178 static void print_help (void);
179 static void print_version (void);
180 static void cleanup (void);
181 static void free_color_names (struct color_name **);
182 static void process_options (unsigned int, char **, bool *, const struct color **, const char **, FILE **);
183 static void read_print_stream (bool, const struct color **, const char *, FILE *, enum stream_mode);
184 static void find_color_entries (struct color_name **, const struct color **);
185 static void find_color_entry (const char *const, unsigned int, const struct color **);
186 static void print_line (const struct color **, bool, const char * const, unsigned int);
187 static void *malloc_wrap (size_t, const char *, unsigned int);
188 static void *realloc_wrap (void *, size_t, const char *, unsigned int);
189 static char *strdup_wrap (const char *, const char *, unsigned int);
190 static void vfprintf_fail (const char *, ...);
191 static void stack_var (void ***, unsigned int *, unsigned int, void *);
192 static void release_var (void **, unsigned int, void **);
193
194 extern char *optarg;
195 extern int optind;
196
197 int
198 main (int argc, char **argv)
199 {
200 unsigned int arg_cnt = 0;
201
202 bool invalid_opt = false;
203
204 int opt;
205 struct option long_opts[] = {
206 { "exclude-random", required_argument, NULL, 'e' },
207 { "help", no_argument, NULL, 'h' },
208 { "version", no_argument, NULL, 'v' },
209 { 0, 0, 0, 0 },
210 };
211
212 bool bold = false;
213
214 const struct color *colors[2] = {
215 NULL, /* foreground */
216 NULL, /* background */
217 };
218
219 const char *file;
220
221 enum stream_mode mode = SCAN_FIRST;
222
223 program_name = argv[0];
224 atexit (cleanup);
225
226 setvbuf (stdout, NULL, _IOLBF, 0);
227
228 while ((opt = getopt_long (argc, argv, "hv", long_opts, NULL)) != -1)
229 {
230 switch (opt)
231 {
232 case 'e': {
233 char *p;
234 exclude = xstrdup (optarg);
235 STACK_VAR (exclude);
236 for (p = exclude; *p; p++)
237 *p = tolower (*p);
238 if (streq (exclude, "random"))
239 vfprintf_fail (formats[FMT_GENERIC], "--exclude-random switch must be provided a color");
240 break;
241 }
242 case 'h':
243 print_help ();
244 exit (EXIT_SUCCESS);
245 case 'v':
246 print_version ();
247 exit (EXIT_SUCCESS);
248 case '?':
249 invalid_opt = true;
250 break;
251 default: /* never reached */
252 ABORT_TRACE ();
253 }
254 }
255
256 arg_cnt = argc - optind;
257
258 if (arg_cnt == 0 || arg_cnt > 2 || invalid_opt)
259 {
260 print_help ();
261 exit (EXIT_FAILURE);
262 }
263
264 process_options (arg_cnt, &argv[optind], &bold, colors, &file, &stream);
265 read_print_stream (bold, colors, file, stream, mode);
266
267 RELEASE_VAR (exclude);
268
269 exit (EXIT_SUCCESS);
270 }
271
272 static void
273 print_help (void)
274 {
275 unsigned int i;
276
277 printf ("Usage: %s (foreground) OR (foreground)/(background) [-|file]\n\n", program_name);
278 printf ("\tColors (foreground) (background)\n");
279 for (i = 0; i < tables[FOREGROUND].count; i++)
280 {
281 const struct color *entry = &tables[FOREGROUND].entries[i];
282 const char *name = entry->name;
283 const char *code = entry->code;
284 if (code)
285 printf ("\t\t{\033[%s#\033[0m} [%c%c]%s%*s%s\n",
286 code, toupper (*name), *name, name + 1, 10 - (int)strlen (name), " ", name);
287 else
288 printf ("\t\t{-} %s%*s%s\n", name, 13 - (int)strlen (name), " ", name);
289 }
290 printf ("\t\t{*} [Rr]%s%*s%s [--exclude-random=<foreground color>]\n", "andom", 10 - (int)strlen ("random"), " ", "random");
291
292 printf ("\n\tFirst character of color name in upper case denotes increased intensity,\n");
293 printf ("\twhereas for lower case colors will be of normal intensity.\n");
294
295 printf ("\n\tOptions\n");
296 printf ("\t\t-h, --help\n");
297 printf ("\t\t-v, --version\n\n");
298 }
299
300 static void
301 print_version (void)
302 {
303 const char *c_flags;
304 printf ("%s v%s (compiled at %s, %s)\n", "colorize", VERSION, __DATE__, __TIME__);
305 #ifdef CFLAGS
306 c_flags = to_str (CFLAGS);
307 #else
308 c_flags = "unknown";
309 #endif
310 printf ("Compiler flags: %s\n", c_flags);
311 printf ("Buffer size: %d bytes\n", BUF_SIZE - 1);
312 }
313
314 static void
315 cleanup (void)
316 {
317 free_color_names (color_names);
318
319 if (stream && fileno (stream) != STDIN_FILENO)
320 fclose (stream);
321
322 if (vars_list)
323 {
324 unsigned int i;
325 for (i = 0; i < stacked_vars; i++)
326 if (vars_list[i])
327 {
328 free (vars_list[i]);
329 vars_list[i] = NULL;
330 }
331 free (vars_list);
332 vars_list = NULL;
333 }
334 }
335
336 static void
337 free_color_names (struct color_name **color_names)
338 {
339 unsigned int i;
340 for (i = 0; color_names[i]; i++)
341 {
342 free (color_names[i]->name);
343 color_names[i]->name = NULL;
344 free (color_names[i]->orig);
345 color_names[i]->orig = NULL;
346 free (color_names[i]);
347 color_names[i] = NULL;
348 }
349 }
350
351 static void
352 process_options (unsigned int arg_cnt, char **option_strings, bool *bold, const struct color **colors, const char **file, FILE **stream)
353 {
354 int ret;
355 unsigned int index;
356 char *color, *p, *str;
357 struct stat sb;
358
359 const char *color_string = arg_cnt >= 1 ? option_strings[0] : NULL;
360 const char *file_string = arg_cnt == 2 ? option_strings[1] : NULL;
361
362 assert (color_string);
363
364 if (streq (color_string, "-"))
365 {
366 if (file_string)
367 vfprintf_fail (formats[FMT_GENERIC], "hyphen cannot be used as color string");
368 else
369 vfprintf_fail (formats[FMT_GENERIC], "hyphen must be preceeded by color string");
370 }
371
372 ret = stat (color_string, &sb);
373
374 /* Ensure that we don't fail if there's a file with one or more
375 color names in its path. */
376 if (ret != -1)
377 {
378 bool have_file;
379 unsigned int c;
380 const char *color = color_string;
381
382 for (c = 1; c <= 2 && *color; c++)
383 {
384 bool matched = false;
385 unsigned int i;
386 for (i = 0; i < tables[FOREGROUND].count; i++)
387 {
388 const struct color *entry = &tables[FOREGROUND].entries[i];
389 char *p;
390 if ((p = strstr (color, entry->name)) && p == color)
391 {
392 color = p + strlen (entry->name);
393 matched = true;
394 break;
395 }
396 }
397 if (matched && *color == '/' && *(color + 1))
398 color++;
399 else
400 break;
401 }
402
403 have_file = (*color != '\0');
404
405 if (have_file)
406 vfprintf_fail (formats[FMT_GENERIC], "file must be preceeded by color string");
407 }
408
409 if ((p = strchr (color_string, '/')))
410 {
411 if (p == color_string)
412 vfprintf_fail (formats[FMT_GENERIC], "foreground color missing");
413 else if (p == color_string + strlen (color_string) - 1)
414 vfprintf_fail (formats[FMT_GENERIC], "background color missing");
415 else if (strchr (++p, '/'))
416 vfprintf_fail (formats[FMT_GENERIC], "one color pair allowed only");
417 }
418
419 str = xstrdup (color_string);
420 STACK_VAR (str);
421
422 for (index = 0, color = str; *color; index++, color = p)
423 {
424 char *ch, *sep;
425 if ((sep = strchr (color, '/')))
426 {
427 *sep = '\0';
428 p = sep + 1;
429 }
430 else
431 p = color + strlen (color);
432
433 for (ch = color; *ch; ch++)
434 if (!isalpha (*ch))
435 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color, "cannot be made of non-alphabetic characters");
436
437 for (ch = color + 1; *ch; ch++)
438 if (!islower (*ch))
439 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color, "cannot be in mixed lower/upper case");
440
441 if (streq (color, "None"))
442 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color, "cannot be bold");
443
444 if (isupper (*color))
445 {
446 switch (index)
447 {
448 case FOREGROUND:
449 *bold = true;
450 break;
451 case BACKGROUND:
452 vfprintf_fail (formats[FMT_COLOR], tables[BACKGROUND].desc, color, "cannot be bold");
453 break;
454 default: /* never reached */
455 ABORT_TRACE ();
456 }
457 }
458
459 color_names[index] = xmalloc (sizeof (struct color_name));
460
461 color_names[index]->orig = xstrdup (color);
462
463 for (ch = color; *ch; ch++)
464 *ch = tolower (*ch);
465
466 color_names[index]->name = xstrdup (color);
467 }
468
469 RELEASE_VAR (str);
470
471 assert (color_names[FOREGROUND]);
472
473 if (color_names[BACKGROUND])
474 {
475 unsigned int i;
476 unsigned int color_sets[2][2] = { { FOREGROUND, BACKGROUND }, { BACKGROUND, FOREGROUND } };
477 for (i = 0; i < 2; i++)
478 {
479 unsigned int color1 = color_sets[i][0];
480 unsigned int color2 = color_sets[i][1];
481 if (CHECK_COLORS_RANDOM (color1, color2))
482 vfprintf_fail (formats[FMT_RANDOM], tables[color1].desc, color_names[color1]->orig, "cannot be combined with", color_names[color2]->orig);
483 }
484 }
485
486 find_color_entries (color_names, colors);
487 free_color_names (color_names);
488
489 if (!colors[FOREGROUND]->code && colors[BACKGROUND] && colors[BACKGROUND]->code)
490 find_color_entry ("default", FOREGROUND, colors);
491
492 if (file_string)
493 {
494 if (streq (file_string, "-"))
495 *stream = stdin;
496 else
497 {
498 FILE *s;
499 const char *file = file_string;
500 struct stat sb;
501 int errno, ret;
502
503 errno = 0;
504 ret = stat (file, &sb);
505
506 if (ret == -1)
507 vfprintf_fail (formats[FMT_FILE], file, strerror (errno));
508
509 if (!(S_ISREG (sb.st_mode) || S_ISLNK (sb.st_mode) || S_ISFIFO (sb.st_mode)))
510 vfprintf_fail (formats[FMT_FILE], file, "unrecognized file type");
511
512 errno = 0;
513
514 s = fopen (file, "r");
515 if (!s)
516 vfprintf_fail (formats[FMT_FILE], file, strerror (errno));
517 *stream = s;
518 }
519 *file = file_string;
520 }
521 else
522 {
523 *stream = stdin;
524 *file = "stdin";
525 }
526
527 assert (*stream);
528 }
529
530 static void
531 read_print_stream (bool bold, const struct color **colors, const char *file, FILE *stream, enum stream_mode mode)
532 {
533 char buf[BUF_SIZE];
534 unsigned int flags = 0;
535 bool first = false, always = false;
536
537 switch (mode)
538 {
539 case SCAN_FIRST:
540 first = true;
541 break;
542 case SCAN_ALWAYS:
543 always = true;
544 break;
545 default: /* never reached */
546 ABORT_TRACE ();
547 }
548
549 while (!feof (stream))
550 {
551 size_t bytes_read;
552 char *eol;
553 const char *line;
554 memset (buf, '\0', BUF_SIZE);
555 bytes_read = fread (buf, 1, BUF_SIZE - 1, stream);
556 if (bytes_read != (BUF_SIZE - 1) && ferror (stream))
557 vfprintf_fail (formats[FMT_ERROR], BUF_SIZE - 1, "read");
558 line = buf;
559 LOOP: while ((eol = strpbrk (line, "\n\r")))
560 {
561 char *p;
562 if (first || always)
563 {
564 first = false;
565 flags &= ~(CR|LF);
566 if (*eol == '\r')
567 {
568 flags |= CR;
569 if (*(eol + 1) == '\n')
570 flags |= LF;
571 }
572 else if (*eol == '\n')
573 flags |= LF;
574 else
575 vfprintf_fail (formats[FMT_FILE], file, "unrecognized line ending");
576 }
577 if (always)
578 p = eol + SKIP_LINE_ENDINGS (flags);
579 else /* first */
580 {
581 unsigned int i;
582 unsigned int count = sizeof (endings) / sizeof (struct ending);
583 for (i = 0; i < count; i++)
584 {
585 if (flags & endings[i].flags)
586 {
587 char *p;
588 if ((p = strstr (eol, endings[i].newline)) && p == eol)
589 break;
590 else
591 {
592 always = true;
593 goto LOOP;
594 }
595 }
596 }
597 p = eol + SKIP_LINE_ENDINGS (flags);
598 }
599 *eol = '\0';
600 print_line (colors, bold, line, flags);
601 line = p;
602 }
603 print_line (colors, bold, line, 0);
604 }
605 }
606
607 static void
608 find_color_entries (struct color_name **color_names, const struct color **colors)
609 {
610 struct timeval tv;
611 unsigned int index;
612
613 /* randomness */
614 gettimeofday (&tv, NULL);
615 srand (tv.tv_usec * tv.tv_sec);
616
617 for (index = 0; color_names[index]; index++)
618 {
619 const char *color_name = color_names[index]->name;
620
621 const unsigned int count = tables[index].count;
622 const struct color *const color_entries = tables[index].entries;
623
624 if (streq (color_name, "random"))
625 {
626 bool excludable;
627 unsigned int i;
628 do {
629 excludable = false;
630 i = rand() % (count - 2) + 1; /* omit color none and default */
631 switch (index)
632 {
633 case FOREGROUND:
634 /* --exclude-random */
635 if (exclude && streq (exclude, color_entries[i].name))
636 excludable = true;
637 else if (color_names[BACKGROUND] && streq (color_names[BACKGROUND]->name, color_entries[i].name))
638 excludable = true;
639 break;
640 case BACKGROUND:
641 if (streq (colors[FOREGROUND]->name, color_entries[i].name))
642 excludable = true;
643 break;
644 default: /* never reached */
645 ABORT_TRACE ();
646 }
647 } while (excludable);
648 colors[index] = (struct color *)&color_entries[i];
649 }
650 else
651 find_color_entry (color_name, index, colors);
652 }
653 }
654
655 static void
656 find_color_entry (const char *const color_name, unsigned int index, const struct color **colors)
657 {
658 bool found = false;
659 unsigned int i;
660
661 const unsigned int count = tables[index].count;
662 const struct color *const color_entries = tables[index].entries;
663
664 for (i = 0; i < count; i++)
665 if (streq (color_name, color_entries[i].name))
666 {
667 colors[index] = (struct color *)&color_entries[i];
668 found = true;
669 break;
670 }
671 if (!found)
672 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color_name, "not recognized");
673 }
674
675 static void
676 print_line (const struct color **colors, bool bold, const char *const line, unsigned int flags)
677 {
678 if (colors[BACKGROUND] && colors[BACKGROUND]->code)
679 printf ("\033[%s", colors[BACKGROUND]->code);
680 if (colors[FOREGROUND]->code)
681 printf ("\033[%s%s%s\033[0m", bold ? "1;" : "", colors[FOREGROUND]->code, line);
682 else
683 printf (formats[FMT_GENERIC], line);
684 if (flags & CR)
685 putchar ('\r');
686 if (flags & LF)
687 putchar ('\n');
688 }
689
690 static void *
691 malloc_wrap (size_t size, const char *file, unsigned int line)
692 {
693 void *p = malloc (size);
694 if (!p)
695 MEM_ALLOC_FAIL (file, line);
696 return p;
697 }
698
699 static void *
700 realloc_wrap (void *ptr, size_t size, const char *file, unsigned int line)
701 {
702 void *p = realloc (ptr, size);
703 if (!p)
704 MEM_ALLOC_FAIL (file, line);
705 return p;
706 }
707
708 static char *
709 strdup_wrap (const char *str, const char *file, unsigned int line)
710 {
711 const unsigned int len = strlen (str) + 1;
712 char *p = malloc (len);
713 if (!p)
714 MEM_ALLOC_FAIL (file, line);
715 strncpy (p, str, len);
716 return p;
717 }
718
719 static void
720 vfprintf_fail (const char *fmt, ...)
721 {
722 va_list ap;
723 fprintf (stderr, "%s: ", program_name);
724 va_start (ap, fmt);
725 vfprintf (stderr, fmt, ap);
726 va_end (ap);
727 fprintf (stderr, "\n");
728 exit (EXIT_FAILURE);
729 }
730
731 static void
732 stack_var (void ***list, unsigned int *stacked, unsigned int index, void *ptr)
733 {
734 /* nothing to stack */
735 if (ptr == NULL)
736 return;
737 if (!*list)
738 *list = xmalloc (sizeof (void *));
739 else
740 {
741 unsigned int i;
742 for (i = 0; i < *stacked; i++)
743 if (!(*list)[i])
744 {
745 (*list)[i] = ptr;
746 return; /* reused */
747 }
748 *list = xrealloc (*list, (*stacked + 1) * sizeof (void *));
749 }
750 (*list)[index] = ptr;
751 (*stacked)++;
752 }
753
754 static void
755 release_var (void **list, unsigned int stacked, void **ptr)
756 {
757 unsigned int i;
758 /* nothing to release */
759 if (*ptr == NULL)
760 return;
761 for (i = 0; i < stacked; i++)
762 if (list[i] == *ptr)
763 {
764 free (*ptr);
765 *ptr = NULL;
766 list[i] = NULL;
767 return;
768 }
769 }