strbuf: separate callback for strbuf_expand:ing literals

Expanding '%n' and '%xNN' is generic functionality, so extract that from the pretty.c formatter into a callback that can be reused. No functional change intended Signed-off-by: Anders Waldenborg <anders@0x63.nu> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Anders Waldenborg committed Jan 28, 2019 at 22:33 UTC fd2015b323d283c73346d70d2285a927650bb60a
3 files changed +34 -11
pretty.c
+5 -11
@@ -1137,9 +1137,13 @@ static size_t format_commit_one(struct strbuf *sb, /* in UTF-8 */
1137 const char *msg = c->message;
1138 struct commit_list *p;
1139 const char *arg;
1140 - int ch;
1140 + size_t res;
1141
1142 /* these are independent of the commit */
1143 + res = strbuf_expand_literal_cb(sb, placeholder, NULL);
1144 + if (res)
1145 + return res;
1146 +
1147 switch (placeholder[0]) {
1148 case 'C':
1149 if (starts_with(placeholder + 1, "(auto)")) {
@@ -1158,16 +1162,6 @@ static size_t format_commit_one(struct strbuf *sb, /* in UTF-8 */
1162 */
1163 return ret;
1164 }
1161 - case 'n': /* newline */
1162 - strbuf_addch(sb, '\n');
1163 - return 1;
1164 - case 'x':
1165 - /* %x00 == NUL, %x0a == LF, etc. */
1166 - ch = hex2chr(placeholder + 1);
1167 - if (ch < 0)
1168 - return 0;
1169 - strbuf_addch(sb, ch);
1170 - return 3;
1165 case 'w':
1166 if (placeholder[1] == '(') {
1167 unsigned long width = 0, indent1 = 0, indent2 = 0;
strbuf.c
+21
@@ -380,6 +380,27 @@ void strbuf_expand(struct strbuf *sb, const char *format, expand_fn_t fn,
380 }
381 }
382
383 +size_t strbuf_expand_literal_cb(struct strbuf *sb,
384 + const char *placeholder,
385 + void *context)
386 +{
387 + int ch;
388 +
389 + switch (placeholder[0]) {
390 + case 'n': /* newline */
391 + strbuf_addch(sb, '\n');
392 + return 1;
393 + case 'x':
394 + /* %x00 == NUL, %x0a == LF, etc. */
395 + ch = hex2chr(placeholder + 1);
396 + if (ch < 0)
397 + return 0;
398 + strbuf_addch(sb, ch);
399 + return 3;
400 + }
401 + return 0;
402 +}
403 +
404 size_t strbuf_expand_dict_cb(struct strbuf *sb, const char *placeholder,
405 void *context)
406 {
strbuf.h
+8
@@ -320,6 +320,14 @@ void strbuf_expand(struct strbuf *sb,
320 expand_fn_t fn,
321 void *context);
322
323 +/**
324 + * Used as callback for `strbuf_expand` to only expand literals
325 + * (i.e. %n and %xNN). The context argument is ignored.
326 + */
327 +size_t strbuf_expand_literal_cb(struct strbuf *sb,
328 + const char *placeholder,
329 + void *context);
330 +
331 /**
332 * Used as callback for `strbuf_expand()`, expects an array of
333 * struct strbuf_expand_dict_entry as context, i.e. pairs of