From 21f6c460fcda0161993f75421614efb6971af23b Mon Sep 17 00:00:00 2001 From: Tavian Barnes Date: Sat, 11 Mar 2017 14:06:42 -0500 Subject: Make a printf()-style API for colored messages --- color.h | 67 +++++++++++++++++++++++++++++++++++------------------------------ 1 file changed, 36 insertions(+), 31 deletions(-) (limited to 'color.h') diff --git a/color.h b/color.h index 8ba397d..c3b3e41 100644 --- a/color.h +++ b/color.h @@ -13,6 +13,7 @@ #define BFS_COLOR_H #include "bftw.h" +#include /** * A lookup table for colors. @@ -29,54 +30,58 @@ struct colors; struct colors *parse_colors(const char *ls_colors); /** - * Pretty-print a file path. + * Free a color table. * * @param colors - * The color table to use. - * @param ftwbuf - * The bftw() data for the current path. - * @return 0 on success, -1 on failure. + * The color table to free. */ -int pretty_print(const struct colors *colors, const struct BFTW *ftwbuf); +void free_colors(struct colors *colors); -#if __GNUC__ -# define BFS_PRINTF_ATTRIBUTE(f, v) __attribute__((format(printf, f, v))) -#else -# define BFS_PRINTF_ATTRIBUTE(f, v) -#endif +/** + * A file/stream with associated colors. + */ +typedef struct CFILE { + /** The underlying file/stream. */ + FILE *file; + /** The color table to use, if any. */ + const struct colors *colors; +} CFILE; /** - * Pretty-print a warning message. + * Make a colored copy of an open file. * + * @param file + * The underlying file. * @param colors - * The color table to use. - * @param format - * The format string. - * @param ... - * The format string's arguments. - * @return 0 on success, -1 on failure. + * The color table to use if file is a TTY. + * @return A colored wrapper around file. */ -int pretty_warning(const struct colors *colors, const char *format, ...) BFS_PRINTF_ATTRIBUTE(2, 3); +CFILE *cfdup(FILE *file, const struct colors *colors); /** - * Pretty-print an error message. + * Close a colored file. * - * @param colors - * The color table to use. - * @param format - * The format string. - * @param ... - * The format string's arguments. + * @param cfile + * The colored file to close. * @return 0 on success, -1 on failure. */ -int pretty_error(const struct colors *colors, const char *format, ...) BFS_PRINTF_ATTRIBUTE(2, 3); +int cfclose(CFILE *cfile); /** - * Free a color table. + * Colored, formatted output. * - * @param colors - * The color table to free. + * @param cfile + * The colored stream to print to. + * @param format + * A printf()-style format string, supporting these format specifiers: + * + * %%: A literal '%' + * %c: A single character + * %s: A string + * %P: A colored file path, from a const struct BFTW * argument + * %{cc}: Change the color to 'cc' + * @return 0 on success, -1 on failure. */ -void free_colors(struct colors *colors); +int cfprintf(CFILE *cfile, const char *format, ...); #endif // BFS_COLOR_H -- cgit v1.2.3