strbuf: refactor strbuf_trim_trailing_ch()

We often have to split strings at some specified terminator character.
The strbuf_split*() functions, that we can use for this purpose,
return substrings that include the terminator character, so we often
need to remove that character.

When it is a whitespace, newline or directory separator, the
terminator character can easily be removed using an existing triming
function like strbuf_rtrim(), strbuf_trim_trailing_newline() or
strbuf_trim_trailing_dir_sep(). There is no function to remove that
character when it's not one of those characters though.

Let's introduce a new strbuf_trim_trailing_ch() function that can be
used to remove any trailing character, and let's refactor existing code
that manually removed trailing characters using this new function.

We are also going to use this new function in a following commit.

Signed-off-by: Christian Couder <chriscool@tuxfamily.org>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
This commit is contained in:
Christian Couder
2024-09-10 18:29:58 +02:00
committed by Junio C Hamano
parent 31c5b4b16f
commit 8afd0ee95a
3 changed files with 12 additions and 8 deletions

View File

@@ -134,6 +134,13 @@ void strbuf_trim_trailing_dir_sep(struct strbuf *sb)
sb->buf[sb->len] = '\0';
}
void strbuf_trim_trailing_ch(struct strbuf *sb, int c)
{
while (sb->len > 0 && sb->buf[sb->len - 1] == c)
sb->len--;
sb->buf[sb->len] = '\0';
}
void strbuf_trim_trailing_newline(struct strbuf *sb)
{
if (sb->len > 0 && sb->buf[sb->len - 1] == '\n') {

View File

@@ -197,6 +197,9 @@ void strbuf_trim_trailing_dir_sep(struct strbuf *sb);
/* Strip trailing LF or CR/LF */
void strbuf_trim_trailing_newline(struct strbuf *sb);
/* Strip trailing character c */
void strbuf_trim_trailing_ch(struct strbuf *sb, int c);
/**
* Replace the contents of the strbuf with a reencoded form. Returns -1
* on error, 0 on success.

View File

@@ -33,10 +33,7 @@ static int tr2_cfg_load_patterns(void)
tr2_cfg_patterns = strbuf_split_buf(envvar, strlen(envvar), ',', -1);
for (s = tr2_cfg_patterns; *s; s++) {
struct strbuf *buf = *s;
if (buf->len && buf->buf[buf->len - 1] == ',')
strbuf_setlen(buf, buf->len - 1);
strbuf_trim_trailing_ch(*s, ',');
strbuf_trim_trailing_newline(*s);
strbuf_trim(*s);
}
@@ -72,10 +69,7 @@ static int tr2_load_env_vars(void)
tr2_cfg_env_vars = strbuf_split_buf(varlist, strlen(varlist), ',', -1);
for (s = tr2_cfg_env_vars; *s; s++) {
struct strbuf *buf = *s;
if (buf->len && buf->buf[buf->len - 1] == ',')
strbuf_setlen(buf, buf->len - 1);
strbuf_trim_trailing_ch(*s, ',');
strbuf_trim_trailing_newline(*s);
strbuf_trim(*s);
}