From 5d77613152354b41b26c3a2a93155fb40650645d Mon Sep 17 00:00:00 2001 From: Steffen Vogel Date: Mon, 20 Aug 2018 12:12:54 +0200 Subject: [PATCH] utils: add decolor() to remove ANSI escape sequence from string --- include/villas/utils.h | 3 +++ lib/utils.c | 33 +++++++++++++++++++++++++++++++++ tests/unit/utils.c | 10 ++++++++++ 3 files changed, 46 insertions(+) diff --git a/include/villas/utils.h b/include/villas/utils.h index 5a2f742b5..c194493e7 100644 --- a/include/villas/utils.h +++ b/include/villas/utils.h @@ -263,6 +263,9 @@ pid_t spawn(const char *name, char *const argv[]); /** Determines the string length as printed on the screen (ignores escable sequences). */ size_t strlenp(const char *str); +/** Remove ANSI control sequences for colored output. */ +char * decolor(char *str); + #ifdef __cplusplus } diff --git a/lib/utils.c b/lib/utils.c index b45b9f344..f99d7edb5 100644 --- a/lib/utils.c +++ b/lib/utils.c @@ -384,3 +384,36 @@ size_t strlenp(const char *str) return sz; } + +char * decolor(char *str) +{ + char *p, *q; + bool inseq = false; + + for (p = q = str; *p; p++) { + switch (*p) { + case 0x1b: + if (*(++p) == '[') { + inseq = true; + continue; + } + break; + + case 'm': + if (inseq) { + inseq = false; + continue; + } + break; + } + + if (!inseq) { + *q = *p; + q++; + } + } + + *q = '\0'; + + return str; +} diff --git a/tests/unit/utils.c b/tests/unit/utils.c index 5faa58d3e..cfdd98cfc 100644 --- a/tests/unit/utils.c +++ b/tests/unit/utils.c @@ -184,3 +184,13 @@ Test(utils, sha1sum) fclose(f); } + +Test(utils, decolor) +{ + char str[] = "This " CLR_RED("is") " a " CLR_BLU("colored") " " CLR_BLD("text!"); + char expect[] = "This is a colored text!"; + + decolor(str); + + cr_assert_str_eq(str, expect); +}