interplane.Get Omega
Read in your language

git

[Ported from github.com/git/git] Sync with Git 2.56.1

Brought by drakestapleton

branch master Branches Tags History

git / trailer.c

1400 lines · 36498 bytes Raw Blame History
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
19struct 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
41struct 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
51static struct conf_info default_conf_info;
52
53struct 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
63struct arg_item {
64 struct list_head list;
65 char *token;
66 char *value;
67 struct conf_info conf;
68};
69
70static LIST_HEAD(conf_head);
71
72static const char *separators = ":";
73
74static int configured;
75
76#define TRAILER_ARG_STRING "$ARG"
77
78static 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
90static 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 */
101static 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
108static 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
122static int same_value(struct trailer_item *a, struct arg_item *b)
123{
124 return !strcasecmp(a->value, b->value);
125}
126
127static int same_trailer(struct trailer_item *a, struct arg_item *b)
128{
129 return same_token(a, b) && same_value(a, b);
130}
131
132static 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
140static 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
147static void free_trailer_item(struct trailer_item *item)
148{
149 free(item->token);
150 free(item->value);
151 free(item);
152}
153
154static 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
165static 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
174static 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
184static 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
195static 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
218static 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
253static 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
276static 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
315static 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
340static 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
370void 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
389int 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
406int 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
425int 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
438static 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
447static 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
469enum trailer_info_type { TRAILER_KEY, TRAILER_COMMAND, TRAILER_CMD,
470 TRAILER_WHERE, TRAILER_IF_EXISTS, TRAILER_IF_MISSING };
471
472static 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
484static 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
519static 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
592void 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
606static 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
615static 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 */
633static 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 (!whitespace_found && starts_with(c, "://"))
641 return -1;
642 return c - line;
643 }
644 if (!whitespace_found && (isalnum(*c) || *c == '-'))
645 continue;
646 if (c != line && (*c == ' ' || *c == '\t')) {
647 whitespace_found = 1;
648 continue;
649 }
650 break;
651 }
652 return -1;
653}
654
655/*
656 * Obtain the token, value, and conf from the given trailer.
657 *
658 * separator_pos must not be 0, since the token cannot be an empty string.
659 *
660 * If separator_pos is -1, interpret the whole trailer as a token.
661 */
662static void parse_trailer(struct strbuf *tok, struct strbuf *val,
663 const struct conf_info **conf, const char *trailer,
664 ssize_t separator_pos)
665{
666 struct arg_item *item;
667 size_t tok_len;
668 struct list_head *pos;
669
670 if (separator_pos != -1) {
671 strbuf_add(tok, trailer, separator_pos);
672 strbuf_trim(tok);
673 strbuf_addstr(val, trailer + separator_pos + 1);
674 strbuf_trim(val);
675 } else {
676 strbuf_addstr(tok, trailer);
677 strbuf_trim(tok);
678 }
679
680 /* Lookup if the token matches something in the config */
681 tok_len = token_len_without_separator(tok->buf, tok->len);
682 if (conf)
683 *conf = &default_conf_info;
684 list_for_each(pos, &conf_head) {
685 item = list_entry(pos, struct arg_item, list);
686 if (token_matches_item(tok->buf, item, tok_len)) {
687 char *tok_buf = strbuf_detach(tok, NULL);
688 if (conf)
689 *conf = &item->conf;
690 strbuf_addstr(tok, token_from_item(item, tok_buf));
691 free(tok_buf);
692 break;
693 }
694 }
695}
696
697static struct trailer_item *add_trailer_item(struct list_head *head, char *tok,
698 char *val)
699{
700 struct trailer_item *new_item = xcalloc(1, sizeof(*new_item));
701 new_item->token = tok;
702 new_item->value = val;
703 list_add_tail(&new_item->list, head);
704 return new_item;
705}
706
707static void add_arg_item(struct list_head *arg_head, char *tok, char *val,
708 const struct conf_info *conf,
709 const struct new_trailer_item *new_trailer_item)
710{
711 struct arg_item *new_item = xcalloc(1, sizeof(*new_item));
712 new_item->token = tok;
713 new_item->value = val;
714 duplicate_conf(&new_item->conf, conf);
715 if (new_trailer_item) {
716 if (new_trailer_item->where != WHERE_DEFAULT)
717 new_item->conf.where = new_trailer_item->where;
718 if (new_trailer_item->if_exists != EXISTS_DEFAULT)
719 new_item->conf.if_exists = new_trailer_item->if_exists;
720 if (new_trailer_item->if_missing != MISSING_DEFAULT)
721 new_item->conf.if_missing = new_trailer_item->if_missing;
722 }
723 list_add_tail(&new_item->list, arg_head);
724}
725
726void parse_trailers_from_config(struct list_head *config_head)
727{
728 struct arg_item *item;
729 struct list_head *pos;
730
731 /* Add an arg item for each configured trailer with a command */
732 list_for_each(pos, &conf_head) {
733 item = list_entry(pos, struct arg_item, list);
734 if (item->conf.command)
735 add_arg_item(config_head,
736 xstrdup(token_from_item(item, NULL)),
737 xstrdup(""),
738 &item->conf, NULL);
739 }
740}
741
742void parse_trailers_from_command_line_args(struct list_head *arg_head,
743 struct list_head *new_trailer_head)
744{
745 struct strbuf tok = STRBUF_INIT;
746 struct strbuf val = STRBUF_INIT;
747 const struct conf_info *conf;
748 struct list_head *pos;
749
750 /*
751 * In command-line arguments, '=' is accepted (in addition to the
752 * separators that are defined).
753 */
754 char *cl_separators = xstrfmt("=%s", separators);
755
756 /* Add an arg item for each trailer on the command line */
757 list_for_each(pos, new_trailer_head) {
758 struct new_trailer_item *tr =
759 list_entry(pos, struct new_trailer_item, list);
760 ssize_t separator_pos = find_separator(tr->text, cl_separators);
761
762 if (separator_pos == 0) {
763 struct strbuf sb = STRBUF_INIT;
764 strbuf_addstr(&sb, tr->text);
765 strbuf_trim(&sb);
766 error(_("empty trailer token in trailer '%.*s'"),
767 (int) sb.len, sb.buf);
768 strbuf_release(&sb);
769 } else {
770 parse_trailer(&tok, &val, &conf, tr->text,
771 separator_pos);
772 add_arg_item(arg_head,
773 strbuf_detach(&tok, NULL),
774 strbuf_detach(&val, NULL),
775 conf, tr);
776 }
777 }
778
779 free(cl_separators);
780}
781
782int validate_trailer_args(const struct strvec *cli_args)
783{
784 char *cl_separators;
785 int ret = 0;
786
787 trailer_config_init();
788
789 cl_separators = xstrfmt("=%s", separators);
790
791 for (size_t i = 0; i < cli_args->nr; i++) {
792 const char *txt = cli_args->v[i];
793 ssize_t separator_pos;
794
795 if (!*txt) {
796 ret = error(_("empty --trailer argument"));
797 goto out;
798 }
799 separator_pos = find_separator(txt, cl_separators);
800 if (separator_pos == 0) {
801 ret = error(_("invalid trailer '%s': missing key before separator"),
802 txt);
803 goto out;
804 }
805 }
806out:
807 free(cl_separators);
808 return ret;
809}
810
811static const char *next_line(const char *str)
812{
813 const char *nl = strchrnul(str, '\n');
814 return nl + !!*nl;
815}
816
817/*
818 * Return the position of the start of the last line. If len is 0, return -1.
819 */
820static ssize_t last_line(const char *buf, size_t len)
821{
822 ssize_t i;
823 if (len == 0)
824 return -1;
825 if (len == 1)
826 return 0;
827 /*
828 * Skip the last character (in addition to the null terminator),
829 * because if the last character is a newline, it is considered as part
830 * of the last line anyway.
831 */
832 i = len - 2;
833
834 for (; i >= 0; i--) {
835 if (buf[i] == '\n')
836 return i + 1;
837 }
838 return 0;
839}
840
841/*
842 * Find the end of the log message as an offset from the start of the input
843 * (where callers of this function are interested in looking for a trailers
844 * block in the same input). We have to consider two categories of content that
845 * can come at the end of the input which we want to ignore (because they don't
846 * belong in the log message):
847 *
848 * (1) the "patch part" which begins with a "---" divider and has patch
849 * information (like the output of git-format-patch), and
850 *
851 * (2) any trailing comment lines, blank lines like in the output of "git
852 * commit -v", or stuff below the "cut" (scissor) line.
853 *
854 * As a formula, the situation looks like this:
855 *
856 * INPUT = LOG MESSAGE + IGNORED
857 *
858 * where IGNORED can be either of the two categories described above. It may be
859 * that there is nothing to ignore. Now it may be the case that the LOG MESSAGE
860 * contains a trailer block, but that's not the concern of this function.
861 */
862static size_t find_end_of_log_message(const char *input, int no_divider)
863{
864 size_t end;
865 const char *s;
866
867 /* Assume the naive end of the input is already what we want. */
868 end = strlen(input);
869
870 /* Optionally skip over any patch part ("---" line and below). */
871 if (!no_divider) {
872 for (s = input; *s; s = next_line(s)) {
873 const char *v;
874
875 if (skip_prefix(s, "---", &v) && isspace(*v)) {
876 end = s - input;
877 break;
878 }
879 }
880 }
881
882 /* Skip over other ignorable bits. */
883 return end - ignored_log_message_bytes(input, end);
884}
885
886/*
887 * Return the position of the first trailer line or len if there are no
888 * trailers.
889 */
890static size_t find_trailer_block_start(const char *buf, size_t len)
891{
892 const char *s;
893 ssize_t end_of_title, l;
894 int only_spaces = 1;
895 int recognized_prefix = 0, trailer_lines = 0, non_trailer_lines = 0;
896 /*
897 * Number of possible continuation lines encountered. This will be
898 * reset to 0 if we encounter a trailer (since those lines are to be
899 * considered continuations of that trailer), and added to
900 * non_trailer_lines if we encounter a non-trailer (since those lines
901 * are to be considered non-trailers).
902 */
903 int possible_continuation_lines = 0;
904
905 /* The first paragraph is the title and cannot be trailers */
906 for (s = buf; s < buf + len; s = next_line(s)) {
907 if (starts_with_mem(s, buf + len - s, comment_line_str))
908 continue;
909 if (is_blank_line(s))
910 break;
911 }
912 end_of_title = s - buf;
913
914 /*
915 * Get the start of the trailers by looking starting from the end for a
916 * blank line before a set of non-blank lines that (i) are all
917 * trailers, or (ii) contains at least one Git-generated trailer and
918 * consists of at least 25% trailers.
919 */
920 for (l = last_line(buf, len);
921 l >= end_of_title;
922 l = last_line(buf, l)) {
923 const char *bol = buf + l;
924 const char **p;
925 ssize_t separator_pos;
926
927 if (starts_with_mem(bol, buf + len - bol, comment_line_str)) {
928 non_trailer_lines += possible_continuation_lines;
929 possible_continuation_lines = 0;
930 continue;
931 }
932 if (is_blank_line(bol)) {
933 if (only_spaces)
934 continue;
935 non_trailer_lines += possible_continuation_lines;
936 if (recognized_prefix &&
937 trailer_lines * 3 >= non_trailer_lines)
938 return next_line(bol) - buf;
939 else if (trailer_lines && !non_trailer_lines)
940 return next_line(bol) - buf;
941 return len;
942 }
943 only_spaces = 0;
944
945 for (p = git_generated_prefixes; *p; p++) {
946 if (starts_with(bol, *p)) {
947 trailer_lines++;
948 possible_continuation_lines = 0;
949 recognized_prefix = 1;
950 goto continue_outer_loop;
951 }
952 }
953
954 separator_pos = find_separator(bol, separators);
955 if (separator_pos >= 1 && !isspace(bol[0])) {
956 struct list_head *pos;
957
958 trailer_lines++;
959 possible_continuation_lines = 0;
960 if (recognized_prefix)
961 continue;
962 list_for_each(pos, &conf_head) {
963 struct arg_item *item;
964 item = list_entry(pos, struct arg_item, list);
965 if (token_matches_item(bol, item,
966 separator_pos)) {
967 recognized_prefix = 1;
968 break;
969 }
970 }
971 } else if (isspace(bol[0]))
972 possible_continuation_lines++;
973 else {
974 non_trailer_lines++;
975 non_trailer_lines += possible_continuation_lines;
976 possible_continuation_lines = 0;
977 }
978continue_outer_loop:
979 ;
980 }
981
982 return len;
983}
984
985static int ends_with_blank_line(const char *buf, size_t len)
986{
987 ssize_t ll = last_line(buf, len);
988 if (ll < 0)
989 return 0;
990 return is_blank_line(buf + ll);
991}
992
993static void unfold_value(struct strbuf *val)
994{
995 size_t i;
996 size_t pos = 0;
997
998 i = 0;
999 while (i < val->len) {
1000 char c = val->buf[i++];
1001 if (c == '\n') {
1002 /* Collapse continuation down to a single space. */
1003 while (i < val->len && isspace(val->buf[i]))
1004 i++;
1005 c = ' ';
1006 }
1007 val->buf[pos++] = c;
1008 }
1009 strbuf_setlen(val, pos);
1010
1011 /* Empty lines may have left us with whitespace cruft at the edges */
1012 strbuf_trim(val);
1013}
1014
1015static struct trailer_block *trailer_block_new(void)
1016{
1017 struct trailer_block *trailer_block = xcalloc(1, sizeof(*trailer_block));
1018 return trailer_block;
1019}
1020
1021static struct trailer_block *trailer_block_get(const struct process_trailer_options *opts,
1022 const char *str)
1023{
1024 struct trailer_block *trailer_block = trailer_block_new();
1025 size_t end_of_log_message = 0, trailer_block_start = 0;
1026 struct strbuf **trailer_lines, **ptr;
1027 char **trailer_strings = NULL;
1028 size_t nr = 0, alloc = 0;
1029 char **last = NULL;
1030
1031 trailer_config_init();
1032
1033 end_of_log_message = find_end_of_log_message(str, opts->no_divider);
1034 trailer_block_start = find_trailer_block_start(str, end_of_log_message);
1035
1036 trailer_lines = strbuf_split_buf(str + trailer_block_start,
1037 end_of_log_message - trailer_block_start,
1038 '\n',
1039 0);
1040 for (ptr = trailer_lines; *ptr; ptr++) {
1041 if (last && isspace((*ptr)->buf[0])) {
1042 struct strbuf sb = STRBUF_INIT;
1043 strbuf_attach(&sb, *last, strlen(*last), strlen(*last) + 1);
1044 strbuf_addbuf(&sb, *ptr);
1045 *last = strbuf_detach(&sb, NULL);
1046 continue;
1047 }
1048 ALLOC_GROW(trailer_strings, nr + 1, alloc);
1049 trailer_strings[nr] = strbuf_detach(*ptr, NULL);
1050 last = find_separator(trailer_strings[nr], separators) >= 1
1051 ? &trailer_strings[nr]
1052 : NULL;
1053 nr++;
1054 }
1055 strbuf_list_free(trailer_lines);
1056
1057 trailer_block->blank_line_before_trailer = ends_with_blank_line(str,
1058 trailer_block_start);
1059 trailer_block->start = trailer_block_start;
1060 trailer_block->end = end_of_log_message;
1061 trailer_block->trailers = trailer_strings;
1062 trailer_block->trailer_nr = nr;
1063
1064 return trailer_block;
1065}
1066
1067/*
1068 * Parse trailers in "str", populating the trailer_block and "trailer_objects"
1069 * linked list structure.
1070 */
1071struct trailer_block *parse_trailers(const struct process_trailer_options *opts,
1072 const char *str,
1073 struct list_head *trailer_objects)
1074{
1075 struct trailer_block *trailer_block;
1076 struct strbuf tok = STRBUF_INIT;
1077 struct strbuf val = STRBUF_INIT;
1078 size_t i;
1079
1080 trailer_block = trailer_block_get(opts, str);
1081
1082 for (i = 0; i < trailer_block->trailer_nr; i++) {
1083 int separator_pos;
1084 char *trailer = trailer_block->trailers[i];
1085 if (starts_with(trailer, comment_line_str))
1086 continue;
1087 separator_pos = find_separator(trailer, separators);
1088 if (separator_pos >= 1) {
1089 parse_trailer(&tok, &val, NULL, trailer,
1090 separator_pos);
1091 if (opts->unfold)
1092 unfold_value(&val);
1093 add_trailer_item(trailer_objects,
1094 strbuf_detach(&tok, NULL),
1095 strbuf_detach(&val, NULL));
1096 } else if (!opts->only_trailers) {
1097 strbuf_addstr(&val, trailer);
1098 strbuf_strip_suffix(&val, "\n");
1099 add_trailer_item(trailer_objects,
1100 NULL,
1101 strbuf_detach(&val, NULL));
1102 }
1103 }
1104
1105 return trailer_block;
1106}
1107
1108void free_trailers(struct list_head *trailers)
1109{
1110 struct list_head *pos, *p;
1111 list_for_each_safe(pos, p, trailers) {
1112 list_del(pos);
1113 free_trailer_item(list_entry(pos, struct trailer_item, list));
1114 }
1115}
1116
1117size_t trailer_block_start(struct trailer_block *trailer_block)
1118{
1119 return trailer_block->start;
1120}
1121
1122size_t trailer_block_end(struct trailer_block *trailer_block)
1123{
1124 return trailer_block->end;
1125}
1126
1127int blank_line_before_trailer_block(struct trailer_block *trailer_block)
1128{
1129 return trailer_block->blank_line_before_trailer;
1130}
1131
1132void trailer_block_release(struct trailer_block *trailer_block)
1133{
1134 size_t i;
1135 for (i = 0; i < trailer_block->trailer_nr; i++)
1136 free(trailer_block->trailers[i]);
1137 free(trailer_block->trailers);
1138 free(trailer_block);
1139}
1140
1141void format_trailers(const struct process_trailer_options *opts,
1142 struct list_head *trailers,
1143 struct strbuf *out)
1144{
1145 struct strbuf tok = STRBUF_INIT;
1146 struct strbuf val = STRBUF_INIT;
1147 size_t origlen = out->len;
1148 struct list_head *pos;
1149 struct trailer_item *item;
1150
1151 list_for_each(pos, trailers) {
1152 item = list_entry(pos, struct trailer_item, list);
1153 if (item->token) {
1154 strbuf_reset(&tok);
1155 strbuf_addstr(&tok, item->token);
1156 strbuf_reset(&val);
1157 strbuf_addstr(&val, item->value);
1158
1159 /*
1160 * Skip key/value pairs where the value was empty. This
1161 * can happen from trailers specified without a
1162 * separator, like `--trailer "Reviewed-by"` (no
1163 * corresponding value).
1164 */
1165 if (opts->trim_empty && !strlen(item->value))
1166 continue;
1167
1168 if (!opts->filter || opts->filter(&tok, opts->filter_data)) {
1169 if (opts->separator && out->len != origlen)
1170 strbuf_addbuf(out, opts->separator);
1171 if (!opts->value_only)
1172 strbuf_addbuf(out, &tok);
1173 if (!opts->key_only && !opts->value_only) {
1174 if (opts->key_value_separator)
1175 strbuf_addbuf(out, opts->key_value_separator);
1176 else {
1177 char c = last_non_space_char(tok.buf);
1178 if (c && !strchr(separators, c))
1179 strbuf_addf(out, "%c ", separators[0]);
1180 }
1181 }
1182 if (!opts->key_only)
1183 strbuf_addbuf(out, &val);
1184 if (!opts->separator)
1185 strbuf_addch(out, '\n');
1186 }
1187 } else if (!opts->only_trailers) {
1188 if (opts->separator && out->len != origlen) {
1189 strbuf_addbuf(out, opts->separator);
1190 }
1191 strbuf_addstr(out, item->value);
1192 if (opts->separator)
1193 strbuf_rtrim(out);
1194 else
1195 strbuf_addch(out, '\n');
1196 }
1197 }
1198
1199 strbuf_release(&tok);
1200 strbuf_release(&val);
1201}
1202
1203void format_trailers_from_commit(const struct process_trailer_options *opts,
1204 const char *msg,
1205 struct strbuf *out)
1206{
1207 LIST_HEAD(trailer_objects);
1208 struct trailer_block *trailer_block = parse_trailers(opts, msg, &trailer_objects);
1209
1210 /* If we want the whole block untouched, we can take the fast path. */
1211 if (!opts->only_trailers && !opts->unfold && !opts->filter &&
1212 !opts->separator && !opts->key_only && !opts->value_only &&
1213 !opts->key_value_separator) {
1214 strbuf_add(out, msg + trailer_block->start,
1215 trailer_block->end - trailer_block->start);
1216 } else
1217 format_trailers(opts, &trailer_objects, out);
1218
1219 free_trailers(&trailer_objects);
1220 trailer_block_release(trailer_block);
1221}
1222
1223void trailer_iterator_init(struct trailer_iterator *iter, const char *msg)
1224{
1225 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
1226 strbuf_init(&iter->key, 0);
1227 strbuf_init(&iter->val, 0);
1228 opts.no_divider = 1;
1229 iter->internal.trailer_block = trailer_block_get(&opts, msg);
1230 iter->internal.cur = 0;
1231}
1232
1233int trailer_iterator_advance(struct trailer_iterator *iter)
1234{
1235 if (iter->internal.cur < iter->internal.trailer_block->trailer_nr) {
1236 char *line = iter->internal.trailer_block->trailers[iter->internal.cur++];
1237 int separator_pos = find_separator(line, separators);
1238
1239 iter->raw = line;
1240 strbuf_reset(&iter->key);
1241 strbuf_reset(&iter->val);
1242 parse_trailer(&iter->key, &iter->val, NULL,
1243 line, separator_pos);
1244 /* Always unfold values during iteration. */
1245 unfold_value(&iter->val);
1246 return 1;
1247 }
1248 return 0;
1249}
1250
1251void trailer_iterator_release(struct trailer_iterator *iter)
1252{
1253 trailer_block_release(iter->internal.trailer_block);
1254 strbuf_release(&iter->val);
1255 strbuf_release(&iter->key);
1256}
1257
1258struct tempfile *trailer_create_in_place_tempfile(const char *file)
1259{
1260 struct tempfile *tempfile = NULL;
1261 struct stat st;
1262 struct strbuf filename_template = STRBUF_INIT;
1263 const char *tail;
1264
1265 if (stat(file, &st)) {
1266 error_errno(_("could not stat %s"), file);
1267 return NULL;
1268 }
1269 if (!S_ISREG(st.st_mode)) {
1270 error(_("file %s is not a regular file"), file);
1271 return NULL;
1272 }
1273 if (!(st.st_mode & S_IWUSR)) {
1274 error(_("file %s is not writable by user"), file);
1275 return NULL;
1276 }
1277 /* Create temporary file in the same directory as the original */
1278 tail = find_last_dir_sep(file);
1279 if (tail)
1280 strbuf_add(&filename_template, file, tail - file + 1);
1281 strbuf_addstr(&filename_template, "git-interpret-trailers-XXXXXX");
1282
1283 tempfile = mks_tempfile_m(filename_template.buf, st.st_mode);
1284
1285 strbuf_release(&filename_template);
1286
1287 return tempfile;
1288}
1289
1290int amend_strbuf_with_trailers(struct strbuf *buf,
1291 const struct strvec *trailer_args)
1292{
1293 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
1294 LIST_HEAD(new_trailer_head);
1295 struct strbuf out = STRBUF_INIT;
1296 size_t i;
1297 int ret = 0;
1298
1299 opts.no_divider = 1;
1300
1301 for (i = 0; i < trailer_args->nr; i++) {
1302 const char *text = trailer_args->v[i];
1303 struct new_trailer_item *item;
1304
1305 if (!*text) {
1306 ret = error(_("empty --trailer argument"));
1307 goto out;
1308 }
1309 item = xcalloc(1, sizeof(*item));
1310 item->text = xstrdup(text);
1311 list_add_tail(&item->list, &new_trailer_head);
1312 }
1313
1314 process_trailers(&opts, &new_trailer_head, buf, &out);
1315
1316 strbuf_swap(buf, &out);
1317out:
1318 strbuf_release(&out);
1319 free_trailers(&new_trailer_head);
1320
1321 return ret;
1322}
1323
1324static int write_file_in_place(const char *path, const struct strbuf *buf)
1325{
1326 struct tempfile *tempfile = trailer_create_in_place_tempfile(path);
1327 if (!tempfile)
1328 return -1;
1329
1330 if (write_in_full(tempfile->fd, buf->buf, buf->len) < 0)
1331 return error_errno(_("could not write to temporary file"));
1332
1333 if (rename_tempfile(&tempfile, path))
1334 return error_errno(_("could not rename temporary file to %s"), path);
1335
1336 return 0;
1337}
1338
1339int amend_file_with_trailers(const char *path,
1340 const struct strvec *trailer_args)
1341{
1342 struct strbuf buf = STRBUF_INIT;
1343 int ret = 0;
1344
1345 if (!trailer_args)
1346 BUG("amend_file_with_trailers called with NULL trailer_args");
1347 if (!trailer_args->nr)
1348 return 0;
1349
1350 if (validate_trailer_args(trailer_args)) {
1351 ret = -1;
1352 goto out;
1353 }
1354 if (strbuf_read_file(&buf, path, 0) < 0)
1355 ret = error_errno(_("could not read '%s'"), path);
1356 else
1357 amend_strbuf_with_trailers(&buf, trailer_args);
1358
1359 if (!ret)
1360 ret = write_file_in_place(path, &buf);
1361out:
1362 strbuf_release(&buf);
1363 return ret;
1364}
1365
1366void process_trailers(const struct process_trailer_options *opts,
1367 struct list_head *new_trailer_head,
1368 struct strbuf *input, struct strbuf *out)
1369{
1370 LIST_HEAD(head);
1371 struct trailer_block *trailer_block;
1372
1373 trailer_block = parse_trailers(opts, input->buf, &head);
1374
1375 /* Print the lines before the trailer block */
1376 if (!opts->only_trailers)
1377 strbuf_add(out, input->buf, trailer_block_start(trailer_block));
1378
1379 if (!opts->only_trailers && !blank_line_before_trailer_block(trailer_block))
1380 strbuf_addch(out, '\n');
1381
1382 if (!opts->only_input) {
1383 LIST_HEAD(config_head);
1384 LIST_HEAD(arg_head);
1385 parse_trailers_from_config(&config_head);
1386 parse_trailers_from_command_line_args(&arg_head, new_trailer_head);
1387 list_splice(&config_head, &arg_head);
1388 process_trailers_lists(&head, &arg_head);
1389 }
1390
1391 /* Print trailer block. */
1392 format_trailers(opts, &head, out);
1393 free_trailers(&head);
1394
1395 /* Print the lines after the trailer block as is. */
1396 if (!opts->only_trailers)
1397 strbuf_add(out, input->buf + trailer_block_end(trailer_block),
1398 input->len - trailer_block_end(trailer_block));
1399 trailer_block_release(trailer_block);
1400}