tree-diff: respect max_allowed_tree_depth
[git.git] / trailer.c
blobf408f9b058dbbc33b1360cf36e1e023b7bba1a54
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 "tempfile.h"
9 #include "trailer.h"
10 #include "list.h"
12 * Copyright (c) 2013, 2014 Christian Couder <chriscool@tuxfamily.org>
15 struct conf_info {
16 char *name;
17 char *key;
18 char *command;
19 char *cmd;
20 enum trailer_where where;
21 enum trailer_if_exists if_exists;
22 enum trailer_if_missing if_missing;
25 static struct conf_info default_conf_info;
27 struct trailer_item {
28 struct list_head list;
30 * If this is not a trailer line, the line is stored in value
31 * (excluding the terminating newline) and token is NULL.
33 char *token;
34 char *value;
37 struct arg_item {
38 struct list_head list;
39 char *token;
40 char *value;
41 struct conf_info conf;
44 static LIST_HEAD(conf_head);
46 static char *separators = ":";
48 static int configured;
50 #define TRAILER_ARG_STRING "$ARG"
52 static const char *git_generated_prefixes[] = {
53 "Signed-off-by: ",
54 "(cherry picked from commit ",
55 NULL
58 /* Iterate over the elements of the list. */
59 #define list_for_each_dir(pos, head, is_reverse) \
60 for (pos = is_reverse ? (head)->prev : (head)->next; \
61 pos != (head); \
62 pos = is_reverse ? pos->prev : pos->next)
64 static int after_or_end(enum trailer_where where)
66 return (where == WHERE_AFTER) || (where == WHERE_END);
70 * Return the length of the string not including any final
71 * punctuation. E.g., the input "Signed-off-by:" would return
72 * 13, stripping the trailing punctuation but retaining
73 * internal punctuation.
75 static size_t token_len_without_separator(const char *token, size_t len)
77 while (len > 0 && !isalnum(token[len - 1]))
78 len--;
79 return len;
82 static int same_token(struct trailer_item *a, struct arg_item *b)
84 size_t a_len, b_len, min_len;
86 if (!a->token)
87 return 0;
89 a_len = token_len_without_separator(a->token, strlen(a->token));
90 b_len = token_len_without_separator(b->token, strlen(b->token));
91 min_len = (a_len > b_len) ? b_len : a_len;
93 return !strncasecmp(a->token, b->token, min_len);
96 static int same_value(struct trailer_item *a, struct arg_item *b)
98 return !strcasecmp(a->value, b->value);
101 static int same_trailer(struct trailer_item *a, struct arg_item *b)
103 return same_token(a, b) && same_value(a, b);
106 static inline int is_blank_line(const char *str)
108 const char *s = str;
109 while (*s && *s != '\n' && isspace(*s))
110 s++;
111 return !*s || *s == '\n';
114 static inline void strbuf_replace(struct strbuf *sb, const char *a, const char *b)
116 const char *ptr = strstr(sb->buf, a);
117 if (ptr)
118 strbuf_splice(sb, ptr - sb->buf, strlen(a), b, strlen(b));
121 static void free_trailer_item(struct trailer_item *item)
123 free(item->token);
124 free(item->value);
125 free(item);
128 static void free_arg_item(struct arg_item *item)
130 free(item->conf.name);
131 free(item->conf.key);
132 free(item->conf.command);
133 free(item->conf.cmd);
134 free(item->token);
135 free(item->value);
136 free(item);
139 static char last_non_space_char(const char *s)
141 int i;
142 for (i = strlen(s) - 1; i >= 0; i--)
143 if (!isspace(s[i]))
144 return s[i];
145 return '\0';
148 static void print_tok_val(FILE *outfile, const char *tok, const char *val)
150 char c;
152 if (!tok) {
153 fprintf(outfile, "%s\n", val);
154 return;
157 c = last_non_space_char(tok);
158 if (!c)
159 return;
160 if (strchr(separators, c))
161 fprintf(outfile, "%s%s\n", tok, val);
162 else
163 fprintf(outfile, "%s%c %s\n", tok, separators[0], val);
166 static void print_all(FILE *outfile, struct list_head *head,
167 const struct process_trailer_options *opts)
169 struct list_head *pos;
170 struct trailer_item *item;
171 list_for_each(pos, head) {
172 item = list_entry(pos, struct trailer_item, list);
173 if ((!opts->trim_empty || strlen(item->value) > 0) &&
174 (!opts->only_trailers || item->token))
175 print_tok_val(outfile, item->token, item->value);
179 static struct trailer_item *trailer_from_arg(struct arg_item *arg_tok)
181 struct trailer_item *new_item = xcalloc(1, sizeof(*new_item));
182 new_item->token = arg_tok->token;
183 new_item->value = arg_tok->value;
184 arg_tok->token = arg_tok->value = NULL;
185 free_arg_item(arg_tok);
186 return new_item;
189 static void add_arg_to_input_list(struct trailer_item *on_tok,
190 struct arg_item *arg_tok)
192 int aoe = after_or_end(arg_tok->conf.where);
193 struct trailer_item *to_add = trailer_from_arg(arg_tok);
194 if (aoe)
195 list_add(&to_add->list, &on_tok->list);
196 else
197 list_add_tail(&to_add->list, &on_tok->list);
200 static int check_if_different(struct trailer_item *in_tok,
201 struct arg_item *arg_tok,
202 int check_all,
203 struct list_head *head)
205 enum trailer_where where = arg_tok->conf.where;
206 struct list_head *next_head;
207 do {
208 if (same_trailer(in_tok, arg_tok))
209 return 0;
211 * if we want to add a trailer after another one,
212 * we have to check those before this one
214 next_head = after_or_end(where) ? in_tok->list.prev
215 : in_tok->list.next;
216 if (next_head == head)
217 break;
218 in_tok = list_entry(next_head, struct trailer_item, list);
219 } while (check_all);
220 return 1;
223 static char *apply_command(struct conf_info *conf, const char *arg)
225 struct strbuf cmd = STRBUF_INIT;
226 struct strbuf buf = STRBUF_INIT;
227 struct child_process cp = CHILD_PROCESS_INIT;
228 char *result;
230 if (conf->cmd) {
231 strbuf_addstr(&cmd, conf->cmd);
232 strvec_push(&cp.args, cmd.buf);
233 if (arg)
234 strvec_push(&cp.args, arg);
235 } else if (conf->command) {
236 strbuf_addstr(&cmd, conf->command);
237 if (arg)
238 strbuf_replace(&cmd, TRAILER_ARG_STRING, arg);
239 strvec_push(&cp.args, cmd.buf);
241 strvec_pushv(&cp.env, (const char **)local_repo_env);
242 cp.no_stdin = 1;
243 cp.use_shell = 1;
245 if (capture_command(&cp, &buf, 1024)) {
246 error(_("running trailer command '%s' failed"), cmd.buf);
247 strbuf_release(&buf);
248 result = xstrdup("");
249 } else {
250 strbuf_trim(&buf);
251 result = strbuf_detach(&buf, NULL);
254 strbuf_release(&cmd);
255 return result;
258 static void apply_item_command(struct trailer_item *in_tok, struct arg_item *arg_tok)
260 if (arg_tok->conf.command || arg_tok->conf.cmd) {
261 const char *arg;
262 if (arg_tok->value && arg_tok->value[0]) {
263 arg = arg_tok->value;
264 } else {
265 if (in_tok && in_tok->value)
266 arg = xstrdup(in_tok->value);
267 else
268 arg = xstrdup("");
270 arg_tok->value = apply_command(&arg_tok->conf, arg);
271 free((char *)arg);
275 static void apply_arg_if_exists(struct trailer_item *in_tok,
276 struct arg_item *arg_tok,
277 struct trailer_item *on_tok,
278 struct list_head *head)
280 switch (arg_tok->conf.if_exists) {
281 case EXISTS_DO_NOTHING:
282 free_arg_item(arg_tok);
283 break;
284 case EXISTS_REPLACE:
285 apply_item_command(in_tok, arg_tok);
286 add_arg_to_input_list(on_tok, arg_tok);
287 list_del(&in_tok->list);
288 free_trailer_item(in_tok);
289 break;
290 case EXISTS_ADD:
291 apply_item_command(in_tok, arg_tok);
292 add_arg_to_input_list(on_tok, arg_tok);
293 break;
294 case EXISTS_ADD_IF_DIFFERENT:
295 apply_item_command(in_tok, arg_tok);
296 if (check_if_different(in_tok, arg_tok, 1, head))
297 add_arg_to_input_list(on_tok, arg_tok);
298 else
299 free_arg_item(arg_tok);
300 break;
301 case EXISTS_ADD_IF_DIFFERENT_NEIGHBOR:
302 apply_item_command(in_tok, arg_tok);
303 if (check_if_different(on_tok, arg_tok, 0, head))
304 add_arg_to_input_list(on_tok, arg_tok);
305 else
306 free_arg_item(arg_tok);
307 break;
308 default:
309 BUG("trailer.c: unhandled value %d",
310 arg_tok->conf.if_exists);
314 static void apply_arg_if_missing(struct list_head *head,
315 struct arg_item *arg_tok)
317 enum trailer_where where;
318 struct trailer_item *to_add;
320 switch (arg_tok->conf.if_missing) {
321 case MISSING_DO_NOTHING:
322 free_arg_item(arg_tok);
323 break;
324 case MISSING_ADD:
325 where = arg_tok->conf.where;
326 apply_item_command(NULL, arg_tok);
327 to_add = trailer_from_arg(arg_tok);
328 if (after_or_end(where))
329 list_add_tail(&to_add->list, head);
330 else
331 list_add(&to_add->list, head);
332 break;
333 default:
334 BUG("trailer.c: unhandled value %d",
335 arg_tok->conf.if_missing);
339 static int find_same_and_apply_arg(struct list_head *head,
340 struct arg_item *arg_tok)
342 struct list_head *pos;
343 struct trailer_item *in_tok;
344 struct trailer_item *on_tok;
346 enum trailer_where where = arg_tok->conf.where;
347 int middle = (where == WHERE_AFTER) || (where == WHERE_BEFORE);
348 int backwards = after_or_end(where);
349 struct trailer_item *start_tok;
351 if (list_empty(head))
352 return 0;
354 start_tok = list_entry(backwards ? head->prev : head->next,
355 struct trailer_item,
356 list);
358 list_for_each_dir(pos, head, backwards) {
359 in_tok = list_entry(pos, struct trailer_item, list);
360 if (!same_token(in_tok, arg_tok))
361 continue;
362 on_tok = middle ? in_tok : start_tok;
363 apply_arg_if_exists(in_tok, arg_tok, on_tok, head);
364 return 1;
366 return 0;
369 static void process_trailers_lists(struct list_head *head,
370 struct list_head *arg_head)
372 struct list_head *pos, *p;
373 struct arg_item *arg_tok;
375 list_for_each_safe(pos, p, arg_head) {
376 int applied = 0;
377 arg_tok = list_entry(pos, struct arg_item, list);
379 list_del(pos);
381 applied = find_same_and_apply_arg(head, arg_tok);
383 if (!applied)
384 apply_arg_if_missing(head, arg_tok);
388 int trailer_set_where(enum trailer_where *item, const char *value)
390 if (!value)
391 *item = WHERE_DEFAULT;
392 else if (!strcasecmp("after", value))
393 *item = WHERE_AFTER;
394 else if (!strcasecmp("before", value))
395 *item = WHERE_BEFORE;
396 else if (!strcasecmp("end", value))
397 *item = WHERE_END;
398 else if (!strcasecmp("start", value))
399 *item = WHERE_START;
400 else
401 return -1;
402 return 0;
405 int trailer_set_if_exists(enum trailer_if_exists *item, const char *value)
407 if (!value)
408 *item = EXISTS_DEFAULT;
409 else if (!strcasecmp("addIfDifferent", value))
410 *item = EXISTS_ADD_IF_DIFFERENT;
411 else if (!strcasecmp("addIfDifferentNeighbor", value))
412 *item = EXISTS_ADD_IF_DIFFERENT_NEIGHBOR;
413 else if (!strcasecmp("add", value))
414 *item = EXISTS_ADD;
415 else if (!strcasecmp("replace", value))
416 *item = EXISTS_REPLACE;
417 else if (!strcasecmp("doNothing", value))
418 *item = EXISTS_DO_NOTHING;
419 else
420 return -1;
421 return 0;
424 int trailer_set_if_missing(enum trailer_if_missing *item, const char *value)
426 if (!value)
427 *item = MISSING_DEFAULT;
428 else if (!strcasecmp("doNothing", value))
429 *item = MISSING_DO_NOTHING;
430 else if (!strcasecmp("add", value))
431 *item = MISSING_ADD;
432 else
433 return -1;
434 return 0;
437 static void duplicate_conf(struct conf_info *dst, const struct conf_info *src)
439 *dst = *src;
440 dst->name = xstrdup_or_null(src->name);
441 dst->key = xstrdup_or_null(src->key);
442 dst->command = xstrdup_or_null(src->command);
443 dst->cmd = xstrdup_or_null(src->cmd);
446 static struct arg_item *get_conf_item(const char *name)
448 struct list_head *pos;
449 struct arg_item *item;
451 /* Look up item with same name */
452 list_for_each(pos, &conf_head) {
453 item = list_entry(pos, struct arg_item, list);
454 if (!strcasecmp(item->conf.name, name))
455 return item;
458 /* Item does not already exists, create it */
459 CALLOC_ARRAY(item, 1);
460 duplicate_conf(&item->conf, &default_conf_info);
461 item->conf.name = xstrdup(name);
463 list_add_tail(&item->list, &conf_head);
465 return item;
468 enum trailer_info_type { TRAILER_KEY, TRAILER_COMMAND, TRAILER_CMD,
469 TRAILER_WHERE, TRAILER_IF_EXISTS, TRAILER_IF_MISSING };
471 static struct {
472 const char *name;
473 enum trailer_info_type type;
474 } trailer_config_items[] = {
475 { "key", TRAILER_KEY },
476 { "command", TRAILER_COMMAND },
477 { "cmd", TRAILER_CMD },
478 { "where", TRAILER_WHERE },
479 { "ifexists", TRAILER_IF_EXISTS },
480 { "ifmissing", TRAILER_IF_MISSING }
483 static int git_trailer_default_config(const char *conf_key, const char *value,
484 const struct config_context *ctx UNUSED,
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 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 conf->key = xstrdup(value);
555 break;
556 case TRAILER_COMMAND:
557 if (conf->command)
558 warning(_("more than one %s"), conf_key);
559 conf->command = xstrdup(value);
560 break;
561 case TRAILER_CMD:
562 if (conf->cmd)
563 warning(_("more than one %s"), conf_key);
564 conf->cmd = xstrdup(value);
565 break;
566 case TRAILER_WHERE:
567 if (trailer_set_where(&conf->where, value))
568 warning(_("unknown value '%s' for key '%s'"), value, conf_key);
569 break;
570 case TRAILER_IF_EXISTS:
571 if (trailer_set_if_exists(&conf->if_exists, value))
572 warning(_("unknown value '%s' for key '%s'"), value, conf_key);
573 break;
574 case TRAILER_IF_MISSING:
575 if (trailer_set_if_missing(&conf->if_missing, value))
576 warning(_("unknown value '%s' for key '%s'"), value, conf_key);
577 break;
578 default:
579 BUG("trailer.c: unhandled type %d", type);
581 return 0;
584 static void ensure_configured(void)
586 if (configured)
587 return;
589 /* Default config must be setup first */
590 default_conf_info.where = WHERE_END;
591 default_conf_info.if_exists = EXISTS_ADD_IF_DIFFERENT_NEIGHBOR;
592 default_conf_info.if_missing = MISSING_ADD;
593 git_config(git_trailer_default_config, NULL);
594 git_config(git_trailer_config, NULL);
595 configured = 1;
598 static const char *token_from_item(struct arg_item *item, char *tok)
600 if (item->conf.key)
601 return item->conf.key;
602 if (tok)
603 return tok;
604 return item->conf.name;
607 static int token_matches_item(const char *tok, struct arg_item *item, size_t tok_len)
609 if (!strncasecmp(tok, item->conf.name, tok_len))
610 return 1;
611 return item->conf.key ? !strncasecmp(tok, item->conf.key, tok_len) : 0;
615 * If the given line is of the form
616 * "<token><optional whitespace><separator>..." or "<separator>...", return the
617 * location of the separator. Otherwise, return -1. The optional whitespace
618 * is allowed there primarily to allow things like "Bug #43" where <token> is
619 * "Bug" and <separator> is "#".
621 * The separator-starts-line case (in which this function returns 0) is
622 * distinguished from the non-well-formed-line case (in which this function
623 * returns -1) because some callers of this function need such a distinction.
625 static ssize_t find_separator(const char *line, const char *separators)
627 int whitespace_found = 0;
628 const char *c;
629 for (c = line; *c; c++) {
630 if (strchr(separators, *c))
631 return c - line;
632 if (!whitespace_found && (isalnum(*c) || *c == '-'))
633 continue;
634 if (c != line && (*c == ' ' || *c == '\t')) {
635 whitespace_found = 1;
636 continue;
638 break;
640 return -1;
644 * Obtain the token, value, and conf from the given trailer.
646 * separator_pos must not be 0, since the token cannot be an empty string.
648 * If separator_pos is -1, interpret the whole trailer as a token.
650 static void parse_trailer(struct strbuf *tok, struct strbuf *val,
651 const struct conf_info **conf, const char *trailer,
652 ssize_t separator_pos)
654 struct arg_item *item;
655 size_t tok_len;
656 struct list_head *pos;
658 if (separator_pos != -1) {
659 strbuf_add(tok, trailer, separator_pos);
660 strbuf_trim(tok);
661 strbuf_addstr(val, trailer + separator_pos + 1);
662 strbuf_trim(val);
663 } else {
664 strbuf_addstr(tok, trailer);
665 strbuf_trim(tok);
668 /* Lookup if the token matches something in the config */
669 tok_len = token_len_without_separator(tok->buf, tok->len);
670 if (conf)
671 *conf = &default_conf_info;
672 list_for_each(pos, &conf_head) {
673 item = list_entry(pos, struct arg_item, list);
674 if (token_matches_item(tok->buf, item, tok_len)) {
675 char *tok_buf = strbuf_detach(tok, NULL);
676 if (conf)
677 *conf = &item->conf;
678 strbuf_addstr(tok, token_from_item(item, tok_buf));
679 free(tok_buf);
680 break;
685 static struct trailer_item *add_trailer_item(struct list_head *head, char *tok,
686 char *val)
688 struct trailer_item *new_item = xcalloc(1, sizeof(*new_item));
689 new_item->token = tok;
690 new_item->value = val;
691 list_add_tail(&new_item->list, head);
692 return new_item;
695 static void add_arg_item(struct list_head *arg_head, char *tok, char *val,
696 const struct conf_info *conf,
697 const struct new_trailer_item *new_trailer_item)
699 struct arg_item *new_item = xcalloc(1, sizeof(*new_item));
700 new_item->token = tok;
701 new_item->value = val;
702 duplicate_conf(&new_item->conf, conf);
703 if (new_trailer_item) {
704 if (new_trailer_item->where != WHERE_DEFAULT)
705 new_item->conf.where = new_trailer_item->where;
706 if (new_trailer_item->if_exists != EXISTS_DEFAULT)
707 new_item->conf.if_exists = new_trailer_item->if_exists;
708 if (new_trailer_item->if_missing != MISSING_DEFAULT)
709 new_item->conf.if_missing = new_trailer_item->if_missing;
711 list_add_tail(&new_item->list, arg_head);
714 static void process_command_line_args(struct list_head *arg_head,
715 struct list_head *new_trailer_head)
717 struct arg_item *item;
718 struct strbuf tok = STRBUF_INIT;
719 struct strbuf val = STRBUF_INIT;
720 const struct conf_info *conf;
721 struct list_head *pos;
724 * In command-line arguments, '=' is accepted (in addition to the
725 * separators that are defined).
727 char *cl_separators = xstrfmt("=%s", separators);
729 /* Add an arg item for each configured trailer with a command */
730 list_for_each(pos, &conf_head) {
731 item = list_entry(pos, struct arg_item, list);
732 if (item->conf.command)
733 add_arg_item(arg_head,
734 xstrdup(token_from_item(item, NULL)),
735 xstrdup(""),
736 &item->conf, NULL);
739 /* Add an arg item for each trailer on the command line */
740 list_for_each(pos, new_trailer_head) {
741 struct new_trailer_item *tr =
742 list_entry(pos, struct new_trailer_item, list);
743 ssize_t separator_pos = find_separator(tr->text, cl_separators);
745 if (separator_pos == 0) {
746 struct strbuf sb = STRBUF_INIT;
747 strbuf_addstr(&sb, tr->text);
748 strbuf_trim(&sb);
749 error(_("empty trailer token in trailer '%.*s'"),
750 (int) sb.len, sb.buf);
751 strbuf_release(&sb);
752 } else {
753 parse_trailer(&tok, &val, &conf, tr->text,
754 separator_pos);
755 add_arg_item(arg_head,
756 strbuf_detach(&tok, NULL),
757 strbuf_detach(&val, NULL),
758 conf, tr);
762 free(cl_separators);
765 static void read_input_file(struct strbuf *sb, const char *file)
767 if (file) {
768 if (strbuf_read_file(sb, file, 0) < 0)
769 die_errno(_("could not read input file '%s'"), file);
770 } else {
771 if (strbuf_read(sb, fileno(stdin), 0) < 0)
772 die_errno(_("could not read from stdin"));
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 * Return the position of the start of the patch or the length of str if there
808 * is no patch in the message.
810 static size_t find_patch_start(const char *str)
812 const char *s;
814 for (s = str; *s; s = next_line(s)) {
815 const char *v;
817 if (skip_prefix(s, "---", &v) && isspace(*v))
818 return s - str;
821 return s - str;
825 * Return the position of the first trailer line or len if there are no
826 * trailers.
828 static size_t find_trailer_start(const char *buf, size_t len)
830 const char *s;
831 ssize_t end_of_title, l;
832 int only_spaces = 1;
833 int recognized_prefix = 0, trailer_lines = 0, non_trailer_lines = 0;
835 * Number of possible continuation lines encountered. This will be
836 * reset to 0 if we encounter a trailer (since those lines are to be
837 * considered continuations of that trailer), and added to
838 * non_trailer_lines if we encounter a non-trailer (since those lines
839 * are to be considered non-trailers).
841 int possible_continuation_lines = 0;
843 /* The first paragraph is the title and cannot be trailers */
844 for (s = buf; s < buf + len; s = next_line(s)) {
845 if (s[0] == comment_line_char)
846 continue;
847 if (is_blank_line(s))
848 break;
850 end_of_title = s - buf;
853 * Get the start of the trailers by looking starting from the end for a
854 * blank line before a set of non-blank lines that (i) are all
855 * trailers, or (ii) contains at least one Git-generated trailer and
856 * consists of at least 25% trailers.
858 for (l = last_line(buf, len);
859 l >= end_of_title;
860 l = last_line(buf, l)) {
861 const char *bol = buf + l;
862 const char **p;
863 ssize_t separator_pos;
865 if (bol[0] == comment_line_char) {
866 non_trailer_lines += possible_continuation_lines;
867 possible_continuation_lines = 0;
868 continue;
870 if (is_blank_line(bol)) {
871 if (only_spaces)
872 continue;
873 non_trailer_lines += possible_continuation_lines;
874 if (recognized_prefix &&
875 trailer_lines * 3 >= non_trailer_lines)
876 return next_line(bol) - buf;
877 else if (trailer_lines && !non_trailer_lines)
878 return next_line(bol) - buf;
879 return len;
881 only_spaces = 0;
883 for (p = git_generated_prefixes; *p; p++) {
884 if (starts_with(bol, *p)) {
885 trailer_lines++;
886 possible_continuation_lines = 0;
887 recognized_prefix = 1;
888 goto continue_outer_loop;
892 separator_pos = find_separator(bol, separators);
893 if (separator_pos >= 1 && !isspace(bol[0])) {
894 struct list_head *pos;
896 trailer_lines++;
897 possible_continuation_lines = 0;
898 if (recognized_prefix)
899 continue;
900 list_for_each(pos, &conf_head) {
901 struct arg_item *item;
902 item = list_entry(pos, struct arg_item, list);
903 if (token_matches_item(bol, item,
904 separator_pos)) {
905 recognized_prefix = 1;
906 break;
909 } else if (isspace(bol[0]))
910 possible_continuation_lines++;
911 else {
912 non_trailer_lines++;
913 non_trailer_lines += possible_continuation_lines;
914 possible_continuation_lines = 0;
916 continue_outer_loop:
920 return len;
923 /* Return the position of the end of the trailers. */
924 static size_t find_trailer_end(const char *buf, size_t len)
926 return len - ignore_non_trailer(buf, len);
929 static int ends_with_blank_line(const char *buf, size_t len)
931 ssize_t ll = last_line(buf, len);
932 if (ll < 0)
933 return 0;
934 return is_blank_line(buf + ll);
937 static void unfold_value(struct strbuf *val)
939 struct strbuf out = STRBUF_INIT;
940 size_t i;
942 strbuf_grow(&out, val->len);
943 i = 0;
944 while (i < val->len) {
945 char c = val->buf[i++];
946 if (c == '\n') {
947 /* Collapse continuation down to a single space. */
948 while (i < val->len && isspace(val->buf[i]))
949 i++;
950 strbuf_addch(&out, ' ');
951 } else {
952 strbuf_addch(&out, c);
956 /* Empty lines may have left us with whitespace cruft at the edges */
957 strbuf_trim(&out);
959 /* output goes back to val as if we modified it in-place */
960 strbuf_swap(&out, val);
961 strbuf_release(&out);
964 static size_t process_input_file(FILE *outfile,
965 const char *str,
966 struct list_head *head,
967 const struct process_trailer_options *opts)
969 struct trailer_info info;
970 struct strbuf tok = STRBUF_INIT;
971 struct strbuf val = STRBUF_INIT;
972 size_t i;
974 trailer_info_get(&info, str, opts);
976 /* Print lines before the trailers as is */
977 if (!opts->only_trailers)
978 fwrite(str, 1, info.trailer_start - str, outfile);
980 if (!opts->only_trailers && !info.blank_line_before_trailer)
981 fprintf(outfile, "\n");
983 for (i = 0; i < info.trailer_nr; i++) {
984 int separator_pos;
985 char *trailer = info.trailers[i];
986 if (trailer[0] == comment_line_char)
987 continue;
988 separator_pos = find_separator(trailer, separators);
989 if (separator_pos >= 1) {
990 parse_trailer(&tok, &val, NULL, trailer,
991 separator_pos);
992 if (opts->unfold)
993 unfold_value(&val);
994 add_trailer_item(head,
995 strbuf_detach(&tok, NULL),
996 strbuf_detach(&val, NULL));
997 } else if (!opts->only_trailers) {
998 strbuf_addstr(&val, trailer);
999 strbuf_strip_suffix(&val, "\n");
1000 add_trailer_item(head,
1001 NULL,
1002 strbuf_detach(&val, NULL));
1006 trailer_info_release(&info);
1008 return info.trailer_end - str;
1011 static void free_all(struct list_head *head)
1013 struct list_head *pos, *p;
1014 list_for_each_safe(pos, p, head) {
1015 list_del(pos);
1016 free_trailer_item(list_entry(pos, struct trailer_item, list));
1020 static struct tempfile *trailers_tempfile;
1022 static FILE *create_in_place_tempfile(const char *file)
1024 struct stat st;
1025 struct strbuf filename_template = STRBUF_INIT;
1026 const char *tail;
1027 FILE *outfile;
1029 if (stat(file, &st))
1030 die_errno(_("could not stat %s"), file);
1031 if (!S_ISREG(st.st_mode))
1032 die(_("file %s is not a regular file"), file);
1033 if (!(st.st_mode & S_IWUSR))
1034 die(_("file %s is not writable by user"), file);
1036 /* Create temporary file in the same directory as the original */
1037 tail = strrchr(file, '/');
1038 if (tail)
1039 strbuf_add(&filename_template, file, tail - file + 1);
1040 strbuf_addstr(&filename_template, "git-interpret-trailers-XXXXXX");
1042 trailers_tempfile = xmks_tempfile_m(filename_template.buf, st.st_mode);
1043 strbuf_release(&filename_template);
1044 outfile = fdopen_tempfile(trailers_tempfile, "w");
1045 if (!outfile)
1046 die_errno(_("could not open temporary file"));
1048 return outfile;
1051 void process_trailers(const char *file,
1052 const struct process_trailer_options *opts,
1053 struct list_head *new_trailer_head)
1055 LIST_HEAD(head);
1056 struct strbuf sb = STRBUF_INIT;
1057 size_t trailer_end;
1058 FILE *outfile = stdout;
1060 ensure_configured();
1062 read_input_file(&sb, file);
1064 if (opts->in_place)
1065 outfile = create_in_place_tempfile(file);
1067 /* Print the lines before the trailers */
1068 trailer_end = process_input_file(outfile, sb.buf, &head, opts);
1070 if (!opts->only_input) {
1071 LIST_HEAD(arg_head);
1072 process_command_line_args(&arg_head, new_trailer_head);
1073 process_trailers_lists(&head, &arg_head);
1076 print_all(outfile, &head, opts);
1078 free_all(&head);
1080 /* Print the lines after the trailers as is */
1081 if (!opts->only_trailers)
1082 fwrite(sb.buf + trailer_end, 1, sb.len - trailer_end, outfile);
1084 if (opts->in_place)
1085 if (rename_tempfile(&trailers_tempfile, file))
1086 die_errno(_("could not rename temporary file to %s"), file);
1088 strbuf_release(&sb);
1091 void trailer_info_get(struct trailer_info *info, const char *str,
1092 const struct process_trailer_options *opts)
1094 int patch_start, trailer_end, trailer_start;
1095 struct strbuf **trailer_lines, **ptr;
1096 char **trailer_strings = NULL;
1097 size_t nr = 0, alloc = 0;
1098 char **last = NULL;
1100 ensure_configured();
1102 if (opts->no_divider)
1103 patch_start = strlen(str);
1104 else
1105 patch_start = find_patch_start(str);
1107 trailer_end = find_trailer_end(str, patch_start);
1108 trailer_start = find_trailer_start(str, trailer_end);
1110 trailer_lines = strbuf_split_buf(str + trailer_start,
1111 trailer_end - trailer_start,
1112 '\n',
1114 for (ptr = trailer_lines; *ptr; ptr++) {
1115 if (last && isspace((*ptr)->buf[0])) {
1116 struct strbuf sb = STRBUF_INIT;
1117 strbuf_attach(&sb, *last, strlen(*last), strlen(*last));
1118 strbuf_addbuf(&sb, *ptr);
1119 *last = strbuf_detach(&sb, NULL);
1120 continue;
1122 ALLOC_GROW(trailer_strings, nr + 1, alloc);
1123 trailer_strings[nr] = strbuf_detach(*ptr, NULL);
1124 last = find_separator(trailer_strings[nr], separators) >= 1
1125 ? &trailer_strings[nr]
1126 : NULL;
1127 nr++;
1129 strbuf_list_free(trailer_lines);
1131 info->blank_line_before_trailer = ends_with_blank_line(str,
1132 trailer_start);
1133 info->trailer_start = str + trailer_start;
1134 info->trailer_end = str + trailer_end;
1135 info->trailers = trailer_strings;
1136 info->trailer_nr = nr;
1139 void trailer_info_release(struct trailer_info *info)
1141 size_t i;
1142 for (i = 0; i < info->trailer_nr; i++)
1143 free(info->trailers[i]);
1144 free(info->trailers);
1147 static void format_trailer_info(struct strbuf *out,
1148 const struct trailer_info *info,
1149 const struct process_trailer_options *opts)
1151 size_t origlen = out->len;
1152 size_t i;
1154 /* If we want the whole block untouched, we can take the fast path. */
1155 if (!opts->only_trailers && !opts->unfold && !opts->filter &&
1156 !opts->separator && !opts->key_only && !opts->value_only &&
1157 !opts->key_value_separator) {
1158 strbuf_add(out, info->trailer_start,
1159 info->trailer_end - info->trailer_start);
1160 return;
1163 for (i = 0; i < info->trailer_nr; i++) {
1164 char *trailer = info->trailers[i];
1165 ssize_t separator_pos = find_separator(trailer, separators);
1167 if (separator_pos >= 1) {
1168 struct strbuf tok = STRBUF_INIT;
1169 struct strbuf val = STRBUF_INIT;
1171 parse_trailer(&tok, &val, NULL, trailer, separator_pos);
1172 if (!opts->filter || opts->filter(&tok, opts->filter_data)) {
1173 if (opts->unfold)
1174 unfold_value(&val);
1176 if (opts->separator && out->len != origlen)
1177 strbuf_addbuf(out, opts->separator);
1178 if (!opts->value_only)
1179 strbuf_addbuf(out, &tok);
1180 if (!opts->key_only && !opts->value_only) {
1181 if (opts->key_value_separator)
1182 strbuf_addbuf(out, opts->key_value_separator);
1183 else
1184 strbuf_addstr(out, ": ");
1186 if (!opts->key_only)
1187 strbuf_addbuf(out, &val);
1188 if (!opts->separator)
1189 strbuf_addch(out, '\n');
1191 strbuf_release(&tok);
1192 strbuf_release(&val);
1194 } else if (!opts->only_trailers) {
1195 if (opts->separator && out->len != origlen) {
1196 strbuf_addbuf(out, opts->separator);
1198 strbuf_addstr(out, trailer);
1199 if (opts->separator) {
1200 strbuf_rtrim(out);
1207 void format_trailers_from_commit(struct strbuf *out, const char *msg,
1208 const struct process_trailer_options *opts)
1210 struct trailer_info info;
1212 trailer_info_get(&info, msg, opts);
1213 format_trailer_info(out, &info, opts);
1214 trailer_info_release(&info);
1217 void trailer_iterator_init(struct trailer_iterator *iter, const char *msg)
1219 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
1220 strbuf_init(&iter->key, 0);
1221 strbuf_init(&iter->val, 0);
1222 opts.no_divider = 1;
1223 trailer_info_get(&iter->info, msg, &opts);
1224 iter->cur = 0;
1227 int trailer_iterator_advance(struct trailer_iterator *iter)
1229 while (iter->cur < iter->info.trailer_nr) {
1230 char *trailer = iter->info.trailers[iter->cur++];
1231 int separator_pos = find_separator(trailer, separators);
1233 if (separator_pos < 1)
1234 continue; /* not a real trailer */
1236 strbuf_reset(&iter->key);
1237 strbuf_reset(&iter->val);
1238 parse_trailer(&iter->key, &iter->val, NULL,
1239 trailer, separator_pos);
1240 unfold_value(&iter->val);
1241 return 1;
1243 return 0;
1246 void trailer_iterator_release(struct trailer_iterator *iter)
1248 trailer_info_release(&iter->info);
1249 strbuf_release(&iter->val);
1250 strbuf_release(&iter->key);