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