Sync with 'maint'
[git/gitster.git] / trailer.c
blob46f0e4610bf5b949dedbe0132a8f3a3f0fffc644
1 #define USE_THE_REPOSITORY_VARIABLE
3 #include "git-compat-util.h"
4 #include "config.h"
5 #include "environment.h"
6 #include "gettext.h"
7 #include "string-list.h"
8 #include "run-command.h"
9 #include "commit.h"
10 #include "trailer.h"
11 #include "list.h"
13 * Copyright (c) 2013, 2014 Christian Couder <chriscool@tuxfamily.org>
16 struct trailer_block {
18 * True if there is a blank line before the location pointed to by
19 * "start".
21 int blank_line_before_trailer;
24 * The locations of the start and end positions of the trailer block
25 * found, as offsets from the beginning of the source text from which
26 * this trailer block was parsed. If no trailer block is found, these
27 * are both set to 0.
29 size_t start, end;
32 * Array of trailers found.
34 char **trailers;
35 size_t trailer_nr;
38 struct conf_info {
39 char *name;
40 char *key;
41 char *command;
42 char *cmd;
43 enum trailer_where where;
44 enum trailer_if_exists if_exists;
45 enum trailer_if_missing if_missing;
48 static struct conf_info default_conf_info;
50 struct trailer_item {
51 struct list_head list;
53 * If this is not a trailer line, the line is stored in value
54 * (excluding the terminating newline) and token is NULL.
56 char *token;
57 char *value;
60 struct arg_item {
61 struct list_head list;
62 char *token;
63 char *value;
64 struct conf_info conf;
67 static LIST_HEAD(conf_head);
69 static const char *separators = ":";
71 static int configured;
73 #define TRAILER_ARG_STRING "$ARG"
75 static const char *git_generated_prefixes[] = {
76 "Signed-off-by: ",
77 "(cherry picked from commit ",
78 NULL
81 /* Iterate over the elements of the list. */
82 #define list_for_each_dir(pos, head, is_reverse) \
83 for (pos = is_reverse ? (head)->prev : (head)->next; \
84 pos != (head); \
85 pos = is_reverse ? pos->prev : pos->next)
87 static int after_or_end(enum trailer_where where)
89 return (where == WHERE_AFTER) || (where == WHERE_END);
93 * Return the length of the string not including any final
94 * punctuation. E.g., the input "Signed-off-by:" would return
95 * 13, stripping the trailing punctuation but retaining
96 * internal punctuation.
98 static size_t token_len_without_separator(const char *token, size_t len)
100 while (len > 0 && !isalnum(token[len - 1]))
101 len--;
102 return len;
105 static int same_token(struct trailer_item *a, struct arg_item *b)
107 size_t a_len, b_len, min_len;
109 if (!a->token)
110 return 0;
112 a_len = token_len_without_separator(a->token, strlen(a->token));
113 b_len = token_len_without_separator(b->token, strlen(b->token));
114 min_len = (a_len > b_len) ? b_len : a_len;
116 return !strncasecmp(a->token, b->token, min_len);
119 static int same_value(struct trailer_item *a, struct arg_item *b)
121 return !strcasecmp(a->value, b->value);
124 static int same_trailer(struct trailer_item *a, struct arg_item *b)
126 return same_token(a, b) && same_value(a, b);
129 static inline int is_blank_line(const char *str)
131 const char *s = str;
132 while (*s && *s != '\n' && isspace(*s))
133 s++;
134 return !*s || *s == '\n';
137 static inline void strbuf_replace(struct strbuf *sb, const char *a, const char *b)
139 const char *ptr = strstr(sb->buf, a);
140 if (ptr)
141 strbuf_splice(sb, ptr - sb->buf, strlen(a), b, strlen(b));
144 static void free_trailer_item(struct trailer_item *item)
146 free(item->token);
147 free(item->value);
148 free(item);
151 static void free_arg_item(struct arg_item *item)
153 free(item->conf.name);
154 free(item->conf.key);
155 free(item->conf.command);
156 free(item->conf.cmd);
157 free(item->token);
158 free(item->value);
159 free(item);
162 static char last_non_space_char(const char *s)
164 int i;
165 for (i = strlen(s) - 1; i >= 0; i--)
166 if (!isspace(s[i]))
167 return s[i];
168 return '\0';
171 static struct trailer_item *trailer_from_arg(struct arg_item *arg_tok)
173 struct trailer_item *new_item = xcalloc(1, sizeof(*new_item));
174 new_item->token = arg_tok->token;
175 new_item->value = arg_tok->value;
176 arg_tok->token = arg_tok->value = NULL;
177 free_arg_item(arg_tok);
178 return new_item;
181 static void add_arg_to_input_list(struct trailer_item *on_tok,
182 struct arg_item *arg_tok)
184 int aoe = after_or_end(arg_tok->conf.where);
185 struct trailer_item *to_add = trailer_from_arg(arg_tok);
186 if (aoe)
187 list_add(&to_add->list, &on_tok->list);
188 else
189 list_add_tail(&to_add->list, &on_tok->list);
192 static int check_if_different(struct trailer_item *in_tok,
193 struct arg_item *arg_tok,
194 int check_all,
195 struct list_head *head)
197 enum trailer_where where = arg_tok->conf.where;
198 struct list_head *next_head;
199 do {
200 if (same_trailer(in_tok, arg_tok))
201 return 0;
203 * if we want to add a trailer after another one,
204 * we have to check those before this one
206 next_head = after_or_end(where) ? in_tok->list.prev
207 : in_tok->list.next;
208 if (next_head == head)
209 break;
210 in_tok = list_entry(next_head, struct trailer_item, list);
211 } while (check_all);
212 return 1;
215 static char *apply_command(struct conf_info *conf, const char *arg)
217 struct strbuf cmd = STRBUF_INIT;
218 struct strbuf buf = STRBUF_INIT;
219 struct child_process cp = CHILD_PROCESS_INIT;
220 char *result;
222 if (conf->cmd) {
223 strbuf_addstr(&cmd, conf->cmd);
224 strvec_push(&cp.args, cmd.buf);
225 if (arg)
226 strvec_push(&cp.args, arg);
227 } else if (conf->command) {
228 strbuf_addstr(&cmd, conf->command);
229 if (arg)
230 strbuf_replace(&cmd, TRAILER_ARG_STRING, arg);
231 strvec_push(&cp.args, cmd.buf);
233 strvec_pushv(&cp.env, (const char **)local_repo_env);
234 cp.no_stdin = 1;
235 cp.use_shell = 1;
237 if (capture_command(&cp, &buf, 1024)) {
238 error(_("running trailer command '%s' failed"), cmd.buf);
239 strbuf_release(&buf);
240 result = xstrdup("");
241 } else {
242 strbuf_trim(&buf);
243 result = strbuf_detach(&buf, NULL);
246 strbuf_release(&cmd);
247 return result;
250 static void apply_item_command(struct trailer_item *in_tok, struct arg_item *arg_tok)
252 if (arg_tok->conf.command || arg_tok->conf.cmd) {
253 char *value_to_free = NULL;
254 char *arg;
256 if (arg_tok->value && arg_tok->value[0]) {
257 arg = arg_tok->value;
258 } else {
259 if (in_tok && in_tok->value)
260 arg = xstrdup(in_tok->value);
261 else
262 arg = xstrdup("");
263 value_to_free = arg_tok->value;
266 arg_tok->value = apply_command(&arg_tok->conf, arg);
268 free(value_to_free);
269 free(arg);
273 static void apply_arg_if_exists(struct trailer_item *in_tok,
274 struct arg_item *arg_tok,
275 struct trailer_item *on_tok,
276 struct list_head *head)
278 switch (arg_tok->conf.if_exists) {
279 case EXISTS_DO_NOTHING:
280 free_arg_item(arg_tok);
281 break;
282 case EXISTS_REPLACE:
283 apply_item_command(in_tok, arg_tok);
284 add_arg_to_input_list(on_tok, arg_tok);
285 list_del(&in_tok->list);
286 free_trailer_item(in_tok);
287 break;
288 case EXISTS_ADD:
289 apply_item_command(in_tok, arg_tok);
290 add_arg_to_input_list(on_tok, arg_tok);
291 break;
292 case EXISTS_ADD_IF_DIFFERENT:
293 apply_item_command(in_tok, arg_tok);
294 if (check_if_different(in_tok, arg_tok, 1, head))
295 add_arg_to_input_list(on_tok, arg_tok);
296 else
297 free_arg_item(arg_tok);
298 break;
299 case EXISTS_ADD_IF_DIFFERENT_NEIGHBOR:
300 apply_item_command(in_tok, arg_tok);
301 if (check_if_different(on_tok, arg_tok, 0, head))
302 add_arg_to_input_list(on_tok, arg_tok);
303 else
304 free_arg_item(arg_tok);
305 break;
306 default:
307 BUG("trailer.c: unhandled value %d",
308 arg_tok->conf.if_exists);
312 static void apply_arg_if_missing(struct list_head *head,
313 struct arg_item *arg_tok)
315 enum trailer_where where;
316 struct trailer_item *to_add;
318 switch (arg_tok->conf.if_missing) {
319 case MISSING_DO_NOTHING:
320 free_arg_item(arg_tok);
321 break;
322 case MISSING_ADD:
323 where = arg_tok->conf.where;
324 apply_item_command(NULL, arg_tok);
325 to_add = trailer_from_arg(arg_tok);
326 if (after_or_end(where))
327 list_add_tail(&to_add->list, head);
328 else
329 list_add(&to_add->list, head);
330 break;
331 default:
332 BUG("trailer.c: unhandled value %d",
333 arg_tok->conf.if_missing);
337 static int find_same_and_apply_arg(struct list_head *head,
338 struct arg_item *arg_tok)
340 struct list_head *pos;
341 struct trailer_item *in_tok;
342 struct trailer_item *on_tok;
344 enum trailer_where where = arg_tok->conf.where;
345 int middle = (where == WHERE_AFTER) || (where == WHERE_BEFORE);
346 int backwards = after_or_end(where);
347 struct trailer_item *start_tok;
349 if (list_empty(head))
350 return 0;
352 start_tok = list_entry(backwards ? head->prev : head->next,
353 struct trailer_item,
354 list);
356 list_for_each_dir(pos, head, backwards) {
357 in_tok = list_entry(pos, struct trailer_item, list);
358 if (!same_token(in_tok, arg_tok))
359 continue;
360 on_tok = middle ? in_tok : start_tok;
361 apply_arg_if_exists(in_tok, arg_tok, on_tok, head);
362 return 1;
364 return 0;
367 void process_trailers_lists(struct list_head *head,
368 struct list_head *arg_head)
370 struct list_head *pos, *p;
371 struct arg_item *arg_tok;
373 list_for_each_safe(pos, p, arg_head) {
374 int applied = 0;
375 arg_tok = list_entry(pos, struct arg_item, list);
377 list_del(pos);
379 applied = find_same_and_apply_arg(head, arg_tok);
381 if (!applied)
382 apply_arg_if_missing(head, arg_tok);
386 int trailer_set_where(enum trailer_where *item, const char *value)
388 if (!value)
389 *item = WHERE_DEFAULT;
390 else if (!strcasecmp("after", value))
391 *item = WHERE_AFTER;
392 else if (!strcasecmp("before", value))
393 *item = WHERE_BEFORE;
394 else if (!strcasecmp("end", value))
395 *item = WHERE_END;
396 else if (!strcasecmp("start", value))
397 *item = WHERE_START;
398 else
399 return -1;
400 return 0;
403 int trailer_set_if_exists(enum trailer_if_exists *item, const char *value)
405 if (!value)
406 *item = EXISTS_DEFAULT;
407 else if (!strcasecmp("addIfDifferent", value))
408 *item = EXISTS_ADD_IF_DIFFERENT;
409 else if (!strcasecmp("addIfDifferentNeighbor", value))
410 *item = EXISTS_ADD_IF_DIFFERENT_NEIGHBOR;
411 else if (!strcasecmp("add", value))
412 *item = EXISTS_ADD;
413 else if (!strcasecmp("replace", value))
414 *item = EXISTS_REPLACE;
415 else if (!strcasecmp("doNothing", value))
416 *item = EXISTS_DO_NOTHING;
417 else
418 return -1;
419 return 0;
422 int trailer_set_if_missing(enum trailer_if_missing *item, const char *value)
424 if (!value)
425 *item = MISSING_DEFAULT;
426 else if (!strcasecmp("doNothing", value))
427 *item = MISSING_DO_NOTHING;
428 else if (!strcasecmp("add", value))
429 *item = MISSING_ADD;
430 else
431 return -1;
432 return 0;
435 static void duplicate_conf(struct conf_info *dst, const struct conf_info *src)
437 *dst = *src;
438 dst->name = xstrdup_or_null(src->name);
439 dst->key = xstrdup_or_null(src->key);
440 dst->command = xstrdup_or_null(src->command);
441 dst->cmd = xstrdup_or_null(src->cmd);
444 static struct arg_item *get_conf_item(const char *name)
446 struct list_head *pos;
447 struct arg_item *item;
449 /* Look up item with same name */
450 list_for_each(pos, &conf_head) {
451 item = list_entry(pos, struct arg_item, list);
452 if (!strcasecmp(item->conf.name, name))
453 return item;
456 /* Item does not already exists, create it */
457 CALLOC_ARRAY(item, 1);
458 duplicate_conf(&item->conf, &default_conf_info);
459 item->conf.name = xstrdup(name);
461 list_add_tail(&item->list, &conf_head);
463 return item;
466 enum trailer_info_type { TRAILER_KEY, TRAILER_COMMAND, TRAILER_CMD,
467 TRAILER_WHERE, TRAILER_IF_EXISTS, TRAILER_IF_MISSING };
469 static struct {
470 const char *name;
471 enum trailer_info_type type;
472 } trailer_config_items[] = {
473 { "key", TRAILER_KEY },
474 { "command", TRAILER_COMMAND },
475 { "cmd", TRAILER_CMD },
476 { "where", TRAILER_WHERE },
477 { "ifexists", TRAILER_IF_EXISTS },
478 { "ifmissing", TRAILER_IF_MISSING }
481 static int git_trailer_default_config(const char *conf_key, const char *value,
482 const struct config_context *ctx UNUSED,
483 void *cb UNUSED)
485 const char *trailer_item, *variable_name;
487 if (!skip_prefix(conf_key, "trailer.", &trailer_item))
488 return 0;
490 variable_name = strrchr(trailer_item, '.');
491 if (!variable_name) {
492 if (!strcmp(trailer_item, "where")) {
493 if (trailer_set_where(&default_conf_info.where,
494 value) < 0)
495 warning(_("unknown value '%s' for key '%s'"),
496 value, conf_key);
497 } else if (!strcmp(trailer_item, "ifexists")) {
498 if (trailer_set_if_exists(&default_conf_info.if_exists,
499 value) < 0)
500 warning(_("unknown value '%s' for key '%s'"),
501 value, conf_key);
502 } else if (!strcmp(trailer_item, "ifmissing")) {
503 if (trailer_set_if_missing(&default_conf_info.if_missing,
504 value) < 0)
505 warning(_("unknown value '%s' for key '%s'"),
506 value, conf_key);
507 } else if (!strcmp(trailer_item, "separators")) {
508 if (!value)
509 return config_error_nonbool(conf_key);
510 separators = xstrdup(value);
513 return 0;
516 static int git_trailer_config(const char *conf_key, const char *value,
517 const struct config_context *ctx UNUSED,
518 void *cb UNUSED)
520 const char *trailer_item, *variable_name;
521 struct arg_item *item;
522 struct conf_info *conf;
523 char *name = NULL;
524 enum trailer_info_type type;
525 int i;
527 if (!skip_prefix(conf_key, "trailer.", &trailer_item))
528 return 0;
530 variable_name = strrchr(trailer_item, '.');
531 if (!variable_name)
532 return 0;
534 variable_name++;
535 for (i = 0; i < ARRAY_SIZE(trailer_config_items); i++) {
536 if (strcmp(trailer_config_items[i].name, variable_name))
537 continue;
538 name = xstrndup(trailer_item, variable_name - trailer_item - 1);
539 type = trailer_config_items[i].type;
540 break;
543 if (!name)
544 return 0;
546 item = get_conf_item(name);
547 conf = &item->conf;
548 free(name);
550 switch (type) {
551 case TRAILER_KEY:
552 if (conf->key)
553 warning(_("more than one %s"), conf_key);
554 if (!value)
555 return config_error_nonbool(conf_key);
556 conf->key = xstrdup(value);
557 break;
558 case TRAILER_COMMAND:
559 if (conf->command)
560 warning(_("more than one %s"), conf_key);
561 if (!value)
562 return config_error_nonbool(conf_key);
563 conf->command = xstrdup(value);
564 break;
565 case TRAILER_CMD:
566 if (conf->cmd)
567 warning(_("more than one %s"), conf_key);
568 if (!value)
569 return config_error_nonbool(conf_key);
570 conf->cmd = xstrdup(value);
571 break;
572 case TRAILER_WHERE:
573 if (trailer_set_where(&conf->where, value))
574 warning(_("unknown value '%s' for key '%s'"), value, conf_key);
575 break;
576 case TRAILER_IF_EXISTS:
577 if (trailer_set_if_exists(&conf->if_exists, value))
578 warning(_("unknown value '%s' for key '%s'"), value, conf_key);
579 break;
580 case TRAILER_IF_MISSING:
581 if (trailer_set_if_missing(&conf->if_missing, value))
582 warning(_("unknown value '%s' for key '%s'"), value, conf_key);
583 break;
584 default:
585 BUG("trailer.c: unhandled type %d", type);
587 return 0;
590 void trailer_config_init(void)
592 if (configured)
593 return;
595 /* Default config must be setup first */
596 default_conf_info.where = WHERE_END;
597 default_conf_info.if_exists = EXISTS_ADD_IF_DIFFERENT_NEIGHBOR;
598 default_conf_info.if_missing = MISSING_ADD;
599 git_config(git_trailer_default_config, NULL);
600 git_config(git_trailer_config, NULL);
601 configured = 1;
604 static const char *token_from_item(struct arg_item *item, char *tok)
606 if (item->conf.key)
607 return item->conf.key;
608 if (tok)
609 return tok;
610 return item->conf.name;
613 static int token_matches_item(const char *tok, struct arg_item *item, size_t tok_len)
615 if (!strncasecmp(tok, item->conf.name, tok_len))
616 return 1;
617 return item->conf.key ? !strncasecmp(tok, item->conf.key, tok_len) : 0;
621 * If the given line is of the form
622 * "<token><optional whitespace><separator>..." or "<separator>...", return the
623 * location of the separator. Otherwise, return -1. The optional whitespace
624 * is allowed there primarily to allow things like "Bug #43" where <token> is
625 * "Bug" and <separator> is "#".
627 * The separator-starts-line case (in which this function returns 0) is
628 * distinguished from the non-well-formed-line case (in which this function
629 * returns -1) because some callers of this function need such a distinction.
631 static ssize_t find_separator(const char *line, const char *separators)
633 int whitespace_found = 0;
634 const char *c;
635 for (c = line; *c; c++) {
636 if (strchr(separators, *c))
637 return c - line;
638 if (!whitespace_found && (isalnum(*c) || *c == '-'))
639 continue;
640 if (c != line && (*c == ' ' || *c == '\t')) {
641 whitespace_found = 1;
642 continue;
644 break;
646 return -1;
650 * Obtain the token, value, and conf from the given trailer.
652 * separator_pos must not be 0, since the token cannot be an empty string.
654 * If separator_pos is -1, interpret the whole trailer as a token.
656 static void parse_trailer(struct strbuf *tok, struct strbuf *val,
657 const struct conf_info **conf, const char *trailer,
658 ssize_t separator_pos)
660 struct arg_item *item;
661 size_t tok_len;
662 struct list_head *pos;
664 if (separator_pos != -1) {
665 strbuf_add(tok, trailer, separator_pos);
666 strbuf_trim(tok);
667 strbuf_addstr(val, trailer + separator_pos + 1);
668 strbuf_trim(val);
669 } else {
670 strbuf_addstr(tok, trailer);
671 strbuf_trim(tok);
674 /* Lookup if the token matches something in the config */
675 tok_len = token_len_without_separator(tok->buf, tok->len);
676 if (conf)
677 *conf = &default_conf_info;
678 list_for_each(pos, &conf_head) {
679 item = list_entry(pos, struct arg_item, list);
680 if (token_matches_item(tok->buf, item, tok_len)) {
681 char *tok_buf = strbuf_detach(tok, NULL);
682 if (conf)
683 *conf = &item->conf;
684 strbuf_addstr(tok, token_from_item(item, tok_buf));
685 free(tok_buf);
686 break;
691 static struct trailer_item *add_trailer_item(struct list_head *head, char *tok,
692 char *val)
694 struct trailer_item *new_item = xcalloc(1, sizeof(*new_item));
695 new_item->token = tok;
696 new_item->value = val;
697 list_add_tail(&new_item->list, head);
698 return new_item;
701 static void add_arg_item(struct list_head *arg_head, char *tok, char *val,
702 const struct conf_info *conf,
703 const struct new_trailer_item *new_trailer_item)
705 struct arg_item *new_item = xcalloc(1, sizeof(*new_item));
706 new_item->token = tok;
707 new_item->value = val;
708 duplicate_conf(&new_item->conf, conf);
709 if (new_trailer_item) {
710 if (new_trailer_item->where != WHERE_DEFAULT)
711 new_item->conf.where = new_trailer_item->where;
712 if (new_trailer_item->if_exists != EXISTS_DEFAULT)
713 new_item->conf.if_exists = new_trailer_item->if_exists;
714 if (new_trailer_item->if_missing != MISSING_DEFAULT)
715 new_item->conf.if_missing = new_trailer_item->if_missing;
717 list_add_tail(&new_item->list, arg_head);
720 void parse_trailers_from_config(struct list_head *config_head)
722 struct arg_item *item;
723 struct list_head *pos;
725 /* Add an arg item for each configured trailer with a command */
726 list_for_each(pos, &conf_head) {
727 item = list_entry(pos, struct arg_item, list);
728 if (item->conf.command)
729 add_arg_item(config_head,
730 xstrdup(token_from_item(item, NULL)),
731 xstrdup(""),
732 &item->conf, NULL);
736 void parse_trailers_from_command_line_args(struct list_head *arg_head,
737 struct list_head *new_trailer_head)
739 struct strbuf tok = STRBUF_INIT;
740 struct strbuf val = STRBUF_INIT;
741 const struct conf_info *conf;
742 struct list_head *pos;
745 * In command-line arguments, '=' is accepted (in addition to the
746 * separators that are defined).
748 char *cl_separators = xstrfmt("=%s", separators);
750 /* Add an arg item for each trailer on the command line */
751 list_for_each(pos, new_trailer_head) {
752 struct new_trailer_item *tr =
753 list_entry(pos, struct new_trailer_item, list);
754 ssize_t separator_pos = find_separator(tr->text, cl_separators);
756 if (separator_pos == 0) {
757 struct strbuf sb = STRBUF_INIT;
758 strbuf_addstr(&sb, tr->text);
759 strbuf_trim(&sb);
760 error(_("empty trailer token in trailer '%.*s'"),
761 (int) sb.len, sb.buf);
762 strbuf_release(&sb);
763 } else {
764 parse_trailer(&tok, &val, &conf, tr->text,
765 separator_pos);
766 add_arg_item(arg_head,
767 strbuf_detach(&tok, NULL),
768 strbuf_detach(&val, NULL),
769 conf, tr);
773 free(cl_separators);
776 static const char *next_line(const char *str)
778 const char *nl = strchrnul(str, '\n');
779 return nl + !!*nl;
783 * Return the position of the start of the last line. If len is 0, return -1.
785 static ssize_t last_line(const char *buf, size_t len)
787 ssize_t i;
788 if (len == 0)
789 return -1;
790 if (len == 1)
791 return 0;
793 * Skip the last character (in addition to the null terminator),
794 * because if the last character is a newline, it is considered as part
795 * of the last line anyway.
797 i = len - 2;
799 for (; i >= 0; i--) {
800 if (buf[i] == '\n')
801 return i + 1;
803 return 0;
807 * Find the end of the log message as an offset from the start of the input
808 * (where callers of this function are interested in looking for a trailers
809 * block in the same input). We have to consider two categories of content that
810 * can come at the end of the input which we want to ignore (because they don't
811 * belong in the log message):
813 * (1) the "patch part" which begins with a "---" divider and has patch
814 * information (like the output of git-format-patch), and
816 * (2) any trailing comment lines, blank lines like in the output of "git
817 * commit -v", or stuff below the "cut" (scissor) line.
819 * As a formula, the situation looks like this:
821 * INPUT = LOG MESSAGE + IGNORED
823 * where IGNORED can be either of the two categories described above. It may be
824 * that there is nothing to ignore. Now it may be the case that the LOG MESSAGE
825 * contains a trailer block, but that's not the concern of this function.
827 static size_t find_end_of_log_message(const char *input, int no_divider)
829 size_t end;
830 const char *s;
832 /* Assume the naive end of the input is already what we want. */
833 end = strlen(input);
835 /* Optionally skip over any patch part ("---" line and below). */
836 if (!no_divider) {
837 for (s = input; *s; s = next_line(s)) {
838 const char *v;
840 if (skip_prefix(s, "---", &v) && isspace(*v)) {
841 end = s - input;
842 break;
847 /* Skip over other ignorable bits. */
848 return end - ignored_log_message_bytes(input, end);
852 * Return the position of the first trailer line or len if there are no
853 * trailers.
855 static size_t find_trailer_block_start(const char *buf, size_t len)
857 const char *s;
858 ssize_t end_of_title, l;
859 int only_spaces = 1;
860 int recognized_prefix = 0, trailer_lines = 0, non_trailer_lines = 0;
862 * Number of possible continuation lines encountered. This will be
863 * reset to 0 if we encounter a trailer (since those lines are to be
864 * considered continuations of that trailer), and added to
865 * non_trailer_lines if we encounter a non-trailer (since those lines
866 * are to be considered non-trailers).
868 int possible_continuation_lines = 0;
870 /* The first paragraph is the title and cannot be trailers */
871 for (s = buf; s < buf + len; s = next_line(s)) {
872 if (starts_with_mem(s, buf + len - s, comment_line_str))
873 continue;
874 if (is_blank_line(s))
875 break;
877 end_of_title = s - buf;
880 * Get the start of the trailers by looking starting from the end for a
881 * blank line before a set of non-blank lines that (i) are all
882 * trailers, or (ii) contains at least one Git-generated trailer and
883 * consists of at least 25% trailers.
885 for (l = last_line(buf, len);
886 l >= end_of_title;
887 l = last_line(buf, l)) {
888 const char *bol = buf + l;
889 const char **p;
890 ssize_t separator_pos;
892 if (starts_with_mem(bol, buf + len - bol, comment_line_str)) {
893 non_trailer_lines += possible_continuation_lines;
894 possible_continuation_lines = 0;
895 continue;
897 if (is_blank_line(bol)) {
898 if (only_spaces)
899 continue;
900 non_trailer_lines += possible_continuation_lines;
901 if (recognized_prefix &&
902 trailer_lines * 3 >= non_trailer_lines)
903 return next_line(bol) - buf;
904 else if (trailer_lines && !non_trailer_lines)
905 return next_line(bol) - buf;
906 return len;
908 only_spaces = 0;
910 for (p = git_generated_prefixes; *p; p++) {
911 if (starts_with(bol, *p)) {
912 trailer_lines++;
913 possible_continuation_lines = 0;
914 recognized_prefix = 1;
915 goto continue_outer_loop;
919 separator_pos = find_separator(bol, separators);
920 if (separator_pos >= 1 && !isspace(bol[0])) {
921 struct list_head *pos;
923 trailer_lines++;
924 possible_continuation_lines = 0;
925 if (recognized_prefix)
926 continue;
927 list_for_each(pos, &conf_head) {
928 struct arg_item *item;
929 item = list_entry(pos, struct arg_item, list);
930 if (token_matches_item(bol, item,
931 separator_pos)) {
932 recognized_prefix = 1;
933 break;
936 } else if (isspace(bol[0]))
937 possible_continuation_lines++;
938 else {
939 non_trailer_lines++;
940 non_trailer_lines += possible_continuation_lines;
941 possible_continuation_lines = 0;
943 continue_outer_loop:
947 return len;
950 static int ends_with_blank_line(const char *buf, size_t len)
952 ssize_t ll = last_line(buf, len);
953 if (ll < 0)
954 return 0;
955 return is_blank_line(buf + ll);
958 static void unfold_value(struct strbuf *val)
960 struct strbuf out = STRBUF_INIT;
961 size_t i;
963 strbuf_grow(&out, val->len);
964 i = 0;
965 while (i < val->len) {
966 char c = val->buf[i++];
967 if (c == '\n') {
968 /* Collapse continuation down to a single space. */
969 while (i < val->len && isspace(val->buf[i]))
970 i++;
971 strbuf_addch(&out, ' ');
972 } else {
973 strbuf_addch(&out, c);
977 /* Empty lines may have left us with whitespace cruft at the edges */
978 strbuf_trim(&out);
980 /* output goes back to val as if we modified it in-place */
981 strbuf_swap(&out, val);
982 strbuf_release(&out);
985 static struct trailer_block *trailer_block_new(void)
987 struct trailer_block *trailer_block = xcalloc(1, sizeof(*trailer_block));
988 return trailer_block;
991 static struct trailer_block *trailer_block_get(const struct process_trailer_options *opts,
992 const char *str)
994 struct trailer_block *trailer_block = trailer_block_new();
995 size_t end_of_log_message = 0, trailer_block_start = 0;
996 struct strbuf **trailer_lines, **ptr;
997 char **trailer_strings = NULL;
998 size_t nr = 0, alloc = 0;
999 char **last = NULL;
1001 trailer_config_init();
1003 end_of_log_message = find_end_of_log_message(str, opts->no_divider);
1004 trailer_block_start = find_trailer_block_start(str, end_of_log_message);
1006 trailer_lines = strbuf_split_buf(str + trailer_block_start,
1007 end_of_log_message - trailer_block_start,
1008 '\n',
1010 for (ptr = trailer_lines; *ptr; ptr++) {
1011 if (last && isspace((*ptr)->buf[0])) {
1012 struct strbuf sb = STRBUF_INIT;
1013 strbuf_attach(&sb, *last, strlen(*last), strlen(*last));
1014 strbuf_addbuf(&sb, *ptr);
1015 *last = strbuf_detach(&sb, NULL);
1016 continue;
1018 ALLOC_GROW(trailer_strings, nr + 1, alloc);
1019 trailer_strings[nr] = strbuf_detach(*ptr, NULL);
1020 last = find_separator(trailer_strings[nr], separators) >= 1
1021 ? &trailer_strings[nr]
1022 : NULL;
1023 nr++;
1025 strbuf_list_free(trailer_lines);
1027 trailer_block->blank_line_before_trailer = ends_with_blank_line(str,
1028 trailer_block_start);
1029 trailer_block->start = trailer_block_start;
1030 trailer_block->end = end_of_log_message;
1031 trailer_block->trailers = trailer_strings;
1032 trailer_block->trailer_nr = nr;
1034 return trailer_block;
1038 * Parse trailers in "str", populating the trailer_block and "trailer_objects"
1039 * linked list structure.
1041 struct trailer_block *parse_trailers(const struct process_trailer_options *opts,
1042 const char *str,
1043 struct list_head *trailer_objects)
1045 struct trailer_block *trailer_block;
1046 struct strbuf tok = STRBUF_INIT;
1047 struct strbuf val = STRBUF_INIT;
1048 size_t i;
1050 trailer_block = trailer_block_get(opts, str);
1052 for (i = 0; i < trailer_block->trailer_nr; i++) {
1053 int separator_pos;
1054 char *trailer = trailer_block->trailers[i];
1055 if (starts_with(trailer, comment_line_str))
1056 continue;
1057 separator_pos = find_separator(trailer, separators);
1058 if (separator_pos >= 1) {
1059 parse_trailer(&tok, &val, NULL, trailer,
1060 separator_pos);
1061 if (opts->unfold)
1062 unfold_value(&val);
1063 add_trailer_item(trailer_objects,
1064 strbuf_detach(&tok, NULL),
1065 strbuf_detach(&val, NULL));
1066 } else if (!opts->only_trailers) {
1067 strbuf_addstr(&val, trailer);
1068 strbuf_strip_suffix(&val, "\n");
1069 add_trailer_item(trailer_objects,
1070 NULL,
1071 strbuf_detach(&val, NULL));
1075 return trailer_block;
1078 void free_trailers(struct list_head *trailers)
1080 struct list_head *pos, *p;
1081 list_for_each_safe(pos, p, trailers) {
1082 list_del(pos);
1083 free_trailer_item(list_entry(pos, struct trailer_item, list));
1087 size_t trailer_block_start(struct trailer_block *trailer_block)
1089 return trailer_block->start;
1092 size_t trailer_block_end(struct trailer_block *trailer_block)
1094 return trailer_block->end;
1097 int blank_line_before_trailer_block(struct trailer_block *trailer_block)
1099 return trailer_block->blank_line_before_trailer;
1102 void trailer_block_release(struct trailer_block *trailer_block)
1104 size_t i;
1105 for (i = 0; i < trailer_block->trailer_nr; i++)
1106 free(trailer_block->trailers[i]);
1107 free(trailer_block->trailers);
1108 free(trailer_block);
1111 void format_trailers(const struct process_trailer_options *opts,
1112 struct list_head *trailers,
1113 struct strbuf *out)
1115 struct strbuf tok = STRBUF_INIT;
1116 struct strbuf val = STRBUF_INIT;
1117 size_t origlen = out->len;
1118 struct list_head *pos;
1119 struct trailer_item *item;
1121 list_for_each(pos, trailers) {
1122 item = list_entry(pos, struct trailer_item, list);
1123 if (item->token) {
1124 strbuf_reset(&tok);
1125 strbuf_addstr(&tok, item->token);
1126 strbuf_reset(&val);
1127 strbuf_addstr(&val, item->value);
1130 * Skip key/value pairs where the value was empty. This
1131 * can happen from trailers specified without a
1132 * separator, like `--trailer "Reviewed-by"` (no
1133 * corresponding value).
1135 if (opts->trim_empty && !strlen(item->value))
1136 continue;
1138 if (!opts->filter || opts->filter(&tok, opts->filter_data)) {
1139 if (opts->separator && out->len != origlen)
1140 strbuf_addbuf(out, opts->separator);
1141 if (!opts->value_only)
1142 strbuf_addbuf(out, &tok);
1143 if (!opts->key_only && !opts->value_only) {
1144 if (opts->key_value_separator)
1145 strbuf_addbuf(out, opts->key_value_separator);
1146 else {
1147 char c = last_non_space_char(tok.buf);
1148 if (c && !strchr(separators, c))
1149 strbuf_addf(out, "%c ", separators[0]);
1152 if (!opts->key_only)
1153 strbuf_addbuf(out, &val);
1154 if (!opts->separator)
1155 strbuf_addch(out, '\n');
1157 } else if (!opts->only_trailers) {
1158 if (opts->separator && out->len != origlen) {
1159 strbuf_addbuf(out, opts->separator);
1161 strbuf_addstr(out, item->value);
1162 if (opts->separator)
1163 strbuf_rtrim(out);
1164 else
1165 strbuf_addch(out, '\n');
1169 strbuf_release(&tok);
1170 strbuf_release(&val);
1173 void format_trailers_from_commit(const struct process_trailer_options *opts,
1174 const char *msg,
1175 struct strbuf *out)
1177 LIST_HEAD(trailer_objects);
1178 struct trailer_block *trailer_block = parse_trailers(opts, msg, &trailer_objects);
1180 /* If we want the whole block untouched, we can take the fast path. */
1181 if (!opts->only_trailers && !opts->unfold && !opts->filter &&
1182 !opts->separator && !opts->key_only && !opts->value_only &&
1183 !opts->key_value_separator) {
1184 strbuf_add(out, msg + trailer_block->start,
1185 trailer_block->end - trailer_block->start);
1186 } else
1187 format_trailers(opts, &trailer_objects, out);
1189 free_trailers(&trailer_objects);
1190 trailer_block_release(trailer_block);
1193 void trailer_iterator_init(struct trailer_iterator *iter, const char *msg)
1195 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
1196 strbuf_init(&iter->key, 0);
1197 strbuf_init(&iter->val, 0);
1198 opts.no_divider = 1;
1199 iter->internal.trailer_block = trailer_block_get(&opts, msg);
1200 iter->internal.cur = 0;
1203 int trailer_iterator_advance(struct trailer_iterator *iter)
1205 if (iter->internal.cur < iter->internal.trailer_block->trailer_nr) {
1206 char *line = iter->internal.trailer_block->trailers[iter->internal.cur++];
1207 int separator_pos = find_separator(line, separators);
1209 iter->raw = line;
1210 strbuf_reset(&iter->key);
1211 strbuf_reset(&iter->val);
1212 parse_trailer(&iter->key, &iter->val, NULL,
1213 line, separator_pos);
1214 /* Always unfold values during iteration. */
1215 unfold_value(&iter->val);
1216 return 1;
1218 return 0;
1221 void trailer_iterator_release(struct trailer_iterator *iter)
1223 trailer_block_release(iter->internal.trailer_block);
1224 strbuf_release(&iter->val);
1225 strbuf_release(&iter->key);
1228 int amend_file_with_trailers(const char *path, const struct strvec *trailer_args)
1230 struct child_process run_trailer = CHILD_PROCESS_INIT;
1232 run_trailer.git_cmd = 1;
1233 strvec_pushl(&run_trailer.args, "interpret-trailers",
1234 "--in-place", "--no-divider",
1235 path, NULL);
1236 strvec_pushv(&run_trailer.args, trailer_args->v);
1237 return run_command(&run_trailer);