The eighth batch
[git/debian.git] / trailer.c
blob06dc0b7f683edc0217c458831c02c5c00ecf6649
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 const struct config_context *ctx UNUSED,
486 void *cb UNUSED)
488 const char *trailer_item, *variable_name;
490 if (!skip_prefix(conf_key, "trailer.", &trailer_item))
491 return 0;
493 variable_name = strrchr(trailer_item, '.');
494 if (!variable_name) {
495 if (!strcmp(trailer_item, "where")) {
496 if (trailer_set_where(&default_conf_info.where,
497 value) < 0)
498 warning(_("unknown value '%s' for key '%s'"),
499 value, conf_key);
500 } else if (!strcmp(trailer_item, "ifexists")) {
501 if (trailer_set_if_exists(&default_conf_info.if_exists,
502 value) < 0)
503 warning(_("unknown value '%s' for key '%s'"),
504 value, conf_key);
505 } else if (!strcmp(trailer_item, "ifmissing")) {
506 if (trailer_set_if_missing(&default_conf_info.if_missing,
507 value) < 0)
508 warning(_("unknown value '%s' for key '%s'"),
509 value, conf_key);
510 } else if (!strcmp(trailer_item, "separators")) {
511 separators = xstrdup(value);
514 return 0;
517 static int git_trailer_config(const char *conf_key, const char *value,
518 const struct config_context *ctx UNUSED,
519 void *cb UNUSED)
521 const char *trailer_item, *variable_name;
522 struct arg_item *item;
523 struct conf_info *conf;
524 char *name = NULL;
525 enum trailer_info_type type;
526 int i;
528 if (!skip_prefix(conf_key, "trailer.", &trailer_item))
529 return 0;
531 variable_name = strrchr(trailer_item, '.');
532 if (!variable_name)
533 return 0;
535 variable_name++;
536 for (i = 0; i < ARRAY_SIZE(trailer_config_items); i++) {
537 if (strcmp(trailer_config_items[i].name, variable_name))
538 continue;
539 name = xstrndup(trailer_item, variable_name - trailer_item - 1);
540 type = trailer_config_items[i].type;
541 break;
544 if (!name)
545 return 0;
547 item = get_conf_item(name);
548 conf = &item->conf;
549 free(name);
551 switch (type) {
552 case TRAILER_KEY:
553 if (conf->key)
554 warning(_("more than one %s"), conf_key);
555 conf->key = xstrdup(value);
556 break;
557 case TRAILER_COMMAND:
558 if (conf->command)
559 warning(_("more than one %s"), conf_key);
560 conf->command = xstrdup(value);
561 break;
562 case TRAILER_CMD:
563 if (conf->cmd)
564 warning(_("more than one %s"), conf_key);
565 conf->cmd = xstrdup(value);
566 break;
567 case TRAILER_WHERE:
568 if (trailer_set_where(&conf->where, value))
569 warning(_("unknown value '%s' for key '%s'"), value, conf_key);
570 break;
571 case TRAILER_IF_EXISTS:
572 if (trailer_set_if_exists(&conf->if_exists, value))
573 warning(_("unknown value '%s' for key '%s'"), value, conf_key);
574 break;
575 case TRAILER_IF_MISSING:
576 if (trailer_set_if_missing(&conf->if_missing, value))
577 warning(_("unknown value '%s' for key '%s'"), value, conf_key);
578 break;
579 default:
580 BUG("trailer.c: unhandled type %d", type);
582 return 0;
585 static void ensure_configured(void)
587 if (configured)
588 return;
590 /* Default config must be setup first */
591 default_conf_info.where = WHERE_END;
592 default_conf_info.if_exists = EXISTS_ADD_IF_DIFFERENT_NEIGHBOR;
593 default_conf_info.if_missing = MISSING_ADD;
594 git_config(git_trailer_default_config, NULL);
595 git_config(git_trailer_config, NULL);
596 configured = 1;
599 static const char *token_from_item(struct arg_item *item, char *tok)
601 if (item->conf.key)
602 return item->conf.key;
603 if (tok)
604 return tok;
605 return item->conf.name;
608 static int token_matches_item(const char *tok, struct arg_item *item, size_t tok_len)
610 if (!strncasecmp(tok, item->conf.name, tok_len))
611 return 1;
612 return item->conf.key ? !strncasecmp(tok, item->conf.key, tok_len) : 0;
616 * If the given line is of the form
617 * "<token><optional whitespace><separator>..." or "<separator>...", return the
618 * location of the separator. Otherwise, return -1. The optional whitespace
619 * is allowed there primarily to allow things like "Bug #43" where <token> is
620 * "Bug" and <separator> is "#".
622 * The separator-starts-line case (in which this function returns 0) is
623 * distinguished from the non-well-formed-line case (in which this function
624 * returns -1) because some callers of this function need such a distinction.
626 static ssize_t find_separator(const char *line, const char *separators)
628 int whitespace_found = 0;
629 const char *c;
630 for (c = line; *c; c++) {
631 if (strchr(separators, *c))
632 return c - line;
633 if (!whitespace_found && (isalnum(*c) || *c == '-'))
634 continue;
635 if (c != line && (*c == ' ' || *c == '\t')) {
636 whitespace_found = 1;
637 continue;
639 break;
641 return -1;
645 * Obtain the token, value, and conf from the given trailer.
647 * separator_pos must not be 0, since the token cannot be an empty string.
649 * If separator_pos is -1, interpret the whole trailer as a token.
651 static void parse_trailer(struct strbuf *tok, struct strbuf *val,
652 const struct conf_info **conf, const char *trailer,
653 ssize_t separator_pos)
655 struct arg_item *item;
656 size_t tok_len;
657 struct list_head *pos;
659 if (separator_pos != -1) {
660 strbuf_add(tok, trailer, separator_pos);
661 strbuf_trim(tok);
662 strbuf_addstr(val, trailer + separator_pos + 1);
663 strbuf_trim(val);
664 } else {
665 strbuf_addstr(tok, trailer);
666 strbuf_trim(tok);
669 /* Lookup if the token matches something in the config */
670 tok_len = token_len_without_separator(tok->buf, tok->len);
671 if (conf)
672 *conf = &default_conf_info;
673 list_for_each(pos, &conf_head) {
674 item = list_entry(pos, struct arg_item, list);
675 if (token_matches_item(tok->buf, item, tok_len)) {
676 char *tok_buf = strbuf_detach(tok, NULL);
677 if (conf)
678 *conf = &item->conf;
679 strbuf_addstr(tok, token_from_item(item, tok_buf));
680 free(tok_buf);
681 break;
686 static struct trailer_item *add_trailer_item(struct list_head *head, char *tok,
687 char *val)
689 struct trailer_item *new_item = xcalloc(1, sizeof(*new_item));
690 new_item->token = tok;
691 new_item->value = val;
692 list_add_tail(&new_item->list, head);
693 return new_item;
696 static void add_arg_item(struct list_head *arg_head, char *tok, char *val,
697 const struct conf_info *conf,
698 const struct new_trailer_item *new_trailer_item)
700 struct arg_item *new_item = xcalloc(1, sizeof(*new_item));
701 new_item->token = tok;
702 new_item->value = val;
703 duplicate_conf(&new_item->conf, conf);
704 if (new_trailer_item) {
705 if (new_trailer_item->where != WHERE_DEFAULT)
706 new_item->conf.where = new_trailer_item->where;
707 if (new_trailer_item->if_exists != EXISTS_DEFAULT)
708 new_item->conf.if_exists = new_trailer_item->if_exists;
709 if (new_trailer_item->if_missing != MISSING_DEFAULT)
710 new_item->conf.if_missing = new_trailer_item->if_missing;
712 list_add_tail(&new_item->list, arg_head);
715 static void process_command_line_args(struct list_head *arg_head,
716 struct list_head *new_trailer_head)
718 struct arg_item *item;
719 struct strbuf tok = STRBUF_INIT;
720 struct strbuf val = STRBUF_INIT;
721 const struct conf_info *conf;
722 struct list_head *pos;
725 * In command-line arguments, '=' is accepted (in addition to the
726 * separators that are defined).
728 char *cl_separators = xstrfmt("=%s", separators);
730 /* Add an arg item for each configured trailer with a command */
731 list_for_each(pos, &conf_head) {
732 item = list_entry(pos, struct arg_item, list);
733 if (item->conf.command)
734 add_arg_item(arg_head,
735 xstrdup(token_from_item(item, NULL)),
736 xstrdup(""),
737 &item->conf, NULL);
740 /* Add an arg item for each trailer on the command line */
741 list_for_each(pos, new_trailer_head) {
742 struct new_trailer_item *tr =
743 list_entry(pos, struct new_trailer_item, list);
744 ssize_t separator_pos = find_separator(tr->text, cl_separators);
746 if (separator_pos == 0) {
747 struct strbuf sb = STRBUF_INIT;
748 strbuf_addstr(&sb, tr->text);
749 strbuf_trim(&sb);
750 error(_("empty trailer token in trailer '%.*s'"),
751 (int) sb.len, sb.buf);
752 strbuf_release(&sb);
753 } else {
754 parse_trailer(&tok, &val, &conf, tr->text,
755 separator_pos);
756 add_arg_item(arg_head,
757 strbuf_detach(&tok, NULL),
758 strbuf_detach(&val, NULL),
759 conf, tr);
763 free(cl_separators);
766 static void read_input_file(struct strbuf *sb, const char *file)
768 if (file) {
769 if (strbuf_read_file(sb, file, 0) < 0)
770 die_errno(_("could not read input file '%s'"), file);
771 } else {
772 if (strbuf_read(sb, fileno(stdin), 0) < 0)
773 die_errno(_("could not read from stdin"));
777 static const char *next_line(const char *str)
779 const char *nl = strchrnul(str, '\n');
780 return nl + !!*nl;
784 * Return the position of the start of the last line. If len is 0, return -1.
786 static ssize_t last_line(const char *buf, size_t len)
788 ssize_t i;
789 if (len == 0)
790 return -1;
791 if (len == 1)
792 return 0;
794 * Skip the last character (in addition to the null terminator),
795 * because if the last character is a newline, it is considered as part
796 * of the last line anyway.
798 i = len - 2;
800 for (; i >= 0; i--) {
801 if (buf[i] == '\n')
802 return i + 1;
804 return 0;
808 * Return the position of the start of the patch or the length of str if there
809 * is no patch in the message.
811 static size_t find_patch_start(const char *str)
813 const char *s;
815 for (s = str; *s; s = next_line(s)) {
816 const char *v;
818 if (skip_prefix(s, "---", &v) && isspace(*v))
819 return s - str;
822 return s - str;
826 * Return the position of the first trailer line or len if there are no
827 * trailers.
829 static size_t find_trailer_start(const char *buf, size_t len)
831 const char *s;
832 ssize_t end_of_title, l;
833 int only_spaces = 1;
834 int recognized_prefix = 0, trailer_lines = 0, non_trailer_lines = 0;
836 * Number of possible continuation lines encountered. This will be
837 * reset to 0 if we encounter a trailer (since those lines are to be
838 * considered continuations of that trailer), and added to
839 * non_trailer_lines if we encounter a non-trailer (since those lines
840 * are to be considered non-trailers).
842 int possible_continuation_lines = 0;
844 /* The first paragraph is the title and cannot be trailers */
845 for (s = buf; s < buf + len; s = next_line(s)) {
846 if (s[0] == comment_line_char)
847 continue;
848 if (is_blank_line(s))
849 break;
851 end_of_title = s - buf;
854 * Get the start of the trailers by looking starting from the end for a
855 * blank line before a set of non-blank lines that (i) are all
856 * trailers, or (ii) contains at least one Git-generated trailer and
857 * consists of at least 25% trailers.
859 for (l = last_line(buf, len);
860 l >= end_of_title;
861 l = last_line(buf, l)) {
862 const char *bol = buf + l;
863 const char **p;
864 ssize_t separator_pos;
866 if (bol[0] == comment_line_char) {
867 non_trailer_lines += possible_continuation_lines;
868 possible_continuation_lines = 0;
869 continue;
871 if (is_blank_line(bol)) {
872 if (only_spaces)
873 continue;
874 non_trailer_lines += possible_continuation_lines;
875 if (recognized_prefix &&
876 trailer_lines * 3 >= non_trailer_lines)
877 return next_line(bol) - buf;
878 else if (trailer_lines && !non_trailer_lines)
879 return next_line(bol) - buf;
880 return len;
882 only_spaces = 0;
884 for (p = git_generated_prefixes; *p; p++) {
885 if (starts_with(bol, *p)) {
886 trailer_lines++;
887 possible_continuation_lines = 0;
888 recognized_prefix = 1;
889 goto continue_outer_loop;
893 separator_pos = find_separator(bol, separators);
894 if (separator_pos >= 1 && !isspace(bol[0])) {
895 struct list_head *pos;
897 trailer_lines++;
898 possible_continuation_lines = 0;
899 if (recognized_prefix)
900 continue;
901 list_for_each(pos, &conf_head) {
902 struct arg_item *item;
903 item = list_entry(pos, struct arg_item, list);
904 if (token_matches_item(bol, item,
905 separator_pos)) {
906 recognized_prefix = 1;
907 break;
910 } else if (isspace(bol[0]))
911 possible_continuation_lines++;
912 else {
913 non_trailer_lines++;
914 non_trailer_lines += possible_continuation_lines;
915 possible_continuation_lines = 0;
917 continue_outer_loop:
921 return len;
924 /* Return the position of the end of the trailers. */
925 static size_t find_trailer_end(const char *buf, size_t len)
927 return len - ignore_non_trailer(buf, len);
930 static int ends_with_blank_line(const char *buf, size_t len)
932 ssize_t ll = last_line(buf, len);
933 if (ll < 0)
934 return 0;
935 return is_blank_line(buf + ll);
938 static void unfold_value(struct strbuf *val)
940 struct strbuf out = STRBUF_INIT;
941 size_t i;
943 strbuf_grow(&out, val->len);
944 i = 0;
945 while (i < val->len) {
946 char c = val->buf[i++];
947 if (c == '\n') {
948 /* Collapse continuation down to a single space. */
949 while (i < val->len && isspace(val->buf[i]))
950 i++;
951 strbuf_addch(&out, ' ');
952 } else {
953 strbuf_addch(&out, c);
957 /* Empty lines may have left us with whitespace cruft at the edges */
958 strbuf_trim(&out);
960 /* output goes back to val as if we modified it in-place */
961 strbuf_swap(&out, val);
962 strbuf_release(&out);
965 static size_t process_input_file(FILE *outfile,
966 const char *str,
967 struct list_head *head,
968 const struct process_trailer_options *opts)
970 struct trailer_info info;
971 struct strbuf tok = STRBUF_INIT;
972 struct strbuf val = STRBUF_INIT;
973 size_t i;
975 trailer_info_get(&info, str, opts);
977 /* Print lines before the trailers as is */
978 if (!opts->only_trailers)
979 fwrite(str, 1, info.trailer_start - str, outfile);
981 if (!opts->only_trailers && !info.blank_line_before_trailer)
982 fprintf(outfile, "\n");
984 for (i = 0; i < info.trailer_nr; i++) {
985 int separator_pos;
986 char *trailer = info.trailers[i];
987 if (trailer[0] == comment_line_char)
988 continue;
989 separator_pos = find_separator(trailer, separators);
990 if (separator_pos >= 1) {
991 parse_trailer(&tok, &val, NULL, trailer,
992 separator_pos);
993 if (opts->unfold)
994 unfold_value(&val);
995 add_trailer_item(head,
996 strbuf_detach(&tok, NULL),
997 strbuf_detach(&val, NULL));
998 } else if (!opts->only_trailers) {
999 strbuf_addstr(&val, trailer);
1000 strbuf_strip_suffix(&val, "\n");
1001 add_trailer_item(head,
1002 NULL,
1003 strbuf_detach(&val, NULL));
1007 trailer_info_release(&info);
1009 return info.trailer_end - str;
1012 static void free_all(struct list_head *head)
1014 struct list_head *pos, *p;
1015 list_for_each_safe(pos, p, head) {
1016 list_del(pos);
1017 free_trailer_item(list_entry(pos, struct trailer_item, list));
1021 static struct tempfile *trailers_tempfile;
1023 static FILE *create_in_place_tempfile(const char *file)
1025 struct stat st;
1026 struct strbuf filename_template = STRBUF_INIT;
1027 const char *tail;
1028 FILE *outfile;
1030 if (stat(file, &st))
1031 die_errno(_("could not stat %s"), file);
1032 if (!S_ISREG(st.st_mode))
1033 die(_("file %s is not a regular file"), file);
1034 if (!(st.st_mode & S_IWUSR))
1035 die(_("file %s is not writable by user"), file);
1037 /* Create temporary file in the same directory as the original */
1038 tail = strrchr(file, '/');
1039 if (tail)
1040 strbuf_add(&filename_template, file, tail - file + 1);
1041 strbuf_addstr(&filename_template, "git-interpret-trailers-XXXXXX");
1043 trailers_tempfile = xmks_tempfile_m(filename_template.buf, st.st_mode);
1044 strbuf_release(&filename_template);
1045 outfile = fdopen_tempfile(trailers_tempfile, "w");
1046 if (!outfile)
1047 die_errno(_("could not open temporary file"));
1049 return outfile;
1052 void process_trailers(const char *file,
1053 const struct process_trailer_options *opts,
1054 struct list_head *new_trailer_head)
1056 LIST_HEAD(head);
1057 struct strbuf sb = STRBUF_INIT;
1058 size_t trailer_end;
1059 FILE *outfile = stdout;
1061 ensure_configured();
1063 read_input_file(&sb, file);
1065 if (opts->in_place)
1066 outfile = create_in_place_tempfile(file);
1068 /* Print the lines before the trailers */
1069 trailer_end = process_input_file(outfile, sb.buf, &head, opts);
1071 if (!opts->only_input) {
1072 LIST_HEAD(arg_head);
1073 process_command_line_args(&arg_head, new_trailer_head);
1074 process_trailers_lists(&head, &arg_head);
1077 print_all(outfile, &head, opts);
1079 free_all(&head);
1081 /* Print the lines after the trailers as is */
1082 if (!opts->only_trailers)
1083 fwrite(sb.buf + trailer_end, 1, sb.len - trailer_end, outfile);
1085 if (opts->in_place)
1086 if (rename_tempfile(&trailers_tempfile, file))
1087 die_errno(_("could not rename temporary file to %s"), file);
1089 strbuf_release(&sb);
1092 void trailer_info_get(struct trailer_info *info, const char *str,
1093 const struct process_trailer_options *opts)
1095 int patch_start, trailer_end, trailer_start;
1096 struct strbuf **trailer_lines, **ptr;
1097 char **trailer_strings = NULL;
1098 size_t nr = 0, alloc = 0;
1099 char **last = NULL;
1101 ensure_configured();
1103 if (opts->no_divider)
1104 patch_start = strlen(str);
1105 else
1106 patch_start = find_patch_start(str);
1108 trailer_end = find_trailer_end(str, patch_start);
1109 trailer_start = find_trailer_start(str, trailer_end);
1111 trailer_lines = strbuf_split_buf(str + trailer_start,
1112 trailer_end - trailer_start,
1113 '\n',
1115 for (ptr = trailer_lines; *ptr; ptr++) {
1116 if (last && isspace((*ptr)->buf[0])) {
1117 struct strbuf sb = STRBUF_INIT;
1118 strbuf_attach(&sb, *last, strlen(*last), strlen(*last));
1119 strbuf_addbuf(&sb, *ptr);
1120 *last = strbuf_detach(&sb, NULL);
1121 continue;
1123 ALLOC_GROW(trailer_strings, nr + 1, alloc);
1124 trailer_strings[nr] = strbuf_detach(*ptr, NULL);
1125 last = find_separator(trailer_strings[nr], separators) >= 1
1126 ? &trailer_strings[nr]
1127 : NULL;
1128 nr++;
1130 strbuf_list_free(trailer_lines);
1132 info->blank_line_before_trailer = ends_with_blank_line(str,
1133 trailer_start);
1134 info->trailer_start = str + trailer_start;
1135 info->trailer_end = str + trailer_end;
1136 info->trailers = trailer_strings;
1137 info->trailer_nr = nr;
1140 void trailer_info_release(struct trailer_info *info)
1142 size_t i;
1143 for (i = 0; i < info->trailer_nr; i++)
1144 free(info->trailers[i]);
1145 free(info->trailers);
1148 static void format_trailer_info(struct strbuf *out,
1149 const struct trailer_info *info,
1150 const struct process_trailer_options *opts)
1152 size_t origlen = out->len;
1153 size_t i;
1155 /* If we want the whole block untouched, we can take the fast path. */
1156 if (!opts->only_trailers && !opts->unfold && !opts->filter &&
1157 !opts->separator && !opts->key_only && !opts->value_only &&
1158 !opts->key_value_separator) {
1159 strbuf_add(out, info->trailer_start,
1160 info->trailer_end - info->trailer_start);
1161 return;
1164 for (i = 0; i < info->trailer_nr; i++) {
1165 char *trailer = info->trailers[i];
1166 ssize_t separator_pos = find_separator(trailer, separators);
1168 if (separator_pos >= 1) {
1169 struct strbuf tok = STRBUF_INIT;
1170 struct strbuf val = STRBUF_INIT;
1172 parse_trailer(&tok, &val, NULL, trailer, separator_pos);
1173 if (!opts->filter || opts->filter(&tok, opts->filter_data)) {
1174 if (opts->unfold)
1175 unfold_value(&val);
1177 if (opts->separator && out->len != origlen)
1178 strbuf_addbuf(out, opts->separator);
1179 if (!opts->value_only)
1180 strbuf_addbuf(out, &tok);
1181 if (!opts->key_only && !opts->value_only) {
1182 if (opts->key_value_separator)
1183 strbuf_addbuf(out, opts->key_value_separator);
1184 else
1185 strbuf_addstr(out, ": ");
1187 if (!opts->key_only)
1188 strbuf_addbuf(out, &val);
1189 if (!opts->separator)
1190 strbuf_addch(out, '\n');
1192 strbuf_release(&tok);
1193 strbuf_release(&val);
1195 } else if (!opts->only_trailers) {
1196 if (opts->separator && out->len != origlen) {
1197 strbuf_addbuf(out, opts->separator);
1199 strbuf_addstr(out, trailer);
1200 if (opts->separator) {
1201 strbuf_rtrim(out);
1208 void format_trailers_from_commit(struct strbuf *out, const char *msg,
1209 const struct process_trailer_options *opts)
1211 struct trailer_info info;
1213 trailer_info_get(&info, msg, opts);
1214 format_trailer_info(out, &info, opts);
1215 trailer_info_release(&info);
1218 void trailer_iterator_init(struct trailer_iterator *iter, const char *msg)
1220 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
1221 strbuf_init(&iter->key, 0);
1222 strbuf_init(&iter->val, 0);
1223 opts.no_divider = 1;
1224 trailer_info_get(&iter->info, msg, &opts);
1225 iter->cur = 0;
1228 int trailer_iterator_advance(struct trailer_iterator *iter)
1230 while (iter->cur < iter->info.trailer_nr) {
1231 char *trailer = iter->info.trailers[iter->cur++];
1232 int separator_pos = find_separator(trailer, separators);
1234 if (separator_pos < 1)
1235 continue; /* not a real trailer */
1237 strbuf_reset(&iter->key);
1238 strbuf_reset(&iter->val);
1239 parse_trailer(&iter->key, &iter->val, NULL,
1240 trailer, separator_pos);
1241 unfold_value(&iter->val);
1242 return 1;
1244 return 0;
1247 void trailer_iterator_release(struct trailer_iterator *iter)
1249 trailer_info_release(&iter->info);
1250 strbuf_release(&iter->val);
1251 strbuf_release(&iter->key);