]>
git.refcnt.org Git - colorize.git/blob - colorize.c
041ecdb2fc560230f27353b462324597523cf6df
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-2013 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/>.
32 #include <sys/types.h>
40 #define to_str(arg) str(arg)
42 #define streq(s1, s2) (strcmp (s1, s2) == 0)
44 #define xmalloc(size) malloc_wrap(size, __FILE__, __LINE__)
45 #define xrealloc(ptr, size) realloc_wrap(ptr, size, __FILE__, __LINE__)
46 #define xstrdup(str) strdup_wrap(str, __FILE__, __LINE__)
48 #if !defined BUF_SIZE || BUF_SIZE <= 0
50 # define BUF_SIZE 4096 + 1
56 #define SKIP_LINE_ENDINGS(flags) (((flags) & CR) && ((flags) & LF) ? 2 : 1)
58 #define STACK_VAR(ptr) do { \
59 stack_var (&vars_list, &stacked_vars, stacked_vars, ptr); \
62 #define RELEASE_VAR(ptr) do { \
63 release_var (vars_list, stacked_vars, (void **)&ptr); \
67 # define MEM_ALLOC_FAIL(file, line) do { \
68 fprintf (stderr, "Memory allocation failure in source file %s, line %d\n", file, line); \
72 # define MEM_ALLOC_FAIL(file, line) do { \
73 fprintf (stderr, "%s: memory allocation failure\n", program_name); \
78 #define ABORT_TRACE() \
79 fprintf (stderr, "Aborting in source file %s, line %d\n", __FILE__, __LINE__); \
82 #define CHECK_COLORS_RANDOM(color1, color2) \
83 streq (color_names[color1]->name, "random") \
84 && (streq (color_names[color2]->name, "none") \
85 || streq (color_names[color2]->name, "default")) \
87 #define VERSION "0.48"
89 typedef unsigned short bool;
98 static struct color_name
*color_names
[3] = { NULL
, NULL
, NULL
};
105 static const struct color fg_colors
[] = {
113 { "magenta", "36m" },
115 { "default", "39m" },
117 static const struct color bg_colors
[] = {
125 { "magenta", "46m" },
127 { "default", "49m" },
137 static const char *formats
[] = {
139 "%s color '%s' %s", /* color */
140 "%s color '%s' %s '%s'", /* random */
141 "less than %d bytes %s", /* error */
145 enum { FOREGROUND
, BACKGROUND
};
147 static const struct {
148 struct color
const *entries
;
152 { fg_colors
, sizeof (fg_colors
) / sizeof (struct color
), "foreground" },
153 { bg_colors
, sizeof (bg_colors
) / sizeof (struct color
), "background" },
156 enum stream_mode
{ SCAN_FIRST
= 1, SCAN_ALWAYS
};
160 const char newline
[3];
163 static const struct ending endings
[] = {
169 static FILE *stream
= NULL
;
171 static unsigned int stacked_vars
= 0;
172 static void **vars_list
= NULL
;
174 static char *exclude
= NULL
;
176 static const char *program_name
;
178 static void print_help (void);
179 static void print_version (void);
180 static void cleanup (void);
181 static void free_color_names (struct color_name
**);
182 static void process_options (unsigned int, char **, bool *, const struct color
**, const char **, FILE **);
183 static void read_print_stream (bool, const struct color
**, const char *, FILE *, enum stream_mode
);
184 static void find_color_entries (struct color_name
**, const struct color
**);
185 static void find_color_entry (const char *const, unsigned int, const struct color
**);
186 static void print_line (const struct color
**, bool, const char * const, unsigned int);
187 static void *malloc_wrap (size_t, const char *, unsigned int);
188 static void *realloc_wrap (void *, size_t, const char *, unsigned int);
189 static char *strdup_wrap (const char *, const char *, unsigned int);
190 static void vfprintf_fail (const char *, ...);
191 static void stack_var (void ***, unsigned int *, unsigned int, void *);
192 static void release_var (void **, unsigned int, void **);
198 main (int argc
, char **argv
)
200 unsigned int arg_cnt
= 0;
202 bool invalid_opt
= false;
205 struct option long_opts
[] = {
206 { "exclude-random", required_argument
, NULL
, 'e' },
207 { "help", no_argument
, NULL
, 'h' },
208 { "version", no_argument
, NULL
, 'v' },
214 const struct color
*colors
[2] = {
215 NULL
, /* foreground */
216 NULL
, /* background */
221 enum stream_mode mode
= SCAN_FIRST
;
223 program_name
= argv
[0];
226 setvbuf (stdout
, NULL
, _IOLBF
, 0);
228 while ((opt
= getopt_long (argc
, argv
, "hv", long_opts
, NULL
)) != -1)
234 exclude
= xstrdup (optarg
);
236 for (p
= exclude
; *p
; p
++)
238 if (streq (exclude
, "random"))
239 vfprintf_fail (formats
[FMT_GENERIC
], "--exclude-random switch must be provided a color");
251 default: /* never reached */
256 arg_cnt
= argc
- optind
;
258 if (arg_cnt
== 0 || arg_cnt
> 2 || invalid_opt
)
264 process_options (arg_cnt
, &argv
[optind
], &bold
, colors
, &file
, &stream
);
265 read_print_stream (bold
, colors
, file
, stream
, mode
);
267 RELEASE_VAR (exclude
);
277 printf ("Usage: %s (foreground) OR (foreground)/(background) [-|file]\n\n", program_name
);
278 printf ("\tColors (foreground) (background)\n");
279 for (i
= 0; i
< tables
[FOREGROUND
].count
; i
++)
281 const struct color
*entry
= &tables
[FOREGROUND
].entries
[i
];
282 const char *name
= entry
->name
;
283 const char *code
= entry
->code
;
285 printf ("\t\t{\033[%s#\033[0m} [%c%c]%s%*s%s\n",
286 code
, toupper (*name
), *name
, name
+ 1, 10 - (int)strlen (name
), " ", name
);
288 printf ("\t\t{-} %s%*s%s\n", name
, 13 - (int)strlen (name
), " ", name
);
290 printf ("\t\t{*} [Rr]%s%*s%s [--exclude-random=<foreground color>]\n", "andom", 10 - (int)strlen ("random"), " ", "random");
292 printf ("\n\tFirst character of color name in upper case denotes increased intensity,\n");
293 printf ("\twhereas for lower case colors will be of normal intensity.\n");
295 printf ("\n\tOptions\n");
296 printf ("\t\t-h, --help\n");
297 printf ("\t\t-v, --version\n\n");
304 printf ("%s v%s (compiled at %s, %s)\n", "colorize", VERSION
, __DATE__
, __TIME__
);
306 c_flags
= to_str (CFLAGS
);
310 printf ("Compiler flags: %s\n", c_flags
);
311 printf ("Buffer size: %d bytes\n", BUF_SIZE
- 1);
317 free_color_names (color_names
);
319 if (stream
&& fileno (stream
) != STDIN_FILENO
)
325 for (i
= 0; i
< stacked_vars
; i
++)
337 free_color_names (struct color_name
**color_names
)
340 for (i
= 0; color_names
[i
]; i
++)
342 free (color_names
[i
]->name
);
343 color_names
[i
]->name
= NULL
;
344 free (color_names
[i
]->orig
);
345 color_names
[i
]->orig
= NULL
;
346 free (color_names
[i
]);
347 color_names
[i
] = NULL
;
352 process_options (unsigned int arg_cnt
, char **option_strings
, bool *bold
, const struct color
**colors
, const char **file
, FILE **stream
)
356 char *color
, *p
, *str
;
359 const char *color_string
= arg_cnt
>= 1 ? option_strings
[0] : NULL
;
360 const char *file_string
= arg_cnt
== 2 ? option_strings
[1] : NULL
;
362 assert (color_string
);
364 if (streq (color_string
, "-"))
367 vfprintf_fail (formats
[FMT_GENERIC
], "hyphen cannot be used as color string");
369 vfprintf_fail (formats
[FMT_GENERIC
], "hyphen must be preceeded by color string");
372 ret
= stat (color_string
, &sb
);
374 /* Ensure that we don't fail if there's a file with one or more
375 color names in its path. */
380 const char *color
= color_string
;
382 for (c
= 1; c
<= 2 && *color
; c
++)
384 bool matched
= false;
386 for (i
= 0; i
< tables
[FOREGROUND
].count
; i
++)
388 const struct color
*entry
= &tables
[FOREGROUND
].entries
[i
];
390 if ((p
= strstr (color
, entry
->name
)) && p
== color
)
392 color
= p
+ strlen (entry
->name
);
397 if (matched
&& *color
== '/' && *(color
+ 1))
403 have_file
= (*color
!= '\0');
406 vfprintf_fail (formats
[FMT_GENERIC
], "file must be preceeded by color string");
409 if ((p
= strchr (color_string
, '/')))
411 if (p
== color_string
)
412 vfprintf_fail (formats
[FMT_GENERIC
], "foreground color missing");
413 else if (p
== color_string
+ strlen (color_string
) - 1)
414 vfprintf_fail (formats
[FMT_GENERIC
], "background color missing");
415 else if (strchr (++p
, '/'))
416 vfprintf_fail (formats
[FMT_GENERIC
], "one color pair allowed only");
419 str
= xstrdup (color_string
);
422 for (index
= 0, color
= str
; *color
; index
++, color
= p
)
425 if ((sep
= strchr (color
, '/')))
431 p
= color
+ strlen (color
);
433 for (ch
= color
; *ch
; ch
++)
435 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be made of non-alphabetic characters");
437 for (ch
= color
+ 1; *ch
; ch
++)
439 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be in mixed lower/upper case");
441 if (streq (color
, "None"))
442 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color
, "cannot be bold");
444 if (isupper (*color
))
452 vfprintf_fail (formats
[FMT_COLOR
], tables
[BACKGROUND
].desc
, color
, "cannot be bold");
454 default: /* never reached */
459 color_names
[index
] = xmalloc (sizeof (struct color_name
));
461 color_names
[index
]->orig
= xstrdup (color
);
463 for (ch
= color
; *ch
; ch
++)
466 color_names
[index
]->name
= xstrdup (color
);
471 assert (color_names
[FOREGROUND
]);
473 if (color_names
[BACKGROUND
])
476 unsigned int color_sets
[2][2] = { { FOREGROUND
, BACKGROUND
}, { BACKGROUND
, FOREGROUND
} };
477 for (i
= 0; i
< 2; i
++)
479 unsigned int color1
= color_sets
[i
][0];
480 unsigned int color2
= color_sets
[i
][1];
481 if (CHECK_COLORS_RANDOM (color1
, color2
))
482 vfprintf_fail (formats
[FMT_RANDOM
], tables
[color1
].desc
, color_names
[color1
]->orig
, "cannot be combined with", color_names
[color2
]->orig
);
486 find_color_entries (color_names
, colors
);
487 free_color_names (color_names
);
489 if (!colors
[FOREGROUND
]->code
&& colors
[BACKGROUND
] && colors
[BACKGROUND
]->code
)
490 find_color_entry ("default", FOREGROUND
, colors
);
494 if (streq (file_string
, "-"))
499 const char *file
= file_string
;
504 ret
= stat (file
, &sb
);
507 vfprintf_fail (formats
[FMT_FILE
], file
, strerror (errno
));
509 if (!(S_ISREG (sb
.st_mode
) || S_ISLNK (sb
.st_mode
) || S_ISFIFO (sb
.st_mode
)))
510 vfprintf_fail (formats
[FMT_FILE
], file
, "unrecognized file type");
514 s
= fopen (file
, "r");
516 vfprintf_fail (formats
[FMT_FILE
], file
, strerror (errno
));
531 read_print_stream (bool bold
, const struct color
**colors
, const char *file
, FILE *stream
, enum stream_mode mode
)
534 unsigned int flags
= 0;
535 bool first
= false, always
= false;
545 default: /* never reached */
549 while (!feof (stream
))
554 memset (buf
, '\0', BUF_SIZE
);
555 bytes_read
= fread (buf
, 1, BUF_SIZE
- 1, stream
);
556 if (bytes_read
!= (BUF_SIZE
- 1) && ferror (stream
))
557 vfprintf_fail (formats
[FMT_ERROR
], BUF_SIZE
- 1, "read");
559 LOOP
: while ((eol
= strpbrk (line
, "\n\r")))
569 if (*(eol
+ 1) == '\n')
572 else if (*eol
== '\n')
575 vfprintf_fail (formats
[FMT_FILE
], file
, "unrecognized line ending");
578 p
= eol
+ SKIP_LINE_ENDINGS (flags
);
582 unsigned int count
= sizeof (endings
) / sizeof (struct ending
);
583 for (i
= 0; i
< count
; i
++)
585 if (flags
& endings
[i
].flags
)
588 if ((p
= strstr (eol
, endings
[i
].newline
)) && p
== eol
)
597 p
= eol
+ SKIP_LINE_ENDINGS (flags
);
600 print_line (colors
, bold
, line
, flags
);
603 print_line (colors
, bold
, line
, 0);
608 find_color_entries (struct color_name
**color_names
, const struct color
**colors
)
614 gettimeofday (&tv
, NULL
);
615 srand (tv
.tv_usec
* tv
.tv_sec
);
617 for (index
= 0; color_names
[index
]; index
++)
619 const char *color_name
= color_names
[index
]->name
;
621 const unsigned int count
= tables
[index
].count
;
622 const struct color
*const color_entries
= tables
[index
].entries
;
624 if (streq (color_name
, "random"))
630 i
= rand() % (count
- 2) + 1; /* omit color none and default */
634 /* --exclude-random */
635 if (exclude
&& streq (exclude
, color_entries
[i
].name
))
637 else if (color_names
[BACKGROUND
] && streq (color_names
[BACKGROUND
]->name
, color_entries
[i
].name
))
641 if (streq (colors
[FOREGROUND
]->name
, color_entries
[i
].name
))
644 default: /* never reached */
647 } while (excludable
);
648 colors
[index
] = (struct color
*)&color_entries
[i
];
651 find_color_entry (color_name
, index
, colors
);
656 find_color_entry (const char *const color_name
, unsigned int index
, const struct color
**colors
)
661 const unsigned int count
= tables
[index
].count
;
662 const struct color
*const color_entries
= tables
[index
].entries
;
664 for (i
= 0; i
< count
; i
++)
665 if (streq (color_name
, color_entries
[i
].name
))
667 colors
[index
] = (struct color
*)&color_entries
[i
];
672 vfprintf_fail (formats
[FMT_COLOR
], tables
[index
].desc
, color_name
, "not recognized");
676 print_line (const struct color
**colors
, bool bold
, const char *const line
, unsigned int flags
)
678 if (colors
[BACKGROUND
] && colors
[BACKGROUND
]->code
)
679 printf ("\033[%s", colors
[BACKGROUND
]->code
);
680 if (colors
[FOREGROUND
]->code
)
681 printf ("\033[%s%s%s\033[0m", bold
? "1;" : "", colors
[FOREGROUND
]->code
, line
);
683 printf (formats
[FMT_GENERIC
], line
);
691 malloc_wrap (size_t size
, const char *file
, unsigned int line
)
693 void *p
= malloc (size
);
695 MEM_ALLOC_FAIL (file
, line
);
700 realloc_wrap (void *ptr
, size_t size
, const char *file
, unsigned int line
)
702 void *p
= realloc (ptr
, size
);
704 MEM_ALLOC_FAIL (file
, line
);
709 strdup_wrap (const char *str
, const char *file
, unsigned int line
)
711 const unsigned int len
= strlen (str
) + 1;
712 char *p
= malloc (len
);
714 MEM_ALLOC_FAIL (file
, line
);
715 strncpy (p
, str
, len
);
720 vfprintf_fail (const char *fmt
, ...)
723 fprintf (stderr
, "%s: ", program_name
);
725 vfprintf (stderr
, fmt
, ap
);
727 fprintf (stderr
, "\n");
732 stack_var (void ***list
, unsigned int *stacked
, unsigned int index
, void *ptr
)
734 /* nothing to stack */
738 *list
= xmalloc (sizeof (void *));
742 for (i
= 0; i
< *stacked
; i
++)
748 *list
= xrealloc (*list
, (*stacked
+ 1) * sizeof (void *));
750 (*list
)[index
] = ptr
;
755 release_var (void **list
, unsigned int stacked
, void **ptr
)
758 /* nothing to release */
761 for (i
= 0; i
< stacked
; i
++)