]>
git.refcnt.org Git - colorize.git/blob - colorize.c
157c4f0cc80d763249e8ac6a5a7ab79d3aad7023
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-2022 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>
47 #define to_str(arg) str(arg)
49 #define streq(s1, s2) (strcmp (s1, s2) == 0)
50 #define strneq(s1, s2, n) (strncmp (s1, s2, n) == 0)
53 # define xmalloc(size) malloc_wrap(size)
54 # define xcalloc(nmemb, size) calloc_wrap(nmemb, size)
55 # define xrealloc(ptr, size) realloc_wrap(ptr, size)
56 # define xstrdup(str) strdup_wrap(str, NULL, 0)
57 # define str_concat(str1, str2) str_concat_wrap(str1, str2, NULL, 0)
59 # define xmalloc(size) malloc_wrap_debug(size, __FILE__, __LINE__)
60 # define xcalloc(nmemb, size) calloc_wrap_debug(nmemb, size, __FILE__, __LINE__)
61 # define xrealloc(ptr, size) realloc_wrap_debug(ptr, size, __FILE__, __LINE__)
62 # define xstrdup(str) strdup_wrap(str, __FILE__, __LINE__)
63 # define str_concat(str1, str2) str_concat_wrap(str1, str2, __FILE__, __LINE__)
66 #define free_null(ptr) free_wrap((void **)&ptr)
68 #if defined(BUF_SIZE) && (BUF_SIZE <= 0 || BUF_SIZE > 65536)
72 # define BUF_SIZE 4096
78 #define COUNT_OF(obj, type) (sizeof (obj) / sizeof (type))
80 #define SKIP_LINE_ENDINGS(flags) ((flags) == (CR|LF) ? 2 : 1)
82 #define VALID_FILE_TYPE(mode) (S_ISREG (mode) || S_ISLNK (mode) || S_ISFIFO (mode))
84 #define STACK_VAR(ptr) do { \
85 stack (&vars_list, &stacked_vars, stacked_vars, ptr, IS_GENERIC); \
87 #define STACK_FILE(ptr) do { \
88 stack (&vars_list, &stacked_vars, stacked_vars, ptr, IS_FILE); \
90 #define RELEASE(ptr) do { \
91 release (vars_list, stacked_vars, (void **)&ptr); \
95 # define MEM_ALLOC_FAIL() do { \
96 fprintf (stderr, "%s: memory allocation failure\n", program_name); \
97 exit (EXIT_FAILURE); \
100 # define MEM_ALLOC_FAIL_DEBUG(file, line) do { \
101 fprintf (stderr, "Memory allocation failure in source file %s, line %u\n", file, line); \
102 exit (EXIT_FAILURE); \
106 #define ABORT_TRACE() \
107 fprintf (stderr, "Aborting in source file %s, line %u\n", __FILE__, __LINE__); \
110 #define CHECK_COLORS_RANDOM(color1, color2) \
111 streq (color_names[color1]->name, "random") \
112 && (streq (color_names[color2]->name, "none") \
113 || streq (color_names[color2]->name, "default"))
115 #define ALLOC_COMPLETE_PART_LINE 8
117 #if defined(COLOR_SEP_CHAR_COLON)
118 # define COLOR_SEP_CHAR ':'
119 #elif defined(COLOR_SEP_CHAR_SLASH)
120 # define COLOR_SEP_CHAR '/'
122 # define COLOR_SEP_CHAR '/'
125 #define CONF_FILE ".colorize.conf"
128 # define DEBUG_FILE "debug.txt"
131 #define MAX_ATTRIBUTE_CHARS (6 * 2)
133 #define PROGRAM_NAME "colorize"
135 #define VERSION "0.66"
137 typedef enum { false, true } bool;
142 char *exclude_random
;
143 char *omit_color_empty
;
146 enum { DESC_OPTION
, DESC_CONF
};
158 static const struct color fg_colors
[] = {
165 { "magenta", "35m" },
168 { "default", "39m" },
170 static const struct color bg_colors
[] = {
177 { "magenta", "45m" },
180 { "default", "49m" },
200 static const char *formats
[] = {
202 "%s '%s'", /* string */
203 "%s `%s' %s", /* quote */
204 "%s color '%s' %s", /* color */
205 "%s color '%s' %s '%s'", /* random */
206 "less than %lu bytes %s", /* error */
208 "%s: %s: %s", /* type */
209 "%s: option '%s' %s", /* conf */
210 "config file %s: %s" /* conf file */
213 enum { GENERIC
, FOREGROUND
= 0, BACKGROUND
};
215 static const struct {
216 const struct color
*entries
;
220 { fg_colors
, COUNT_OF (fg_colors
, struct color
), "foreground" },
221 { bg_colors
, COUNT_OF (bg_colors
, struct color
), "background" },
224 static unsigned int opts_set
;
227 OPT_EXCLUDE_RANDOM_SET
= 0x02,
228 OPT_OMIT_COLOR_EMPTY_SET
= 0x04
232 char *exclude_random
;
233 } opts_arg
= { NULL
, NULL
};
241 OPT_OMIT_COLOR_EMPTY
,
246 static const struct option long_opts
[] = {
247 { "attr", required_argument
, &opt_type
, OPT_ATTR
},
248 { "clean", no_argument
, &opt_type
, OPT_CLEAN
},
249 { "clean-all", no_argument
, &opt_type
, OPT_CLEAN_ALL
},
250 { "config", required_argument
, &opt_type
, OPT_CONFIG
},
251 { "exclude-random", required_argument
, &opt_type
, OPT_EXCLUDE_RANDOM
},
252 { "omit-color-empty", no_argument
, &opt_type
, OPT_OMIT_COLOR_EMPTY
},
253 { "help", no_argument
, &opt_type
, OPT_HELP
},
254 { "version", no_argument
, &opt_type
, OPT_VERSION
},
255 { NULL
, 0, NULL
, 0 },
260 ATTR_UNDERSCORE
= 0x02,
263 ATTR_CONCEALED
= 0x10
286 static unsigned int stacked_vars
;
287 static struct var_list
*vars_list
;
290 static bool clean_all
;
291 static bool omit_color_empty
;
293 static char attr
[MAX_ATTRIBUTE_CHARS
+ 1];
294 static char *exclude
;
296 static const char *program_name
;
299 static void print_tstamp (FILE *);
301 static void process_opts (int, char **, char **);
302 static void conf_file_path (char **);
303 static void process_opt_attr (const char *, const bool);
304 static void write_attr (const struct attr
*, unsigned int *, const bool);
305 static void process_opt_exclude_random (const char *, const bool);
306 static void parse_conf (const char *, struct conf
*);
307 static void assign_conf (const char *, struct conf
*, const char *, char *);
308 static void init_conf_vars (const struct conf
*);
309 static void init_opts_vars (void);
310 static void print_hint (void);
311 static void print_help (void);
312 static void print_version (void);
313 static void cleanup (void);
314 static void free_color_names (struct color_name
**);
315 static void free_conf (struct conf
*);
316 static void process_args (unsigned int, char **, char *, const struct color
**, const char **, FILE **, struct conf
*);
317 static void process_file_arg (const char *, const char **, FILE **);
318 static bool skip_path_colors (const char *, const char *, const struct stat
*, const bool);
319 static void gather_color_names (const char *, char *, struct color_name
**);
320 static void read_print_stream (const char *, const struct color
**, const char *, FILE *);
321 static void merge_print_line (const char *, const char *, FILE *);
322 static void complete_part_line (const char *, char **, FILE *);
323 static bool get_next_char (char *, const char **, FILE *, bool *);
324 static void save_char (char, char **, size_t *, size_t *);
325 static void find_color_entries (struct color_name
**, const struct color
**);
326 static void find_color_entry (const struct color_name
*, unsigned int, const struct color
**);
327 static void print_line (const char *, const struct color
**, const char * const, unsigned int, bool);
328 static void print_clean (const char *);
329 static bool is_esc (const char *);
330 static const char *get_end_of_esc (const char *);
331 static const char *get_end_of_text (const char *);
332 static void print_text (const char *, size_t);
333 static bool gather_esc_offsets (const char *, const char **, const char **);
334 static bool validate_esc_clean_all (const char **);
335 static bool validate_esc_clean (int, unsigned int, unsigned int *, const char **, bool *);
336 static bool is_reset (int, unsigned int, const char **);
337 static bool is_attr (int, unsigned int, unsigned int, const char **);
338 static bool is_fg_color (int, const char **);
339 static bool is_bg_color (int, unsigned int, const char **);
341 static void *malloc_wrap (size_t);
342 static void *calloc_wrap (size_t, size_t);
343 static void *realloc_wrap (void *, size_t);
345 static void *malloc_wrap_debug (size_t, const char *, unsigned int);
346 static void *calloc_wrap_debug (size_t, size_t, const char *, unsigned int);
347 static void *realloc_wrap_debug (void *, size_t, const char *, unsigned int);
349 static void free_wrap (void **);
350 static char *strdup_wrap (const char *, const char *, unsigned int);
351 static char *str_concat_wrap (const char *, const char *, const char *, unsigned int);
352 static char *expand_string (const char *);
353 static bool get_bytes_size (unsigned long, struct bytes_size
*);
354 static char *get_file_type (mode_t
);
355 static bool has_color_name (const char *, const char *);
356 static FILE *open_file (const char *, const char *);
357 static void vfprintf_diag (const char *, ...);
358 static void vfprintf_fail (const char *, ...);
359 static void stack (struct var_list
**, unsigned int *, unsigned int, void *, enum var_type
);
360 static void release (struct var_list
*, unsigned int, void **);
363 main (int argc
, char **argv
)
365 unsigned int arg_cnt
;
367 const struct color
*colors
[2] = {
368 NULL
, /* foreground */
369 NULL
, /* background */
372 const char *file
= NULL
;
374 char *conf_file
= NULL
;
375 struct conf config
= { NULL
, NULL
, NULL
, NULL
};
377 program_name
= argv
[0];
380 setvbuf (stdout
, NULL
, _IOLBF
, 0);
383 log
= open_file (DEBUG_FILE
, "w");
385 /* We're in debugging mode, hence we can't invoke STACK_FILE()
386 prior to print_tstamp(), because both cause text to be written
387 to the same logfile which is expected to have the timestamp
394 process_opts (argc
, argv
, &conf_file
);
396 #ifdef CONF_FILE_TEST
397 conf_file
= to_str (CONF_FILE_TEST
);
399 if (conf_file
== NULL
)
401 conf_file_path (&conf_file
);
402 STACK_VAR (conf_file
);
407 if ((s
= expand_string (conf_file
)))
412 STACK_VAR (conf_file
);
414 if (access (conf_file
, F_OK
) == -1)
415 vfprintf_fail (formats
[FMT_CONF_FILE
], conf_file
, strerror (errno
));
418 #if defined(CONF_FILE_TEST) || !defined(TEST)
419 if (access (conf_file
, F_OK
) != -1)
420 parse_conf (conf_file
, &config
);
422 #if !defined(CONF_FILE_TEST) && !defined(TEST)
425 init_conf_vars (&config
);
429 arg_cnt
= argc
- optind
;
431 if (clean
|| clean_all
)
433 if (clean
&& clean_all
)
434 vfprintf_fail (formats
[FMT_GENERIC
], "--clean and --clean-all switch are mutually exclusive");
436 vfprintf_fail ("--clean%s switch cannot be used with more than one file", clean_all
? "-all" : "");
439 const struct option_set
{
443 { "attr", OPT_ATTR_SET
},
444 { "exclude-random", OPT_EXCLUDE_RANDOM_SET
},
445 { "omit-color-empty", OPT_OMIT_COLOR_EMPTY_SET
},
447 for (i
= 0; i
< COUNT_OF (options
, struct option_set
); i
++)
448 if (opts_set
& options
[i
].set
)
449 vfprintf_diag ("--%s switch has no meaning with --clean%s", options
[i
].option
, clean_all
? "-all" : "");
454 if (arg_cnt
== 0 || arg_cnt
> 2)
456 vfprintf_diag ("%u arguments provided, expected 1-2 arguments or --clean[-all]", arg_cnt
);
462 if (clean
|| clean_all
)
463 process_file_arg (argv
[optind
], &file
, &stream
);
465 process_args (arg_cnt
, &argv
[optind
], &attr
[0], colors
, &file
, &stream
, &config
);
466 read_print_stream (&attr
[0], colors
, file
, stream
);
477 print_tstamp (FILE *log
)
488 perror ("localtime");
491 written
= strftime (str
, sizeof (str
), "%Y-%m-%d %H:%M:%S %Z", tm
);
493 vfprintf_fail (formats
[FMT_GENERIC
], "strftime: 0 returned");
495 fprintf (log
, "%s\n", str
);
502 #define DUP_CONFIG() \
503 *conf_file = xstrdup (optarg); \
506 #define PRINT_HELP_EXIT() \
510 #define PRINT_VERSION_EXIT() \
515 process_opts (int argc
, char **argv
, char **conf_file
)
518 while ((opt
= getopt_long (argc
, argv
, "c:hV", long_opts
, NULL
)) != -1)
522 case 0: /* long opts */
526 opts_set
|= OPT_ATTR_SET
;
527 opts_arg
.attr
= xstrdup (optarg
);
528 STACK_VAR (opts_arg
.attr
);
538 case OPT_EXCLUDE_RANDOM
:
539 opts_set
|= OPT_EXCLUDE_RANDOM_SET
;
540 opts_arg
.exclude_random
= xstrdup (optarg
);
541 STACK_VAR (opts_arg
.exclude_random
);
543 case OPT_OMIT_COLOR_EMPTY
:
544 opts_set
|= OPT_OMIT_COLOR_EMPTY_SET
;
549 PRINT_VERSION_EXIT ();
550 default: /* never reached */
559 PRINT_VERSION_EXIT ();
563 default: /* never reached */
570 conf_file_path (char **conf_file
)
574 struct passwd
*passwd
;
579 if ((passwd
= getpwuid (uid
)) == NULL
)
582 vfprintf_diag ("password file entry for uid %lu not found", (unsigned long)uid
);
587 /* getpwuid() leaks memory */
588 size
= strlen (passwd
->pw_dir
) + 1 + strlen (CONF_FILE
) + 1;
589 path
= xmalloc (size
);
590 snprintf (path
, size
, "%s/%s", passwd
->pw_dir
, CONF_FILE
);
596 process_opt_attr (const char *p
, const bool is_opt
)
598 /* If attributes are added to this "list", also increase MAX_ATTRIBUTE_CHARS! */
599 const struct attr attrs
[] = {
600 { "bold", 1, ATTR_BOLD
},
601 { "underscore", 4, ATTR_UNDERSCORE
},
602 { "blink", 5, ATTR_BLINK
},
603 { "reverse", 7, ATTR_REVERSE
},
604 { "concealed", 8, ATTR_CONCEALED
},
606 unsigned int attr_types
= 0;
607 const char *desc_type
[2] = { "--attr switch", "attr conf option" };
608 const unsigned int DESC_TYPE
= is_opt
? DESC_OPTION
: DESC_CONF
;
613 if (!isalnum ((unsigned char)*p
))
614 vfprintf_fail ("%s must be provided a string", desc_type
[DESC_TYPE
]);
616 while (isalnum ((unsigned char)*p
))
618 if (*p
!= '\0' && *p
!= ',')
619 vfprintf_fail ("%s must have strings separated by ,", desc_type
[DESC_TYPE
]);
622 bool valid_attr
= false;
624 for (i
= 0; i
< COUNT_OF (attrs
, struct attr
); i
++)
626 const size_t name_len
= strlen (attrs
[i
].name
);
627 if ((size_t)(p
- s
) == name_len
&& strneq (s
, attrs
[i
].name
, name_len
))
629 write_attr (&attrs
[i
], &attr_types
, is_opt
);
636 char *attr_invalid
= xmalloc ((p
- s
) + 1);
637 STACK_VAR (attr_invalid
);
638 strncpy (attr_invalid
, s
, p
- s
);
639 attr_invalid
[p
- s
] = '\0';
640 vfprintf_fail ("%s attribute '%s' is not valid", desc_type
[DESC_TYPE
], attr_invalid
);
641 RELEASE (attr_invalid
); /* never reached */
650 write_attr (const struct attr
*attr_i
, unsigned int *attr_types
, const bool is_opt
)
652 const unsigned int val
= attr_i
->val
;
653 const enum attr_type attr_type
= attr_i
->type
;
654 const char *attr_name
= attr_i
->name
;
656 if (*attr_types
& attr_type
)
657 vfprintf_fail ("%s has attribute '%s' twice or more",
658 is_opt
? "--attr switch" : "attr conf option", attr_name
);
659 snprintf (attr
+ strlen (attr
), 3, "%u;", val
);
660 *attr_types
|= attr_type
;
664 process_opt_exclude_random (const char *s
, const bool is_opt
)
669 exclude
= xstrdup (s
);
671 for (i
= 1; i
< tables
[GENERIC
].count
- 1; i
++) /* skip color none and default */
673 const struct color
*entry
= &tables
[GENERIC
].entries
[i
];
674 if (streq (exclude
, entry
->name
))
681 vfprintf_fail ("%s must be provided a plain color",
682 is_opt
? "--exclude-random switch" : "exclude-random conf option");
686 init_opts_vars (void)
688 if (opts_set
& OPT_ATTR_SET
)
690 attr
[0] = '\0'; /* Clear attr string to discard values from the config file. */
691 process_opt_attr (opts_arg
.attr
, true);
693 if (opts_set
& OPT_EXCLUDE_RANDOM_SET
)
694 process_opt_exclude_random (opts_arg
.exclude_random
, true);
695 if (opts_set
& OPT_OMIT_COLOR_EMPTY_SET
)
696 omit_color_empty
= true;
698 RELEASE (opts_arg
.attr
);
699 RELEASE (opts_arg
.exclude_random
);
702 #define IS_SPACE(c) ((c) == ' ' || (c) == '\t')
705 parse_conf (const char *conf_file
, struct conf
*config
)
707 unsigned int cnt
= 0;
711 conf
= open_file (conf_file
, "r");
714 while (fgets (line
, sizeof (line
), conf
))
717 char *assign
, *comment
, *opt
, *value
;
721 if ((p
= strchr (line
, '\r')) && *(p
+ 1) != '\n')
722 vfprintf_fail ("%s: CR ending of line %u is not supported, switch to CRLF/LF instead", conf_file
, cnt
);
723 if (strlen (line
) > (sizeof (line
) - 2))
724 vfprintf_fail ("%s: line %u exceeds maximum of %u characters", conf_file
, cnt
, (unsigned int)(sizeof (line
) - 2));
725 if ((p
= strpbrk (line
, "\n\r")))
727 /* NAME PARSING (start) */
729 /* skip leading spaces and tabs for name */
730 while (IS_SPACE (*p
))
732 /* skip line if a) string end, b) comment, [cd]) newline */
733 if (*p
== '\0' || *p
== '#' || *p
== '\n' || *p
== '\r')
736 if (!(assign
= strchr (opt
, '='))) /* check for = */
739 if ((s
= strpbrk (opt
, "# ")))
741 vfprintf_fail (formats
[FMT_CONF
], conf_file
, opt
, "not followed by =");
744 /* skip trailing spaces and tabs for name */
745 while (IS_SPACE (*(p
- 1)))
748 /* NAME PARSING (end) */
749 /* NAME VALIDATION (start) */
750 for (p
= opt
; *p
; p
++)
751 if (!isalnum ((unsigned char)*p
) && *p
!= '-')
752 vfprintf_fail (formats
[FMT_CONF
], conf_file
, opt
, "cannot be made of non-option characters");
753 /* NAME VALIDATION (end) */
754 /* VALUE PARSING (start) */
756 /* skip leading spaces and tabs for value */
757 while (IS_SPACE (*p
))
759 /* skip line if comment */
763 if ((comment
= strchr (p
, '#')))
767 /* skip trailing spaces and tabs for value */
768 while (IS_SPACE (*(p
- 1)))
771 /* VALUE PARSING (end) */
773 /* save option name */
776 /* save option value (allow empty ones) */
777 val
= strlen (value
) ? xstrdup (value
) : NULL
;
780 assign_conf (conf_file
, config
, cfg
, val
);
787 #define ASSIGN_CONF(str,val) do { \
793 assign_conf (const char *conf_file
, struct conf
*config
, const char *cfg
, char *val
)
795 if (streq (cfg
, "attr"))
796 ASSIGN_CONF (config
->attr
, val
);
797 else if (streq (cfg
, "color"))
798 ASSIGN_CONF (config
->color
, val
);
799 else if (streq (cfg
, "exclude-random"))
800 ASSIGN_CONF (config
->exclude_random
, val
);
801 else if (streq (cfg
, "omit-color-empty"))
802 ASSIGN_CONF (config
->omit_color_empty
, val
);
804 vfprintf_fail (formats
[FMT_CONF
], conf_file
, cfg
, "not recognized");
808 init_conf_vars (const struct conf
*config
)
811 process_opt_attr (config
->attr
, false);
812 if (config
->exclude_random
)
813 process_opt_exclude_random (config
->exclude_random
, false);
814 if (config
->omit_color_empty
)
816 if (streq (config
->omit_color_empty
, "yes"))
817 omit_color_empty
= true;
818 else if (streq (config
->omit_color_empty
, "no"))
819 omit_color_empty
= false;
821 vfprintf_fail (formats
[FMT_GENERIC
], "omit-color-empty conf option is not valid");
828 fprintf (stderr
, "Type `%s --help' for help screen.\n", program_name
);
836 const char *short_opt
;
839 const struct opt_data opts_data
[] = {
840 { "attr", NULL
, "=ATTR1,ATTR2,..." },
841 { "config", "c", "=PATH" },
842 { "exclude-random", NULL
, "=COLOR" },
843 { "help", "h", NULL
},
844 { "version", "V", NULL
},
846 const struct option
*opt
= long_opts
;
849 printf ("Usage: %s (foreground) OR (foreground)%c(background) OR --clean[-all] [-|file]\n\n", program_name
, COLOR_SEP_CHAR
);
850 printf ("\tColors (foreground) (background)\n");
851 for (i
= 0; i
< tables
[FOREGROUND
].count
; i
++)
853 const struct color
*entry
= &tables
[FOREGROUND
].entries
[i
];
854 const char *name
= entry
->name
;
855 const char *code
= entry
->code
;
857 printf ("\t\t{\033[%s#\033[0m} [%c%c]%s%*s%s\n",
858 code
, toupper ((unsigned char)*name
), *name
, name
+ 1, 10 - (int)strlen (name
), " ", name
);
860 printf ("\t\t{-} %s%*s%s\n", name
, 13 - (int)strlen (name
), " ", name
);
862 printf ("\t\t{*} [Rr]%s%*s%s [--exclude-random=<foreground color>]\n", "andom", 10 - (int)strlen ("random"), " ", "random");
864 printf ("\n\tFirst character of color name in upper case denotes increased intensity,\n");
865 printf ("\twhereas for lower case colors will be of normal intensity.\n");
867 printf ("\n\tOptions\n");
868 for (; opt
->name
; opt
++)
870 const struct opt_data
*opt_data
= NULL
;
872 for (i
= 0; i
< COUNT_OF (opts_data
, struct opt_data
); i
++)
873 if (streq (opt
->name
, opts_data
[i
].name
))
875 opt_data
= &opts_data
[i
];
880 if (opt_data
->short_opt
)
881 printf ("\t\t-%s, --%s", opt_data
->short_opt
, opt
->name
);
883 printf ("\t\t --%s", opt
->name
);
885 printf ("%s", opt_data
->arg
);
889 printf ("\t\t --%s\n", opt
->name
);
898 # include "version.h"
900 const char *const version
= NULL
;
902 const char *version_prefix
, *version_string
;
903 const char *c_flags
, *ld_flags
, *cpp_flags
;
904 const char *const desc_flags_unknown
= "unknown";
905 struct bytes_size bytes_size
;
908 c_flags
= to_str (CFLAGS
);
910 c_flags
= desc_flags_unknown
;
913 ld_flags
= to_str (LDFLAGS
);
915 ld_flags
= desc_flags_unknown
;
918 cpp_flags
= to_str (CPPFLAGS
);
920 cpp_flags
= desc_flags_unknown
;
927 version_prefix
= version
? "" : "v";
928 version_string
= version
? version
: VERSION
;
929 printf ("%s %s%s (compiled at %s, %s)\n", PROGRAM_NAME
, version_prefix
, version_string
, __DATE__
, __TIME__
);
931 printf ("Compiler flags: %s\n", c_flags
);
932 printf ("Linker flags: %s\n", ld_flags
);
933 printf ("Preprocessor flags: %s\n", cpp_flags
);
934 if (get_bytes_size (BUF_SIZE
, &bytes_size
))
936 if (BUF_SIZE
% 1024 == 0)
937 printf ("Buffer size: %u%c\n", bytes_size
.size
, bytes_size
.unit
);
939 printf ("Buffer size: %u%c, %u byte%s\n", bytes_size
.size
, bytes_size
.unit
,
940 BUF_SIZE
% 1024, BUF_SIZE
% 1024 > 1 ? "s" : "");
943 printf ("Buffer size: %lu byte%s\n", (unsigned long)BUF_SIZE
, BUF_SIZE
> 1 ? "s" : "");
944 printf ("Color separator: '%c'\n", COLOR_SEP_CHAR
);
945 printf ("Debugging: %s\n", debug
? "yes" : "no");
951 if (stream
&& fileno (stream
) != STDIN_FILENO
)
961 for (i
= 0; i
< stacked_vars
; i
++)
963 struct var_list
*var
= &vars_list
[i
];
974 default: /* never reached */
978 free_null (vars_list
);
983 free_color_names (struct color_name
**color_names
)
986 for (i
= 0; color_names
[i
]; i
++)
988 RELEASE (color_names
[i
]->name
);
989 RELEASE (color_names
[i
]->orig
);
990 RELEASE (color_names
[i
]);
995 free_conf (struct conf
*config
)
997 RELEASE (config
->attr
);
998 RELEASE (config
->color
);
999 RELEASE (config
->exclude_random
);
1000 RELEASE (config
->omit_color_empty
);
1004 process_args (unsigned int arg_cnt
, char **arg_strings
, char *attr
, const struct color
**colors
, const char **file
, FILE **stream
, struct conf
*config
)
1006 bool has_hyphen
, use_conf_color
;
1010 struct color_name
*color_names
[3] = {
1011 NULL
, /* foreground */
1012 NULL
, /* background */
1013 NULL
, /* sentinel value */
1016 const char *color_string
= arg_cnt
>= 1 ? arg_strings
[0] : NULL
;
1017 const char *file_string
= arg_cnt
== 2 ? arg_strings
[1] : NULL
;
1019 assert (color_string
!= NULL
);
1021 has_hyphen
= streq (color_string
, "-");
1026 vfprintf_fail (formats
[FMT_GENERIC
], "hyphen cannot be used as color string");
1027 else if (!config
->color
)
1028 vfprintf_fail (formats
[FMT_GENERIC
], "hyphen must be preceded by color string");
1031 if (!has_hyphen
&& (ret
= lstat (color_string
, &sb
)) == 0) /* exists */
1032 /* Ensure that we don't fail if there's a file with one or more
1033 color names in its path. */
1034 use_conf_color
= skip_path_colors (color_string
, file_string
, &sb
, !!config
->color
);
1035 else if (has_hyphen
)
1036 use_conf_color
= true;
1038 use_conf_color
= false;
1040 /* Use color from config file. */
1041 if (arg_cnt
== 1 && use_conf_color
)
1043 file_string
= color_string
;
1044 color_string
= config
->color
;
1047 if ((p
= strchr (color_string
, COLOR_SEP_CHAR
)))
1049 if (p
== color_string
)
1050 vfprintf_fail (formats
[FMT_STRING
], "foreground color missing in string", color_string
);
1051 else if (p
== color_string
+ strlen (color_string
) - 1)
1052 vfprintf_fail (formats
[FMT_STRING
], "background color missing in string", color_string
);
1053 else if (strchr (++p
, COLOR_SEP_CHAR
))
1054 vfprintf_fail (formats
[FMT_STRING
], "one color pair allowed only for string", color_string
);
1057 gather_color_names (color_string
, attr
, color_names
);
1059 assert (color_names
[FOREGROUND
] != NULL
);
1061 if (color_names
[BACKGROUND
])
1064 const unsigned int color_sets
[2][2] = { { FOREGROUND
, BACKGROUND
}, { BACKGROUND
, FOREGROUND
} };
1065 for (i
= 0; i
< 2; i
++)
1067 const unsigned int color1
= color_sets
[i
][0];
1068 const unsigned int color2
= color_sets
[i
][1];
1069 if (CHECK_COLORS_RANDOM (color1
, color2
))
1070 vfprintf_fail (formats
[FMT_RANDOM
], tables
[color1
].desc
, color_names
[color1
]->orig
, "cannot be combined with", color_names
[color2
]->orig
);
1074 find_color_entries (color_names
, colors
);
1075 assert (colors
[FOREGROUND
] != NULL
);
1076 free_color_names (color_names
);
1078 if (!colors
[FOREGROUND
]->code
&& colors
[BACKGROUND
] && colors
[BACKGROUND
]->code
)
1080 struct color_name color_name
;
1081 color_name
.name
= color_name
.orig
= "default";
1083 find_color_entry (&color_name
, FOREGROUND
, colors
);
1084 assert (colors
[FOREGROUND
]->code
!= NULL
);
1087 process_file_arg (file_string
, file
, stream
);
1091 process_file_arg (const char *file_string
, const char **file
, FILE **stream
)
1095 if (streq (file_string
, "-"))
1099 const char *file
= file_string
;
1104 ret
= stat (file
, &sb
);
1107 vfprintf_fail (formats
[FMT_FILE
], file
, strerror (errno
));
1109 if (!VALID_FILE_TYPE (sb
.st_mode
))
1110 vfprintf_fail (formats
[FMT_TYPE
], file
, "unrecognized type", get_file_type (sb
.st_mode
));
1112 *stream
= open_file (file
, "r");
1113 STACK_FILE (*stream
);
1115 *file
= file_string
;
1123 assert (*stream
!= NULL
);
1124 assert (*file
!= NULL
);
1128 skip_path_colors (const char *color_string
, const char *file_string
, const struct stat
*sb
, const bool has_conf
)
1132 const char *color
= color_string
;
1133 const mode_t mode
= sb
->st_mode
;
1135 for (c
= 1; c
<= 2 && *color
; c
++)
1137 bool matched
= false;
1139 for (i
= 0; i
< tables
[GENERIC
].count
; i
++)
1141 const struct color
*entry
= &tables
[GENERIC
].entries
[i
];
1142 if (has_color_name (color
, entry
->name
))
1144 color
+= strlen (entry
->name
);
1149 if (!matched
&& has_color_name (color
, "random"))
1151 color
+= strlen ("random");
1154 if (matched
&& *color
== COLOR_SEP_CHAR
&& *(color
+ 1))
1160 have_file
= (*color
!= '\0');
1164 const char *file_existing
= color_string
;
1166 vfprintf_fail (formats
[FMT_QUOTE
], get_file_type (mode
), file_existing
, "cannot be used as color string");
1169 if (VALID_FILE_TYPE (mode
))
1173 vfprintf_fail (formats
[FMT_QUOTE
], get_file_type (mode
), file_existing
, "must be preceded by color string");
1176 vfprintf_fail (formats
[FMT_QUOTE
], get_file_type (mode
), file_existing
, "is not a valid file type");
1183 gather_color_names (const char *color_string
, char *attr
, struct color_name
**color_names
)
1186 char *color
, *p
, *str
;
1188 str
= xstrdup (color_string
);
1191 for (index
= 0, color
= str
; *color
; index
++, color
= p
)
1196 if ((sep
= strchr (color
, COLOR_SEP_CHAR
)))
1202 p
= color
+ strlen (color
);
1205 for (ch
= color
; *ch
; ch
++)
1206 if (!isalpha ((unsigned char)*ch
))
1207 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be made of non-alphabetic characters");
1209 for (ch
= color
+ 1; *ch
; ch
++)
1210 if (!islower ((unsigned char)*ch
))
1211 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be in mixed lower/upper case");
1213 if (streq (color
, "None"))
1214 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be bold");
1216 if (isupper ((unsigned char)*color
))
1221 snprintf (attr
+ strlen (attr
), 3, "1;");
1224 vfprintf_fail (formats
[FMT_COLOR
], tables
[BACKGROUND
].desc
, color
, "cannot be bold");
1226 default: /* never reached */
1231 color_names
[index
] = xcalloc (1, sizeof (struct color_name
));
1232 STACK_VAR (color_names
[index
]);
1234 color_names
[index
]->orig
= xstrdup (color
);
1235 STACK_VAR (color_names
[index
]->orig
);
1237 for (ch
= color
; *ch
; ch
++)
1238 *ch
= tolower ((unsigned char)*ch
);
1240 color_names
[index
]->name
= xstrdup (color
);
1241 STACK_VAR (color_names
[index
]->name
);
1248 read_print_stream (const char *attr
, const struct color
**colors
, const char *file
, FILE *stream
)
1250 char buf
[BUF_SIZE
+ 1];
1251 unsigned int flags
= 0;
1253 while (!feof (stream
))
1258 bytes_read
= fread (buf
, 1, BUF_SIZE
, stream
);
1259 if (bytes_read
!= BUF_SIZE
&& ferror (stream
))
1260 vfprintf_fail (formats
[FMT_ERROR
], BUF_SIZE
, "read");
1261 buf
[bytes_read
] = '\0';
1263 while ((eol
= strpbrk (line
, "\n\r")))
1265 const bool has_text
= (eol
> line
);
1271 if (*(eol
+ 1) == '\n')
1274 else if (*eol
== '\n')
1276 else /* never reached */
1277 vfprintf_fail (formats
[FMT_FILE
], file
, "unrecognized line ending");
1278 p
= eol
+ SKIP_LINE_ENDINGS (flags
);
1280 print_line (attr
, colors
, line
, flags
,
1281 omit_color_empty
? has_text
: true);
1287 print_line (attr
, colors
, line
, 0, true);
1289 else if (*line
!= '\0')
1292 if ((clean
|| clean_all
) && (p
= strrchr (line
, '\033')))
1293 merge_print_line (line
, p
, stream
);
1295 print_line (attr
, colors
, line
, 0, true);
1301 merge_print_line (const char *line
, const char *p
, FILE *stream
)
1304 char *merged_esc
= NULL
;
1305 const char *esc
= "";
1306 const char char_restore
= *p
;
1308 complete_part_line (p
+ 1, &buf
, stream
);
1312 /* form escape sequence */
1313 esc
= merged_esc
= str_concat (p
, buf
);
1314 /* shorten partial line accordingly */
1319 #ifdef TEST_MERGE_PART_LINE
1320 printf ("%s%s", line
, esc
);
1322 _exit (EXIT_SUCCESS
);
1325 *(char *)p
= char_restore
;
1332 complete_part_line (const char *p
, char **buf
, FILE *stream
)
1334 bool got_next_char
= false, read_from_stream
;
1338 if (get_next_char (&ch
, &p
, stream
, &read_from_stream
))
1342 if (read_from_stream
)
1343 save_char (ch
, buf
, &i
, &size
);
1347 if (read_from_stream
)
1348 ungetc ((int)ch
, stream
);
1349 return; /* cancel */
1353 return; /* cancel */
1355 while (get_next_char (&ch
, &p
, stream
, &read_from_stream
))
1357 if (isdigit (ch
) || ch
== ';')
1359 if (read_from_stream
)
1360 save_char (ch
, buf
, &i
, &size
);
1362 else /* got next character */
1364 got_next_char
= true;
1373 if (read_from_stream
)
1374 save_char (ch
, buf
, &i
, &size
);
1378 if (read_from_stream
)
1379 ungetc ((int)ch
, stream
);
1380 return; /* cancel */
1384 return; /* cancel */
1388 get_next_char (char *ch
, const char **p
, FILE *stream
, bool *read_from_stream
)
1393 if ((c
= fgetc (stream
)) != EOF
)
1396 *read_from_stream
= true;
1401 *read_from_stream
= false;
1409 *read_from_stream
= false;
1415 save_char (char ch
, char **buf
, size_t *i
, size_t *size
)
1419 *size
= ALLOC_COMPLETE_PART_LINE
;
1420 *buf
= xmalloc (*size
);
1422 /* +1: effective occupied size of buffer */
1423 else if ((*i
+ 1) == *size
)
1426 *buf
= xrealloc (*buf
, *size
);
1429 (*buf
)[*i
+ 1] = '\0';
1434 find_color_entries (struct color_name
**color_names
, const struct color
**colors
)
1440 gettimeofday (&tv
, NULL
);
1441 srand (tv
.tv_usec
* tv
.tv_sec
);
1443 for (index
= 0; color_names
[index
]; index
++)
1445 const char *color_name
= color_names
[index
]->name
;
1447 const unsigned int count
= tables
[index
].count
;
1448 const struct color
*const color_entries
= tables
[index
].entries
;
1450 if (streq (color_name
, "random"))
1456 i
= rand() % (count
- 2) + 1; /* omit color none and default */
1460 /* --exclude-random */
1461 if (exclude
&& streq (exclude
, color_entries
[i
].name
))
1463 else if (color_names
[BACKGROUND
] && streq (color_names
[BACKGROUND
]->name
, color_entries
[i
].name
))
1467 if (streq (colors
[FOREGROUND
]->name
, color_entries
[i
].name
))
1470 default: /* never reached */
1473 } while (excludable
);
1474 colors
[index
] = (struct color
*)&color_entries
[i
];
1477 find_color_entry (color_names
[index
], index
, colors
);
1482 find_color_entry (const struct color_name
*color_name
, unsigned int index
, const struct color
**colors
)
1487 const unsigned int count
= tables
[index
].count
;
1488 const struct color
*const color_entries
= tables
[index
].entries
;
1490 for (i
= 0; i
< count
; i
++)
1491 if (streq (color_name
->name
, color_entries
[i
].name
))
1493 colors
[index
] = (struct color
*)&color_entries
[i
];
1498 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color_name
->orig
, "not recognized");
1502 print_line (const char *attr
, const struct color
**colors
, const char *const line
, unsigned int flags
, bool emit_colors
)
1505 if (clean
|| clean_all
)
1507 /* skip for --omit-color-empty? */
1508 else if (emit_colors
)
1510 /* Foreground color code is guaranteed to be set when background color code is present. */
1511 if (colors
[BACKGROUND
] && colors
[BACKGROUND
]->code
)
1512 printf ("\033[%s", colors
[BACKGROUND
]->code
);
1513 if (colors
[FOREGROUND
]->code
)
1514 printf ("\033[%s%s%s\033[0m", attr
, colors
[FOREGROUND
]->code
, line
);
1516 printf (formats
[FMT_GENERIC
], line
);
1525 print_clean (const char *line
)
1527 const char *p
= line
;
1530 p
= get_end_of_esc (p
);
1534 const char *text_start
= p
;
1535 const char *text_end
= get_end_of_text (p
);
1536 print_text (text_start
, text_end
- text_start
);
1537 p
= get_end_of_esc (text_end
);
1542 is_esc (const char *p
)
1544 return gather_esc_offsets (p
, NULL
, NULL
);
1548 get_end_of_esc (const char *p
)
1551 const char *end
= NULL
;
1552 while ((esc
= strchr (p
, '\033')))
1554 if (gather_esc_offsets (esc
, NULL
, &end
))
1558 return end
? end
+ 1 : p
+ strlen (p
);
1562 get_end_of_text (const char *p
)
1565 const char *start
= NULL
;
1566 while ((esc
= strchr (p
, '\033')))
1568 if (gather_esc_offsets (esc
, &start
, NULL
))
1572 return start
? start
: p
+ strlen (p
);
1576 print_text (const char *p
, size_t len
)
1578 size_t bytes_written
;
1579 bytes_written
= fwrite (p
, 1, len
, stdout
);
1580 if (bytes_written
!= len
)
1581 vfprintf_fail (formats
[FMT_ERROR
], (unsigned long)len
, "written");
1585 gather_esc_offsets (const char *p
, const char **start
, const char **end
)
1588 if (*p
== 27 && *(p
+ 1) == '[')
1591 const char *const begin
= p
;
1594 valid
= validate_esc_clean_all (&p
);
1598 unsigned int prev_iter
, iter
;
1600 prev_iter
= iter
= 0;
1602 check_values
= false;
1604 if (!isdigit ((unsigned char)*p
))
1607 while (isdigit ((unsigned char)*p
))
1611 else /* check range */
1616 const unsigned int digits
= p
- digit
;
1617 for (i
= 0; i
< digits
; i
++)
1621 valid
= validate_esc_clean (value
, iter
, &prev_iter
, &p
, &check_values
);
1623 } while (check_values
);
1638 validate_esc_clean_all (const char **p
)
1640 while (isdigit ((unsigned char)**p
) || **p
== ';')
1642 return (**p
== 'm');
1646 validate_esc_clean (int value
, unsigned int iter
, unsigned int *prev_iter
, const char **p
, bool *check_values
)
1648 if (is_reset (value
, iter
, p
))
1650 else if (is_attr (value
, iter
, *prev_iter
, p
))
1653 *check_values
= true;
1655 return false; /* partial escape sequence, need another valid value */
1657 else if (is_fg_color (value
, p
))
1659 else if (is_bg_color (value
, iter
, p
))
1666 is_reset (int value
, unsigned int iter
, const char **p
)
1668 return (value
== 0 && iter
== 1 && **p
== 'm');
1672 is_attr (int value
, unsigned int iter
, unsigned int prev_iter
, const char **p
)
1674 return ((value
> 0 && value
< 10) && (iter
- prev_iter
== 1) && **p
== ';');
1678 is_fg_color (int value
, const char **p
)
1680 return (((value
>= 30 && value
<= 37) || value
== 39) && **p
== 'm');
1684 is_bg_color (int value
, unsigned int iter
, const char **p
)
1686 return (((value
>= 40 && value
<= 47) || value
== 49) && iter
== 1 && **p
== 'm');
1691 malloc_wrap (size_t size
)
1693 void *p
= malloc (size
);
1700 calloc_wrap (size_t nmemb
, size_t size
)
1702 void *p
= calloc (nmemb
, size
);
1709 realloc_wrap (void *ptr
, size_t size
)
1711 void *p
= realloc (ptr
, size
);
1717 static const char *const format_debug
= "%s: %10s %7lu bytes [source file %s, line %5u]\n";
1719 malloc_wrap_debug (size_t size
, const char *file
, unsigned int line
)
1721 void *p
= malloc (size
);
1723 MEM_ALLOC_FAIL_DEBUG (file
, line
);
1724 fprintf (log
, format_debug
, program_name
, "malloc'ed", (unsigned long)size
, file
, line
);
1729 calloc_wrap_debug (size_t nmemb
, size_t size
, const char *file
, unsigned int line
)
1731 void *p
= calloc (nmemb
, size
);
1733 MEM_ALLOC_FAIL_DEBUG (file
, line
);
1734 fprintf (log
, format_debug
, program_name
, "calloc'ed", (unsigned long)(nmemb
* size
), file
, line
);
1739 realloc_wrap_debug (void *ptr
, size_t size
, const char *file
, unsigned int line
)
1741 void *p
= realloc (ptr
, size
);
1743 MEM_ALLOC_FAIL_DEBUG (file
, line
);
1744 fprintf (log
, format_debug
, program_name
, "realloc'ed", (unsigned long)size
, file
, line
);
1750 free_wrap (void **ptr
)
1757 # define do_malloc(len, file, line) malloc_wrap(len)
1759 # define do_malloc(len, file, line) malloc_wrap_debug(len, file, line)
1763 strdup_wrap (const char *str
, const char *file
, unsigned int line
)
1765 const size_t len
= strlen (str
) + 1;
1766 char *p
= do_malloc (len
, file
, line
);
1767 strncpy (p
, str
, len
);
1772 str_concat_wrap (const char *str1
, const char *str2
, const char *file
, unsigned int line
)
1774 const size_t len
= strlen (str1
) + strlen (str2
) + 1;
1777 p
= str
= do_malloc (len
, file
, line
);
1778 strncpy (p
, str1
, strlen (str1
));
1780 strncpy (p
, str2
, strlen (str2
));
1788 expand_string (const char *str
)
1793 wordexp (str
, &p
, 0);
1794 if (p
.we_wordc
>= 1)
1795 s
= xstrdup (p
.we_wordv
[0]);
1802 get_bytes_size (unsigned long bytes
, struct bytes_size
*bytes_size
)
1804 const char *unit
, units
[] = { '0', 'K', 'M', 'G', '\0' };
1805 unsigned long size
= bytes
;
1809 while (size
>= 1024 && *(unit
+ 1))
1814 bytes_size
->size
= (unsigned int)size
;
1815 bytes_size
->unit
= *unit
;
1820 get_file_type (mode_t mode
)
1824 else if (S_ISDIR (mode
))
1826 else if (S_ISCHR (mode
))
1827 return "character device";
1828 else if (S_ISBLK (mode
))
1829 return "block device";
1830 else if (S_ISFIFO (mode
))
1831 return "named pipe";
1832 else if (S_ISLNK (mode
))
1833 return "symbolic link";
1834 else if (S_ISSOCK (mode
))
1841 has_color_name (const char *str
, const char *name
)
1845 assert (strlen (str
) > 0);
1846 assert (strlen (name
) > 0);
1848 if (!(*str
== *name
|| *str
== toupper ((unsigned char)*name
)))
1850 else if (*(name
+ 1) != '\0'
1851 && !((p
= strstr (str
+ 1, name
+ 1)) && p
== str
+ 1))
1858 open_file (const char *file
, const char *mode
)
1863 stream
= fopen (file
, mode
);
1865 vfprintf_fail (formats
[FMT_FILE
], file
, strerror (errno
));
1870 #define DO_VFPRINTF(fmt) \
1872 fprintf (stderr, "%s: ", program_name); \
1873 va_start (ap, fmt); \
1874 vfprintf (stderr, fmt, ap); \
1876 fprintf (stderr, "\n");
1879 vfprintf_diag (const char *fmt
, ...)
1885 vfprintf_fail (const char *fmt
, ...)
1888 exit (EXIT_FAILURE
);
1892 stack (struct var_list
**list
, unsigned int *stacked
, unsigned int index
, void *ptr
, enum var_type type
)
1894 struct var_list
*var
;
1895 /* nothing to stack */
1899 *list
= xmalloc (sizeof (struct var_list
));
1903 for (i
= 0; i
< *stacked
; i
++)
1906 if (var
->type
== IS_UNUSED
)
1910 return; /* reused */
1913 *list
= xrealloc (*list
, (*stacked
+ 1) * sizeof (struct var_list
));
1915 var
= &(*list
)[index
];
1922 release (struct var_list
*list
, unsigned int stacked
, void **ptr
)
1925 /* nothing to release */
1928 for (i
= 0; i
< stacked
; i
++)
1930 struct var_list
*var
= &list
[i
];
1931 if (var
->type
!= IS_UNUSED
1932 && var
->ptr
== *ptr
)
1942 default: /* never reached */
1947 var
->type
= IS_UNUSED
;