]> git.refcnt.org Git - colorize.git/blob - colorize.c
Quote color string in error messages
[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-2014 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 _BSD_SOURCE
23 #define _XOPEN_SOURCE 700
24 #include <assert.h>
25 #include <ctype.h>
26 #include <errno.h>
27 #include <getopt.h>
28 #include <stdarg.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <sys/time.h>
33 #include <sys/types.h>
34 #include <sys/stat.h>
35 #include <time.h>
36 #include <unistd.h>
37
38 #ifndef DEBUG
39 # define DEBUG 0
40 #endif
41
42 #define str(arg) #arg
43 #define to_str(arg) str(arg)
44
45 #define streq(s1, s2) (strcmp (s1, s2) == 0)
46
47 #if DEBUG
48 # define xmalloc(size) malloc_wrap_debug(size, __FILE__, __LINE__)
49 # define xcalloc(nmemb, size) calloc_wrap_debug(nmemb, size, __FILE__, __LINE__)
50 # define xrealloc(ptr, size) realloc_wrap_debug(ptr, size, __FILE__, __LINE__)
51 #else
52 # define xmalloc(size) malloc_wrap(size)
53 # define xcalloc(nmemb, size) calloc_wrap(nmemb, size)
54 # define xrealloc(ptr, size) realloc_wrap(ptr, size)
55 #endif
56
57 #define free_null(ptr) free_wrap((void **)&ptr)
58 #define xstrdup(str) strdup_wrap(str)
59
60 #if BUF_SIZE <= 0
61 # undef BUF_SIZE
62 #endif
63 #ifndef BUF_SIZE
64 # define BUF_SIZE 4096
65 #endif
66
67 #define LF 0x01
68 #define CR 0x02
69
70 #define SKIP_LINE_ENDINGS(flags) (((flags) & CR) && ((flags) & LF) ? 2 : 1)
71
72 #define VALID_FILE_TYPE(mode) (S_ISREG (mode) || S_ISLNK (mode) || S_ISFIFO (mode))
73
74 #define STACK_VAR(ptr) do { \
75 stack_var (&vars_list, &stacked_vars, stacked_vars, ptr); \
76 } while (false)
77
78 #define RELEASE_VAR(ptr) do { \
79 release_var (vars_list, stacked_vars, (void **)&ptr); \
80 } while (false)
81
82 #define MEM_ALLOC_FAIL_DEBUG(file, line) do { \
83 fprintf (stderr, "Memory allocation failure in source file %s, line %u\n", file, line); \
84 exit (2); \
85 } while (false)
86 #define MEM_ALLOC_FAIL() do { \
87 fprintf (stderr, "%s: memory allocation failure\n", program_name); \
88 exit (2); \
89 } while (false)
90
91 #define ABORT_TRACE() \
92 fprintf (stderr, "Aborting in source file %s, line %u\n", __FILE__, __LINE__); \
93 abort (); \
94
95 #define CHECK_COLORS_RANDOM(color1, color2) \
96 streq (color_names[color1]->name, "random") \
97 && (streq (color_names[color2]->name, "none") \
98 || streq (color_names[color2]->name, "default")) \
99
100 #define COLOR_SEP_CHAR '/'
101
102 #define VERSION "0.53"
103
104 typedef enum { false, true } bool;
105
106 struct color_name {
107 char *name;
108 char *orig;
109 };
110
111 static struct color_name *color_names[3] = { NULL, NULL, NULL };
112
113 struct color {
114 const char *name;
115 const char *code;
116 };
117
118 static const struct color fg_colors[] = {
119 { "none", NULL },
120 { "black", "30m" },
121 { "red", "31m" },
122 { "green", "32m" },
123 { "yellow", "33m" },
124 { "blue", "34m" },
125 { "magenta", "35m" },
126 { "cyan", "36m" },
127 { "white", "37m" },
128 { "default", "39m" },
129 };
130 static const struct color bg_colors[] = {
131 { "none", NULL },
132 { "black", "40m" },
133 { "red", "41m" },
134 { "green", "42m" },
135 { "yellow", "43m" },
136 { "blue", "44m" },
137 { "magenta", "45m" },
138 { "cyan", "46m" },
139 { "white", "47m" },
140 { "default", "49m" },
141 };
142
143 enum fmts {
144 FMT_GENERIC,
145 FMT_STRING,
146 FMT_QUOTE,
147 FMT_COLOR,
148 FMT_RANDOM,
149 FMT_ERROR,
150 FMT_FILE,
151 FMT_TYPE
152 };
153 static const char *formats[] = {
154 "%s", /* generic */
155 "%s '%s'", /* string */
156 "%s `%s' %s", /* quote */
157 "%s color '%s' %s", /* color */
158 "%s color '%s' %s '%s'", /* random */
159 "less than %u bytes %s", /* error */
160 "%s: %s", /* file */
161 "%s: %s: %s", /* type */
162 };
163
164 enum { FOREGROUND, BACKGROUND };
165
166 static const struct {
167 struct color const *entries;
168 unsigned int count;
169 const char *desc;
170 } tables[] = {
171 { fg_colors, sizeof (fg_colors) / sizeof (struct color), "foreground" },
172 { bg_colors, sizeof (bg_colors) / sizeof (struct color), "background" },
173 };
174
175 static FILE *stream = NULL;
176
177 static unsigned int stacked_vars = 0;
178 static void **vars_list = NULL;
179
180 static bool clean = false;
181 static bool clean_all = false;
182
183 static char *exclude = NULL;
184
185 static const char *program_name;
186
187 static void print_hint (void);
188 static void print_help (void);
189 static void print_version (void);
190 static void cleanup (void);
191 static void free_color_names (struct color_name **);
192 static void process_args (unsigned int, char **, bool *, const struct color **, const char **, FILE **);
193 static void process_file_arg (const char *, const char **, FILE **);
194 static void read_print_stream (bool, const struct color **, const char *, FILE *);
195 static void find_color_entries (struct color_name **, const struct color **);
196 static void find_color_entry (const struct color_name *, unsigned int, const struct color **);
197 static void print_line (bool, const struct color **, const char * const, unsigned int);
198 static void print_clean (const char *);
199 static void print_free_offsets (const char *, char ***, unsigned int);
200 static void *malloc_wrap (size_t);
201 static void *calloc_wrap (size_t, size_t);
202 static void *realloc_wrap (void *, size_t);
203 static void *malloc_wrap_debug (size_t, const char *, unsigned int);
204 static void *calloc_wrap_debug (size_t, size_t, const char *, unsigned int);
205 static void *realloc_wrap_debug (void *, size_t, const char *, unsigned int);
206 static void free_wrap (void **);
207 static char *strdup_wrap (const char *);
208 static char *str_concat (const char *, const char *);
209 static char *get_file_type (mode_t);
210 static bool has_color_name (const char *, const char *);
211 static void vfprintf_diag (const char *, ...);
212 static void vfprintf_fail (const char *, ...);
213 static void stack_var (void ***, unsigned int *, unsigned int, void *);
214 static void release_var (void **, unsigned int, void **);
215
216 #define SET_OPT_TYPE(type) \
217 opt_type = type; \
218 opt = 0; \
219 goto PARSE_OPT; \
220
221 extern char *optarg;
222 extern int optind;
223
224 static int opt_type = 0;
225
226 int
227 main (int argc, char **argv)
228 {
229 unsigned int arg_cnt = 0;
230
231 enum {
232 OPT_CLEAN = 1,
233 OPT_CLEAN_ALL,
234 OPT_EXCLUDE_RANDOM,
235 OPT_HELP,
236 OPT_VERSION
237 };
238
239 int opt;
240 struct option long_opts[] = {
241 { "clean", no_argument, &opt_type, OPT_CLEAN },
242 { "clean-all", no_argument, &opt_type, OPT_CLEAN_ALL },
243 { "exclude-random", required_argument, &opt_type, OPT_EXCLUDE_RANDOM },
244 { "help", no_argument, &opt_type, OPT_HELP },
245 { "version", no_argument, &opt_type, OPT_VERSION },
246 { NULL, 0, NULL, 0 },
247 };
248
249 bool bold = false;
250
251 const struct color *colors[2] = {
252 NULL, /* foreground */
253 NULL, /* background */
254 };
255
256 const char *file = NULL;
257
258 program_name = argv[0];
259 atexit (cleanup);
260
261 setvbuf (stdout, NULL, _IOLBF, 0);
262
263 while ((opt = getopt_long (argc, argv, "hv", long_opts, NULL)) != -1)
264 {
265 PARSE_OPT:
266 switch (opt)
267 {
268 case 0: /* long opts */
269 switch (opt_type)
270 {
271 case OPT_CLEAN:
272 clean = true;
273 break;
274 case OPT_CLEAN_ALL:
275 clean_all = true;
276 break;
277 case OPT_EXCLUDE_RANDOM: {
278 bool valid = false;
279 unsigned int i;
280 exclude = xstrdup (optarg);
281 STACK_VAR (exclude);
282 for (i = 1; i < tables[FOREGROUND].count - 1; i++) /* skip color none and default */
283 {
284 const struct color *entry = &tables[FOREGROUND].entries[i];
285 if (streq (exclude, entry->name))
286 {
287 valid = true;
288 break;
289 }
290 }
291 if (!valid)
292 vfprintf_fail (formats[FMT_GENERIC], "--exclude-random switch must be provided a plain color");
293 break;
294 }
295 case OPT_HELP:
296 print_help ();
297 exit (EXIT_SUCCESS);
298 case OPT_VERSION:
299 print_version ();
300 exit (EXIT_SUCCESS);
301 default: /* never reached */
302 ABORT_TRACE ();
303 }
304 break;
305 case 'h':
306 SET_OPT_TYPE (OPT_HELP);
307 case 'v':
308 SET_OPT_TYPE (OPT_VERSION);
309 case '?':
310 print_hint ();
311 exit (EXIT_FAILURE);
312 default: /* never reached */
313 ABORT_TRACE ();
314 }
315 }
316
317 arg_cnt = argc - optind;
318
319 if (clean || clean_all)
320 {
321 if (clean && clean_all)
322 vfprintf_fail (formats[FMT_GENERIC], "--clean and --clean-all switch are mutually exclusive");
323 if (arg_cnt > 1)
324 {
325 const char *format = "%s %s";
326 const char *message = "switch cannot be used with more than one file";
327 if (clean)
328 vfprintf_fail (format, "--clean", message);
329 else if (clean_all)
330 vfprintf_fail (format, "--clean-all", message);
331 }
332 }
333 else
334 {
335 if (arg_cnt == 0 || arg_cnt > 2)
336 {
337 vfprintf_diag ("%u arguments provided, expected 1-2 arguments or clean option", arg_cnt);
338 print_hint ();
339 exit (EXIT_FAILURE);
340 }
341 }
342
343 if (clean || clean_all)
344 process_file_arg (argv[optind], &file, &stream);
345 else
346 process_args (arg_cnt, &argv[optind], &bold, colors, &file, &stream);
347 read_print_stream (bold, colors, file, stream);
348
349 RELEASE_VAR (exclude);
350
351 exit (EXIT_SUCCESS);
352 }
353
354 static void
355 print_hint (void)
356 {
357 fprintf (stderr, "Type `%s --help' for help screen.\n", program_name);
358 }
359
360 static void
361 print_help (void)
362 {
363 unsigned int i;
364
365 printf ("Usage: %s (foreground) OR (foreground)%c(background) OR --clean[-all] [-|file]\n\n", program_name, COLOR_SEP_CHAR);
366 printf ("\tColors (foreground) (background)\n");
367 for (i = 0; i < tables[FOREGROUND].count; i++)
368 {
369 const struct color *entry = &tables[FOREGROUND].entries[i];
370 const char *name = entry->name;
371 const char *code = entry->code;
372 if (code)
373 printf ("\t\t{\033[%s#\033[0m} [%c%c]%s%*s%s\n",
374 code, toupper (*name), *name, name + 1, 10 - (int)strlen (name), " ", name);
375 else
376 printf ("\t\t{-} %s%*s%s\n", name, 13 - (int)strlen (name), " ", name);
377 }
378 printf ("\t\t{*} [Rr]%s%*s%s [--exclude-random=<foreground color>]\n", "andom", 10 - (int)strlen ("random"), " ", "random");
379
380 printf ("\n\tFirst character of color name in upper case denotes increased intensity,\n");
381 printf ("\twhereas for lower case colors will be of normal intensity.\n");
382
383 printf ("\n\tOptions\n");
384 printf ("\t\t --clean\n");
385 printf ("\t\t --clean-all\n");
386 printf ("\t\t --exclude-random\n");
387 printf ("\t\t-h, --help\n");
388 printf ("\t\t-v, --version\n\n");
389 }
390
391 static void
392 print_version (void)
393 {
394 const char *c_flags;
395 bool debug;
396 #ifdef CFLAGS
397 c_flags = to_str (CFLAGS);
398 #else
399 c_flags = "unknown";
400 #endif
401 #if DEBUG
402 debug = true;
403 #else
404 debug = false;
405 #endif
406 printf ("%s v%s (compiled at %s, %s)\n", "colorize", VERSION, __DATE__, __TIME__);
407 printf ("Compiler flags: %s\n", c_flags);
408 printf ("Buffer size: %u bytes\n", BUF_SIZE);
409 printf ("Debugging: %s\n", debug ? "yes" : "no");
410 }
411
412 static void
413 cleanup (void)
414 {
415 free_color_names (color_names);
416
417 if (stream && fileno (stream) != STDIN_FILENO)
418 fclose (stream);
419
420 if (vars_list)
421 {
422 unsigned int i;
423 for (i = 0; i < stacked_vars; i++)
424 if (vars_list[i])
425 free_null (vars_list[i]);
426
427 free_null (vars_list);
428 }
429 }
430
431 static void
432 free_color_names (struct color_name **color_names)
433 {
434 unsigned int i;
435 for (i = 0; color_names[i]; i++)
436 {
437 free_null (color_names[i]->name);
438 free_null (color_names[i]->orig);
439 free_null (color_names[i]);
440 }
441 }
442
443 static void
444 process_args (unsigned int arg_cnt, char **arg_strings, bool *bold, const struct color **colors, const char **file, FILE **stream)
445 {
446 int ret;
447 unsigned int index;
448 char *color, *p, *str;
449 struct stat sb;
450
451 const char *color_string = arg_cnt >= 1 ? arg_strings[0] : NULL;
452 const char *file_string = arg_cnt == 2 ? arg_strings[1] : NULL;
453
454 assert (color_string);
455
456 if (streq (color_string, "-"))
457 {
458 if (file_string)
459 vfprintf_fail (formats[FMT_GENERIC], "hyphen cannot be used as color string");
460 else
461 vfprintf_fail (formats[FMT_GENERIC], "hyphen must be preceeded by color string");
462 }
463
464 ret = lstat (color_string, &sb);
465
466 /* Ensure that we don't fail if there's a file with one or more
467 color names in its path. */
468 if (ret != -1)
469 {
470 bool have_file;
471 unsigned int c;
472 const char *color = color_string;
473 const mode_t mode = sb.st_mode;
474
475 for (c = 1; c <= 2 && *color; c++)
476 {
477 bool matched = false;
478 unsigned int i;
479 for (i = 0; i < tables[FOREGROUND].count; i++)
480 {
481 const struct color *entry = &tables[FOREGROUND].entries[i];
482 if (has_color_name (color, entry->name))
483 {
484 color += strlen (entry->name);
485 matched = true;
486 break;
487 }
488 }
489 if (!matched && has_color_name (color, "random"))
490 {
491 color += strlen ("random");
492 matched = true;
493 }
494 if (matched && *color == COLOR_SEP_CHAR && *(color + 1))
495 color++;
496 else
497 break;
498 }
499
500 have_file = (*color != '\0');
501
502 if (have_file)
503 {
504 if (file_string)
505 vfprintf_fail (formats[FMT_QUOTE], get_file_type (mode), color_string, "cannot be used as color string");
506 else
507 {
508 if (VALID_FILE_TYPE (mode))
509 vfprintf_fail (formats[FMT_QUOTE], get_file_type (mode), color_string, "must be preceeded by color string");
510 else
511 vfprintf_fail (formats[FMT_QUOTE], get_file_type (mode), color_string, "is not a valid file type");
512 }
513 }
514 }
515
516 if ((p = strchr (color_string, COLOR_SEP_CHAR)))
517 {
518 if (p == color_string)
519 vfprintf_fail (formats[FMT_STRING], "foreground color missing in string", color_string);
520 else if (p == color_string + strlen (color_string) - 1)
521 vfprintf_fail (formats[FMT_STRING], "background color missing in string", color_string);
522 else if (strchr (++p, COLOR_SEP_CHAR))
523 vfprintf_fail (formats[FMT_STRING], "one color pair allowed only for string", color_string);
524 }
525
526 str = xstrdup (color_string);
527 STACK_VAR (str);
528
529 for (index = 0, color = str; *color; index++, color = p)
530 {
531 char *ch, *sep;
532
533 p = NULL;
534 if ((sep = strchr (color, COLOR_SEP_CHAR)))
535 {
536 *sep = '\0';
537 p = sep + 1;
538 }
539 else
540 p = color + strlen (color);
541 assert (p);
542
543 for (ch = color; *ch; ch++)
544 if (!isalpha (*ch))
545 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color, "cannot be made of non-alphabetic characters");
546
547 for (ch = color + 1; *ch; ch++)
548 if (!islower (*ch))
549 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color, "cannot be in mixed lower/upper case");
550
551 if (streq (color, "None"))
552 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color, "cannot be bold");
553
554 if (isupper (*color))
555 {
556 switch (index)
557 {
558 case FOREGROUND:
559 *bold = true;
560 break;
561 case BACKGROUND:
562 vfprintf_fail (formats[FMT_COLOR], tables[BACKGROUND].desc, color, "cannot be bold");
563 break;
564 default: /* never reached */
565 ABORT_TRACE ();
566 }
567 }
568
569 color_names[index] = xcalloc (1, sizeof (struct color_name));
570
571 color_names[index]->orig = xstrdup (color);
572
573 for (ch = color; *ch; ch++)
574 *ch = tolower (*ch);
575
576 color_names[index]->name = xstrdup (color);
577 }
578
579 RELEASE_VAR (str);
580
581 assert (color_names[FOREGROUND]);
582
583 if (color_names[BACKGROUND])
584 {
585 unsigned int i;
586 unsigned int color_sets[2][2] = { { FOREGROUND, BACKGROUND }, { BACKGROUND, FOREGROUND } };
587 for (i = 0; i < 2; i++)
588 {
589 unsigned int color1 = color_sets[i][0];
590 unsigned int color2 = color_sets[i][1];
591 if (CHECK_COLORS_RANDOM (color1, color2))
592 vfprintf_fail (formats[FMT_RANDOM], tables[color1].desc, color_names[color1]->orig, "cannot be combined with", color_names[color2]->orig);
593 }
594 }
595
596 find_color_entries (color_names, colors);
597 free_color_names (color_names);
598
599 if (!colors[FOREGROUND]->code && colors[BACKGROUND] && colors[BACKGROUND]->code)
600 {
601 struct color_name color_name;
602 color_name.name = color_name.orig = "default";
603
604 find_color_entry (&color_name, FOREGROUND, colors);
605 }
606
607 process_file_arg (file_string, file, stream);
608 }
609
610 static void
611 process_file_arg (const char *file_string, const char **file, FILE **stream)
612 {
613 if (file_string)
614 {
615 if (streq (file_string, "-"))
616 *stream = stdin;
617 else
618 {
619 FILE *s;
620 const char *file = file_string;
621 struct stat sb;
622 int errno, ret;
623
624 errno = 0;
625 ret = lstat (file, &sb);
626
627 if (ret == -1)
628 vfprintf_fail (formats[FMT_FILE], file, strerror (errno));
629
630 if (!VALID_FILE_TYPE (sb.st_mode))
631 vfprintf_fail (formats[FMT_TYPE], file, "unrecognized type", get_file_type (sb.st_mode));
632
633 errno = 0;
634
635 s = fopen (file, "r");
636 if (!s)
637 vfprintf_fail (formats[FMT_FILE], file, strerror (errno));
638 *stream = s;
639 }
640 *file = file_string;
641 }
642 else
643 {
644 *stream = stdin;
645 *file = "stdin";
646 }
647
648 assert (*stream);
649 assert (*file);
650 }
651
652 #define MERGE_PRINT_LINE(part_line, line, flags, check_eof) do { \
653 char *current_line, *merged_line = NULL; \
654 if (part_line) \
655 { \
656 merged_line = str_concat (part_line, line); \
657 free_null (part_line); \
658 } \
659 current_line = merged_line ? merged_line : (char *)line; \
660 if (!check_eof || *current_line != '\0') \
661 print_line (bold, colors, current_line, flags); \
662 free (merged_line); \
663 } while (false)
664
665 static void
666 read_print_stream (bool bold, const struct color **colors, const char *file, FILE *stream)
667 {
668 char buf[BUF_SIZE + 1], *part_line = NULL;
669 unsigned int flags = 0;
670
671 while (!feof (stream))
672 {
673 size_t bytes_read;
674 char *eol;
675 const char *line;
676 memset (buf, '\0', BUF_SIZE + 1);
677 bytes_read = fread (buf, 1, BUF_SIZE, stream);
678 if (bytes_read != BUF_SIZE && ferror (stream))
679 vfprintf_fail (formats[FMT_ERROR], BUF_SIZE, "read");
680 line = buf;
681 while ((eol = strpbrk (line, "\n\r")))
682 {
683 char *p;
684 flags &= ~(CR|LF);
685 if (*eol == '\r')
686 {
687 flags |= CR;
688 if (*(eol + 1) == '\n')
689 flags |= LF;
690 }
691 else if (*eol == '\n')
692 flags |= LF;
693 else
694 vfprintf_fail (formats[FMT_FILE], file, "unrecognized line ending");
695 p = eol + SKIP_LINE_ENDINGS (flags);
696 *eol = '\0';
697 MERGE_PRINT_LINE (part_line, line, flags, false);
698 line = p;
699 }
700 if (feof (stream)) {
701 MERGE_PRINT_LINE (part_line, line, 0, true);
702 }
703 else if (*line != '\0')
704 {
705 if (!clean && !clean_all) /* efficiency */
706 print_line (bold, colors, line, 0);
707 else if (!part_line)
708 part_line = xstrdup (line);
709 else
710 {
711 char *merged_line = str_concat (part_line, line);
712 free (part_line);
713 part_line = merged_line;
714 }
715 }
716 }
717 }
718
719 static void
720 find_color_entries (struct color_name **color_names, const struct color **colors)
721 {
722 struct timeval tv;
723 unsigned int index;
724
725 /* randomness */
726 gettimeofday (&tv, NULL);
727 srand (tv.tv_usec * tv.tv_sec);
728
729 for (index = 0; color_names[index]; index++)
730 {
731 const char *color_name = color_names[index]->name;
732
733 const unsigned int count = tables[index].count;
734 const struct color *const color_entries = tables[index].entries;
735
736 if (streq (color_name, "random"))
737 {
738 bool excludable;
739 unsigned int i;
740 do {
741 excludable = false;
742 i = rand() % (count - 2) + 1; /* omit color none and default */
743 switch (index)
744 {
745 case FOREGROUND:
746 /* --exclude-random */
747 if (exclude && streq (exclude, color_entries[i].name))
748 excludable = true;
749 else if (color_names[BACKGROUND] && streq (color_names[BACKGROUND]->name, color_entries[i].name))
750 excludable = true;
751 break;
752 case BACKGROUND:
753 if (streq (colors[FOREGROUND]->name, color_entries[i].name))
754 excludable = true;
755 break;
756 default: /* never reached */
757 ABORT_TRACE ();
758 }
759 } while (excludable);
760 colors[index] = (struct color *)&color_entries[i];
761 }
762 else
763 find_color_entry (color_names[index], index, colors);
764 }
765 }
766
767 static void
768 find_color_entry (const struct color_name *color_name, unsigned int index, const struct color **colors)
769 {
770 bool found = false;
771 unsigned int i;
772
773 const unsigned int count = tables[index].count;
774 const struct color *const color_entries = tables[index].entries;
775
776 for (i = 0; i < count; i++)
777 if (streq (color_name->name, color_entries[i].name))
778 {
779 colors[index] = (struct color *)&color_entries[i];
780 found = true;
781 break;
782 }
783 if (!found)
784 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color_name->orig, "not recognized");
785 }
786
787 static void
788 print_line (bool bold, const struct color **colors, const char *const line, unsigned int flags)
789 {
790 /* --clean[-all] */
791 if (clean || clean_all)
792 print_clean (line);
793 else
794 {
795 /* Foreground color code is guaranteed to be set when background color code is present. */
796 if (colors[BACKGROUND] && colors[BACKGROUND]->code)
797 printf ("\033[%s", colors[BACKGROUND]->code);
798 if (colors[FOREGROUND]->code)
799 printf ("\033[%s%s%s\033[0m", bold ? "1;" : "", colors[FOREGROUND]->code, line);
800 else
801 printf (formats[FMT_GENERIC], line);
802 }
803 if (flags & CR)
804 putchar ('\r');
805 if (flags & LF)
806 putchar ('\n');
807 }
808
809 static void
810 print_clean (const char *line)
811 {
812 const char *p;
813 char ***offsets = NULL;
814 unsigned int count = 0, i = 0;
815
816 for (p = line; *p;)
817 {
818 /* ESC[ */
819 if (*p == 27 && *(p + 1) == '[')
820 {
821 const char *begin = p;
822 p += 2;
823 if (clean_all)
824 {
825 while (isdigit (*p) || *p == ';')
826 p++;
827 }
828 else if (clean)
829 {
830 bool check_values;
831 unsigned int iter = 0;
832 const char *digit;
833 do {
834 check_values = false;
835 iter++;
836 if (!isdigit (*p))
837 goto DISCARD;
838 digit = p;
839 while (isdigit (*p))
840 p++;
841 if (p - digit > 2)
842 goto DISCARD;
843 else /* check range */
844 {
845 char val[3];
846 int value;
847 unsigned int i;
848 const unsigned int digits = p - digit;
849 for (i = 0; i < digits; i++)
850 val[i] = *digit++;
851 val[i] = '\0';
852 value = atoi (val);
853 if (value == 0) /* reset */
854 {
855 if (iter > 1)
856 goto DISCARD;
857 goto END;
858 }
859 else if (value == 1) /* bold */
860 {
861 bool discard = false;
862 if (iter > 1)
863 discard = true;
864 else if (*p != ';')
865 discard = true;
866 if (discard)
867 goto DISCARD;
868 p++;
869 check_values = true;
870 }
871 else if ((value >= 30 && value <= 37) || value == 39) /* foreground colors */
872 goto END;
873 else if ((value >= 40 && value <= 47) || value == 49) /* background colors */
874 {
875 if (iter > 1)
876 goto DISCARD;
877 goto END;
878 }
879 else
880 goto DISCARD;
881 }
882 } while (iter == 1 && check_values);
883 }
884 END: if (*p == 'm')
885 {
886 const char *end = p++;
887 if (!offsets)
888 offsets = xmalloc (++count * sizeof (char **));
889 else
890 offsets = xrealloc (offsets, ++count * sizeof (char **));
891 offsets[i] = xmalloc (2 * sizeof (char *));
892 offsets[i][0] = (char *)begin; /* ESC */
893 offsets[i][1] = (char *)end; /* m */
894 i++;
895 continue;
896 }
897 DISCARD:
898 continue;
899 }
900 p++;
901 }
902
903 if (offsets)
904 print_free_offsets (line, offsets, count);
905 else
906 printf (formats[FMT_GENERIC], line);
907 }
908
909 #define SET_CHAR(offset, new, old) \
910 *old = *offset; \
911 *offset = new; \
912
913 #define RESTORE_CHAR(offset, old) \
914 *offset = old; \
915
916 static void
917 print_free_offsets (const char *line, char ***offsets, unsigned int count)
918 {
919 char ch;
920 unsigned int i;
921
922 SET_CHAR (offsets[0][0], '\0', &ch);
923 printf (formats[FMT_GENERIC], line);
924 RESTORE_CHAR (offsets[0][0], ch);
925
926 for (i = 0; i < count; i++)
927 {
928 char ch;
929 bool next_offset = false;
930 if (i + 1 < count)
931 {
932 SET_CHAR (offsets[i + 1][0], '\0', &ch);
933 next_offset = true;
934 }
935 printf (formats[FMT_GENERIC], offsets[i][1] + 1);
936 if (next_offset)
937 RESTORE_CHAR (offsets[i + 1][0], ch);
938 }
939 for (i = 0; i < count; i++)
940 free_null (offsets[i]);
941 free_null (offsets);
942 }
943
944 static void *
945 malloc_wrap (size_t size)
946 {
947 void *p = malloc (size);
948 if (!p)
949 MEM_ALLOC_FAIL ();
950 return p;
951 }
952
953 static void *
954 calloc_wrap (size_t nmemb, size_t size)
955 {
956 void *p = calloc (nmemb, size);
957 if (!p)
958 MEM_ALLOC_FAIL ();
959 return p;
960 }
961
962 static void *
963 realloc_wrap (void *ptr, size_t size)
964 {
965 void *p = realloc (ptr, size);
966 if (!p)
967 MEM_ALLOC_FAIL ();
968 return p;
969 }
970
971 static void *
972 malloc_wrap_debug (size_t size, const char *file, unsigned int line)
973 {
974 void *p = malloc (size);
975 if (!p)
976 MEM_ALLOC_FAIL_DEBUG (file, line);
977 return p;
978 }
979
980 static void *
981 calloc_wrap_debug (size_t nmemb, size_t size, const char *file, unsigned int line)
982 {
983 void *p = calloc (nmemb, size);
984 if (!p)
985 MEM_ALLOC_FAIL_DEBUG (file, line);
986 return p;
987 }
988
989 static void *
990 realloc_wrap_debug (void *ptr, size_t size, const char *file, unsigned int line)
991 {
992 void *p = realloc (ptr, size);
993 if (!p)
994 MEM_ALLOC_FAIL_DEBUG (file, line);
995 return p;
996 }
997
998 static void
999 free_wrap (void **ptr)
1000 {
1001 free (*ptr);
1002 *ptr = NULL;
1003 }
1004
1005 static char *
1006 strdup_wrap (const char *str)
1007 {
1008 const size_t len = strlen (str) + 1;
1009 char *p = xmalloc (len);
1010 strncpy (p, str, len);
1011 return p;
1012 }
1013
1014 static char *
1015 str_concat (const char *str1, const char *str2)
1016 {
1017 const size_t len = strlen (str1) + strlen (str2) + 1;
1018 char *p, *str;
1019
1020 p = str = xmalloc (len);
1021 strncpy (p, str1, strlen (str1));
1022 p += strlen (str1);
1023 strncpy (p, str2, strlen (str2));
1024 p += strlen (str2);
1025 *p = '\0';
1026
1027 return str;
1028 }
1029
1030 static char *
1031 get_file_type (mode_t mode)
1032 {
1033 if (S_ISREG (mode))
1034 return "file";
1035 else if (S_ISDIR (mode))
1036 return "directory";
1037 else if (S_ISCHR (mode))
1038 return "character device";
1039 else if (S_ISBLK (mode))
1040 return "block device";
1041 else if (S_ISFIFO (mode))
1042 return "named pipe";
1043 else if (S_ISLNK (mode))
1044 return "symbolic link";
1045 else if (S_ISSOCK (mode))
1046 return "socket";
1047 else
1048 return "file";
1049 }
1050
1051 static bool
1052 has_color_name (const char *str, const char *name)
1053 {
1054 char *p;
1055
1056 assert (strlen (str));
1057 assert (strlen (name));
1058
1059 if (!(*str == *name || *str == toupper (*name)))
1060 return false;
1061 else if (*(name + 1) != '\0'
1062 && !((p = strstr (str + 1, name + 1)) && p == str + 1))
1063 return false;
1064
1065 return true;
1066 }
1067
1068 #define DO_VFPRINTF(fmt) \
1069 va_list ap; \
1070 fprintf (stderr, "%s: ", program_name); \
1071 va_start (ap, fmt); \
1072 vfprintf (stderr, fmt, ap); \
1073 va_end (ap); \
1074 fprintf (stderr, "\n"); \
1075
1076 static void
1077 vfprintf_diag (const char *fmt, ...)
1078 {
1079 DO_VFPRINTF (fmt);
1080 }
1081
1082 static void
1083 vfprintf_fail (const char *fmt, ...)
1084 {
1085 DO_VFPRINTF (fmt);
1086 exit (EXIT_FAILURE);
1087 }
1088
1089 static void
1090 stack_var (void ***list, unsigned int *stacked, unsigned int index, void *ptr)
1091 {
1092 /* nothing to stack */
1093 if (ptr == NULL)
1094 return;
1095 if (!*list)
1096 *list = xmalloc (sizeof (void *));
1097 else
1098 {
1099 unsigned int i;
1100 for (i = 0; i < *stacked; i++)
1101 if (!(*list)[i])
1102 {
1103 (*list)[i] = ptr;
1104 return; /* reused */
1105 }
1106 *list = xrealloc (*list, (*stacked + 1) * sizeof (void *));
1107 }
1108 (*list)[index] = ptr;
1109 (*stacked)++;
1110 }
1111
1112 static void
1113 release_var (void **list, unsigned int stacked, void **ptr)
1114 {
1115 unsigned int i;
1116 /* nothing to release */
1117 if (*ptr == NULL)
1118 return;
1119 for (i = 0; i < stacked; i++)
1120 if (list[i] == *ptr)
1121 {
1122 free (*ptr);
1123 *ptr = NULL;
1124 list[i] = NULL;
1125 return;
1126 }
1127 }