Raw
1 #define USE_THE_REPOSITORY_VARIABLE
2
3 #include "git-compat-util.h"
4 #include "config.h"
5 #include "environment.h"
6 #include "gettext.h"
7 #include "string-list.h"
8 #include "run-command.h"
9 #include "commit.h"
10 #include "strvec.h"
11 #include "trailer.h"
12 #include "list.h"
13 #include "tempfile.h"
14
15 /*
16 * Copyright (c) 2013, 2014 Christian Couder <chriscool@tuxfamily.org>
17 */
18
19 struct trailer_block {
20 /*
21 * True if there is a blank line before the location pointed to by
22 * "start".
23 */
24 int blank_line_before_trailer;
25
26 /*
27 * The locations of the start and end positions of the trailer block
28 * found, as offsets from the beginning of the source text from which
29 * this trailer block was parsed. If no trailer block is found, these
30 * are both set to 0.
31 */
32 size_t start, end;
33
34 /*
35 * Array of trailers found.
36 */
37 char **trailers;
38 size_t trailer_nr;
39 };
40
41 struct conf_info {
42 char *name;
43 char *key;
44 char *command;
45 char *cmd;
46 enum trailer_where where;
47 enum trailer_if_exists if_exists;
48 enum trailer_if_missing if_missing;
49 };
50
51 static struct conf_info default_conf_info;
52
53 struct trailer_item {
54 struct list_head list;
55 /*
56 * If this is not a trailer line, the line is stored in value
57 * (excluding the terminating newline) and token is NULL.
58 */
59 char *token;
60 char *value;
61 };
62
63 struct arg_item {
64 struct list_head list;
65 char *token;
66 char *value;
67 struct conf_info conf;
68 };
69
70 static LIST_HEAD(conf_head);
71
72 static const char *separators = ":";
73
74 static int configured;
75
76 #define TRAILER_ARG_STRING "$ARG"
77
78 static const char *git_generated_prefixes[] = {
79 "Signed-off-by: ",
80 "(cherry picked from commit ",
81 NULL
82 };
83
84 /* Iterate over the elements of the list. */
85 #define list_for_each_dir(pos, head, is_reverse) \
86 for (pos = is_reverse ? (head)->prev : (head)->next; \
87 pos != (head); \
88 pos = is_reverse ? pos->prev : pos->next)
89
90 static int after_or_end(enum trailer_where where)
91 {
92 return (where == WHERE_AFTER) || (where == WHERE_END);
93 }
94
95 /*
96 * Return the length of the string not including any final
97 * punctuation. E.g., the input "Signed-off-by:" would return
98 * 13, stripping the trailing punctuation but retaining
99 * internal punctuation.
100 */
101 static size_t token_len_without_separator(const char *token, size_t len)
102 {
103 while (len > 0 && !isalnum(token[len - 1]))
104 len--;
105 return len;
106 }
107
108 static int same_token(struct trailer_item *a, struct arg_item *b)
109 {
110 size_t a_len, b_len, min_len;
111
112 if (!a->token)
113 return 0;
114
115 a_len = token_len_without_separator(a->token, strlen(a->token));
116 b_len = token_len_without_separator(b->token, strlen(b->token));
117 min_len = (a_len > b_len) ? b_len : a_len;
118
119 return !strncasecmp(a->token, b->token, min_len);
120 }
121
122 static int same_value(struct trailer_item *a, struct arg_item *b)
123 {
124 return !strcasecmp(a->value, b->value);
125 }
126
127 static int same_trailer(struct trailer_item *a, struct arg_item *b)
128 {
129 return same_token(a, b) && same_value(a, b);
130 }
131
132 static inline int is_blank_line(const char *str)
133 {
134 const char *s = str;
135 while (*s && *s != '\n' && isspace(*s))
136 s++;
137 return !*s || *s == '\n';
138 }
139
140 static inline void strbuf_replace(struct strbuf *sb, const char *a, const char *b)
141 {
142 const char *ptr = strstr(sb->buf, a);
143 if (ptr)
144 strbuf_splice(sb, ptr - sb->buf, strlen(a), b, strlen(b));
145 }
146
147 static void free_trailer_item(struct trailer_item *item)
148 {
149 free(item->token);
150 free(item->value);
151 free(item);
152 }
153
154 static void free_arg_item(struct arg_item *item)
155 {
156 free(item->conf.name);
157 free(item->conf.key);
158 free(item->conf.command);
159 free(item->conf.cmd);
160 free(item->token);
161 free(item->value);
162 free(item);
163 }
164
165 static char last_non_space_char(const char *s)
166 {
167 int i;
168 for (i = strlen(s) - 1; i >= 0; i--)
169 if (!isspace(s[i]))
170 return s[i];
171 return '\0';
172 }
173
174 static struct trailer_item *trailer_from_arg(struct arg_item *arg_tok)
175 {
176 struct trailer_item *new_item = xcalloc(1, sizeof(*new_item));
177 new_item->token = arg_tok->token;
178 new_item->value = arg_tok->value;
179 arg_tok->token = arg_tok->value = NULL;
180 free_arg_item(arg_tok);
181 return new_item;
182 }
183
184 static void add_arg_to_input_list(struct trailer_item *on_tok,
185 struct arg_item *arg_tok)
186 {
187 int aoe = after_or_end(arg_tok->conf.where);
188 struct trailer_item *to_add = trailer_from_arg(arg_tok);
189 if (aoe)
190 list_add(&to_add->list, &on_tok->list);
191 else
192 list_add_tail(&to_add->list, &on_tok->list);
193 }
194
195 static int check_if_different(struct trailer_item *in_tok,
196 struct arg_item *arg_tok,
197 int check_all,
198 struct list_head *head)
199 {
200 enum trailer_where where = arg_tok->conf.where;
201 struct list_head *next_head;
202 do {
203 if (same_trailer(in_tok, arg_tok))
204 return 0;
205 /*
206 * if we want to add a trailer after another one,
207 * we have to check those before this one
208 */
209 next_head = after_or_end(where) ? in_tok->list.prev
210 : in_tok->list.next;
211 if (next_head == head)
212 break;
213 in_tok = list_entry(next_head, struct trailer_item, list);
214 } while (check_all);
215 return 1;
216 }
217
218 static char *apply_command(struct conf_info *conf, const char *arg)
219 {
220 struct strbuf cmd = STRBUF_INIT;
221 struct strbuf buf = STRBUF_INIT;
222 struct child_process cp = CHILD_PROCESS_INIT;
223 char *result;
224
225 if (conf->cmd) {
226 strbuf_addstr(&cmd, conf->cmd);
227 strvec_push(&cp.args, cmd.buf);
228 if (arg)
229 strvec_push(&cp.args, arg);
230 } else if (conf->command) {
231 strbuf_addstr(&cmd, conf->command);
232 if (arg)
233 strbuf_replace(&cmd, TRAILER_ARG_STRING, arg);
234 strvec_push(&cp.args, cmd.buf);
235 }
236 strvec_pushv(&cp.env, (const char **)local_repo_env);
237 cp.no_stdin = 1;
238 cp.use_shell = 1;
239
240 if (capture_command(&cp, &buf, 1024)) {
241 error(_("running trailer command '%s' failed"), cmd.buf);
242 strbuf_release(&buf);
243 result = xstrdup("");
244 } else {
245 strbuf_trim(&buf);
246 result = strbuf_detach(&buf, NULL);
247 }
248
249 strbuf_release(&cmd);
250 return result;
251 }
252
253 static void apply_item_command(struct trailer_item *in_tok, struct arg_item *arg_tok)
254 {
255 if (arg_tok->conf.command || arg_tok->conf.cmd) {
256 char *value_to_free = NULL;
257 char *arg;
258
259 if (arg_tok->value && arg_tok->value[0]) {
260 arg = arg_tok->value;
261 } else {
262 if (in_tok && in_tok->value)
263 arg = xstrdup(in_tok->value);
264 else
265 arg = xstrdup("");
266 value_to_free = arg_tok->value;
267 }
268
269 arg_tok->value = apply_command(&arg_tok->conf, arg);
270
271 free(value_to_free);
272 free(arg);
273 }
274 }
275
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)
280 {
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);
312 }
313 }
314
315 static void apply_arg_if_missing(struct list_head *head,
316 struct arg_item *arg_tok)
317 {
318 enum trailer_where where;
319 struct trailer_item *to_add;
320
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);
337 }
338 }
339
340 static int find_same_and_apply_arg(struct list_head *head,
341 struct arg_item *arg_tok)
342 {
343 struct list_head *pos;
344 struct trailer_item *in_tok;
345 struct trailer_item *on_tok;
346
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;
351
352 if (list_empty(head))
353 return 0;
354
355 start_tok = list_entry(backwards ? head->prev : head->next,
356 struct trailer_item,
357 list);
358
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;
366 }
367 return 0;
368 }
369
370 void process_trailers_lists(struct list_head *head,
371 struct list_head *arg_head)
372 {
373 struct list_head *pos, *p;
374 struct arg_item *arg_tok;
375
376 list_for_each_safe(pos, p, arg_head) {
377 int applied = 0;
378 arg_tok = list_entry(pos, struct arg_item, list);
379
380 list_del(pos);
381
382 applied = find_same_and_apply_arg(head, arg_tok);
383
384 if (!applied)
385 apply_arg_if_missing(head, arg_tok);
386 }
387 }
388
389 int trailer_set_where(enum trailer_where *item, const char *value)
390 {
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;
404 }
405
406 int trailer_set_if_exists(enum trailer_if_exists *item, const char *value)
407 {
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;
423 }
424
425 int trailer_set_if_missing(enum trailer_if_missing *item, const char *value)
426 {
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;
436 }
437
438 static void duplicate_conf(struct conf_info *dst, const struct conf_info *src)
439 {
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);
445 }
446
447 static struct arg_item *get_conf_item(const char *name)
448 {
449 struct list_head *pos;
450 struct arg_item *item;
451
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;
457 }
458
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);
463
464 list_add_tail(&item->list, &conf_head);
465
466 return item;
467 }
468
469 enum trailer_info_type { TRAILER_KEY, TRAILER_COMMAND, TRAILER_CMD,
470 TRAILER_WHERE, TRAILER_IF_EXISTS, TRAILER_IF_MISSING };
471
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 }
482 };
483
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)
487 {
488 const char *trailer_item, *variable_name;
489
490 if (!skip_prefix(conf_key, "trailer.", &trailer_item))
491 return 0;
492
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 if (!value)
512 return config_error_nonbool(conf_key);
513 separators = xstrdup(value);
514 }
515 }
516 return 0;
517 }
518
519 static int git_trailer_config(const char *conf_key, const char *value,
520 const struct config_context *ctx UNUSED,
521 void *cb UNUSED)
522 {
523 const char *trailer_item, *variable_name;
524 struct arg_item *item;
525 struct conf_info *conf;
526 char *name = NULL;
527 enum trailer_info_type type;
528
529 if (!skip_prefix(conf_key, "trailer.", &trailer_item))
530 return 0;
531
532 variable_name = strrchr(trailer_item, '.');
533 if (!variable_name)
534 return 0;
535
536 variable_name++;
537 for (size_t i = 0; i < ARRAY_SIZE(trailer_config_items); i++) {
538 if (strcmp(trailer_config_items[i].name, variable_name))
539 continue;
540 name = xstrndup(trailer_item, variable_name - trailer_item - 1);
541 type = trailer_config_items[i].type;
542 break;
543 }
544
545 if (!name)
546 return 0;
547
548 item = get_conf_item(name);
549 conf = &item->conf;
550 free(name);
551
552 switch (type) {
553 case TRAILER_KEY:
554 if (conf->key)
555 warning(_("more than one %s"), conf_key);
556 if (!value)
557 return config_error_nonbool(conf_key);
558 conf->key = xstrdup(value);
559 break;
560 case TRAILER_COMMAND:
561 if (conf->command)
562 warning(_("more than one %s"), conf_key);
563 if (!value)
564 return config_error_nonbool(conf_key);
565 conf->command = xstrdup(value);
566 break;
567 case TRAILER_CMD:
568 if (conf->cmd)
569 warning(_("more than one %s"), conf_key);
570 if (!value)
571 return config_error_nonbool(conf_key);
572 conf->cmd = xstrdup(value);
573 break;
574 case TRAILER_WHERE:
575 if (trailer_set_where(&conf->where, value))
576 warning(_("unknown value '%s' for key '%s'"), value, conf_key);
577 break;
578 case TRAILER_IF_EXISTS:
579 if (trailer_set_if_exists(&conf->if_exists, value))
580 warning(_("unknown value '%s' for key '%s'"), value, conf_key);
581 break;
582 case TRAILER_IF_MISSING:
583 if (trailer_set_if_missing(&conf->if_missing, value))
584 warning(_("unknown value '%s' for key '%s'"), value, conf_key);
585 break;
586 default:
587 BUG("trailer.c: unhandled type %d", type);
588 }
589 return 0;
590 }
591
592 void trailer_config_init(void)
593 {
594 if (configured)
595 return;
596
597 /* Default config must be setup first */
598 default_conf_info.where = WHERE_END;
599 default_conf_info.if_exists = EXISTS_ADD_IF_DIFFERENT_NEIGHBOR;
600 default_conf_info.if_missing = MISSING_ADD;
601 repo_config(the_repository, git_trailer_default_config, NULL);
602 repo_config(the_repository, git_trailer_config, NULL);
603 configured = 1;
604 }
605
606 static const char *token_from_item(struct arg_item *item, char *tok)
607 {
608 if (item->conf.key)
609 return item->conf.key;
610 if (tok)
611 return tok;
612 return item->conf.name;
613 }
614
615 static int token_matches_item(const char *tok, struct arg_item *item, size_t tok_len)
616 {
617 if (!strncasecmp(tok, item->conf.name, tok_len))
618 return 1;
619 return item->conf.key ? !strncasecmp(tok, item->conf.key, tok_len) : 0;
620 }
621
622 /*
623 * If the given line is of the form
624 * "<token><optional whitespace><separator>..." or "<separator>...", return the
625 * location of the separator. Otherwise, return -1. The optional whitespace
626 * is allowed there primarily to allow things like "Bug #43" where <token> is
627 * "Bug" and <separator> is "#".
628 *
629 * The separator-starts-line case (in which this function returns 0) is
630 * distinguished from the non-well-formed-line case (in which this function
631 * returns -1) because some callers of this function need such a distinction.
632 */
633 static ssize_t find_separator(const char *line, const char *separators)
634 {
635 int whitespace_found = 0;
636 const char *c;
637 for (c = line; *c; c++) {
638 if (strchr(separators, *c)) {
639 /* avoid accidental URL matches (://) */
640 if (*c == ':' && c[1] == '/' && c[2] == '/' &&
641 !whitespace_found)
642 return -1;
643 return c - line;
644 }
645 if (!whitespace_found && (isalnum(*c) || *c == '-'))
646 continue;
647 if (c != line && (*c == ' ' || *c == '\t')) {
648 whitespace_found = 1;
649 continue;
650 }
651 break;
652 }
653 return -1;
654 }
655
656 /*
657 * Obtain the token, value, and conf from the given trailer.
658 *
659 * separator_pos must not be 0, since the token cannot be an empty string.
660 *
661 * If separator_pos is -1, interpret the whole trailer as a token.
662 */
663 static void parse_trailer(struct strbuf *tok, struct strbuf *val,
664 const struct conf_info **conf, const char *trailer,
665 ssize_t separator_pos)
666 {
667 struct arg_item *item;
668 size_t tok_len;
669 struct list_head *pos;
670
671 if (separator_pos != -1) {
672 strbuf_add(tok, trailer, separator_pos);
673 strbuf_trim(tok);
674 strbuf_addstr(val, trailer + separator_pos + 1);
675 strbuf_trim(val);
676 } else {
677 strbuf_addstr(tok, trailer);
678 strbuf_trim(tok);
679 }
680
681 /* Lookup if the token matches something in the config */
682 tok_len = token_len_without_separator(tok->buf, tok->len);
683 if (conf)
684 *conf = &default_conf_info;
685 list_for_each(pos, &conf_head) {
686 item = list_entry(pos, struct arg_item, list);
687 if (token_matches_item(tok->buf, item, tok_len)) {
688 char *tok_buf = strbuf_detach(tok, NULL);
689 if (conf)
690 *conf = &item->conf;
691 strbuf_addstr(tok, token_from_item(item, tok_buf));
692 free(tok_buf);
693 break;
694 }
695 }
696 }
697
698 static struct trailer_item *add_trailer_item(struct list_head *head, char *tok,
699 char *val)
700 {
701 struct trailer_item *new_item = xcalloc(1, sizeof(*new_item));
702 new_item->token = tok;
703 new_item->value = val;
704 list_add_tail(&new_item->list, head);
705 return new_item;
706 }
707
708 static void add_arg_item(struct list_head *arg_head, char *tok, char *val,
709 const struct conf_info *conf,
710 const struct new_trailer_item *new_trailer_item)
711 {
712 struct arg_item *new_item = xcalloc(1, sizeof(*new_item));
713 new_item->token = tok;
714 new_item->value = val;
715 duplicate_conf(&new_item->conf, conf);
716 if (new_trailer_item) {
717 if (new_trailer_item->where != WHERE_DEFAULT)
718 new_item->conf.where = new_trailer_item->where;
719 if (new_trailer_item->if_exists != EXISTS_DEFAULT)
720 new_item->conf.if_exists = new_trailer_item->if_exists;
721 if (new_trailer_item->if_missing != MISSING_DEFAULT)
722 new_item->conf.if_missing = new_trailer_item->if_missing;
723 }
724 list_add_tail(&new_item->list, arg_head);
725 }
726
727 void parse_trailers_from_config(struct list_head *config_head)
728 {
729 struct arg_item *item;
730 struct list_head *pos;
731
732 /* Add an arg item for each configured trailer with a command */
733 list_for_each(pos, &conf_head) {
734 item = list_entry(pos, struct arg_item, list);
735 if (item->conf.command)
736 add_arg_item(config_head,
737 xstrdup(token_from_item(item, NULL)),
738 xstrdup(""),
739 &item->conf, NULL);
740 }
741 }
742
743 void parse_trailers_from_command_line_args(struct list_head *arg_head,
744 struct list_head *new_trailer_head)
745 {
746 struct strbuf tok = STRBUF_INIT;
747 struct strbuf val = STRBUF_INIT;
748 const struct conf_info *conf;
749 struct list_head *pos;
750
751 /*
752 * In command-line arguments, '=' is accepted (in addition to the
753 * separators that are defined).
754 */
755 char *cl_separators = xstrfmt("=%s", separators);
756
757 /* Add an arg item for each trailer on the command line */
758 list_for_each(pos, new_trailer_head) {
759 struct new_trailer_item *tr =
760 list_entry(pos, struct new_trailer_item, list);
761 ssize_t separator_pos = find_separator(tr->text, cl_separators);
762
763 if (separator_pos == 0) {
764 struct strbuf sb = STRBUF_INIT;
765 strbuf_addstr(&sb, tr->text);
766 strbuf_trim(&sb);
767 error(_("empty trailer token in trailer '%.*s'"),
768 (int) sb.len, sb.buf);
769 strbuf_release(&sb);
770 } else {
771 parse_trailer(&tok, &val, &conf, tr->text,
772 separator_pos);
773 add_arg_item(arg_head,
774 strbuf_detach(&tok, NULL),
775 strbuf_detach(&val, NULL),
776 conf, tr);
777 }
778 }
779
780 free(cl_separators);
781 }
782
783 int validate_trailer_args(const struct strvec *cli_args)
784 {
785 char *cl_separators;
786 int ret = 0;
787
788 trailer_config_init();
789
790 cl_separators = xstrfmt("=%s", separators);
791
792 for (size_t i = 0; i < cli_args->nr; i++) {
793 const char *txt = cli_args->v[i];
794 ssize_t separator_pos;
795
796 if (!*txt) {
797 ret = error(_("empty --trailer argument"));
798 goto out;
799 }
800 separator_pos = find_separator(txt, cl_separators);
801 if (separator_pos == 0) {
802 ret = error(_("invalid trailer '%s': missing key before separator"),
803 txt);
804 goto out;
805 }
806 }
807 out:
808 free(cl_separators);
809 return ret;
810 }
811
812 static const char *next_line(const char *str)
813 {
814 const char *nl = strchrnul(str, '\n');
815 return nl + !!*nl;
816 }
817
818 /*
819 * Return the position of the start of the last line. If len is 0, return -1.
820 */
821 static ssize_t last_line(const char *buf, size_t len)
822 {
823 ssize_t i;
824 if (len == 0)
825 return -1;
826 if (len == 1)
827 return 0;
828 /*
829 * Skip the last character (in addition to the null terminator),
830 * because if the last character is a newline, it is considered as part
831 * of the last line anyway.
832 */
833 i = len - 2;
834
835 for (; i >= 0; i--) {
836 if (buf[i] == '\n')
837 return i + 1;
838 }
839 return 0;
840 }
841
842 /*
843 * Find the end of the log message as an offset from the start of the input
844 * (where callers of this function are interested in looking for a trailers
845 * block in the same input). We have to consider two categories of content that
846 * can come at the end of the input which we want to ignore (because they don't
847 * belong in the log message):
848 *
849 * (1) the "patch part" which begins with a "---" divider and has patch
850 * information (like the output of git-format-patch), and
851 *
852 * (2) any trailing comment lines, blank lines like in the output of "git
853 * commit -v", or stuff below the "cut" (scissor) line.
854 *
855 * As a formula, the situation looks like this:
856 *
857 * INPUT = LOG MESSAGE + IGNORED
858 *
859 * where IGNORED can be either of the two categories described above. It may be
860 * that there is nothing to ignore. Now it may be the case that the LOG MESSAGE
861 * contains a trailer block, but that's not the concern of this function.
862 */
863 static size_t find_end_of_log_message(const char *input, int no_divider)
864 {
865 size_t end;
866 const char *s;
867
868 /* Assume the naive end of the input is already what we want. */
869 end = strlen(input);
870
871 /* Optionally skip over any patch part ("---" line and below). */
872 if (!no_divider) {
873 for (s = input; *s; s = next_line(s)) {
874 const char *v;
875
876 if (skip_prefix(s, "---", &v) && isspace(*v)) {
877 end = s - input;
878 break;
879 }
880 }
881 }
882
883 /* Skip over other ignorable bits. */
884 return end - ignored_log_message_bytes(input, end);
885 }
886
887 /*
888 * Return the position of the first trailer line or len if there are no
889 * trailers.
890 */
891 static size_t find_trailer_block_start(const char *buf, size_t len)
892 {
893 const char *s;
894 ssize_t end_of_title, l;
895 int only_spaces = 1;
896 int recognized_prefix = 0, trailer_lines = 0, non_trailer_lines = 0;
897 /*
898 * Number of possible continuation lines encountered. This will be
899 * reset to 0 if we encounter a trailer (since those lines are to be
900 * considered continuations of that trailer), and added to
901 * non_trailer_lines if we encounter a non-trailer (since those lines
902 * are to be considered non-trailers).
903 */
904 int possible_continuation_lines = 0;
905
906 /* The first paragraph is the title and cannot be trailers */
907 for (s = buf; s < buf + len; s = next_line(s)) {
908 if (starts_with_mem(s, buf + len - s, comment_line_str))
909 continue;
910 if (is_blank_line(s))
911 break;
912 }
913 end_of_title = s - buf;
914
915 /*
916 * Get the start of the trailers by looking starting from the end for a
917 * blank line before a set of non-blank lines that (i) are all
918 * trailers, or (ii) contains at least one Git-generated trailer and
919 * consists of at least 25% trailers.
920 */
921 for (l = last_line(buf, len);
922 l >= end_of_title;
923 l = last_line(buf, l)) {
924 const char *bol = buf + l;
925 const char **p;
926 ssize_t separator_pos;
927
928 if (starts_with_mem(bol, buf + len - bol, comment_line_str)) {
929 non_trailer_lines += possible_continuation_lines;
930 possible_continuation_lines = 0;
931 continue;
932 }
933 if (is_blank_line(bol)) {
934 if (only_spaces)
935 continue;
936 non_trailer_lines += possible_continuation_lines;
937 if (recognized_prefix &&
938 trailer_lines * 3 >= non_trailer_lines)
939 return next_line(bol) - buf;
940 else if (trailer_lines && !non_trailer_lines)
941 return next_line(bol) - buf;
942 return len;
943 }
944 only_spaces = 0;
945
946 for (p = git_generated_prefixes; *p; p++) {
947 if (starts_with(bol, *p)) {
948 trailer_lines++;
949 possible_continuation_lines = 0;
950 recognized_prefix = 1;
951 goto continue_outer_loop;
952 }
953 }
954
955 separator_pos = find_separator(bol, separators);
956 if (separator_pos >= 1 && !isspace(bol[0])) {
957 struct list_head *pos;
958
959 trailer_lines++;
960 possible_continuation_lines = 0;
961 if (recognized_prefix)
962 continue;
963 list_for_each(pos, &conf_head) {
964 struct arg_item *item;
965 item = list_entry(pos, struct arg_item, list);
966 if (token_matches_item(bol, item,
967 separator_pos)) {
968 recognized_prefix = 1;
969 break;
970 }
971 }
972 } else if (isspace(bol[0]))
973 possible_continuation_lines++;
974 else {
975 non_trailer_lines++;
976 non_trailer_lines += possible_continuation_lines;
977 possible_continuation_lines = 0;
978 }
979 continue_outer_loop:
980 ;
981 }
982
983 return len;
984 }
985
986 static int ends_with_blank_line(const char *buf, size_t len)
987 {
988 ssize_t ll = last_line(buf, len);
989 if (ll < 0)
990 return 0;
991 return is_blank_line(buf + ll);
992 }
993
994 static void unfold_value(struct strbuf *val)
995 {
996 size_t i;
997 size_t pos = 0;
998
999 i = 0;
1000 while (i < val->len) {
1001 char c = val->buf[i++];
1002 if (c == '\n') {
1003 /* Collapse continuation down to a single space. */
1004 while (i < val->len && isspace(val->buf[i]))
1005 i++;
1006 c = ' ';
1007 }
1008 val->buf[pos++] = c;
1009 }
1010 strbuf_setlen(val, pos);
1011
1012 /* Empty lines may have left us with whitespace cruft at the edges */
1013 strbuf_trim(val);
1014 }
1015
1016 static struct trailer_block *trailer_block_new(void)
1017 {
1018 struct trailer_block *trailer_block = xcalloc(1, sizeof(*trailer_block));
1019 return trailer_block;
1020 }
1021
1022 static struct trailer_block *trailer_block_get(const struct process_trailer_options *opts,
1023 const char *str)
1024 {
1025 struct trailer_block *trailer_block = trailer_block_new();
1026 size_t end_of_log_message = 0, trailer_block_start = 0;
1027 struct strbuf **trailer_lines, **ptr;
1028 char **trailer_strings = NULL;
1029 size_t nr = 0, alloc = 0;
1030 char **last = NULL;
1031
1032 trailer_config_init();
1033
1034 end_of_log_message = find_end_of_log_message(str, opts->no_divider);
1035 trailer_block_start = find_trailer_block_start(str, end_of_log_message);
1036
1037 trailer_lines = strbuf_split_buf(str + trailer_block_start,
1038 end_of_log_message - trailer_block_start,
1039 '\n',
1040 0);
1041 for (ptr = trailer_lines; *ptr; ptr++) {
1042 if (last && isspace((*ptr)->buf[0])) {
1043 struct strbuf sb = STRBUF_INIT;
1044 strbuf_attach(&sb, *last, strlen(*last), strlen(*last) + 1);
1045 strbuf_addbuf(&sb, *ptr);
1046 *last = strbuf_detach(&sb, NULL);
1047 continue;
1048 }
1049 ALLOC_GROW(trailer_strings, nr + 1, alloc);
1050 trailer_strings[nr] = strbuf_detach(*ptr, NULL);
1051 last = find_separator(trailer_strings[nr], separators) >= 1
1052 ? &trailer_strings[nr]
1053 : NULL;
1054 nr++;
1055 }
1056 strbuf_list_free(trailer_lines);
1057
1058 trailer_block->blank_line_before_trailer = ends_with_blank_line(str,
1059 trailer_block_start);
1060 trailer_block->start = trailer_block_start;
1061 trailer_block->end = end_of_log_message;
1062 trailer_block->trailers = trailer_strings;
1063 trailer_block->trailer_nr = nr;
1064
1065 return trailer_block;
1066 }
1067
1068 /*
1069 * Parse trailers in "str", populating the trailer_block and "trailer_objects"
1070 * linked list structure.
1071 */
1072 struct trailer_block *parse_trailers(const struct process_trailer_options *opts,
1073 const char *str,
1074 struct list_head *trailer_objects)
1075 {
1076 struct trailer_block *trailer_block;
1077 struct strbuf tok = STRBUF_INIT;
1078 struct strbuf val = STRBUF_INIT;
1079 size_t i;
1080
1081 trailer_block = trailer_block_get(opts, str);
1082
1083 for (i = 0; i < trailer_block->trailer_nr; i++) {
1084 int separator_pos;
1085 char *trailer = trailer_block->trailers[i];
1086 if (starts_with(trailer, comment_line_str))
1087 continue;
1088 separator_pos = find_separator(trailer, separators);
1089 if (separator_pos >= 1) {
1090 parse_trailer(&tok, &val, NULL, trailer,
1091 separator_pos);
1092 if (opts->unfold)
1093 unfold_value(&val);
1094 add_trailer_item(trailer_objects,
1095 strbuf_detach(&tok, NULL),
1096 strbuf_detach(&val, NULL));
1097 } else if (!opts->only_trailers) {
1098 strbuf_addstr(&val, trailer);
1099 strbuf_strip_suffix(&val, "\n");
1100 add_trailer_item(trailer_objects,
1101 NULL,
1102 strbuf_detach(&val, NULL));
1103 }
1104 }
1105
1106 return trailer_block;
1107 }
1108
1109 void free_trailers(struct list_head *trailers)
1110 {
1111 struct list_head *pos, *p;
1112 list_for_each_safe(pos, p, trailers) {
1113 list_del(pos);
1114 free_trailer_item(list_entry(pos, struct trailer_item, list));
1115 }
1116 }
1117
1118 size_t trailer_block_start(struct trailer_block *trailer_block)
1119 {
1120 return trailer_block->start;
1121 }
1122
1123 size_t trailer_block_end(struct trailer_block *trailer_block)
1124 {
1125 return trailer_block->end;
1126 }
1127
1128 int blank_line_before_trailer_block(struct trailer_block *trailer_block)
1129 {
1130 return trailer_block->blank_line_before_trailer;
1131 }
1132
1133 void trailer_block_release(struct trailer_block *trailer_block)
1134 {
1135 size_t i;
1136 for (i = 0; i < trailer_block->trailer_nr; i++)
1137 free(trailer_block->trailers[i]);
1138 free(trailer_block->trailers);
1139 free(trailer_block);
1140 }
1141
1142 void format_trailers(const struct process_trailer_options *opts,
1143 struct list_head *trailers,
1144 struct strbuf *out)
1145 {
1146 struct strbuf tok = STRBUF_INIT;
1147 struct strbuf val = STRBUF_INIT;
1148 size_t origlen = out->len;
1149 struct list_head *pos;
1150 struct trailer_item *item;
1151
1152 list_for_each(pos, trailers) {
1153 item = list_entry(pos, struct trailer_item, list);
1154 if (item->token) {
1155 strbuf_reset(&tok);
1156 strbuf_addstr(&tok, item->token);
1157 strbuf_reset(&val);
1158 strbuf_addstr(&val, item->value);
1159
1160 /*
1161 * Skip key/value pairs where the value was empty. This
1162 * can happen from trailers specified without a
1163 * separator, like `--trailer "Reviewed-by"` (no
1164 * corresponding value).
1165 */
1166 if (opts->trim_empty && !strlen(item->value))
1167 continue;
1168
1169 if (!opts->filter || opts->filter(&tok, opts->filter_data)) {
1170 if (opts->separator && out->len != origlen)
1171 strbuf_addbuf(out, opts->separator);
1172 if (!opts->value_only)
1173 strbuf_addbuf(out, &tok);
1174 if (!opts->key_only && !opts->value_only) {
1175 if (opts->key_value_separator)
1176 strbuf_addbuf(out, opts->key_value_separator);
1177 else {
1178 char c = last_non_space_char(tok.buf);
1179 if (c && !strchr(separators, c))
1180 strbuf_addf(out, "%c ", separators[0]);
1181 }
1182 }
1183 if (!opts->key_only)
1184 strbuf_addbuf(out, &val);
1185 if (!opts->separator)
1186 strbuf_addch(out, '\n');
1187 }
1188 } else if (!opts->only_trailers) {
1189 if (opts->separator && out->len != origlen) {
1190 strbuf_addbuf(out, opts->separator);
1191 }
1192 strbuf_addstr(out, item->value);
1193 if (opts->separator)
1194 strbuf_rtrim(out);
1195 else
1196 strbuf_addch(out, '\n');
1197 }
1198 }
1199
1200 strbuf_release(&tok);
1201 strbuf_release(&val);
1202 }
1203
1204 void format_trailers_from_commit(const struct process_trailer_options *opts,
1205 const char *msg,
1206 struct strbuf *out)
1207 {
1208 LIST_HEAD(trailer_objects);
1209 struct trailer_block *trailer_block = parse_trailers(opts, msg, &trailer_objects);
1210
1211 /* If we want the whole block untouched, we can take the fast path. */
1212 if (!opts->only_trailers && !opts->unfold && !opts->filter &&
1213 !opts->separator && !opts->key_only && !opts->value_only &&
1214 !opts->key_value_separator) {
1215 strbuf_add(out, msg + trailer_block->start,
1216 trailer_block->end - trailer_block->start);
1217 } else
1218 format_trailers(opts, &trailer_objects, out);
1219
1220 free_trailers(&trailer_objects);
1221 trailer_block_release(trailer_block);
1222 }
1223
1224 void trailer_iterator_init(struct trailer_iterator *iter, const char *msg)
1225 {
1226 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
1227 strbuf_init(&iter->key, 0);
1228 strbuf_init(&iter->val, 0);
1229 opts.no_divider = 1;
1230 iter->internal.trailer_block = trailer_block_get(&opts, msg);
1231 iter->internal.cur = 0;
1232 }
1233
1234 int trailer_iterator_advance(struct trailer_iterator *iter)
1235 {
1236 if (iter->internal.cur < iter->internal.trailer_block->trailer_nr) {
1237 char *line = iter->internal.trailer_block->trailers[iter->internal.cur++];
1238 int separator_pos = find_separator(line, separators);
1239
1240 iter->raw = line;
1241 strbuf_reset(&iter->key);
1242 strbuf_reset(&iter->val);
1243 parse_trailer(&iter->key, &iter->val, NULL,
1244 line, separator_pos);
1245 /* Always unfold values during iteration. */
1246 unfold_value(&iter->val);
1247 return 1;
1248 }
1249 return 0;
1250 }
1251
1252 void trailer_iterator_release(struct trailer_iterator *iter)
1253 {
1254 trailer_block_release(iter->internal.trailer_block);
1255 strbuf_release(&iter->val);
1256 strbuf_release(&iter->key);
1257 }
1258
1259 struct tempfile *trailer_create_in_place_tempfile(const char *file)
1260 {
1261 struct tempfile *tempfile = NULL;
1262 struct stat st;
1263 struct strbuf filename_template = STRBUF_INIT;
1264 const char *tail;
1265
1266 if (stat(file, &st)) {
1267 error_errno(_("could not stat %s"), file);
1268 return NULL;
1269 }
1270 if (!S_ISREG(st.st_mode)) {
1271 error(_("file %s is not a regular file"), file);
1272 return NULL;
1273 }
1274 if (!(st.st_mode & S_IWUSR)) {
1275 error(_("file %s is not writable by user"), file);
1276 return NULL;
1277 }
1278 /* Create temporary file in the same directory as the original */
1279 tail = find_last_dir_sep(file);
1280 if (tail)
1281 strbuf_add(&filename_template, file, tail - file + 1);
1282 strbuf_addstr(&filename_template, "git-interpret-trailers-XXXXXX");
1283
1284 tempfile = mks_tempfile_m(filename_template.buf, st.st_mode);
1285
1286 strbuf_release(&filename_template);
1287
1288 return tempfile;
1289 }
1290
1291 int amend_strbuf_with_trailers(struct strbuf *buf,
1292 const struct strvec *trailer_args)
1293 {
1294 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
1295 LIST_HEAD(new_trailer_head);
1296 struct strbuf out = STRBUF_INIT;
1297 size_t i;
1298 int ret = 0;
1299
1300 opts.no_divider = 1;
1301
1302 for (i = 0; i < trailer_args->nr; i++) {
1303 const char *text = trailer_args->v[i];
1304 struct new_trailer_item *item;
1305
1306 if (!*text) {
1307 ret = error(_("empty --trailer argument"));
1308 goto out;
1309 }
1310 item = xcalloc(1, sizeof(*item));
1311 item->text = xstrdup(text);
1312 list_add_tail(&item->list, &new_trailer_head);
1313 }
1314
1315 process_trailers(&opts, &new_trailer_head, buf, &out);
1316
1317 strbuf_swap(buf, &out);
1318 out:
1319 strbuf_release(&out);
1320 free_trailers(&new_trailer_head);
1321
1322 return ret;
1323 }
1324
1325 static int write_file_in_place(const char *path, const struct strbuf *buf)
1326 {
1327 struct tempfile *tempfile = trailer_create_in_place_tempfile(path);
1328 if (!tempfile)
1329 return -1;
1330
1331 if (write_in_full(tempfile->fd, buf->buf, buf->len) < 0)
1332 return error_errno(_("could not write to temporary file"));
1333
1334 if (rename_tempfile(&tempfile, path))
1335 return error_errno(_("could not rename temporary file to %s"), path);
1336
1337 return 0;
1338 }
1339
1340 int amend_file_with_trailers(const char *path,
1341 const struct strvec *trailer_args)
1342 {
1343 struct strbuf buf = STRBUF_INIT;
1344 int ret = 0;
1345
1346 if (!trailer_args)
1347 BUG("amend_file_with_trailers called with NULL trailer_args");
1348 if (!trailer_args->nr)
1349 return 0;
1350
1351 if (validate_trailer_args(trailer_args)) {
1352 ret = -1;
1353 goto out;
1354 }
1355 if (strbuf_read_file(&buf, path, 0) < 0)
1356 ret = error_errno(_("could not read '%s'"), path);
1357 else
1358 amend_strbuf_with_trailers(&buf, trailer_args);
1359
1360 if (!ret)
1361 ret = write_file_in_place(path, &buf);
1362 out:
1363 strbuf_release(&buf);
1364 return ret;
1365 }
1366
1367 void process_trailers(const struct process_trailer_options *opts,
1368 struct list_head *new_trailer_head,
1369 struct strbuf *input, struct strbuf *out)
1370 {
1371 LIST_HEAD(head);
1372 struct trailer_block *trailer_block;
1373
1374 trailer_block = parse_trailers(opts, input->buf, &head);
1375
1376 /* Print the lines before the trailer block */
1377 if (!opts->only_trailers)
1378 strbuf_add(out, input->buf, trailer_block_start(trailer_block));
1379
1380 if (!opts->only_trailers && !blank_line_before_trailer_block(trailer_block))
1381 strbuf_addch(out, '\n');
1382
1383 if (!opts->only_input) {
1384 LIST_HEAD(config_head);
1385 LIST_HEAD(arg_head);
1386 parse_trailers_from_config(&config_head);
1387 parse_trailers_from_command_line_args(&arg_head, new_trailer_head);
1388 list_splice(&config_head, &arg_head);
1389 process_trailers_lists(&head, &arg_head);
1390 }
1391
1392 /* Print trailer block. */
1393 format_trailers(opts, &head, out);
1394 free_trailers(&head);
1395
1396 /* Print the lines after the trailer block as is. */
1397 if (!opts->only_trailers)
1398 strbuf_add(out, input->buf + trailer_block_end(trailer_block),
1399 input->len - trailer_block_end(trailer_block));
1400 trailer_block_release(trailer_block);
1401 }