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