Skip to content

Commit f225987

Browse files
peffgitster
authored andcommitted
format_config: simplify buffer handling
When formatting a config value into a strbuf, we may end up stringifying it into a fixed-size buffer using sprintf, and then copying that buffer into the strbuf. We can eliminate the middle-man (and drop some calls to sprintf!) by writing directly to the strbuf. The reason it was written this way in the first place is that we need to know before writing the value whether to insert a delimiter. Instead of delaying the write of the value, we speculatively write the delimiter, and roll it back in the single case that cares. Signed-off-by: Jeff King <peff@peff.net> Signed-off-by: Junio C Hamano <gitster@pobox.com>
1 parent 9f1429d commit f225987

1 file changed

Lines changed: 16 additions & 22 deletions

File tree

builtin/config.c

Lines changed: 16 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -111,41 +111,35 @@ static int format_config(struct strbuf *buf, const char *key_, const char *value
111111
if (show_keys)
112112
strbuf_addstr(buf, key_);
113113
if (!omit_values) {
114-
int must_free_vptr = 0;
115-
int must_add_delim = show_keys;
116-
char value[256];
117-
const char *vptr = value;
114+
if (show_keys)
115+
strbuf_addch(buf, key_delim);
118116

119117
if (types == TYPE_INT)
120-
sprintf(value, "%"PRId64,
121-
git_config_int64(key_, value_ ? value_ : ""));
118+
strbuf_addf(buf, "%"PRId64,
119+
git_config_int64(key_, value_ ? value_ : ""));
122120
else if (types == TYPE_BOOL)
123-
vptr = git_config_bool(key_, value_) ? "true" : "false";
121+
strbuf_addstr(buf, git_config_bool(key_, value_) ?
122+
"true" : "false");
124123
else if (types == TYPE_BOOL_OR_INT) {
125124
int is_bool, v;
126125
v = git_config_bool_or_int(key_, value_, &is_bool);
127126
if (is_bool)
128-
vptr = v ? "true" : "false";
127+
strbuf_addstr(buf, v ? "true" : "false");
129128
else
130-
sprintf(value, "%d", v);
129+
strbuf_addf(buf, "%d", v);
131130
} else if (types == TYPE_PATH) {
132-
if (git_config_pathname(&vptr, key_, value_) < 0)
131+
const char *v;
132+
if (git_config_pathname(&v, key_, value_) < 0)
133133
return -1;
134-
must_free_vptr = 1;
134+
strbuf_addstr(buf, v);
135+
free((char *)v);
135136
} else if (value_) {
136-
vptr = value_;
137+
strbuf_addstr(buf, value_);
137138
} else {
138-
/* Just show the key name */
139-
vptr = "";
140-
must_add_delim = 0;
139+
/* Just show the key name; back out delimiter */
140+
if (show_keys)
141+
strbuf_setlen(buf, buf->len - 1);
141142
}
142-
143-
if (must_add_delim)
144-
strbuf_addch(buf, key_delim);
145-
strbuf_addstr(buf, vptr);
146-
147-
if (must_free_vptr)
148-
free((char *)vptr);
149143
}
150144
strbuf_addch(buf, term);
151145
return 0;

0 commit comments

Comments
 (0)