]>
git.refcnt.org Git - colorize.git/blob - colorize.c
f80bdced0626687af9494834053e7991c89576b2
2 * colorize - Read text from standard input stream or file and print
3 * it colorized through use of ANSI escape sequences
5 * Copyright (c) 2011-2018 Steven Schubiger
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.
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.
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/>.
22 #define _DEFAULT_SOURCE
24 #define _XOPEN_SOURCE 700
25 #define _FILE_OFFSET_BITS 64
36 #include <sys/types.h>
46 #define to_str(arg) str(arg)
48 #define streq(s1, s2) (strcmp (s1, s2) == 0)
49 #define strneq(s1, s2, n) (strncmp (s1, s2, n) == 0)
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 # define xstrdup(str) strdup_wrap(str, NULL, 0)
56 # define str_concat(str1, str2) str_concat_wrap(str1, str2, NULL, 0)
58 # define xmalloc(size) malloc_wrap_debug(size, __FILE__, __LINE__)
59 # define xcalloc(nmemb, size) calloc_wrap_debug(nmemb, size, __FILE__, __LINE__)
60 # define xrealloc(ptr, size) realloc_wrap_debug(ptr, size, __FILE__, __LINE__)
61 # define xstrdup(str) strdup_wrap(str, __FILE__, __LINE__)
62 # define str_concat(str1, str2) str_concat_wrap(str1, str2, __FILE__, __LINE__)
65 #define free_null(ptr) free_wrap((void **)&ptr)
67 #if defined(BUF_SIZE) && (BUF_SIZE <= 0 || BUF_SIZE > 65536)
71 # define BUF_SIZE 4096
77 #define COUNT_OF(obj, type) (sizeof (obj) / sizeof (type))
79 #define SKIP_LINE_ENDINGS(flags) ((flags) == (CR|LF) ? 2 : 1)
81 #define VALID_FILE_TYPE(mode) (S_ISREG (mode) || S_ISLNK (mode) || S_ISFIFO (mode))
83 #define STACK_VAR(ptr) do { \
84 stack_var (&vars_list, &stacked_vars, stacked_vars, ptr); \
87 #define RELEASE_VAR(ptr) do { \
88 release_var (vars_list, stacked_vars, (void **)&ptr); \
92 # define MEM_ALLOC_FAIL() do { \
93 fprintf (stderr, "%s: memory allocation failure\n", program_name); \
94 exit (EXIT_FAILURE); \
97 # define MEM_ALLOC_FAIL_DEBUG(file, line) do { \
98 fprintf (stderr, "Memory allocation failure in source file %s, line %u\n", file, line); \
99 exit (EXIT_FAILURE); \
103 #define ABORT_TRACE() \
104 fprintf (stderr, "Aborting in source file %s, line %u\n", __FILE__, __LINE__); \
107 #define CHECK_COLORS_RANDOM(color1, color2) \
108 streq (color_names[color1]->name, "random") \
109 && (streq (color_names[color2]->name, "none") \
110 || streq (color_names[color2]->name, "default"))
112 #define ALLOC_COMPLETE_PART_LINE 8
114 #if defined(COLOR_SEP_CHAR_COLON)
115 # define COLOR_SEP_CHAR ':'
116 #elif defined(COLOR_SEP_CHAR_SLASH)
117 # define COLOR_SEP_CHAR '/'
119 # define COLOR_SEP_CHAR '/'
122 #define CONF_FILE ".colorize.conf"
125 # define DEBUG_FILE "debug.txt"
128 #define MAX_ATTRIBUTE_CHARS (6 * 2)
130 #define PROGRAM_NAME "colorize"
132 #define VERSION "0.64"
134 typedef enum { false, true } bool;
139 char *exclude_random
;
140 char *omit_color_empty
;
143 enum { DESC_OPTION
, DESC_CONF
};
155 static const struct color fg_colors
[] = {
162 { "magenta", "35m" },
165 { "default", "39m" },
167 static const struct color bg_colors
[] = {
174 { "magenta", "45m" },
177 { "default", "49m" },
196 static const char *formats
[] = {
198 "%s '%s'", /* string */
199 "%s `%s' %s", /* quote */
200 "%s color '%s' %s", /* color */
201 "%s color '%s' %s '%s'", /* random */
202 "less than %lu bytes %s", /* error */
204 "%s: %s: %s", /* type */
205 "%s: option '%s' %s" /* conf */
208 enum { GENERIC
, FOREGROUND
= 0, BACKGROUND
};
210 static const struct {
211 const struct color
*entries
;
215 { fg_colors
, COUNT_OF (fg_colors
, struct color
), "foreground" },
216 { bg_colors
, COUNT_OF (bg_colors
, struct color
), "background" },
224 OPT_OMIT_COLOR_EMPTY
,
229 static const struct option long_opts
[] = {
230 { "attr", required_argument
, &opt_type
, OPT_ATTR
},
231 { "clean", no_argument
, &opt_type
, OPT_CLEAN
},
232 { "clean-all", no_argument
, &opt_type
, OPT_CLEAN_ALL
},
233 { "exclude-random", required_argument
, &opt_type
, OPT_EXCLUDE_RANDOM
},
234 { "omit-color-empty", no_argument
, &opt_type
, OPT_OMIT_COLOR_EMPTY
},
235 { "help", no_argument
, &opt_type
, OPT_HELP
},
236 { "version", no_argument
, &opt_type
, OPT_VERSION
},
237 { NULL
, 0, NULL
, 0 },
242 ATTR_UNDERSCORE
= 0x02,
245 ATTR_CONCEALED
= 0x10
258 static unsigned int stacked_vars
;
259 static void **vars_list
;
262 static bool clean_all
;
263 static bool omit_color_empty
;
265 static char attr
[MAX_ATTRIBUTE_CHARS
+ 1];
266 static char *exclude
;
268 static const char *program_name
;
271 static void print_tstamp (FILE *);
273 static void process_opts (int, char **);
274 static void process_opt_attr (const char *, const bool);
275 static void write_attr (const struct attr
*, unsigned int *, const bool);
276 static void process_opt_exclude_random (const char *, const bool);
277 static void parse_conf (const char *, struct conf
*);
278 static void assign_conf (const char *, struct conf
*, const char *, char *);
279 static void init_conf_vars (const struct conf
*);
280 static void print_hint (void);
281 static void print_help (void);
282 static void print_version (void);
283 static void cleanup (void);
284 static void free_color_names (struct color_name
**);
285 static void free_conf (struct conf
*);
286 static void process_args (unsigned int, char **, char *, const struct color
**, const char **, FILE **, struct conf
*);
287 static void process_file_arg (const char *, const char **, FILE **);
288 static bool skip_path_colors (const char *, const char *, const struct stat
*, const bool);
289 static void gather_color_names (const char *, char *, struct color_name
**);
290 static void read_print_stream (const char *, const struct color
**, const char *, FILE *);
291 static void merge_print_line (const char *, const char *, FILE *);
292 static void complete_part_line (const char *, char **, FILE *);
293 static bool get_next_char (char *, const char **, FILE *, bool *);
294 static void save_char (char, char **, size_t *, size_t *);
295 static void find_color_entries (struct color_name
**, const struct color
**);
296 static void find_color_entry (const struct color_name
*, unsigned int, const struct color
**);
297 static void print_line (const char *, const struct color
**, const char * const, unsigned int, bool);
298 static void print_clean (const char *);
299 static bool is_esc (const char *);
300 static const char *get_end_of_esc (const char *);
301 static const char *get_end_of_text (const char *);
302 static void print_text (const char *, size_t);
303 static bool gather_esc_offsets (const char *, const char **, const char **);
304 static bool validate_esc_clean_all (const char **);
305 static bool validate_esc_clean (int, unsigned int, unsigned int *, const char **, bool *);
306 static bool is_reset (int, unsigned int, const char **);
307 static bool is_attr (int, unsigned int, unsigned int, const char **);
308 static bool is_fg_color (int, const char **);
309 static bool is_bg_color (int, unsigned int, const char **);
311 static void *malloc_wrap (size_t);
312 static void *calloc_wrap (size_t, size_t);
313 static void *realloc_wrap (void *, size_t);
315 static void *malloc_wrap_debug (size_t, const char *, unsigned int);
316 static void *calloc_wrap_debug (size_t, size_t, const char *, unsigned int);
317 static void *realloc_wrap_debug (void *, size_t, const char *, unsigned int);
319 static void free_wrap (void **);
320 static char *strdup_wrap (const char *, const char *, unsigned int);
321 static char *str_concat_wrap (const char *, const char *, const char *, unsigned int);
322 static bool get_bytes_size (unsigned long, struct bytes_size
*);
323 static char *get_file_type (mode_t
);
324 static bool has_color_name (const char *, const char *);
325 static FILE *open_file (const char *, const char *);
326 static void vfprintf_diag (const char *, ...);
327 static void vfprintf_fail (const char *, ...);
328 static void stack_var (void ***, unsigned int *, unsigned int, void *);
329 static void release_var (void **, unsigned int, void **);
334 main (int argc
, char **argv
)
336 unsigned int arg_cnt
;
338 const struct color
*colors
[2] = {
339 NULL
, /* foreground */
340 NULL
, /* background */
343 const char *file
= NULL
;
347 struct passwd
*passwd
;
350 struct conf config
= { NULL
, NULL
, NULL
, NULL
};
352 program_name
= argv
[0];
355 setvbuf (stdout
, NULL
, _IOLBF
, 0);
358 log
= open_file (DEBUG_FILE
, "w");
364 #ifdef CONF_FILE_TEST
365 conf_file
= to_str (CONF_FILE_TEST
);
369 if ((passwd
= getpwuid (uid
)) == NULL
)
372 vfprintf_diag ("password file entry for uid %lu not found", (unsigned long)uid
);
377 size
= strlen (passwd
->pw_dir
) + 1 + strlen (CONF_FILE
) + 1;
378 conf_file
= xmalloc (size
);
379 snprintf (conf_file
, size
, "%s/%s", passwd
->pw_dir
, CONF_FILE
);
381 #if defined(CONF_FILE_TEST) || !defined(TEST)
382 if (access (conf_file
, F_OK
) != -1)
383 parse_conf (conf_file
, &config
);
385 #if !defined(CONF_FILE_TEST) && !defined(TEST)
388 init_conf_vars (&config
);
390 process_opts (argc
, argv
);
392 arg_cnt
= argc
- optind
;
394 if (clean
|| clean_all
)
396 if (clean
&& clean_all
)
397 vfprintf_fail (formats
[FMT_GENERIC
], "--clean and --clean-all switch are mutually exclusive");
400 const char *const format
= "%s %s";
401 const char *const message
= "switch cannot be used with more than one file";
403 vfprintf_fail (format
, "--clean", message
);
405 vfprintf_fail (format
, "--clean-all", message
);
410 if (arg_cnt
== 0 || arg_cnt
> 2)
412 vfprintf_diag ("%u arguments provided, expected 1-2 arguments or clean option", arg_cnt
);
418 if (clean
|| clean_all
)
419 process_file_arg (argv
[optind
], &file
, &stream
);
421 process_args (arg_cnt
, &argv
[optind
], &attr
[0], colors
, &file
, &stream
, &config
);
422 read_print_stream (&attr
[0], colors
, file
, stream
);
426 RELEASE_VAR (exclude
);
433 print_tstamp (FILE *log
)
444 perror ("localtime");
447 written
= strftime (str
, sizeof (str
), "%Y-%m-%d %H:%M:%S %Z", tm
);
449 vfprintf_fail (formats
[FMT_GENERIC
], "strftime: 0 returned");
451 fprintf (log
, "%s\n", str
);
458 #define PRINT_HELP_EXIT() \
462 #define PRINT_VERSION_EXIT() \
469 process_opts (int argc
, char **argv
)
472 while ((opt
= getopt_long (argc
, argv
, "hV", long_opts
, NULL
)) != -1)
476 case 0: /* long opts */
480 attr
[0] = '\0'; /* Clear attr string to discard values from the config file. */
481 process_opt_attr (optarg
, true);
489 case OPT_EXCLUDE_RANDOM
:
490 process_opt_exclude_random (optarg
, true);
492 case OPT_OMIT_COLOR_EMPTY
:
493 omit_color_empty
= true;
498 PRINT_VERSION_EXIT ();
499 default: /* never reached */
506 PRINT_VERSION_EXIT ();
510 default: /* never reached */
517 process_opt_attr (const char *p
, const bool is_opt
)
519 /* If attributes are added to this "list", also increase MAX_ATTRIBUTE_CHARS! */
520 const struct attr attrs
[] = {
521 { "bold", 1, ATTR_BOLD
},
522 { "underscore", 4, ATTR_UNDERSCORE
},
523 { "blink", 5, ATTR_BLINK
},
524 { "reverse", 7, ATTR_REVERSE
},
525 { "concealed", 8, ATTR_CONCEALED
},
527 unsigned int attr_types
= 0;
528 const char *desc_type
[2] = { "--attr switch", "attr conf option" };
529 unsigned int DESC_TYPE
= is_opt
? DESC_OPTION
: DESC_CONF
;
535 vfprintf_fail ("%s must be provided a string", desc_type
[DESC_TYPE
]);
539 if (*p
!= '\0' && *p
!= ',')
540 vfprintf_fail ("%s must have strings separated by ,", desc_type
[DESC_TYPE
]);
543 bool valid_attr
= false;
545 for (i
= 0; i
< COUNT_OF (attrs
, struct attr
); i
++)
547 const size_t name_len
= strlen (attrs
[i
].name
);
548 if ((size_t)(p
- s
) == name_len
&& strneq (s
, attrs
[i
].name
, name_len
))
550 write_attr (&attrs
[i
], &attr_types
, is_opt
);
557 char *attr_invalid
= xmalloc ((p
- s
) + 1);
558 STACK_VAR (attr_invalid
);
559 strncpy (attr_invalid
, s
, p
- s
);
560 attr_invalid
[p
- s
] = '\0';
561 vfprintf_fail ("%s attribute '%s' is not valid", desc_type
[DESC_TYPE
], attr_invalid
);
562 RELEASE_VAR (attr_invalid
); /* never reached */
571 write_attr (const struct attr
*attr_i
, unsigned int *attr_types
, const bool is_opt
)
573 const unsigned int val
= attr_i
->val
;
574 const enum attr_type attr_type
= attr_i
->type
;
575 const char *attr_name
= attr_i
->name
;
577 if (*attr_types
& attr_type
)
578 vfprintf_fail ("%s has attribute '%s' twice or more",
579 is_opt
? "--attr switch" : "attr conf option", attr_name
);
580 snprintf (attr
+ strlen (attr
), 3, "%u;", val
);
581 *attr_types
|= attr_type
;
585 process_opt_exclude_random (const char *s
, const bool is_opt
)
590 RELEASE_VAR (exclude
);
591 exclude
= xstrdup (s
);
593 for (i
= 1; i
< tables
[GENERIC
].count
- 1; i
++) /* skip color none and default */
595 const struct color
*entry
= &tables
[GENERIC
].entries
[i
];
596 if (streq (exclude
, entry
->name
))
603 vfprintf_fail ("%s must be provided a plain color",
604 is_opt
? "--exlude-random switch" : "exclude-random conf option");
607 #define IS_SPACE(c) ((c) == ' ' || (c) == '\t')
610 parse_conf (const char *conf_file
, struct conf
*config
)
615 conf
= open_file (conf_file
, "r");
617 while (fgets (line
, sizeof (line
), conf
))
620 char *assign
, *comment
, *opt
, *value
;
623 if (strlen (line
) > (sizeof (line
) - 2))
624 vfprintf_fail ("%s: line exceeds maximum of %u characters", conf_file
, (unsigned int)(sizeof (line
) - 2));
625 if ((p
= strrchr (line
, '\n')))
627 /* NAME PARSING (start) */
629 /* skip leading spaces and tabs for name */
630 while (IS_SPACE (*p
))
632 /* skip line if a) string end, b) comment, [cd]) newline */
633 if (*p
== '\0' || *p
== '#' || *p
== '\n' || *p
== '\r')
636 if (!(assign
= strchr (opt
, '='))) /* check for = */
639 if ((space
= strchr (opt
, ' ')))
641 vfprintf_fail (formats
[FMT_CONF
], conf_file
, opt
, "not followed by =");
644 /* skip trailing spaces and tabs for name */
645 while (IS_SPACE (*(p
- 1)))
648 /* NAME PARSING (end) */
649 /* NAME VALIDATION (start) */
650 for (p
= opt
; *p
; p
++)
651 if (!isalnum (*p
) && *p
!= '-')
652 vfprintf_fail (formats
[FMT_CONF
], conf_file
, opt
, "cannot be made of non-option characters");
653 /* NAME VALIDATION (end) */
654 /* VALUE PARSING (start) */
656 /* skip leading spaces and tabs for value */
657 while (IS_SPACE (*p
))
659 /* skip line if comment */
663 if ((comment
= strchr (p
, '#')))
667 /* skip trailing spaces and tabs for value */
668 while (IS_SPACE (*(p
- 1)))
671 /* VALUE PARSING (end) */
673 /* save option name */
675 /* save option value (allow empty ones) */
676 val
= strlen (value
) ? xstrdup (value
) : NULL
;
678 assign_conf (conf_file
, config
, cfg
, val
);
686 assign_conf (const char *conf_file
, struct conf
*config
, const char *cfg
, char *val
)
688 if (streq (cfg
, "attr"))
693 else if (streq (cfg
, "color"))
695 free (config
->color
);
698 else if (streq (cfg
, "exclude-random"))
700 free (config
->exclude_random
);
701 config
->exclude_random
= val
;
703 else if (streq (cfg
, "omit-color-empty"))
705 free (config
->omit_color_empty
);
706 config
->omit_color_empty
= val
;
709 vfprintf_fail (formats
[FMT_CONF
], conf_file
, cfg
, "not recognized");
713 init_conf_vars (const struct conf
*config
)
716 process_opt_attr (config
->attr
, false);
717 if (config
->exclude_random
)
718 process_opt_exclude_random (config
->exclude_random
, false);
719 if (config
->omit_color_empty
)
721 if (streq (config
->omit_color_empty
, "yes"))
722 omit_color_empty
= true;
723 else if (streq (config
->omit_color_empty
, "no"))
724 omit_color_empty
= false;
726 vfprintf_fail ("omit-color-empty conf option is not valid");
733 fprintf (stderr
, "Type `%s --help' for help screen.\n", program_name
);
741 const char *short_opt
;
744 const struct opt_data opts_data
[] = {
745 { "attr", NULL
, "=ATTR1,ATTR2,..." },
746 { "exclude-random", NULL
, "=COLOR" },
747 { "help", "h", NULL
},
748 { "version", "V", NULL
},
750 const struct option
*opt
= long_opts
;
753 printf ("Usage: %s (foreground) OR (foreground)%c(background) OR --clean[-all] [-|file]\n\n", program_name
, COLOR_SEP_CHAR
);
754 printf ("\tColors (foreground) (background)\n");
755 for (i
= 0; i
< tables
[FOREGROUND
].count
; i
++)
757 const struct color
*entry
= &tables
[FOREGROUND
].entries
[i
];
758 const char *name
= entry
->name
;
759 const char *code
= entry
->code
;
761 printf ("\t\t{\033[%s#\033[0m} [%c%c]%s%*s%s\n",
762 code
, toupper (*name
), *name
, name
+ 1, 10 - (int)strlen (name
), " ", name
);
764 printf ("\t\t{-} %s%*s%s\n", name
, 13 - (int)strlen (name
), " ", name
);
766 printf ("\t\t{*} [Rr]%s%*s%s [--exclude-random=<foreground color>]\n", "andom", 10 - (int)strlen ("random"), " ", "random");
768 printf ("\n\tFirst character of color name in upper case denotes increased intensity,\n");
769 printf ("\twhereas for lower case colors will be of normal intensity.\n");
771 printf ("\n\tOptions\n");
772 for (; opt
->name
; opt
++)
774 const struct opt_data
*opt_data
= NULL
;
776 for (i
= 0; i
< COUNT_OF (opts_data
, struct opt_data
); i
++)
777 if (streq (opt
->name
, opts_data
[i
].name
))
779 opt_data
= &opts_data
[i
];
784 if (opt_data
->short_opt
)
785 printf ("\t\t-%s, --%s\n", opt_data
->short_opt
, opt
->name
);
787 printf ("\t\t --%s%s\n", opt
->name
, opt_data
->arg
);
790 printf ("\t\t --%s\n", opt
->name
);
799 # include "version.h"
801 const char *const version
= NULL
;
803 const char *version_prefix
, *version_string
;
804 const char *c_flags
, *ld_flags
, *cpp_flags
;
805 const char *const desc_flags_unknown
= "unknown";
806 struct bytes_size bytes_size
;
809 c_flags
= to_str (CFLAGS
);
811 c_flags
= desc_flags_unknown
;
814 ld_flags
= to_str (LDFLAGS
);
816 ld_flags
= desc_flags_unknown
;
819 cpp_flags
= to_str (CPPFLAGS
);
821 cpp_flags
= desc_flags_unknown
;
828 version_prefix
= version
? "" : "v";
829 version_string
= version
? version
: VERSION
;
830 printf ("%s %s%s (compiled at %s, %s)\n", PROGRAM_NAME
, version_prefix
, version_string
, __DATE__
, __TIME__
);
832 printf ("Compiler flags: %s\n", c_flags
);
833 printf ("Linker flags: %s\n", ld_flags
);
834 printf ("Preprocessor flags: %s\n", cpp_flags
);
835 if (get_bytes_size (BUF_SIZE
, &bytes_size
))
837 if (BUF_SIZE
% 1024 == 0)
838 printf ("Buffer size: %u%c\n", bytes_size
.size
, bytes_size
.unit
);
840 printf ("Buffer size: %u%c, %u byte%s\n", bytes_size
.size
, bytes_size
.unit
,
841 BUF_SIZE
% 1024, BUF_SIZE
% 1024 > 1 ? "s" : "");
844 printf ("Buffer size: %lu byte%s\n", (unsigned long)BUF_SIZE
, BUF_SIZE
> 1 ? "s" : "");
845 printf ("Color separator: '%c'\n", COLOR_SEP_CHAR
);
846 printf ("Debugging: %s\n", debug
? "yes" : "no");
852 if (stream
&& fileno (stream
) != STDIN_FILENO
)
862 for (i
= 0; i
< stacked_vars
; i
++)
864 free_null (vars_list
);
869 free_color_names (struct color_name
**color_names
)
872 for (i
= 0; color_names
[i
]; i
++)
874 RELEASE_VAR (color_names
[i
]->name
);
875 RELEASE_VAR (color_names
[i
]->orig
);
876 RELEASE_VAR (color_names
[i
]);
881 free_conf (struct conf
*config
)
884 free (config
->color
);
885 free (config
->exclude_random
);
886 free (config
->omit_color_empty
);
890 process_args (unsigned int arg_cnt
, char **arg_strings
, char *attr
, const struct color
**colors
, const char **file
, FILE **stream
, struct conf
*config
)
896 struct color_name
*color_names
[3] = {
897 NULL
, /* foreground */
898 NULL
, /* background */
899 NULL
, /* sentinel value */
902 const char *color_string
= arg_cnt
>= 1 ? arg_strings
[0] : NULL
;
903 const char *file_string
= arg_cnt
== 2 ? arg_strings
[1] : NULL
;
905 assert (color_string
!= NULL
);
907 if (streq (color_string
, "-"))
910 vfprintf_fail (formats
[FMT_GENERIC
], "hyphen cannot be used as color string");
912 vfprintf_fail (formats
[FMT_GENERIC
], "hyphen must be preceded by color string");
915 if ((ret
= lstat (color_string
, &sb
)) == 0) /* exists */
916 /* Ensure that we don't fail if there's a file with one or more
917 color names in its path. */
918 use_conf_color
= skip_path_colors (color_string
, file_string
, &sb
, !!config
->color
);
920 /* Use color from config file. */
922 && (access (color_string
, F_OK
) != -1)
925 file_string
= color_string
;
926 color_string
= config
->color
;
929 if ((p
= strchr (color_string
, COLOR_SEP_CHAR
)))
931 if (p
== color_string
)
932 vfprintf_fail (formats
[FMT_STRING
], "foreground color missing in string", color_string
);
933 else if (p
== color_string
+ strlen (color_string
) - 1)
934 vfprintf_fail (formats
[FMT_STRING
], "background color missing in string", color_string
);
935 else if (strchr (++p
, COLOR_SEP_CHAR
))
936 vfprintf_fail (formats
[FMT_STRING
], "one color pair allowed only for string", color_string
);
939 gather_color_names (color_string
, attr
, color_names
);
941 assert (color_names
[FOREGROUND
] != NULL
);
943 if (color_names
[BACKGROUND
])
946 const unsigned int color_sets
[2][2] = { { FOREGROUND
, BACKGROUND
}, { BACKGROUND
, FOREGROUND
} };
947 for (i
= 0; i
< 2; i
++)
949 const unsigned int color1
= color_sets
[i
][0];
950 const unsigned int color2
= color_sets
[i
][1];
951 if (CHECK_COLORS_RANDOM (color1
, color2
))
952 vfprintf_fail (formats
[FMT_RANDOM
], tables
[color1
].desc
, color_names
[color1
]->orig
, "cannot be combined with", color_names
[color2
]->orig
);
956 find_color_entries (color_names
, colors
);
957 assert (colors
[FOREGROUND
] != NULL
);
958 free_color_names (color_names
);
960 if (!colors
[FOREGROUND
]->code
&& colors
[BACKGROUND
] && colors
[BACKGROUND
]->code
)
962 struct color_name color_name
;
963 color_name
.name
= color_name
.orig
= "default";
965 find_color_entry (&color_name
, FOREGROUND
, colors
);
966 assert (colors
[FOREGROUND
]->code
!= NULL
);
969 process_file_arg (file_string
, file
, stream
);
973 process_file_arg (const char *file_string
, const char **file
, FILE **stream
)
977 if (streq (file_string
, "-"))
981 const char *file
= file_string
;
986 ret
= stat (file
, &sb
);
989 vfprintf_fail (formats
[FMT_FILE
], file
, strerror (errno
));
991 if (!VALID_FILE_TYPE (sb
.st_mode
))
992 vfprintf_fail (formats
[FMT_TYPE
], file
, "unrecognized type", get_file_type (sb
.st_mode
));
994 *stream
= open_file (file
, "r");
1004 assert (*stream
!= NULL
);
1005 assert (*file
!= NULL
);
1009 skip_path_colors (const char *color_string
, const char *file_string
, const struct stat
*sb
, const bool has_conf
)
1013 const char *color
= color_string
;
1014 const mode_t mode
= sb
->st_mode
;
1016 for (c
= 1; c
<= 2 && *color
; c
++)
1018 bool matched
= false;
1020 for (i
= 0; i
< tables
[GENERIC
].count
; i
++)
1022 const struct color
*entry
= &tables
[GENERIC
].entries
[i
];
1023 if (has_color_name (color
, entry
->name
))
1025 color
+= strlen (entry
->name
);
1030 if (!matched
&& has_color_name (color
, "random"))
1032 color
+= strlen ("random");
1035 if (matched
&& *color
== COLOR_SEP_CHAR
&& *(color
+ 1))
1041 have_file
= (*color
!= '\0');
1045 const char *file_existing
= color_string
;
1047 vfprintf_fail (formats
[FMT_QUOTE
], get_file_type (mode
), file_existing
, "cannot be used as color string");
1050 if (VALID_FILE_TYPE (mode
))
1054 vfprintf_fail (formats
[FMT_QUOTE
], get_file_type (mode
), file_existing
, "must be preceded by color string");
1057 vfprintf_fail (formats
[FMT_QUOTE
], get_file_type (mode
), file_existing
, "is not a valid file type");
1064 gather_color_names (const char *color_string
, char *attr
, struct color_name
**color_names
)
1067 char *color
, *p
, *str
;
1069 str
= xstrdup (color_string
);
1072 for (index
= 0, color
= str
; *color
; index
++, color
= p
)
1077 if ((sep
= strchr (color
, COLOR_SEP_CHAR
)))
1083 p
= color
+ strlen (color
);
1086 for (ch
= color
; *ch
; ch
++)
1088 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be made of non-alphabetic characters");
1090 for (ch
= color
+ 1; *ch
; ch
++)
1092 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be in mixed lower/upper case");
1094 if (streq (color
, "None"))
1095 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be bold");
1097 if (isupper (*color
))
1102 snprintf (attr
+ strlen (attr
), 3, "1;");
1105 vfprintf_fail (formats
[FMT_COLOR
], tables
[BACKGROUND
].desc
, color
, "cannot be bold");
1106 default: /* never reached */
1111 color_names
[index
] = xcalloc (1, sizeof (struct color_name
));
1112 STACK_VAR (color_names
[index
]);
1114 color_names
[index
]->orig
= xstrdup (color
);
1115 STACK_VAR (color_names
[index
]->orig
);
1117 for (ch
= color
; *ch
; ch
++)
1118 *ch
= tolower (*ch
);
1120 color_names
[index
]->name
= xstrdup (color
);
1121 STACK_VAR (color_names
[index
]->name
);
1128 read_print_stream (const char *attr
, const struct color
**colors
, const char *file
, FILE *stream
)
1130 char buf
[BUF_SIZE
+ 1];
1131 unsigned int flags
= 0;
1133 while (!feof (stream
))
1138 bytes_read
= fread (buf
, 1, BUF_SIZE
, stream
);
1139 if (bytes_read
!= BUF_SIZE
&& ferror (stream
))
1140 vfprintf_fail (formats
[FMT_ERROR
], BUF_SIZE
, "read");
1141 buf
[bytes_read
] = '\0';
1143 while ((eol
= strpbrk (line
, "\n\r")))
1145 const bool has_text
= (eol
> line
);
1151 if (*(eol
+ 1) == '\n')
1154 else if (*eol
== '\n')
1156 else /* never reached */
1157 vfprintf_fail (formats
[FMT_FILE
], file
, "unrecognized line ending");
1158 p
= eol
+ SKIP_LINE_ENDINGS (flags
);
1160 print_line (attr
, colors
, line
, flags
,
1161 omit_color_empty
? has_text
: true);
1167 print_line (attr
, colors
, line
, 0, true);
1169 else if (*line
!= '\0')
1172 if ((clean
|| clean_all
) && (p
= strrchr (line
, '\033')))
1173 merge_print_line (line
, p
, stream
);
1175 print_line (attr
, colors
, line
, 0, true);
1181 merge_print_line (const char *line
, const char *p
, FILE *stream
)
1184 char *merged_esc
= NULL
;
1185 const char *esc
= "";
1186 const char char_restore
= *p
;
1188 complete_part_line (p
+ 1, &buf
, stream
);
1192 /* form escape sequence */
1193 esc
= merged_esc
= str_concat (p
, buf
);
1194 /* shorten partial line accordingly */
1199 #ifdef TEST_MERGE_PART_LINE
1200 printf ("%s%s", line
, esc
);
1202 _exit (EXIT_SUCCESS
);
1205 *(char *)p
= char_restore
;
1212 complete_part_line (const char *p
, char **buf
, FILE *stream
)
1214 bool got_next_char
= false, read_from_stream
;
1218 if (get_next_char (&ch
, &p
, stream
, &read_from_stream
))
1222 if (read_from_stream
)
1223 save_char (ch
, buf
, &i
, &size
);
1227 if (read_from_stream
)
1228 ungetc ((int)ch
, stream
);
1229 return; /* cancel */
1233 return; /* cancel */
1235 while (get_next_char (&ch
, &p
, stream
, &read_from_stream
))
1237 if (isdigit (ch
) || ch
== ';')
1239 if (read_from_stream
)
1240 save_char (ch
, buf
, &i
, &size
);
1242 else /* got next character */
1244 got_next_char
= true;
1253 if (read_from_stream
)
1254 save_char (ch
, buf
, &i
, &size
);
1258 if (read_from_stream
)
1259 ungetc ((int)ch
, stream
);
1260 return; /* cancel */
1264 return; /* cancel */
1268 get_next_char (char *ch
, const char **p
, FILE *stream
, bool *read_from_stream
)
1273 if ((c
= fgetc (stream
)) != EOF
)
1276 *read_from_stream
= true;
1281 *read_from_stream
= false;
1289 *read_from_stream
= false;
1295 save_char (char ch
, char **buf
, size_t *i
, size_t *size
)
1299 *size
= ALLOC_COMPLETE_PART_LINE
;
1300 *buf
= xmalloc (*size
);
1302 /* +1: effective occupied size of buffer */
1303 else if ((*i
+ 1) == *size
)
1306 *buf
= xrealloc (*buf
, *size
);
1309 (*buf
)[*i
+ 1] = '\0';
1314 find_color_entries (struct color_name
**color_names
, const struct color
**colors
)
1320 gettimeofday (&tv
, NULL
);
1321 srand (tv
.tv_usec
* tv
.tv_sec
);
1323 for (index
= 0; color_names
[index
]; index
++)
1325 const char *color_name
= color_names
[index
]->name
;
1327 const unsigned int count
= tables
[index
].count
;
1328 const struct color
*const color_entries
= tables
[index
].entries
;
1330 if (streq (color_name
, "random"))
1336 i
= rand() % (count
- 2) + 1; /* omit color none and default */
1340 /* --exclude-random */
1341 if (exclude
&& streq (exclude
, color_entries
[i
].name
))
1343 else if (color_names
[BACKGROUND
] && streq (color_names
[BACKGROUND
]->name
, color_entries
[i
].name
))
1347 if (streq (colors
[FOREGROUND
]->name
, color_entries
[i
].name
))
1350 default: /* never reached */
1353 } while (excludable
);
1354 colors
[index
] = (struct color
*)&color_entries
[i
];
1357 find_color_entry (color_names
[index
], index
, colors
);
1362 find_color_entry (const struct color_name
*color_name
, unsigned int index
, const struct color
**colors
)
1367 const unsigned int count
= tables
[index
].count
;
1368 const struct color
*const color_entries
= tables
[index
].entries
;
1370 for (i
= 0; i
< count
; i
++)
1371 if (streq (color_name
->name
, color_entries
[i
].name
))
1373 colors
[index
] = (struct color
*)&color_entries
[i
];
1378 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color_name
->orig
, "not recognized");
1382 print_line (const char *attr
, const struct color
**colors
, const char *const line
, unsigned int flags
, bool emit_colors
)
1385 if (clean
|| clean_all
)
1387 /* skip for --omit-color-empty? */
1388 else if (emit_colors
)
1390 /* Foreground color code is guaranteed to be set when background color code is present. */
1391 if (colors
[BACKGROUND
] && colors
[BACKGROUND
]->code
)
1392 printf ("\033[%s", colors
[BACKGROUND
]->code
);
1393 if (colors
[FOREGROUND
]->code
)
1394 printf ("\033[%s%s%s\033[0m", attr
, colors
[FOREGROUND
]->code
, line
);
1396 printf (formats
[FMT_GENERIC
], line
);
1405 print_clean (const char *line
)
1407 const char *p
= line
;
1410 p
= get_end_of_esc (p
);
1414 const char *text_start
= p
;
1415 const char *text_end
= get_end_of_text (p
);
1416 print_text (text_start
, text_end
- text_start
);
1417 p
= get_end_of_esc (text_end
);
1422 is_esc (const char *p
)
1424 return gather_esc_offsets (p
, NULL
, NULL
);
1428 get_end_of_esc (const char *p
)
1431 const char *end
= NULL
;
1432 while ((esc
= strchr (p
, '\033')))
1434 if (gather_esc_offsets (esc
, NULL
, &end
))
1438 return end
? end
+ 1 : p
+ strlen (p
);
1442 get_end_of_text (const char *p
)
1445 const char *start
= NULL
;
1446 while ((esc
= strchr (p
, '\033')))
1448 if (gather_esc_offsets (esc
, &start
, NULL
))
1452 return start
? start
: p
+ strlen (p
);
1456 print_text (const char *p
, size_t len
)
1458 size_t bytes_written
;
1459 bytes_written
= fwrite (p
, 1, len
, stdout
);
1460 if (bytes_written
!= len
)
1461 vfprintf_fail (formats
[FMT_ERROR
], (unsigned long)len
, "written");
1465 gather_esc_offsets (const char *p
, const char **start
, const char **end
)
1468 if (*p
== 27 && *(p
+ 1) == '[')
1471 const char *const begin
= p
;
1474 valid
= validate_esc_clean_all (&p
);
1478 unsigned int prev_iter
, iter
;
1480 prev_iter
= iter
= 0;
1482 check_values
= false;
1487 while (isdigit (*p
))
1491 else /* check range */
1496 const unsigned int digits
= p
- digit
;
1497 for (i
= 0; i
< digits
; i
++)
1501 valid
= validate_esc_clean (value
, iter
, &prev_iter
, &p
, &check_values
);
1503 } while (check_values
);
1518 validate_esc_clean_all (const char **p
)
1520 while (isdigit (**p
) || **p
== ';')
1522 return (**p
== 'm');
1526 validate_esc_clean (int value
, unsigned int iter
, unsigned int *prev_iter
, const char **p
, bool *check_values
)
1528 if (is_reset (value
, iter
, p
))
1530 else if (is_attr (value
, iter
, *prev_iter
, p
))
1533 *check_values
= true;
1535 return false; /* partial escape sequence, need another valid value */
1537 else if (is_fg_color (value
, p
))
1539 else if (is_bg_color (value
, iter
, p
))
1546 is_reset (int value
, unsigned int iter
, const char **p
)
1548 return (value
== 0 && iter
== 1 && **p
== 'm');
1552 is_attr (int value
, unsigned int iter
, unsigned int prev_iter
, const char **p
)
1554 return ((value
> 0 && value
< 10) && (iter
- prev_iter
== 1) && **p
== ';');
1558 is_fg_color (int value
, const char **p
)
1560 return (((value
>= 30 && value
<= 37) || value
== 39) && **p
== 'm');
1564 is_bg_color (int value
, unsigned int iter
, const char **p
)
1566 return (((value
>= 40 && value
<= 47) || value
== 49) && iter
== 1 && **p
== 'm');
1571 malloc_wrap (size_t size
)
1573 void *p
= malloc (size
);
1580 calloc_wrap (size_t nmemb
, size_t size
)
1582 void *p
= calloc (nmemb
, size
);
1589 realloc_wrap (void *ptr
, size_t size
)
1591 void *p
= realloc (ptr
, size
);
1597 static const char *const format_debug
= "%s: %10s %7lu bytes [source file %s, line %5u]\n";
1599 malloc_wrap_debug (size_t size
, const char *file
, unsigned int line
)
1601 void *p
= malloc (size
);
1603 MEM_ALLOC_FAIL_DEBUG (file
, line
);
1604 fprintf (log
, format_debug
, program_name
, "malloc'ed", (unsigned long)size
, file
, line
);
1609 calloc_wrap_debug (size_t nmemb
, size_t size
, const char *file
, unsigned int line
)
1611 void *p
= calloc (nmemb
, size
);
1613 MEM_ALLOC_FAIL_DEBUG (file
, line
);
1614 fprintf (log
, format_debug
, program_name
, "calloc'ed", (unsigned long)(nmemb
* size
), file
, line
);
1619 realloc_wrap_debug (void *ptr
, size_t size
, const char *file
, unsigned int line
)
1621 void *p
= realloc (ptr
, size
);
1623 MEM_ALLOC_FAIL_DEBUG (file
, line
);
1624 fprintf (log
, format_debug
, program_name
, "realloc'ed", (unsigned long)size
, file
, line
);
1630 free_wrap (void **ptr
)
1637 # define do_malloc(len, file, line) malloc_wrap(len)
1639 # define do_malloc(len, file, line) malloc_wrap_debug(len, file, line)
1643 strdup_wrap (const char *str
, const char *file
, unsigned int line
)
1645 const size_t len
= strlen (str
) + 1;
1646 char *p
= do_malloc (len
, file
, line
);
1647 strncpy (p
, str
, len
);
1652 str_concat_wrap (const char *str1
, const char *str2
, const char *file
, unsigned int line
)
1654 const size_t len
= strlen (str1
) + strlen (str2
) + 1;
1657 p
= str
= do_malloc (len
, file
, line
);
1658 strncpy (p
, str1
, strlen (str1
));
1660 strncpy (p
, str2
, strlen (str2
));
1668 get_bytes_size (unsigned long bytes
, struct bytes_size
*bytes_size
)
1670 const char *unit
, units
[] = { '0', 'K', 'M', 'G', '\0' };
1671 unsigned long size
= bytes
;
1675 while (size
>= 1024 && *(unit
+ 1))
1680 bytes_size
->size
= (unsigned int)size
;
1681 bytes_size
->unit
= *unit
;
1686 get_file_type (mode_t mode
)
1690 else if (S_ISDIR (mode
))
1692 else if (S_ISCHR (mode
))
1693 return "character device";
1694 else if (S_ISBLK (mode
))
1695 return "block device";
1696 else if (S_ISFIFO (mode
))
1697 return "named pipe";
1698 else if (S_ISLNK (mode
))
1699 return "symbolic link";
1700 else if (S_ISSOCK (mode
))
1707 has_color_name (const char *str
, const char *name
)
1711 assert (strlen (str
) > 0);
1712 assert (strlen (name
) > 0);
1714 if (!(*str
== *name
|| *str
== toupper (*name
)))
1716 else if (*(name
+ 1) != '\0'
1717 && !((p
= strstr (str
+ 1, name
+ 1)) && p
== str
+ 1))
1724 open_file (const char *file
, const char *mode
)
1729 stream
= fopen (file
, mode
);
1731 vfprintf_fail (formats
[FMT_FILE
], file
, strerror (errno
));
1736 #define DO_VFPRINTF(fmt) \
1738 fprintf (stderr, "%s: ", program_name); \
1739 va_start (ap, fmt); \
1740 vfprintf (stderr, fmt, ap); \
1742 fprintf (stderr, "\n");
1745 vfprintf_diag (const char *fmt
, ...)
1751 vfprintf_fail (const char *fmt
, ...)
1754 exit (EXIT_FAILURE
);
1758 stack_var (void ***list
, unsigned int *stacked
, unsigned int index
, void *ptr
)
1760 /* nothing to stack */
1764 *list
= xmalloc (sizeof (void *));
1768 for (i
= 0; i
< *stacked
; i
++)
1772 return; /* reused */
1774 *list
= xrealloc (*list
, (*stacked
+ 1) * sizeof (void *));
1776 (*list
)[index
] = ptr
;
1781 release_var (void **list
, unsigned int stacked
, void **ptr
)
1784 /* nothing to release */
1787 for (i
= 0; i
< stacked
; i
++)
1788 if (list
[i
] == *ptr
)