refs/files: fix NULL pointer deref when releasing ref store
[git/gitster.git] / trailer.c
blob724cb78be5fda6ec5090f75b0d92a3c1c54bdba4
1 #include "git-compat-util.h"
2 #include "config.h"
3 #include "environment.h"
4 #include "gettext.h"
5 #include "string-list.h"
6 #include "run-command.h"
7 #include "commit.h"
8 #include "trailer.h"
9 #include "list.h"
11 * Copyright (c) 2013, 2014 Christian Couder <chriscool@tuxfamily.org>
14 struct conf_info {
15 char *name;
16 char *key;
17 char *command;
18 char *cmd;
19 enum trailer_where where;
20 enum trailer_if_exists if_exists;
21 enum trailer_if_missing if_missing;
24 static struct conf_info default_conf_info;
26 struct trailer_item {
27 struct list_head list;
29 * If this is not a trailer line, the line is stored in value
30 * (excluding the terminating newline) and token is NULL.
32 char *token;
33 char *value;
36 struct arg_item {
37 struct list_head list;
38 char *token;
39 char *value;
40 struct conf_info conf;
43 static LIST_HEAD(conf_head);
45 static char *separators = ":";
47 static int configured;
49 #define TRAILER_ARG_STRING "$ARG"
51 static const char *git_generated_prefixes[] = {
52 "Signed-off-by: ",
53 "(cherry picked from commit ",
54 NULL
57 /* Iterate over the elements of the list. */
58 #define list_for_each_dir(pos, head, is_reverse) \
59 for (pos = is_reverse ? (head)->prev : (head)->next; \
60 pos != (head); \
61 pos = is_reverse ? pos->prev : pos->next)
63 static int after_or_end(enum trailer_where where)
65 return (where == WHERE_AFTER) || (where == WHERE_END);
69 * Return the length of the string not including any final
70 * punctuation. E.g., the input "Signed-off-by:" would return
71 * 13, stripping the trailing punctuation but retaining
72 * internal punctuation.
74 static size_t token_len_without_separator(const char *token, size_t len)
76 while (len > 0 && !isalnum(token[len - 1]))
77 len--;
78 return len;
81 static int same_token(struct trailer_item *a, struct arg_item *b)
83 size_t a_len, b_len, min_len;
85 if (!a->token)
86 return 0;
88 a_len = token_len_without_separator(a->token, strlen(a->token));
89 b_len = token_len_without_separator(b->token, strlen(b->token));
90 min_len = (a_len > b_len) ? b_len : a_len;
92 return !strncasecmp(a->token, b->token, min_len);
95 static int same_value(struct trailer_item *a, struct arg_item *b)
97 return !strcasecmp(a->value, b->value);
100 static int same_trailer(struct trailer_item *a, struct arg_item *b)
102 return same_token(a, b) && same_value(a, b);
105 static inline int is_blank_line(const char *str)
107 const char *s = str;
108 while (*s && *s != '\n' && isspace(*s))
109 s++;
110 return !*s || *s == '\n';
113 static inline void strbuf_replace(struct strbuf *sb, const char *a, const char *b)
115 const char *ptr = strstr(sb->buf, a);
116 if (ptr)
117 strbuf_splice(sb, ptr - sb->buf, strlen(a), b, strlen(b));
120 static void free_trailer_item(struct trailer_item *item)
122 free(item->token);
123 free(item->value);
124 free(item);
127 static void free_arg_item(struct arg_item *item)
129 free(item->conf.name);
130 free(item->conf.key);
131 free(item->conf.command);
132 free(item->conf.cmd);
133 free(item->token);
134 free(item->value);
135 free(item);
138 static char last_non_space_char(const char *s)
140 int i;
141 for (i = strlen(s) - 1; i >= 0; i--)
142 if (!isspace(s[i]))
143 return s[i];
144 return '\0';
147 static struct trailer_item *trailer_from_arg(struct arg_item *arg_tok)
149 struct trailer_item *new_item = xcalloc(1, sizeof(*new_item));
150 new_item->token = arg_tok->token;
151 new_item->value = arg_tok->value;
152 arg_tok->token = arg_tok->value = NULL;
153 free_arg_item(arg_tok);
154 return new_item;
157 static void add_arg_to_input_list(struct trailer_item *on_tok,
158 struct arg_item *arg_tok)
160 int aoe = after_or_end(arg_tok->conf.where);
161 struct trailer_item *to_add = trailer_from_arg(arg_tok);
162 if (aoe)
163 list_add(&to_add->list, &on_tok->list);
164 else
165 list_add_tail(&to_add->list, &on_tok->list);
168 static int check_if_different(struct trailer_item *in_tok,
169 struct arg_item *arg_tok,
170 int check_all,
171 struct list_head *head)
173 enum trailer_where where = arg_tok->conf.where;
174 struct list_head *next_head;
175 do {
176 if (same_trailer(in_tok, arg_tok))
177 return 0;
179 * if we want to add a trailer after another one,
180 * we have to check those before this one
182 next_head = after_or_end(where) ? in_tok->list.prev
183 : in_tok->list.next;
184 if (next_head == head)
185 break;
186 in_tok = list_entry(next_head, struct trailer_item, list);
187 } while (check_all);
188 return 1;
191 static char *apply_command(struct conf_info *conf, const char *arg)
193 struct strbuf cmd = STRBUF_INIT;
194 struct strbuf buf = STRBUF_INIT;
195 struct child_process cp = CHILD_PROCESS_INIT;
196 char *result;
198 if (conf->cmd) {
199 strbuf_addstr(&cmd, conf->cmd);
200 strvec_push(&cp.args, cmd.buf);
201 if (arg)
202 strvec_push(&cp.args, arg);
203 } else if (conf->command) {
204 strbuf_addstr(&cmd, conf->command);
205 if (arg)
206 strbuf_replace(&cmd, TRAILER_ARG_STRING, arg);
207 strvec_push(&cp.args, cmd.buf);
209 strvec_pushv(&cp.env, (const char **)local_repo_env);
210 cp.no_stdin = 1;
211 cp.use_shell = 1;
213 if (capture_command(&cp, &buf, 1024)) {
214 error(_("running trailer command '%s' failed"), cmd.buf);
215 strbuf_release(&buf);
216 result = xstrdup("");
217 } else {
218 strbuf_trim(&buf);
219 result = strbuf_detach(&buf, NULL);
222 strbuf_release(&cmd);
223 return result;
226 static void apply_item_command(struct trailer_item *in_tok, struct arg_item *arg_tok)
228 if (arg_tok->conf.command || arg_tok->conf.cmd) {
229 const char *arg;
230 if (arg_tok->value && arg_tok->value[0]) {
231 arg = arg_tok->value;
232 } else {
233 if (in_tok && in_tok->value)
234 arg = xstrdup(in_tok->value);
235 else
236 arg = xstrdup("");
238 arg_tok->value = apply_command(&arg_tok->conf, arg);
239 free((char *)arg);
243 static void apply_arg_if_exists(struct trailer_item *in_tok,
244 struct arg_item *arg_tok,
245 struct trailer_item *on_tok,
246 struct list_head *head)
248 switch (arg_tok->conf.if_exists) {
249 case EXISTS_DO_NOTHING:
250 free_arg_item(arg_tok);
251 break;
252 case EXISTS_REPLACE:
253 apply_item_command(in_tok, arg_tok);
254 add_arg_to_input_list(on_tok, arg_tok);
255 list_del(&in_tok->list);
256 free_trailer_item(in_tok);
257 break;
258 case EXISTS_ADD:
259 apply_item_command(in_tok, arg_tok);
260 add_arg_to_input_list(on_tok, arg_tok);
261 break;
262 case EXISTS_ADD_IF_DIFFERENT:
263 apply_item_command(in_tok, arg_tok);
264 if (check_if_different(in_tok, arg_tok, 1, head))
265 add_arg_to_input_list(on_tok, arg_tok);
266 else
267 free_arg_item(arg_tok);
268 break;
269 case EXISTS_ADD_IF_DIFFERENT_NEIGHBOR:
270 apply_item_command(in_tok, arg_tok);
271 if (check_if_different(on_tok, arg_tok, 0, head))
272 add_arg_to_input_list(on_tok, arg_tok);
273 else
274 free_arg_item(arg_tok);
275 break;
276 default:
277 BUG("trailer.c: unhandled value %d",
278 arg_tok->conf.if_exists);
282 static void apply_arg_if_missing(struct list_head *head,
283 struct arg_item *arg_tok)
285 enum trailer_where where;
286 struct trailer_item *to_add;
288 switch (arg_tok->conf.if_missing) {
289 case MISSING_DO_NOTHING:
290 free_arg_item(arg_tok);
291 break;
292 case MISSING_ADD:
293 where = arg_tok->conf.where;
294 apply_item_command(NULL, arg_tok);
295 to_add = trailer_from_arg(arg_tok);
296 if (after_or_end(where))
297 list_add_tail(&to_add->list, head);
298 else
299 list_add(&to_add->list, head);
300 break;
301 default:
302 BUG("trailer.c: unhandled value %d",
303 arg_tok->conf.if_missing);
307 static int find_same_and_apply_arg(struct list_head *head,
308 struct arg_item *arg_tok)
310 struct list_head *pos;
311 struct trailer_item *in_tok;
312 struct trailer_item *on_tok;
314 enum trailer_where where = arg_tok->conf.where;
315 int middle = (where == WHERE_AFTER) || (where == WHERE_BEFORE);
316 int backwards = after_or_end(where);
317 struct trailer_item *start_tok;
319 if (list_empty(head))
320 return 0;
322 start_tok = list_entry(backwards ? head->prev : head->next,
323 struct trailer_item,
324 list);
326 list_for_each_dir(pos, head, backwards) {
327 in_tok = list_entry(pos, struct trailer_item, list);
328 if (!same_token(in_tok, arg_tok))
329 continue;
330 on_tok = middle ? in_tok : start_tok;
331 apply_arg_if_exists(in_tok, arg_tok, on_tok, head);
332 return 1;
334 return 0;
337 void process_trailers_lists(struct list_head *head,
338 struct list_head *arg_head)
340 struct list_head *pos, *p;
341 struct arg_item *arg_tok;
343 list_for_each_safe(pos, p, arg_head) {
344 int applied = 0;
345 arg_tok = list_entry(pos, struct arg_item, list);
347 list_del(pos);
349 applied = find_same_and_apply_arg(head, arg_tok);
351 if (!applied)
352 apply_arg_if_missing(head, arg_tok);
356 int trailer_set_where(enum trailer_where *item, const char *value)
358 if (!value)
359 *item = WHERE_DEFAULT;
360 else if (!strcasecmp("after", value))
361 *item = WHERE_AFTER;
362 else if (!strcasecmp("before", value))
363 *item = WHERE_BEFORE;
364 else if (!strcasecmp("end", value))
365 *item = WHERE_END;
366 else if (!strcasecmp("start", value))
367 *item = WHERE_START;
368 else
369 return -1;
370 return 0;
373 int trailer_set_if_exists(enum trailer_if_exists *item, const char *value)
375 if (!value)
376 *item = EXISTS_DEFAULT;
377 else if (!strcasecmp("addIfDifferent", value))
378 *item = EXISTS_ADD_IF_DIFFERENT;
379 else if (!strcasecmp("addIfDifferentNeighbor", value))
380 *item = EXISTS_ADD_IF_DIFFERENT_NEIGHBOR;
381 else if (!strcasecmp("add", value))
382 *item = EXISTS_ADD;
383 else if (!strcasecmp("replace", value))
384 *item = EXISTS_REPLACE;
385 else if (!strcasecmp("doNothing", value))
386 *item = EXISTS_DO_NOTHING;
387 else
388 return -1;
389 return 0;
392 int trailer_set_if_missing(enum trailer_if_missing *item, const char *value)
394 if (!value)
395 *item = MISSING_DEFAULT;
396 else if (!strcasecmp("doNothing", value))
397 *item = MISSING_DO_NOTHING;
398 else if (!strcasecmp("add", value))
399 *item = MISSING_ADD;
400 else
401 return -1;
402 return 0;
405 static void duplicate_conf(struct conf_info *dst, const struct conf_info *src)
407 *dst = *src;
408 dst->name = xstrdup_or_null(src->name);
409 dst->key = xstrdup_or_null(src->key);
410 dst->command = xstrdup_or_null(src->command);
411 dst->cmd = xstrdup_or_null(src->cmd);
414 static struct arg_item *get_conf_item(const char *name)
416 struct list_head *pos;
417 struct arg_item *item;
419 /* Look up item with same name */
420 list_for_each(pos, &conf_head) {
421 item = list_entry(pos, struct arg_item, list);
422 if (!strcasecmp(item->conf.name, name))
423 return item;
426 /* Item does not already exists, create it */
427 CALLOC_ARRAY(item, 1);
428 duplicate_conf(&item->conf, &default_conf_info);
429 item->conf.name = xstrdup(name);
431 list_add_tail(&item->list, &conf_head);
433 return item;
436 enum trailer_info_type { TRAILER_KEY, TRAILER_COMMAND, TRAILER_CMD,
437 TRAILER_WHERE, TRAILER_IF_EXISTS, TRAILER_IF_MISSING };
439 static struct {
440 const char *name;
441 enum trailer_info_type type;
442 } trailer_config_items[] = {
443 { "key", TRAILER_KEY },
444 { "command", TRAILER_COMMAND },
445 { "cmd", TRAILER_CMD },
446 { "where", TRAILER_WHERE },
447 { "ifexists", TRAILER_IF_EXISTS },
448 { "ifmissing", TRAILER_IF_MISSING }
451 static int git_trailer_default_config(const char *conf_key, const char *value,
452 const struct config_context *ctx UNUSED,
453 void *cb UNUSED)
455 const char *trailer_item, *variable_name;
457 if (!skip_prefix(conf_key, "trailer.", &trailer_item))
458 return 0;
460 variable_name = strrchr(trailer_item, '.');
461 if (!variable_name) {
462 if (!strcmp(trailer_item, "where")) {
463 if (trailer_set_where(&default_conf_info.where,
464 value) < 0)
465 warning(_("unknown value '%s' for key '%s'"),
466 value, conf_key);
467 } else if (!strcmp(trailer_item, "ifexists")) {
468 if (trailer_set_if_exists(&default_conf_info.if_exists,
469 value) < 0)
470 warning(_("unknown value '%s' for key '%s'"),
471 value, conf_key);
472 } else if (!strcmp(trailer_item, "ifmissing")) {
473 if (trailer_set_if_missing(&default_conf_info.if_missing,
474 value) < 0)
475 warning(_("unknown value '%s' for key '%s'"),
476 value, conf_key);
477 } else if (!strcmp(trailer_item, "separators")) {
478 if (!value)
479 return config_error_nonbool(conf_key);
480 separators = xstrdup(value);
483 return 0;
486 static int git_trailer_config(const char *conf_key, const char *value,
487 const struct config_context *ctx UNUSED,
488 void *cb UNUSED)
490 const char *trailer_item, *variable_name;
491 struct arg_item *item;
492 struct conf_info *conf;
493 char *name = NULL;
494 enum trailer_info_type type;
495 int i;
497 if (!skip_prefix(conf_key, "trailer.", &trailer_item))
498 return 0;
500 variable_name = strrchr(trailer_item, '.');
501 if (!variable_name)
502 return 0;
504 variable_name++;
505 for (i = 0; i < ARRAY_SIZE(trailer_config_items); i++) {
506 if (strcmp(trailer_config_items[i].name, variable_name))
507 continue;
508 name = xstrndup(trailer_item, variable_name - trailer_item - 1);
509 type = trailer_config_items[i].type;
510 break;
513 if (!name)
514 return 0;
516 item = get_conf_item(name);
517 conf = &item->conf;
518 free(name);
520 switch (type) {
521 case TRAILER_KEY:
522 if (conf->key)
523 warning(_("more than one %s"), conf_key);
524 if (!value)
525 return config_error_nonbool(conf_key);
526 conf->key = xstrdup(value);
527 break;
528 case TRAILER_COMMAND:
529 if (conf->command)
530 warning(_("more than one %s"), conf_key);
531 if (!value)
532 return config_error_nonbool(conf_key);
533 conf->command = xstrdup(value);
534 break;
535 case TRAILER_CMD:
536 if (conf->cmd)
537 warning(_("more than one %s"), conf_key);
538 if (!value)
539 return config_error_nonbool(conf_key);
540 conf->cmd = xstrdup(value);
541 break;
542 case TRAILER_WHERE:
543 if (trailer_set_where(&conf->where, value))
544 warning(_("unknown value '%s' for key '%s'"), value, conf_key);
545 break;
546 case TRAILER_IF_EXISTS:
547 if (trailer_set_if_exists(&conf->if_exists, value))
548 warning(_("unknown value '%s' for key '%s'"), value, conf_key);
549 break;
550 case TRAILER_IF_MISSING:
551 if (trailer_set_if_missing(&conf->if_missing, value))
552 warning(_("unknown value '%s' for key '%s'"), value, conf_key);
553 break;
554 default:
555 BUG("trailer.c: unhandled type %d", type);
557 return 0;
560 void trailer_config_init(void)
562 if (configured)
563 return;
565 /* Default config must be setup first */
566 default_conf_info.where = WHERE_END;
567 default_conf_info.if_exists = EXISTS_ADD_IF_DIFFERENT_NEIGHBOR;
568 default_conf_info.if_missing = MISSING_ADD;
569 git_config(git_trailer_default_config, NULL);
570 git_config(git_trailer_config, NULL);
571 configured = 1;
574 static const char *token_from_item(struct arg_item *item, char *tok)
576 if (item->conf.key)
577 return item->conf.key;
578 if (tok)
579 return tok;
580 return item->conf.name;
583 static int token_matches_item(const char *tok, struct arg_item *item, size_t tok_len)
585 if (!strncasecmp(tok, item->conf.name, tok_len))
586 return 1;
587 return item->conf.key ? !strncasecmp(tok, item->conf.key, tok_len) : 0;
591 * If the given line is of the form
592 * "<token><optional whitespace><separator>..." or "<separator>...", return the
593 * location of the separator. Otherwise, return -1. The optional whitespace
594 * is allowed there primarily to allow things like "Bug #43" where <token> is
595 * "Bug" and <separator> is "#".
597 * The separator-starts-line case (in which this function returns 0) is
598 * distinguished from the non-well-formed-line case (in which this function
599 * returns -1) because some callers of this function need such a distinction.
601 static ssize_t find_separator(const char *line, const char *separators)
603 int whitespace_found = 0;
604 const char *c;
605 for (c = line; *c; c++) {
606 if (strchr(separators, *c))
607 return c - line;
608 if (!whitespace_found && (isalnum(*c) || *c == '-'))
609 continue;
610 if (c != line && (*c == ' ' || *c == '\t')) {
611 whitespace_found = 1;
612 continue;
614 break;
616 return -1;
620 * Obtain the token, value, and conf from the given trailer.
622 * separator_pos must not be 0, since the token cannot be an empty string.
624 * If separator_pos is -1, interpret the whole trailer as a token.
626 static void parse_trailer(struct strbuf *tok, struct strbuf *val,
627 const struct conf_info **conf, const char *trailer,
628 ssize_t separator_pos)
630 struct arg_item *item;
631 size_t tok_len;
632 struct list_head *pos;
634 if (separator_pos != -1) {
635 strbuf_add(tok, trailer, separator_pos);
636 strbuf_trim(tok);
637 strbuf_addstr(val, trailer + separator_pos + 1);
638 strbuf_trim(val);
639 } else {
640 strbuf_addstr(tok, trailer);
641 strbuf_trim(tok);
644 /* Lookup if the token matches something in the config */
645 tok_len = token_len_without_separator(tok->buf, tok->len);
646 if (conf)
647 *conf = &default_conf_info;
648 list_for_each(pos, &conf_head) {
649 item = list_entry(pos, struct arg_item, list);
650 if (token_matches_item(tok->buf, item, tok_len)) {
651 char *tok_buf = strbuf_detach(tok, NULL);
652 if (conf)
653 *conf = &item->conf;
654 strbuf_addstr(tok, token_from_item(item, tok_buf));
655 free(tok_buf);
656 break;
661 static struct trailer_item *add_trailer_item(struct list_head *head, char *tok,
662 char *val)
664 struct trailer_item *new_item = xcalloc(1, sizeof(*new_item));
665 new_item->token = tok;
666 new_item->value = val;
667 list_add_tail(&new_item->list, head);
668 return new_item;
671 static void add_arg_item(struct list_head *arg_head, char *tok, char *val,
672 const struct conf_info *conf,
673 const struct new_trailer_item *new_trailer_item)
675 struct arg_item *new_item = xcalloc(1, sizeof(*new_item));
676 new_item->token = tok;
677 new_item->value = val;
678 duplicate_conf(&new_item->conf, conf);
679 if (new_trailer_item) {
680 if (new_trailer_item->where != WHERE_DEFAULT)
681 new_item->conf.where = new_trailer_item->where;
682 if (new_trailer_item->if_exists != EXISTS_DEFAULT)
683 new_item->conf.if_exists = new_trailer_item->if_exists;
684 if (new_trailer_item->if_missing != MISSING_DEFAULT)
685 new_item->conf.if_missing = new_trailer_item->if_missing;
687 list_add_tail(&new_item->list, arg_head);
690 void parse_trailers_from_config(struct list_head *config_head)
692 struct arg_item *item;
693 struct list_head *pos;
695 /* Add an arg item for each configured trailer with a command */
696 list_for_each(pos, &conf_head) {
697 item = list_entry(pos, struct arg_item, list);
698 if (item->conf.command)
699 add_arg_item(config_head,
700 xstrdup(token_from_item(item, NULL)),
701 xstrdup(""),
702 &item->conf, NULL);
706 void parse_trailers_from_command_line_args(struct list_head *arg_head,
707 struct list_head *new_trailer_head)
709 struct strbuf tok = STRBUF_INIT;
710 struct strbuf val = STRBUF_INIT;
711 const struct conf_info *conf;
712 struct list_head *pos;
715 * In command-line arguments, '=' is accepted (in addition to the
716 * separators that are defined).
718 char *cl_separators = xstrfmt("=%s", separators);
720 /* Add an arg item for each trailer on the command line */
721 list_for_each(pos, new_trailer_head) {
722 struct new_trailer_item *tr =
723 list_entry(pos, struct new_trailer_item, list);
724 ssize_t separator_pos = find_separator(tr->text, cl_separators);
726 if (separator_pos == 0) {
727 struct strbuf sb = STRBUF_INIT;
728 strbuf_addstr(&sb, tr->text);
729 strbuf_trim(&sb);
730 error(_("empty trailer token in trailer '%.*s'"),
731 (int) sb.len, sb.buf);
732 strbuf_release(&sb);
733 } else {
734 parse_trailer(&tok, &val, &conf, tr->text,
735 separator_pos);
736 add_arg_item(arg_head,
737 strbuf_detach(&tok, NULL),
738 strbuf_detach(&val, NULL),
739 conf, tr);
743 free(cl_separators);
746 static const char *next_line(const char *str)
748 const char *nl = strchrnul(str, '\n');
749 return nl + !!*nl;
753 * Return the position of the start of the last line. If len is 0, return -1.
755 static ssize_t last_line(const char *buf, size_t len)
757 ssize_t i;
758 if (len == 0)
759 return -1;
760 if (len == 1)
761 return 0;
763 * Skip the last character (in addition to the null terminator),
764 * because if the last character is a newline, it is considered as part
765 * of the last line anyway.
767 i = len - 2;
769 for (; i >= 0; i--) {
770 if (buf[i] == '\n')
771 return i + 1;
773 return 0;
777 * Find the end of the log message as an offset from the start of the input
778 * (where callers of this function are interested in looking for a trailers
779 * block in the same input). We have to consider two categories of content that
780 * can come at the end of the input which we want to ignore (because they don't
781 * belong in the log message):
783 * (1) the "patch part" which begins with a "---" divider and has patch
784 * information (like the output of git-format-patch), and
786 * (2) any trailing comment lines, blank lines like in the output of "git
787 * commit -v", or stuff below the "cut" (scissor) line.
789 * As a formula, the situation looks like this:
791 * INPUT = LOG MESSAGE + IGNORED
793 * where IGNORED can be either of the two categories described above. It may be
794 * that there is nothing to ignore. Now it may be the case that the LOG MESSAGE
795 * contains a trailer block, but that's not the concern of this function.
797 static size_t find_end_of_log_message(const char *input, int no_divider)
799 size_t end;
800 const char *s;
802 /* Assume the naive end of the input is already what we want. */
803 end = strlen(input);
805 /* Optionally skip over any patch part ("---" line and below). */
806 if (!no_divider) {
807 for (s = input; *s; s = next_line(s)) {
808 const char *v;
810 if (skip_prefix(s, "---", &v) && isspace(*v)) {
811 end = s - input;
812 break;
817 /* Skip over other ignorable bits. */
818 return end - ignored_log_message_bytes(input, end);
822 * Return the position of the first trailer line or len if there are no
823 * trailers.
825 static size_t find_trailer_block_start(const char *buf, size_t len)
827 const char *s;
828 ssize_t end_of_title, l;
829 int only_spaces = 1;
830 int recognized_prefix = 0, trailer_lines = 0, non_trailer_lines = 0;
832 * Number of possible continuation lines encountered. This will be
833 * reset to 0 if we encounter a trailer (since those lines are to be
834 * considered continuations of that trailer), and added to
835 * non_trailer_lines if we encounter a non-trailer (since those lines
836 * are to be considered non-trailers).
838 int possible_continuation_lines = 0;
840 /* The first paragraph is the title and cannot be trailers */
841 for (s = buf; s < buf + len; s = next_line(s)) {
842 if (starts_with_mem(s, buf + len - s, comment_line_str))
843 continue;
844 if (is_blank_line(s))
845 break;
847 end_of_title = s - buf;
850 * Get the start of the trailers by looking starting from the end for a
851 * blank line before a set of non-blank lines that (i) are all
852 * trailers, or (ii) contains at least one Git-generated trailer and
853 * consists of at least 25% trailers.
855 for (l = last_line(buf, len);
856 l >= end_of_title;
857 l = last_line(buf, l)) {
858 const char *bol = buf + l;
859 const char **p;
860 ssize_t separator_pos;
862 if (starts_with_mem(bol, buf + len - bol, comment_line_str)) {
863 non_trailer_lines += possible_continuation_lines;
864 possible_continuation_lines = 0;
865 continue;
867 if (is_blank_line(bol)) {
868 if (only_spaces)
869 continue;
870 non_trailer_lines += possible_continuation_lines;
871 if (recognized_prefix &&
872 trailer_lines * 3 >= non_trailer_lines)
873 return next_line(bol) - buf;
874 else if (trailer_lines && !non_trailer_lines)
875 return next_line(bol) - buf;
876 return len;
878 only_spaces = 0;
880 for (p = git_generated_prefixes; *p; p++) {
881 if (starts_with(bol, *p)) {
882 trailer_lines++;
883 possible_continuation_lines = 0;
884 recognized_prefix = 1;
885 goto continue_outer_loop;
889 separator_pos = find_separator(bol, separators);
890 if (separator_pos >= 1 && !isspace(bol[0])) {
891 struct list_head *pos;
893 trailer_lines++;
894 possible_continuation_lines = 0;
895 if (recognized_prefix)
896 continue;
897 list_for_each(pos, &conf_head) {
898 struct arg_item *item;
899 item = list_entry(pos, struct arg_item, list);
900 if (token_matches_item(bol, item,
901 separator_pos)) {
902 recognized_prefix = 1;
903 break;
906 } else if (isspace(bol[0]))
907 possible_continuation_lines++;
908 else {
909 non_trailer_lines++;
910 non_trailer_lines += possible_continuation_lines;
911 possible_continuation_lines = 0;
913 continue_outer_loop:
917 return len;
920 static int ends_with_blank_line(const char *buf, size_t len)
922 ssize_t ll = last_line(buf, len);
923 if (ll < 0)
924 return 0;
925 return is_blank_line(buf + ll);
928 static void unfold_value(struct strbuf *val)
930 struct strbuf out = STRBUF_INIT;
931 size_t i;
933 strbuf_grow(&out, val->len);
934 i = 0;
935 while (i < val->len) {
936 char c = val->buf[i++];
937 if (c == '\n') {
938 /* Collapse continuation down to a single space. */
939 while (i < val->len && isspace(val->buf[i]))
940 i++;
941 strbuf_addch(&out, ' ');
942 } else {
943 strbuf_addch(&out, c);
947 /* Empty lines may have left us with whitespace cruft at the edges */
948 strbuf_trim(&out);
950 /* output goes back to val as if we modified it in-place */
951 strbuf_swap(&out, val);
952 strbuf_release(&out);
956 * Parse trailers in "str", populating the trailer info and "head"
957 * linked list structure.
959 void parse_trailers(const struct process_trailer_options *opts,
960 struct trailer_info *info,
961 const char *str,
962 struct list_head *head)
964 struct strbuf tok = STRBUF_INIT;
965 struct strbuf val = STRBUF_INIT;
966 size_t i;
968 trailer_info_get(opts, str, info);
970 for (i = 0; i < info->trailer_nr; i++) {
971 int separator_pos;
972 char *trailer = info->trailers[i];
973 if (starts_with(trailer, comment_line_str))
974 continue;
975 separator_pos = find_separator(trailer, separators);
976 if (separator_pos >= 1) {
977 parse_trailer(&tok, &val, NULL, trailer,
978 separator_pos);
979 if (opts->unfold)
980 unfold_value(&val);
981 add_trailer_item(head,
982 strbuf_detach(&tok, NULL),
983 strbuf_detach(&val, NULL));
984 } else if (!opts->only_trailers) {
985 strbuf_addstr(&val, trailer);
986 strbuf_strip_suffix(&val, "\n");
987 add_trailer_item(head,
988 NULL,
989 strbuf_detach(&val, NULL));
994 void free_trailers(struct list_head *trailers)
996 struct list_head *pos, *p;
997 list_for_each_safe(pos, p, trailers) {
998 list_del(pos);
999 free_trailer_item(list_entry(pos, struct trailer_item, list));
1003 void trailer_info_get(const struct process_trailer_options *opts,
1004 const char *str,
1005 struct trailer_info *info)
1007 size_t end_of_log_message = 0, trailer_block_start = 0;
1008 struct strbuf **trailer_lines, **ptr;
1009 char **trailer_strings = NULL;
1010 size_t nr = 0, alloc = 0;
1011 char **last = NULL;
1013 trailer_config_init();
1015 end_of_log_message = find_end_of_log_message(str, opts->no_divider);
1016 trailer_block_start = find_trailer_block_start(str, end_of_log_message);
1018 trailer_lines = strbuf_split_buf(str + trailer_block_start,
1019 end_of_log_message - trailer_block_start,
1020 '\n',
1022 for (ptr = trailer_lines; *ptr; ptr++) {
1023 if (last && isspace((*ptr)->buf[0])) {
1024 struct strbuf sb = STRBUF_INIT;
1025 strbuf_attach(&sb, *last, strlen(*last), strlen(*last));
1026 strbuf_addbuf(&sb, *ptr);
1027 *last = strbuf_detach(&sb, NULL);
1028 continue;
1030 ALLOC_GROW(trailer_strings, nr + 1, alloc);
1031 trailer_strings[nr] = strbuf_detach(*ptr, NULL);
1032 last = find_separator(trailer_strings[nr], separators) >= 1
1033 ? &trailer_strings[nr]
1034 : NULL;
1035 nr++;
1037 strbuf_list_free(trailer_lines);
1039 info->blank_line_before_trailer = ends_with_blank_line(str,
1040 trailer_block_start);
1041 info->trailer_block_start = trailer_block_start;
1042 info->trailer_block_end = end_of_log_message;
1043 info->trailers = trailer_strings;
1044 info->trailer_nr = nr;
1047 void trailer_info_release(struct trailer_info *info)
1049 size_t i;
1050 for (i = 0; i < info->trailer_nr; i++)
1051 free(info->trailers[i]);
1052 free(info->trailers);
1055 void format_trailers(const struct process_trailer_options *opts,
1056 struct list_head *trailers,
1057 struct strbuf *out)
1059 size_t origlen = out->len;
1060 struct list_head *pos;
1061 struct trailer_item *item;
1063 list_for_each(pos, trailers) {
1064 item = list_entry(pos, struct trailer_item, list);
1065 if (item->token) {
1066 struct strbuf tok = STRBUF_INIT;
1067 struct strbuf val = STRBUF_INIT;
1068 strbuf_addstr(&tok, item->token);
1069 strbuf_addstr(&val, item->value);
1072 * Skip key/value pairs where the value was empty. This
1073 * can happen from trailers specified without a
1074 * separator, like `--trailer "Reviewed-by"` (no
1075 * corresponding value).
1077 if (opts->trim_empty && !strlen(item->value))
1078 continue;
1080 if (!opts->filter || opts->filter(&tok, opts->filter_data)) {
1081 if (opts->separator && out->len != origlen)
1082 strbuf_addbuf(out, opts->separator);
1083 if (!opts->value_only)
1084 strbuf_addbuf(out, &tok);
1085 if (!opts->key_only && !opts->value_only) {
1086 if (opts->key_value_separator)
1087 strbuf_addbuf(out, opts->key_value_separator);
1088 else {
1089 char c = last_non_space_char(tok.buf);
1090 if (c && !strchr(separators, c))
1091 strbuf_addf(out, "%c ", separators[0]);
1094 if (!opts->key_only)
1095 strbuf_addbuf(out, &val);
1096 if (!opts->separator)
1097 strbuf_addch(out, '\n');
1099 strbuf_release(&tok);
1100 strbuf_release(&val);
1102 } else if (!opts->only_trailers) {
1103 if (opts->separator && out->len != origlen) {
1104 strbuf_addbuf(out, opts->separator);
1106 strbuf_addstr(out, item->value);
1107 if (opts->separator)
1108 strbuf_rtrim(out);
1109 else
1110 strbuf_addch(out, '\n');
1115 void format_trailers_from_commit(const struct process_trailer_options *opts,
1116 const char *msg,
1117 struct strbuf *out)
1119 LIST_HEAD(trailer_objects);
1120 struct trailer_info info;
1122 parse_trailers(opts, &info, msg, &trailer_objects);
1124 /* If we want the whole block untouched, we can take the fast path. */
1125 if (!opts->only_trailers && !opts->unfold && !opts->filter &&
1126 !opts->separator && !opts->key_only && !opts->value_only &&
1127 !opts->key_value_separator) {
1128 strbuf_add(out, msg + info.trailer_block_start,
1129 info.trailer_block_end - info.trailer_block_start);
1130 } else
1131 format_trailers(opts, &trailer_objects, out);
1133 free_trailers(&trailer_objects);
1134 trailer_info_release(&info);
1137 void trailer_iterator_init(struct trailer_iterator *iter, const char *msg)
1139 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
1140 strbuf_init(&iter->key, 0);
1141 strbuf_init(&iter->val, 0);
1142 opts.no_divider = 1;
1143 trailer_info_get(&opts, msg, &iter->internal.info);
1144 iter->internal.cur = 0;
1147 int trailer_iterator_advance(struct trailer_iterator *iter)
1149 while (iter->internal.cur < iter->internal.info.trailer_nr) {
1150 char *trailer = iter->internal.info.trailers[iter->internal.cur++];
1151 int separator_pos = find_separator(trailer, separators);
1153 if (separator_pos < 1)
1154 continue; /* not a real trailer */
1156 strbuf_reset(&iter->key);
1157 strbuf_reset(&iter->val);
1158 parse_trailer(&iter->key, &iter->val, NULL,
1159 trailer, separator_pos);
1160 /* Always unfold values during iteration. */
1161 unfold_value(&iter->val);
1162 return 1;
1164 return 0;
1167 void trailer_iterator_release(struct trailer_iterator *iter)
1169 trailer_info_release(&iter->internal.info);
1170 strbuf_release(&iter->val);
1171 strbuf_release(&iter->key);
1174 int amend_file_with_trailers(const char *path, const struct strvec *trailer_args)
1176 struct child_process run_trailer = CHILD_PROCESS_INIT;
1178 run_trailer.git_cmd = 1;
1179 strvec_pushl(&run_trailer.args, "interpret-trailers",
1180 "--in-place", "--no-divider",
1181 path, NULL);
1182 strvec_pushv(&run_trailer.args, trailer_args->v);
1183 return run_command(&run_trailer);