static char * colorize_string (NmCli *nmc, NmcTermColor color, NmcTermFormat color_fmt, const char *str, gboolean *dealloc) { char *out; if ( use_colors (nmc) && (color != NMC_TERM_COLOR_NORMAL || color_fmt != NMC_TERM_FORMAT_NORMAL)) { out = nmc_colorize (nmc, color, color_fmt, str); *dealloc = TRUE; } else { out = (char *) str; *dealloc = FALSE; } return out; }
void debug(debug_t *debugger, const char *fmt, ...) { // noop when disabled if (0 == debugger->enabled) return; char *pre = NULL; char *post = NULL; va_list args; va_start(args, fmt); if (use_colors(debugger->stream)) { // [color][name][/color] if (-1 == asprintf(&pre, FMT, debugger->color, debugger->name)) { va_end(args); return; } } else { // [name] if (!(pre = strdup(debugger->name))) { va_end(args); return; } } // format args if (-1 == vasprintf(&post, fmt, args)) { free(pre); va_end(args); return; } // print to stream fprintf(debugger->stream, " %s : %s\n", pre, post); // release memory free(pre); free(post); }
char * nmc_colorize (NmCli *nmc, NmcTermColor color, NmcTermFormat format, const char *fmt, ...) { va_list args; char *str, *colored; const char *ansi_color, *color_end, *ansi_fmt, *format_end; static const char *end_seq = "\33[0m"; va_start (args, fmt); str = g_strdup_vprintf (fmt, args); va_end (args); if (!use_colors (nmc)) return str; ansi_color = nmc_term_color_sequence (color); ansi_fmt = nmc_term_format_sequence (format); color_end = *ansi_color ? end_seq : ""; format_end = *ansi_fmt ? end_seq : ""; colored = g_strdup_printf ("%s%s%s%s%s", ansi_fmt, ansi_color, str, color_end, format_end); g_free (str); return colored; }