1
0
Fork 0
mirror of https://git.rwth-aachen.de/acs/public/villas/node/ synced 2025-03-09 00:00:00 +01:00

utils: add decolor() to remove ANSI escape sequence from string

This commit is contained in:
Steffen Vogel 2018-08-20 12:12:54 +02:00
parent 2a7dee8324
commit 5d77613152
3 changed files with 46 additions and 0 deletions

View file

@ -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
}

View file

@ -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;
}

View file

@ -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);
}