]> git.refcnt.org Git - colorize.git/blob - colorize.c
Enhance message if color string exists as file
[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 {
407 if (file_string)
408 vfprintf_fail (formats[FMT_GENERIC], "file cannot be used as color string");
409 else
410 vfprintf_fail (formats[FMT_GENERIC], "file must be preceeded by color string");
411 }
412 }
413
414 if ((p = strchr (color_string, '/')))
415 {
416 if (p == color_string)
417 vfprintf_fail (formats[FMT_GENERIC], "foreground color missing");
418 else if (p == color_string + strlen (color_string) - 1)
419 vfprintf_fail (formats[FMT_GENERIC], "background color missing");
420 else if (strchr (++p, '/'))
421 vfprintf_fail (formats[FMT_GENERIC], "one color pair allowed only");
422 }
423
424 str = xstrdup (color_string);
425 STACK_VAR (str);
426
427 for (index = 0, color = str; *color; index++, color = p)
428 {
429 char *ch, *sep;
430 if ((sep = strchr (color, '/')))
431 {
432 *sep = '\0';
433 p = sep + 1;
434 }
435 else
436 p = color + strlen (color);
437
438 for (ch = color; *ch; ch++)
439 if (!isalpha (*ch))
440 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color, "cannot be made of non-alphabetic characters");
441
442 for (ch = color + 1; *ch; ch++)
443 if (!islower (*ch))
444 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color, "cannot be in mixed lower/upper case");
445
446 if (streq (color, "None"))
447 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color, "cannot be bold");
448
449 if (isupper (*color))
450 {
451 switch (index)
452 {
453 case FOREGROUND:
454 *bold = true;
455 break;
456 case BACKGROUND:
457 vfprintf_fail (formats[FMT_COLOR], tables[BACKGROUND].desc, color, "cannot be bold");
458 break;
459 default: /* never reached */
460 ABORT_TRACE ();
461 }
462 }
463
464 color_names[index] = xmalloc (sizeof (struct color_name));
465
466 color_names[index]->orig = xstrdup (color);
467
468 for (ch = color; *ch; ch++)
469 *ch = tolower (*ch);
470
471 color_names[index]->name = xstrdup (color);
472 }
473
474 RELEASE_VAR (str);
475
476 assert (color_names[FOREGROUND]);
477
478 if (color_names[BACKGROUND])
479 {
480 unsigned int i;
481 unsigned int color_sets[2][2] = { { FOREGROUND, BACKGROUND }, { BACKGROUND, FOREGROUND } };
482 for (i = 0; i < 2; i++)
483 {
484 unsigned int color1 = color_sets[i][0];
485 unsigned int color2 = color_sets[i][1];
486 if (CHECK_COLORS_RANDOM (color1, color2))
487 vfprintf_fail (formats[FMT_RANDOM], tables[color1].desc, color_names[color1]->orig, "cannot be combined with", color_names[color2]->orig);
488 }
489 }
490
491 find_color_entries (color_names, colors);
492 free_color_names (color_names);
493
494 if (!colors[FOREGROUND]->code && colors[BACKGROUND] && colors[BACKGROUND]->code)
495 find_color_entry ("default", FOREGROUND, colors);
496
497 if (file_string)
498 {
499 if (streq (file_string, "-"))
500 *stream = stdin;
501 else
502 {
503 FILE *s;
504 const char *file = file_string;
505 struct stat sb;
506 int errno, ret;
507
508 errno = 0;
509 ret = stat (file, &sb);
510
511 if (ret == -1)
512 vfprintf_fail (formats[FMT_FILE], file, strerror (errno));
513
514 if (!(S_ISREG (sb.st_mode) || S_ISLNK (sb.st_mode) || S_ISFIFO (sb.st_mode)))
515 vfprintf_fail (formats[FMT_FILE], file, "unrecognized file type");
516
517 errno = 0;
518
519 s = fopen (file, "r");
520 if (!s)
521 vfprintf_fail (formats[FMT_FILE], file, strerror (errno));
522 *stream = s;
523 }
524 *file = file_string;
525 }
526 else
527 {
528 *stream = stdin;
529 *file = "stdin";
530 }
531
532 assert (*stream);
533 }
534
535 static void
536 read_print_stream (bool bold, const struct color **colors, const char *file, FILE *stream, enum stream_mode mode)
537 {
538 char buf[BUF_SIZE];
539 unsigned int flags = 0;
540 bool first = false, always = false;
541
542 switch (mode)
543 {
544 case SCAN_FIRST:
545 first = true;
546 break;
547 case SCAN_ALWAYS:
548 always = true;
549 break;
550 default: /* never reached */
551 ABORT_TRACE ();
552 }
553
554 while (!feof (stream))
555 {
556 size_t bytes_read;
557 char *eol;
558 const char *line;
559 memset (buf, '\0', BUF_SIZE);
560 bytes_read = fread (buf, 1, BUF_SIZE - 1, stream);
561 if (bytes_read != (BUF_SIZE - 1) && ferror (stream))
562 vfprintf_fail (formats[FMT_ERROR], BUF_SIZE - 1, "read");
563 line = buf;
564 LOOP: while ((eol = strpbrk (line, "\n\r")))
565 {
566 char *p;
567 if (first || always)
568 {
569 first = false;
570 flags &= ~(CR|LF);
571 if (*eol == '\r')
572 {
573 flags |= CR;
574 if (*(eol + 1) == '\n')
575 flags |= LF;
576 }
577 else if (*eol == '\n')
578 flags |= LF;
579 else
580 vfprintf_fail (formats[FMT_FILE], file, "unrecognized line ending");
581 }
582 if (always)
583 p = eol + SKIP_LINE_ENDINGS (flags);
584 else /* first */
585 {
586 unsigned int i;
587 unsigned int count = sizeof (endings) / sizeof (struct ending);
588 for (i = 0; i < count; i++)
589 {
590 if (flags & endings[i].flags)
591 {
592 char *p;
593 if ((p = strstr (eol, endings[i].newline)) && p == eol)
594 break;
595 else
596 {
597 always = true;
598 goto LOOP;
599 }
600 }
601 }
602 p = eol + SKIP_LINE_ENDINGS (flags);
603 }
604 *eol = '\0';
605 print_line (colors, bold, line, flags);
606 line = p;
607 }
608 print_line (colors, bold, line, 0);
609 }
610 }
611
612 static void
613 find_color_entries (struct color_name **color_names, const struct color **colors)
614 {
615 struct timeval tv;
616 unsigned int index;
617
618 /* randomness */
619 gettimeofday (&tv, NULL);
620 srand (tv.tv_usec * tv.tv_sec);
621
622 for (index = 0; color_names[index]; index++)
623 {
624 const char *color_name = color_names[index]->name;
625
626 const unsigned int count = tables[index].count;
627 const struct color *const color_entries = tables[index].entries;
628
629 if (streq (color_name, "random"))
630 {
631 bool excludable;
632 unsigned int i;
633 do {
634 excludable = false;
635 i = rand() % (count - 2) + 1; /* omit color none and default */
636 switch (index)
637 {
638 case FOREGROUND:
639 /* --exclude-random */
640 if (exclude && streq (exclude, color_entries[i].name))
641 excludable = true;
642 else if (color_names[BACKGROUND] && streq (color_names[BACKGROUND]->name, color_entries[i].name))
643 excludable = true;
644 break;
645 case BACKGROUND:
646 if (streq (colors[FOREGROUND]->name, color_entries[i].name))
647 excludable = true;
648 break;
649 default: /* never reached */
650 ABORT_TRACE ();
651 }
652 } while (excludable);
653 colors[index] = (struct color *)&color_entries[i];
654 }
655 else
656 find_color_entry (color_name, index, colors);
657 }
658 }
659
660 static void
661 find_color_entry (const char *const color_name, unsigned int index, const struct color **colors)
662 {
663 bool found = false;
664 unsigned int i;
665
666 const unsigned int count = tables[index].count;
667 const struct color *const color_entries = tables[index].entries;
668
669 for (i = 0; i < count; i++)
670 if (streq (color_name, color_entries[i].name))
671 {
672 colors[index] = (struct color *)&color_entries[i];
673 found = true;
674 break;
675 }
676 if (!found)
677 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color_name, "not recognized");
678 }
679
680 static void
681 print_line (const struct color **colors, bool bold, const char *const line, unsigned int flags)
682 {
683 if (colors[BACKGROUND] && colors[BACKGROUND]->code)
684 printf ("\033[%s", colors[BACKGROUND]->code);
685 if (colors[FOREGROUND]->code)
686 printf ("\033[%s%s%s\033[0m", bold ? "1;" : "", colors[FOREGROUND]->code, line);
687 else
688 printf (formats[FMT_GENERIC], line);
689 if (flags & CR)
690 putchar ('\r');
691 if (flags & LF)
692 putchar ('\n');
693 }
694
695 static void *
696 malloc_wrap (size_t size, const char *file, unsigned int line)
697 {
698 void *p = malloc (size);
699 if (!p)
700 MEM_ALLOC_FAIL (file, line);
701 return p;
702 }
703
704 static void *
705 realloc_wrap (void *ptr, size_t size, const char *file, unsigned int line)
706 {
707 void *p = realloc (ptr, size);
708 if (!p)
709 MEM_ALLOC_FAIL (file, line);
710 return p;
711 }
712
713 static char *
714 strdup_wrap (const char *str, const char *file, unsigned int line)
715 {
716 const unsigned int len = strlen (str) + 1;
717 char *p = malloc (len);
718 if (!p)
719 MEM_ALLOC_FAIL (file, line);
720 strncpy (p, str, len);
721 return p;
722 }
723
724 static void
725 vfprintf_fail (const char *fmt, ...)
726 {
727 va_list ap;
728 fprintf (stderr, "%s: ", program_name);
729 va_start (ap, fmt);
730 vfprintf (stderr, fmt, ap);
731 va_end (ap);
732 fprintf (stderr, "\n");
733 exit (EXIT_FAILURE);
734 }
735
736 static void
737 stack_var (void ***list, unsigned int *stacked, unsigned int index, void *ptr)
738 {
739 /* nothing to stack */
740 if (ptr == NULL)
741 return;
742 if (!*list)
743 *list = xmalloc (sizeof (void *));
744 else
745 {
746 unsigned int i;
747 for (i = 0; i < *stacked; i++)
748 if (!(*list)[i])
749 {
750 (*list)[i] = ptr;
751 return; /* reused */
752 }
753 *list = xrealloc (*list, (*stacked + 1) * sizeof (void *));
754 }
755 (*list)[index] = ptr;
756 (*stacked)++;
757 }
758
759 static void
760 release_var (void **list, unsigned int stacked, void **ptr)
761 {
762 unsigned int i;
763 /* nothing to release */
764 if (*ptr == NULL)
765 return;
766 for (i = 0; i < stacked; i++)
767 if (list[i] == *ptr)
768 {
769 free (*ptr);
770 *ptr = NULL;
771 list[i] = NULL;
772 return;
773 }
774 }