Git 2.41.1
[git.git] / trailer.c
bloba2c3ed6f28cc9fedffe50946acdb3594d21f9e7e
1 #include "git-compat-util.h"
2 #include "alloc.h"
3 #include "config.h"
4 #include "environment.h"
5 #include "gettext.h"
6 #include "string-list.h"
7 #include "run-command.h"
8 #include "commit.h"
9 #include "tempfile.h"
10 #include "trailer.h"
11 #include "list.h"
13 * Copyright (c) 2013, 2014 Christian Couder <chriscool@tuxfamily.org>
16 struct conf_info {
17 char *name;
18 char *key;
19 char *command;
20 char *cmd;
21 enum trailer_where where;
22 enum trailer_if_exists if_exists;
23 enum trailer_if_missing if_missing;
26 static struct conf_info default_conf_info;
28 struct trailer_item {
29 struct list_head list;
31 * If this is not a trailer line, the line is stored in value
32 * (excluding the terminating newline) and token is NULL.
34 char *token;
35 char *value;
38 struct arg_item {
39 struct list_head list;
40 char *token;
41 char *value;
42 struct conf_info conf;
45 static LIST_HEAD(conf_head);
47 static char *separators = ":";
49 static int configured;
51 #define TRAILER_ARG_STRING "$ARG"
53 static const char *git_generated_prefixes[] = {
54 "Signed-off-by: ",
55 "(cherry picked from commit ",
56 NULL
59 /* Iterate over the elements of the list. */
60 #define list_for_each_dir(pos, head, is_reverse) \
61 for (pos = is_reverse ? (head)->prev : (head)->next; \
62 pos != (head); \
63 pos = is_reverse ? pos->prev : pos->next)
65 static int after_or_end(enum trailer_where where)
67 return (where == WHERE_AFTER) || (where == WHERE_END);
71 * Return the length of the string not including any final
72 * punctuation. E.g., the input "Signed-off-by:" would return
73 * 13, stripping the trailing punctuation but retaining
74 * internal punctuation.
76 static size_t token_len_without_separator(const char *token, size_t len)
78 while (len > 0 && !isalnum(token[len - 1]))
79 len--;
80 return len;
83 static int same_token(struct trailer_item *a, struct arg_item *b)
85 size_t a_len, b_len, min_len;
87 if (!a->token)
88 return 0;
90 a_len = token_len_without_separator(a->token, strlen(a->token));
91 b_len = token_len_without_separator(b->token, strlen(b->token));
92 min_len = (a_len > b_len) ? b_len : a_len;
94 return !strncasecmp(a->token, b->token, min_len);
97 static int same_value(struct trailer_item *a, struct arg_item *b)
99 return !strcasecmp(a->value, b->value);
102 static int same_trailer(struct trailer_item *a, struct arg_item *b)
104 return same_token(a, b) && same_value(a, b);
107 static inline int is_blank_line(const char *str)
109 const char *s = str;
110 while (*s && *s != '\n' && isspace(*s))
111 s++;
112 return !*s || *s == '\n';
115 static inline void strbuf_replace(struct strbuf *sb, const char *a, const char *b)
117 const char *ptr = strstr(sb->buf, a);
118 if (ptr)
119 strbuf_splice(sb, ptr - sb->buf, strlen(a), b, strlen(b));
122 static void free_trailer_item(struct trailer_item *item)
124 free(item->token);
125 free(item->value);
126 free(item);
129 static void free_arg_item(struct arg_item *item)
131 free(item->conf.name);
132 free(item->conf.key);
133 free(item->conf.command);
134 free(item->conf.cmd);
135 free(item->token);
136 free(item->value);
137 free(item);
140 static char last_non_space_char(const char *s)
142 int i;
143 for (i = strlen(s) - 1; i >= 0; i--)
144 if (!isspace(s[i]))
145 return s[i];
146 return '\0';
149 static void print_tok_val(FILE *outfile, const char *tok, const char *val)
151 char c;
153 if (!tok) {
154 fprintf(outfile, "%s\n", val);
155 return;
158 c = last_non_space_char(tok);
159 if (!c)
160 return;
161 if (strchr(separators, c))
162 fprintf(outfile, "%s%s\n", tok, val);
163 else
164 fprintf(outfile, "%s%c %s\n", tok, separators[0], val);
167 static void print_all(FILE *outfile, struct list_head *head,
168 const struct process_trailer_options *opts)
170 struct list_head *pos;
171 struct trailer_item *item;
172 list_for_each(pos, head) {
173 item = list_entry(pos, struct trailer_item, list);
174 if ((!opts->trim_empty || strlen(item->value) > 0) &&
175 (!opts->only_trailers || item->token))
176 print_tok_val(outfile, item->token, item->value);
180 static struct trailer_item *trailer_from_arg(struct arg_item *arg_tok)
182 struct trailer_item *new_item = xcalloc(1, sizeof(*new_item));
183 new_item->token = arg_tok->token;
184 new_item->value = arg_tok->value;
185 arg_tok->token = arg_tok->value = NULL;
186 free_arg_item(arg_tok);
187 return new_item;
190 static void add_arg_to_input_list(struct trailer_item *on_tok,
191 struct arg_item *arg_tok)
193 int aoe = after_or_end(arg_tok->conf.where);
194 struct trailer_item *to_add = trailer_from_arg(arg_tok);
195 if (aoe)
196 list_add(&to_add->list, &on_tok->list);
197 else
198 list_add_tail(&to_add->list, &on_tok->list);
201 static int check_if_different(struct trailer_item *in_tok,
202 struct arg_item *arg_tok,
203 int check_all,
204 struct list_head *head)
206 enum trailer_where where = arg_tok->conf.where;
207 struct list_head *next_head;
208 do {
209 if (same_trailer(in_tok, arg_tok))
210 return 0;
212 * if we want to add a trailer after another one,
213 * we have to check those before this one
215 next_head = after_or_end(where) ? in_tok->list.prev
216 : in_tok->list.next;
217 if (next_head == head)
218 break;
219 in_tok = list_entry(next_head, struct trailer_item, list);
220 } while (check_all);
221 return 1;
224 static char *apply_command(struct conf_info *conf, const char *arg)
226 struct strbuf cmd = STRBUF_INIT;
227 struct strbuf buf = STRBUF_INIT;
228 struct child_process cp = CHILD_PROCESS_INIT;
229 char *result;
231 if (conf->cmd) {
232 strbuf_addstr(&cmd, conf->cmd);
233 strvec_push(&cp.args, cmd.buf);
234 if (arg)
235 strvec_push(&cp.args, arg);
236 } else if (conf->command) {
237 strbuf_addstr(&cmd, conf->command);
238 if (arg)
239 strbuf_replace(&cmd, TRAILER_ARG_STRING, arg);
240 strvec_push(&cp.args, cmd.buf);
242 strvec_pushv(&cp.env, (const char **)local_repo_env);
243 cp.no_stdin = 1;
244 cp.use_shell = 1;
246 if (capture_command(&cp, &buf, 1024)) {
247 error(_("running trailer command '%s' failed"), cmd.buf);
248 strbuf_release(&buf);
249 result = xstrdup("");
250 } else {
251 strbuf_trim(&buf);
252 result = strbuf_detach(&buf, NULL);
255 strbuf_release(&cmd);
256 return result;
259 static void apply_item_command(struct trailer_item *in_tok, struct arg_item *arg_tok)
261 if (arg_tok->conf.command || arg_tok->conf.cmd) {
262 const char *arg;
263 if (arg_tok->value && arg_tok->value[0]) {
264 arg = arg_tok->value;
265 } else {
266 if (in_tok && in_tok->value)
267 arg = xstrdup(in_tok->value);
268 else
269 arg = xstrdup("");
271 arg_tok->value = apply_command(&arg_tok->conf, arg);
272 free((char *)arg);
276 static void apply_arg_if_exists(struct trailer_item *in_tok,
277 struct arg_item *arg_tok,
278 struct trailer_item *on_tok,
279 struct list_head *head)
281 switch (arg_tok->conf.if_exists) {
282 case EXISTS_DO_NOTHING:
283 free_arg_item(arg_tok);
284 break;
285 case EXISTS_REPLACE:
286 apply_item_command(in_tok, arg_tok);
287 add_arg_to_input_list(on_tok, arg_tok);
288 list_del(&in_tok->list);
289 free_trailer_item(in_tok);
290 break;
291 case EXISTS_ADD:
292 apply_item_command(in_tok, arg_tok);
293 add_arg_to_input_list(on_tok, arg_tok);
294 break;
295 case EXISTS_ADD_IF_DIFFERENT:
296 apply_item_command(in_tok, arg_tok);
297 if (check_if_different(in_tok, arg_tok, 1, head))
298 add_arg_to_input_list(on_tok, arg_tok);
299 else
300 free_arg_item(arg_tok);
301 break;
302 case EXISTS_ADD_IF_DIFFERENT_NEIGHBOR:
303 apply_item_command(in_tok, arg_tok);
304 if (check_if_different(on_tok, arg_tok, 0, head))
305 add_arg_to_input_list(on_tok, arg_tok);
306 else
307 free_arg_item(arg_tok);
308 break;
309 default:
310 BUG("trailer.c: unhandled value %d",
311 arg_tok->conf.if_exists);
315 static void apply_arg_if_missing(struct list_head *head,
316 struct arg_item *arg_tok)
318 enum trailer_where where;
319 struct trailer_item *to_add;
321 switch (arg_tok->conf.if_missing) {
322 case MISSING_DO_NOTHING:
323 free_arg_item(arg_tok);
324 break;
325 case MISSING_ADD:
326 where = arg_tok->conf.where;
327 apply_item_command(NULL, arg_tok);
328 to_add = trailer_from_arg(arg_tok);
329 if (after_or_end(where))
330 list_add_tail(&to_add->list, head);
331 else
332 list_add(&to_add->list, head);
333 break;
334 default:
335 BUG("trailer.c: unhandled value %d",
336 arg_tok->conf.if_missing);
340 static int find_same_and_apply_arg(struct list_head *head,
341 struct arg_item *arg_tok)
343 struct list_head *pos;
344 struct trailer_item *in_tok;
345 struct trailer_item *on_tok;
347 enum trailer_where where = arg_tok->conf.where;
348 int middle = (where == WHERE_AFTER) || (where == WHERE_BEFORE);
349 int backwards = after_or_end(where);
350 struct trailer_item *start_tok;
352 if (list_empty(head))
353 return 0;
355 start_tok = list_entry(backwards ? head->prev : head->next,
356 struct trailer_item,
357 list);
359 list_for_each_dir(pos, head, backwards) {
360 in_tok = list_entry(pos, struct trailer_item, list);
361 if (!same_token(in_tok, arg_tok))
362 continue;
363 on_tok = middle ? in_tok : start_tok;
364 apply_arg_if_exists(in_tok, arg_tok, on_tok, head);
365 return 1;
367 return 0;
370 static void process_trailers_lists(struct list_head *head,
371 struct list_head *arg_head)
373 struct list_head *pos, *p;
374 struct arg_item *arg_tok;
376 list_for_each_safe(pos, p, arg_head) {
377 int applied = 0;
378 arg_tok = list_entry(pos, struct arg_item, list);
380 list_del(pos);
382 applied = find_same_and_apply_arg(head, arg_tok);
384 if (!applied)
385 apply_arg_if_missing(head, arg_tok);
389 int trailer_set_where(enum trailer_where *item, const char *value)
391 if (!value)
392 *item = WHERE_DEFAULT;
393 else if (!strcasecmp("after", value))
394 *item = WHERE_AFTER;
395 else if (!strcasecmp("before", value))
396 *item = WHERE_BEFORE;
397 else if (!strcasecmp("end", value))
398 *item = WHERE_END;
399 else if (!strcasecmp("start", value))
400 *item = WHERE_START;
401 else
402 return -1;
403 return 0;
406 int trailer_set_if_exists(enum trailer_if_exists *item, const char *value)
408 if (!value)
409 *item = EXISTS_DEFAULT;
410 else if (!strcasecmp("addIfDifferent", value))
411 *item = EXISTS_ADD_IF_DIFFERENT;
412 else if (!strcasecmp("addIfDifferentNeighbor", value))
413 *item = EXISTS_ADD_IF_DIFFERENT_NEIGHBOR;
414 else if (!strcasecmp("add", value))
415 *item = EXISTS_ADD;
416 else if (!strcasecmp("replace", value))
417 *item = EXISTS_REPLACE;
418 else if (!strcasecmp("doNothing", value))
419 *item = EXISTS_DO_NOTHING;
420 else
421 return -1;
422 return 0;
425 int trailer_set_if_missing(enum trailer_if_missing *item, const char *value)
427 if (!value)
428 *item = MISSING_DEFAULT;
429 else if (!strcasecmp("doNothing", value))
430 *item = MISSING_DO_NOTHING;
431 else if (!strcasecmp("add", value))
432 *item = MISSING_ADD;
433 else
434 return -1;
435 return 0;
438 static void duplicate_conf(struct conf_info *dst, const struct conf_info *src)
440 *dst = *src;
441 dst->name = xstrdup_or_null(src->name);
442 dst->key = xstrdup_or_null(src->key);
443 dst->command = xstrdup_or_null(src->command);
444 dst->cmd = xstrdup_or_null(src->cmd);
447 static struct arg_item *get_conf_item(const char *name)
449 struct list_head *pos;
450 struct arg_item *item;
452 /* Look up item with same name */
453 list_for_each(pos, &conf_head) {
454 item = list_entry(pos, struct arg_item, list);
455 if (!strcasecmp(item->conf.name, name))
456 return item;
459 /* Item does not already exists, create it */
460 CALLOC_ARRAY(item, 1);
461 duplicate_conf(&item->conf, &default_conf_info);
462 item->conf.name = xstrdup(name);
464 list_add_tail(&item->list, &conf_head);
466 return item;
469 enum trailer_info_type { TRAILER_KEY, TRAILER_COMMAND, TRAILER_CMD,
470 TRAILER_WHERE, TRAILER_IF_EXISTS, TRAILER_IF_MISSING };
472 static struct {
473 const char *name;
474 enum trailer_info_type type;
475 } trailer_config_items[] = {
476 { "key", TRAILER_KEY },
477 { "command", TRAILER_COMMAND },
478 { "cmd", TRAILER_CMD },
479 { "where", TRAILER_WHERE },
480 { "ifexists", TRAILER_IF_EXISTS },
481 { "ifmissing", TRAILER_IF_MISSING }
484 static int git_trailer_default_config(const char *conf_key, const char *value,
485 void *cb UNUSED)
487 const char *trailer_item, *variable_name;
489 if (!skip_prefix(conf_key, "trailer.", &trailer_item))
490 return 0;
492 variable_name = strrchr(trailer_item, '.');
493 if (!variable_name) {
494 if (!strcmp(trailer_item, "where")) {
495 if (trailer_set_where(&default_conf_info.where,
496 value) < 0)
497 warning(_("unknown value '%s' for key '%s'"),
498 value, conf_key);
499 } else if (!strcmp(trailer_item, "ifexists")) {
500 if (trailer_set_if_exists(&default_conf_info.if_exists,
501 value) < 0)
502 warning(_("unknown value '%s' for key '%s'"),
503 value, conf_key);
504 } else if (!strcmp(trailer_item, "ifmissing")) {
505 if (trailer_set_if_missing(&default_conf_info.if_missing,
506 value) < 0)
507 warning(_("unknown value '%s' for key '%s'"),
508 value, conf_key);
509 } else if (!strcmp(trailer_item, "separators")) {
510 separators = xstrdup(value);
513 return 0;
516 static int git_trailer_config(const char *conf_key, const char *value,
517 void *cb UNUSED)
519 const char *trailer_item, *variable_name;
520 struct arg_item *item;
521 struct conf_info *conf;
522 char *name = NULL;
523 enum trailer_info_type type;
524 int i;
526 if (!skip_prefix(conf_key, "trailer.", &trailer_item))
527 return 0;
529 variable_name = strrchr(trailer_item, '.');
530 if (!variable_name)
531 return 0;
533 variable_name++;
534 for (i = 0; i < ARRAY_SIZE(trailer_config_items); i++) {
535 if (strcmp(trailer_config_items[i].name, variable_name))
536 continue;
537 name = xstrndup(trailer_item, variable_name - trailer_item - 1);
538 type = trailer_config_items[i].type;
539 break;
542 if (!name)
543 return 0;
545 item = get_conf_item(name);
546 conf = &item->conf;
547 free(name);
549 switch (type) {
550 case TRAILER_KEY:
551 if (conf->key)
552 warning(_("more than one %s"), conf_key);
553 conf->key = xstrdup(value);
554 break;
555 case TRAILER_COMMAND:
556 if (conf->command)
557 warning(_("more than one %s"), conf_key);
558 conf->command = xstrdup(value);
559 break;
560 case TRAILER_CMD:
561 if (conf->cmd)
562 warning(_("more than one %s"), conf_key);
563 conf->cmd = xstrdup(value);
564 break;
565 case TRAILER_WHERE:
566 if (trailer_set_where(&conf->where, value))
567 warning(_("unknown value '%s' for key '%s'"), value, conf_key);
568 break;
569 case TRAILER_IF_EXISTS:
570 if (trailer_set_if_exists(&conf->if_exists, value))
571 warning(_("unknown value '%s' for key '%s'"), value, conf_key);
572 break;
573 case TRAILER_IF_MISSING:
574 if (trailer_set_if_missing(&conf->if_missing, value))
575 warning(_("unknown value '%s' for key '%s'"), value, conf_key);
576 break;
577 default:
578 BUG("trailer.c: unhandled type %d", type);
580 return 0;
583 static void ensure_configured(void)
585 if (configured)
586 return;
588 /* Default config must be setup first */
589 default_conf_info.where = WHERE_END;
590 default_conf_info.if_exists = EXISTS_ADD_IF_DIFFERENT_NEIGHBOR;
591 default_conf_info.if_missing = MISSING_ADD;
592 git_config(git_trailer_default_config, NULL);
593 git_config(git_trailer_config, NULL);
594 configured = 1;
597 static const char *token_from_item(struct arg_item *item, char *tok)
599 if (item->conf.key)
600 return item->conf.key;
601 if (tok)
602 return tok;
603 return item->conf.name;
606 static int token_matches_item(const char *tok, struct arg_item *item, size_t tok_len)
608 if (!strncasecmp(tok, item->conf.name, tok_len))
609 return 1;
610 return item->conf.key ? !strncasecmp(tok, item->conf.key, tok_len) : 0;
614 * If the given line is of the form
615 * "<token><optional whitespace><separator>..." or "<separator>...", return the
616 * location of the separator. Otherwise, return -1. The optional whitespace
617 * is allowed there primarily to allow things like "Bug #43" where <token> is
618 * "Bug" and <separator> is "#".
620 * The separator-starts-line case (in which this function returns 0) is
621 * distinguished from the non-well-formed-line case (in which this function
622 * returns -1) because some callers of this function need such a distinction.
624 static ssize_t find_separator(const char *line, const char *separators)
626 int whitespace_found = 0;
627 const char *c;
628 for (c = line; *c; c++) {
629 if (strchr(separators, *c))
630 return c - line;
631 if (!whitespace_found && (isalnum(*c) || *c == '-'))
632 continue;
633 if (c != line && (*c == ' ' || *c == '\t')) {
634 whitespace_found = 1;
635 continue;
637 break;
639 return -1;
643 * Obtain the token, value, and conf from the given trailer.
645 * separator_pos must not be 0, since the token cannot be an empty string.
647 * If separator_pos is -1, interpret the whole trailer as a token.
649 static void parse_trailer(struct strbuf *tok, struct strbuf *val,
650 const struct conf_info **conf, const char *trailer,
651 ssize_t separator_pos)
653 struct arg_item *item;
654 size_t tok_len;
655 struct list_head *pos;
657 if (separator_pos != -1) {
658 strbuf_add(tok, trailer, separator_pos);
659 strbuf_trim(tok);
660 strbuf_addstr(val, trailer + separator_pos + 1);
661 strbuf_trim(val);
662 } else {
663 strbuf_addstr(tok, trailer);
664 strbuf_trim(tok);
667 /* Lookup if the token matches something in the config */
668 tok_len = token_len_without_separator(tok->buf, tok->len);
669 if (conf)
670 *conf = &default_conf_info;
671 list_for_each(pos, &conf_head) {
672 item = list_entry(pos, struct arg_item, list);
673 if (token_matches_item(tok->buf, item, tok_len)) {
674 char *tok_buf = strbuf_detach(tok, NULL);
675 if (conf)
676 *conf = &item->conf;
677 strbuf_addstr(tok, token_from_item(item, tok_buf));
678 free(tok_buf);
679 break;
684 static struct trailer_item *add_trailer_item(struct list_head *head, char *tok,
685 char *val)
687 struct trailer_item *new_item = xcalloc(1, sizeof(*new_item));
688 new_item->token = tok;
689 new_item->value = val;
690 list_add_tail(&new_item->list, head);
691 return new_item;
694 static void add_arg_item(struct list_head *arg_head, char *tok, char *val,
695 const struct conf_info *conf,
696 const struct new_trailer_item *new_trailer_item)
698 struct arg_item *new_item = xcalloc(1, sizeof(*new_item));
699 new_item->token = tok;
700 new_item->value = val;
701 duplicate_conf(&new_item->conf, conf);
702 if (new_trailer_item) {
703 if (new_trailer_item->where != WHERE_DEFAULT)
704 new_item->conf.where = new_trailer_item->where;
705 if (new_trailer_item->if_exists != EXISTS_DEFAULT)
706 new_item->conf.if_exists = new_trailer_item->if_exists;
707 if (new_trailer_item->if_missing != MISSING_DEFAULT)
708 new_item->conf.if_missing = new_trailer_item->if_missing;
710 list_add_tail(&new_item->list, arg_head);
713 static void process_command_line_args(struct list_head *arg_head,
714 struct list_head *new_trailer_head)
716 struct arg_item *item;
717 struct strbuf tok = STRBUF_INIT;
718 struct strbuf val = STRBUF_INIT;
719 const struct conf_info *conf;
720 struct list_head *pos;
723 * In command-line arguments, '=' is accepted (in addition to the
724 * separators that are defined).
726 char *cl_separators = xstrfmt("=%s", separators);
728 /* Add an arg item for each configured trailer with a command */
729 list_for_each(pos, &conf_head) {
730 item = list_entry(pos, struct arg_item, list);
731 if (item->conf.command)
732 add_arg_item(arg_head,
733 xstrdup(token_from_item(item, NULL)),
734 xstrdup(""),
735 &item->conf, NULL);
738 /* Add an arg item for each trailer on the command line */
739 list_for_each(pos, new_trailer_head) {
740 struct new_trailer_item *tr =
741 list_entry(pos, struct new_trailer_item, list);
742 ssize_t separator_pos = find_separator(tr->text, cl_separators);
744 if (separator_pos == 0) {
745 struct strbuf sb = STRBUF_INIT;
746 strbuf_addstr(&sb, tr->text);
747 strbuf_trim(&sb);
748 error(_("empty trailer token in trailer '%.*s'"),
749 (int) sb.len, sb.buf);
750 strbuf_release(&sb);
751 } else {
752 parse_trailer(&tok, &val, &conf, tr->text,
753 separator_pos);
754 add_arg_item(arg_head,
755 strbuf_detach(&tok, NULL),
756 strbuf_detach(&val, NULL),
757 conf, tr);
761 free(cl_separators);
764 static void read_input_file(struct strbuf *sb, const char *file)
766 if (file) {
767 if (strbuf_read_file(sb, file, 0) < 0)
768 die_errno(_("could not read input file '%s'"), file);
769 } else {
770 if (strbuf_read(sb, fileno(stdin), 0) < 0)
771 die_errno(_("could not read from stdin"));
775 static const char *next_line(const char *str)
777 const char *nl = strchrnul(str, '\n');
778 return nl + !!*nl;
782 * Return the position of the start of the last line. If len is 0, return -1.
784 static ssize_t last_line(const char *buf, size_t len)
786 ssize_t i;
787 if (len == 0)
788 return -1;
789 if (len == 1)
790 return 0;
792 * Skip the last character (in addition to the null terminator),
793 * because if the last character is a newline, it is considered as part
794 * of the last line anyway.
796 i = len - 2;
798 for (; i >= 0; i--) {
799 if (buf[i] == '\n')
800 return i + 1;
802 return 0;
806 * Return the position of the start of the patch or the length of str if there
807 * is no patch in the message.
809 static size_t find_patch_start(const char *str)
811 const char *s;
813 for (s = str; *s; s = next_line(s)) {
814 const char *v;
816 if (skip_prefix(s, "---", &v) && isspace(*v))
817 return s - str;
820 return s - str;
824 * Return the position of the first trailer line or len if there are no
825 * trailers.
827 static size_t find_trailer_start(const char *buf, size_t len)
829 const char *s;
830 ssize_t end_of_title, l;
831 int only_spaces = 1;
832 int recognized_prefix = 0, trailer_lines = 0, non_trailer_lines = 0;
834 * Number of possible continuation lines encountered. This will be
835 * reset to 0 if we encounter a trailer (since those lines are to be
836 * considered continuations of that trailer), and added to
837 * non_trailer_lines if we encounter a non-trailer (since those lines
838 * are to be considered non-trailers).
840 int possible_continuation_lines = 0;
842 /* The first paragraph is the title and cannot be trailers */
843 for (s = buf; s < buf + len; s = next_line(s)) {
844 if (s[0] == comment_line_char)
845 continue;
846 if (is_blank_line(s))
847 break;
849 end_of_title = s - buf;
852 * Get the start of the trailers by looking starting from the end for a
853 * blank line before a set of non-blank lines that (i) are all
854 * trailers, or (ii) contains at least one Git-generated trailer and
855 * consists of at least 25% trailers.
857 for (l = last_line(buf, len);
858 l >= end_of_title;
859 l = last_line(buf, l)) {
860 const char *bol = buf + l;
861 const char **p;
862 ssize_t separator_pos;
864 if (bol[0] == comment_line_char) {
865 non_trailer_lines += possible_continuation_lines;
866 possible_continuation_lines = 0;
867 continue;
869 if (is_blank_line(bol)) {
870 if (only_spaces)
871 continue;
872 non_trailer_lines += possible_continuation_lines;
873 if (recognized_prefix &&
874 trailer_lines * 3 >= non_trailer_lines)
875 return next_line(bol) - buf;
876 else if (trailer_lines && !non_trailer_lines)
877 return next_line(bol) - buf;
878 return len;
880 only_spaces = 0;
882 for (p = git_generated_prefixes; *p; p++) {
883 if (starts_with(bol, *p)) {
884 trailer_lines++;
885 possible_continuation_lines = 0;
886 recognized_prefix = 1;
887 goto continue_outer_loop;
891 separator_pos = find_separator(bol, separators);
892 if (separator_pos >= 1 && !isspace(bol[0])) {
893 struct list_head *pos;
895 trailer_lines++;
896 possible_continuation_lines = 0;
897 if (recognized_prefix)
898 continue;
899 list_for_each(pos, &conf_head) {
900 struct arg_item *item;
901 item = list_entry(pos, struct arg_item, list);
902 if (token_matches_item(bol, item,
903 separator_pos)) {
904 recognized_prefix = 1;
905 break;
908 } else if (isspace(bol[0]))
909 possible_continuation_lines++;
910 else {
911 non_trailer_lines++;
912 non_trailer_lines += possible_continuation_lines;
913 possible_continuation_lines = 0;
915 continue_outer_loop:
919 return len;
922 /* Return the position of the end of the trailers. */
923 static size_t find_trailer_end(const char *buf, size_t len)
925 return len - ignore_non_trailer(buf, len);
928 static int ends_with_blank_line(const char *buf, size_t len)
930 ssize_t ll = last_line(buf, len);
931 if (ll < 0)
932 return 0;
933 return is_blank_line(buf + ll);
936 static void unfold_value(struct strbuf *val)
938 struct strbuf out = STRBUF_INIT;
939 size_t i;
941 strbuf_grow(&out, val->len);
942 i = 0;
943 while (i < val->len) {
944 char c = val->buf[i++];
945 if (c == '\n') {
946 /* Collapse continuation down to a single space. */
947 while (i < val->len && isspace(val->buf[i]))
948 i++;
949 strbuf_addch(&out, ' ');
950 } else {
951 strbuf_addch(&out, c);
955 /* Empty lines may have left us with whitespace cruft at the edges */
956 strbuf_trim(&out);
958 /* output goes back to val as if we modified it in-place */
959 strbuf_swap(&out, val);
960 strbuf_release(&out);
963 static size_t process_input_file(FILE *outfile,
964 const char *str,
965 struct list_head *head,
966 const struct process_trailer_options *opts)
968 struct trailer_info info;
969 struct strbuf tok = STRBUF_INIT;
970 struct strbuf val = STRBUF_INIT;
971 size_t i;
973 trailer_info_get(&info, str, opts);
975 /* Print lines before the trailers as is */
976 if (!opts->only_trailers)
977 fwrite(str, 1, info.trailer_start - str, outfile);
979 if (!opts->only_trailers && !info.blank_line_before_trailer)
980 fprintf(outfile, "\n");
982 for (i = 0; i < info.trailer_nr; i++) {
983 int separator_pos;
984 char *trailer = info.trailers[i];
985 if (trailer[0] == comment_line_char)
986 continue;
987 separator_pos = find_separator(trailer, separators);
988 if (separator_pos >= 1) {
989 parse_trailer(&tok, &val, NULL, trailer,
990 separator_pos);
991 if (opts->unfold)
992 unfold_value(&val);
993 add_trailer_item(head,
994 strbuf_detach(&tok, NULL),
995 strbuf_detach(&val, NULL));
996 } else if (!opts->only_trailers) {
997 strbuf_addstr(&val, trailer);
998 strbuf_strip_suffix(&val, "\n");
999 add_trailer_item(head,
1000 NULL,
1001 strbuf_detach(&val, NULL));
1005 trailer_info_release(&info);
1007 return info.trailer_end - str;
1010 static void free_all(struct list_head *head)
1012 struct list_head *pos, *p;
1013 list_for_each_safe(pos, p, head) {
1014 list_del(pos);
1015 free_trailer_item(list_entry(pos, struct trailer_item, list));
1019 static struct tempfile *trailers_tempfile;
1021 static FILE *create_in_place_tempfile(const char *file)
1023 struct stat st;
1024 struct strbuf filename_template = STRBUF_INIT;
1025 const char *tail;
1026 FILE *outfile;
1028 if (stat(file, &st))
1029 die_errno(_("could not stat %s"), file);
1030 if (!S_ISREG(st.st_mode))
1031 die(_("file %s is not a regular file"), file);
1032 if (!(st.st_mode & S_IWUSR))
1033 die(_("file %s is not writable by user"), file);
1035 /* Create temporary file in the same directory as the original */
1036 tail = strrchr(file, '/');
1037 if (tail)
1038 strbuf_add(&filename_template, file, tail - file + 1);
1039 strbuf_addstr(&filename_template, "git-interpret-trailers-XXXXXX");
1041 trailers_tempfile = xmks_tempfile_m(filename_template.buf, st.st_mode);
1042 strbuf_release(&filename_template);
1043 outfile = fdopen_tempfile(trailers_tempfile, "w");
1044 if (!outfile)
1045 die_errno(_("could not open temporary file"));
1047 return outfile;
1050 void process_trailers(const char *file,
1051 const struct process_trailer_options *opts,
1052 struct list_head *new_trailer_head)
1054 LIST_HEAD(head);
1055 struct strbuf sb = STRBUF_INIT;
1056 size_t trailer_end;
1057 FILE *outfile = stdout;
1059 ensure_configured();
1061 read_input_file(&sb, file);
1063 if (opts->in_place)
1064 outfile = create_in_place_tempfile(file);
1066 /* Print the lines before the trailers */
1067 trailer_end = process_input_file(outfile, sb.buf, &head, opts);
1069 if (!opts->only_input) {
1070 LIST_HEAD(arg_head);
1071 process_command_line_args(&arg_head, new_trailer_head);
1072 process_trailers_lists(&head, &arg_head);
1075 print_all(outfile, &head, opts);
1077 free_all(&head);
1079 /* Print the lines after the trailers as is */
1080 if (!opts->only_trailers)
1081 fwrite(sb.buf + trailer_end, 1, sb.len - trailer_end, outfile);
1083 if (opts->in_place)
1084 if (rename_tempfile(&trailers_tempfile, file))
1085 die_errno(_("could not rename temporary file to %s"), file);
1087 strbuf_release(&sb);
1090 void trailer_info_get(struct trailer_info *info, const char *str,
1091 const struct process_trailer_options *opts)
1093 int patch_start, trailer_end, trailer_start;
1094 struct strbuf **trailer_lines, **ptr;
1095 char **trailer_strings = NULL;
1096 size_t nr = 0, alloc = 0;
1097 char **last = NULL;
1099 ensure_configured();
1101 if (opts->no_divider)
1102 patch_start = strlen(str);
1103 else
1104 patch_start = find_patch_start(str);
1106 trailer_end = find_trailer_end(str, patch_start);
1107 trailer_start = find_trailer_start(str, trailer_end);
1109 trailer_lines = strbuf_split_buf(str + trailer_start,
1110 trailer_end - trailer_start,
1111 '\n',
1113 for (ptr = trailer_lines; *ptr; ptr++) {
1114 if (last && isspace((*ptr)->buf[0])) {
1115 struct strbuf sb = STRBUF_INIT;
1116 strbuf_attach(&sb, *last, strlen(*last), strlen(*last));
1117 strbuf_addbuf(&sb, *ptr);
1118 *last = strbuf_detach(&sb, NULL);
1119 continue;
1121 ALLOC_GROW(trailer_strings, nr + 1, alloc);
1122 trailer_strings[nr] = strbuf_detach(*ptr, NULL);
1123 last = find_separator(trailer_strings[nr], separators) >= 1
1124 ? &trailer_strings[nr]
1125 : NULL;
1126 nr++;
1128 strbuf_list_free(trailer_lines);
1130 info->blank_line_before_trailer = ends_with_blank_line(str,
1131 trailer_start);
1132 info->trailer_start = str + trailer_start;
1133 info->trailer_end = str + trailer_end;
1134 info->trailers = trailer_strings;
1135 info->trailer_nr = nr;
1138 void trailer_info_release(struct trailer_info *info)
1140 size_t i;
1141 for (i = 0; i < info->trailer_nr; i++)
1142 free(info->trailers[i]);
1143 free(info->trailers);
1146 static void format_trailer_info(struct strbuf *out,
1147 const struct trailer_info *info,
1148 const struct process_trailer_options *opts)
1150 size_t origlen = out->len;
1151 size_t i;
1153 /* If we want the whole block untouched, we can take the fast path. */
1154 if (!opts->only_trailers && !opts->unfold && !opts->filter &&
1155 !opts->separator && !opts->key_only && !opts->value_only &&
1156 !opts->key_value_separator) {
1157 strbuf_add(out, info->trailer_start,
1158 info->trailer_end - info->trailer_start);
1159 return;
1162 for (i = 0; i < info->trailer_nr; i++) {
1163 char *trailer = info->trailers[i];
1164 ssize_t separator_pos = find_separator(trailer, separators);
1166 if (separator_pos >= 1) {
1167 struct strbuf tok = STRBUF_INIT;
1168 struct strbuf val = STRBUF_INIT;
1170 parse_trailer(&tok, &val, NULL, trailer, separator_pos);
1171 if (!opts->filter || opts->filter(&tok, opts->filter_data)) {
1172 if (opts->unfold)
1173 unfold_value(&val);
1175 if (opts->separator && out->len != origlen)
1176 strbuf_addbuf(out, opts->separator);
1177 if (!opts->value_only)
1178 strbuf_addbuf(out, &tok);
1179 if (!opts->key_only && !opts->value_only) {
1180 if (opts->key_value_separator)
1181 strbuf_addbuf(out, opts->key_value_separator);
1182 else
1183 strbuf_addstr(out, ": ");
1185 if (!opts->key_only)
1186 strbuf_addbuf(out, &val);
1187 if (!opts->separator)
1188 strbuf_addch(out, '\n');
1190 strbuf_release(&tok);
1191 strbuf_release(&val);
1193 } else if (!opts->only_trailers) {
1194 if (opts->separator && out->len != origlen) {
1195 strbuf_addbuf(out, opts->separator);
1197 strbuf_addstr(out, trailer);
1198 if (opts->separator) {
1199 strbuf_rtrim(out);
1206 void format_trailers_from_commit(struct strbuf *out, const char *msg,
1207 const struct process_trailer_options *opts)
1209 struct trailer_info info;
1211 trailer_info_get(&info, msg, opts);
1212 format_trailer_info(out, &info, opts);
1213 trailer_info_release(&info);
1216 void trailer_iterator_init(struct trailer_iterator *iter, const char *msg)
1218 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
1219 strbuf_init(&iter->key, 0);
1220 strbuf_init(&iter->val, 0);
1221 opts.no_divider = 1;
1222 trailer_info_get(&iter->info, msg, &opts);
1223 iter->cur = 0;
1226 int trailer_iterator_advance(struct trailer_iterator *iter)
1228 while (iter->cur < iter->info.trailer_nr) {
1229 char *trailer = iter->info.trailers[iter->cur++];
1230 int separator_pos = find_separator(trailer, separators);
1232 if (separator_pos < 1)
1233 continue; /* not a real trailer */
1235 strbuf_reset(&iter->key);
1236 strbuf_reset(&iter->val);
1237 parse_trailer(&iter->key, &iter->val, NULL,
1238 trailer, separator_pos);
1239 unfold_value(&iter->val);
1240 return 1;
1242 return 0;
1245 void trailer_iterator_release(struct trailer_iterator *iter)
1247 trailer_info_release(&iter->info);
1248 strbuf_release(&iter->val);
1249 strbuf_release(&iter->key);