]> git.ipfire.org Git - thirdparty/git.git/blob - trailer.c
Merge branch 'js/check-null-from-read-object-file'
[thirdparty/git.git] / trailer.c
1 #include "git-compat-util.h"
2 #include "config.h"
3 #include "environment.h"
4 #include "gettext.h"
5 #include "string-list.h"
6 #include "run-command.h"
7 #include "commit.h"
8 #include "tempfile.h"
9 #include "trailer.h"
10 #include "list.h"
11 /*
12 * Copyright (c) 2013, 2014 Christian Couder <chriscool@tuxfamily.org>
13 */
14
15 struct conf_info {
16 char *name;
17 char *key;
18 char *command;
19 char *cmd;
20 enum trailer_where where;
21 enum trailer_if_exists if_exists;
22 enum trailer_if_missing if_missing;
23 };
24
25 static struct conf_info default_conf_info;
26
27 struct trailer_item {
28 struct list_head list;
29 /*
30 * If this is not a trailer line, the line is stored in value
31 * (excluding the terminating newline) and token is NULL.
32 */
33 char *token;
34 char *value;
35 };
36
37 struct arg_item {
38 struct list_head list;
39 char *token;
40 char *value;
41 struct conf_info conf;
42 };
43
44 static LIST_HEAD(conf_head);
45
46 static char *separators = ":";
47
48 static int configured;
49
50 #define TRAILER_ARG_STRING "$ARG"
51
52 static const char *git_generated_prefixes[] = {
53 "Signed-off-by: ",
54 "(cherry picked from commit ",
55 NULL
56 };
57
58 /* Iterate over the elements of the list. */
59 #define list_for_each_dir(pos, head, is_reverse) \
60 for (pos = is_reverse ? (head)->prev : (head)->next; \
61 pos != (head); \
62 pos = is_reverse ? pos->prev : pos->next)
63
64 static int after_or_end(enum trailer_where where)
65 {
66 return (where == WHERE_AFTER) || (where == WHERE_END);
67 }
68
69 /*
70 * Return the length of the string not including any final
71 * punctuation. E.g., the input "Signed-off-by:" would return
72 * 13, stripping the trailing punctuation but retaining
73 * internal punctuation.
74 */
75 static size_t token_len_without_separator(const char *token, size_t len)
76 {
77 while (len > 0 && !isalnum(token[len - 1]))
78 len--;
79 return len;
80 }
81
82 static int same_token(struct trailer_item *a, struct arg_item *b)
83 {
84 size_t a_len, b_len, min_len;
85
86 if (!a->token)
87 return 0;
88
89 a_len = token_len_without_separator(a->token, strlen(a->token));
90 b_len = token_len_without_separator(b->token, strlen(b->token));
91 min_len = (a_len > b_len) ? b_len : a_len;
92
93 return !strncasecmp(a->token, b->token, min_len);
94 }
95
96 static int same_value(struct trailer_item *a, struct arg_item *b)
97 {
98 return !strcasecmp(a->value, b->value);
99 }
100
101 static int same_trailer(struct trailer_item *a, struct arg_item *b)
102 {
103 return same_token(a, b) && same_value(a, b);
104 }
105
106 static inline int is_blank_line(const char *str)
107 {
108 const char *s = str;
109 while (*s && *s != '\n' && isspace(*s))
110 s++;
111 return !*s || *s == '\n';
112 }
113
114 static inline void strbuf_replace(struct strbuf *sb, const char *a, const char *b)
115 {
116 const char *ptr = strstr(sb->buf, a);
117 if (ptr)
118 strbuf_splice(sb, ptr - sb->buf, strlen(a), b, strlen(b));
119 }
120
121 static void free_trailer_item(struct trailer_item *item)
122 {
123 free(item->token);
124 free(item->value);
125 free(item);
126 }
127
128 static void free_arg_item(struct arg_item *item)
129 {
130 free(item->conf.name);
131 free(item->conf.key);
132 free(item->conf.command);
133 free(item->conf.cmd);
134 free(item->token);
135 free(item->value);
136 free(item);
137 }
138
139 static char last_non_space_char(const char *s)
140 {
141 int i;
142 for (i = strlen(s) - 1; i >= 0; i--)
143 if (!isspace(s[i]))
144 return s[i];
145 return '\0';
146 }
147
148 static void print_tok_val(FILE *outfile, const char *tok, const char *val)
149 {
150 char c;
151
152 if (!tok) {
153 fprintf(outfile, "%s\n", val);
154 return;
155 }
156
157 c = last_non_space_char(tok);
158 if (!c)
159 return;
160 if (strchr(separators, c))
161 fprintf(outfile, "%s%s\n", tok, val);
162 else
163 fprintf(outfile, "%s%c %s\n", tok, separators[0], val);
164 }
165
166 static void print_all(FILE *outfile, struct list_head *head,
167 const struct process_trailer_options *opts)
168 {
169 struct list_head *pos;
170 struct trailer_item *item;
171 list_for_each(pos, head) {
172 item = list_entry(pos, struct trailer_item, list);
173 if ((!opts->trim_empty || strlen(item->value) > 0) &&
174 (!opts->only_trailers || item->token))
175 print_tok_val(outfile, item->token, item->value);
176 }
177 }
178
179 static struct trailer_item *trailer_from_arg(struct arg_item *arg_tok)
180 {
181 struct trailer_item *new_item = xcalloc(1, sizeof(*new_item));
182 new_item->token = arg_tok->token;
183 new_item->value = arg_tok->value;
184 arg_tok->token = arg_tok->value = NULL;
185 free_arg_item(arg_tok);
186 return new_item;
187 }
188
189 static void add_arg_to_input_list(struct trailer_item *on_tok,
190 struct arg_item *arg_tok)
191 {
192 int aoe = after_or_end(arg_tok->conf.where);
193 struct trailer_item *to_add = trailer_from_arg(arg_tok);
194 if (aoe)
195 list_add(&to_add->list, &on_tok->list);
196 else
197 list_add_tail(&to_add->list, &on_tok->list);
198 }
199
200 static int check_if_different(struct trailer_item *in_tok,
201 struct arg_item *arg_tok,
202 int check_all,
203 struct list_head *head)
204 {
205 enum trailer_where where = arg_tok->conf.where;
206 struct list_head *next_head;
207 do {
208 if (same_trailer(in_tok, arg_tok))
209 return 0;
210 /*
211 * if we want to add a trailer after another one,
212 * we have to check those before this one
213 */
214 next_head = after_or_end(where) ? in_tok->list.prev
215 : in_tok->list.next;
216 if (next_head == head)
217 break;
218 in_tok = list_entry(next_head, struct trailer_item, list);
219 } while (check_all);
220 return 1;
221 }
222
223 static char *apply_command(struct conf_info *conf, const char *arg)
224 {
225 struct strbuf cmd = STRBUF_INIT;
226 struct strbuf buf = STRBUF_INIT;
227 struct child_process cp = CHILD_PROCESS_INIT;
228 char *result;
229
230 if (conf->cmd) {
231 strbuf_addstr(&cmd, conf->cmd);
232 strvec_push(&cp.args, cmd.buf);
233 if (arg)
234 strvec_push(&cp.args, arg);
235 } else if (conf->command) {
236 strbuf_addstr(&cmd, conf->command);
237 if (arg)
238 strbuf_replace(&cmd, TRAILER_ARG_STRING, arg);
239 strvec_push(&cp.args, cmd.buf);
240 }
241 strvec_pushv(&cp.env, (const char **)local_repo_env);
242 cp.no_stdin = 1;
243 cp.use_shell = 1;
244
245 if (capture_command(&cp, &buf, 1024)) {
246 error(_("running trailer command '%s' failed"), cmd.buf);
247 strbuf_release(&buf);
248 result = xstrdup("");
249 } else {
250 strbuf_trim(&buf);
251 result = strbuf_detach(&buf, NULL);
252 }
253
254 strbuf_release(&cmd);
255 return result;
256 }
257
258 static void apply_item_command(struct trailer_item *in_tok, struct arg_item *arg_tok)
259 {
260 if (arg_tok->conf.command || arg_tok->conf.cmd) {
261 const char *arg;
262 if (arg_tok->value && arg_tok->value[0]) {
263 arg = arg_tok->value;
264 } else {
265 if (in_tok && in_tok->value)
266 arg = xstrdup(in_tok->value);
267 else
268 arg = xstrdup("");
269 }
270 arg_tok->value = apply_command(&arg_tok->conf, arg);
271 free((char *)arg);
272 }
273 }
274
275 static void apply_arg_if_exists(struct trailer_item *in_tok,
276 struct arg_item *arg_tok,
277 struct trailer_item *on_tok,
278 struct list_head *head)
279 {
280 switch (arg_tok->conf.if_exists) {
281 case EXISTS_DO_NOTHING:
282 free_arg_item(arg_tok);
283 break;
284 case EXISTS_REPLACE:
285 apply_item_command(in_tok, arg_tok);
286 add_arg_to_input_list(on_tok, arg_tok);
287 list_del(&in_tok->list);
288 free_trailer_item(in_tok);
289 break;
290 case EXISTS_ADD:
291 apply_item_command(in_tok, arg_tok);
292 add_arg_to_input_list(on_tok, arg_tok);
293 break;
294 case EXISTS_ADD_IF_DIFFERENT:
295 apply_item_command(in_tok, arg_tok);
296 if (check_if_different(in_tok, arg_tok, 1, head))
297 add_arg_to_input_list(on_tok, arg_tok);
298 else
299 free_arg_item(arg_tok);
300 break;
301 case EXISTS_ADD_IF_DIFFERENT_NEIGHBOR:
302 apply_item_command(in_tok, arg_tok);
303 if (check_if_different(on_tok, arg_tok, 0, head))
304 add_arg_to_input_list(on_tok, arg_tok);
305 else
306 free_arg_item(arg_tok);
307 break;
308 default:
309 BUG("trailer.c: unhandled value %d",
310 arg_tok->conf.if_exists);
311 }
312 }
313
314 static void apply_arg_if_missing(struct list_head *head,
315 struct arg_item *arg_tok)
316 {
317 enum trailer_where where;
318 struct trailer_item *to_add;
319
320 switch (arg_tok->conf.if_missing) {
321 case MISSING_DO_NOTHING:
322 free_arg_item(arg_tok);
323 break;
324 case MISSING_ADD:
325 where = arg_tok->conf.where;
326 apply_item_command(NULL, arg_tok);
327 to_add = trailer_from_arg(arg_tok);
328 if (after_or_end(where))
329 list_add_tail(&to_add->list, head);
330 else
331 list_add(&to_add->list, head);
332 break;
333 default:
334 BUG("trailer.c: unhandled value %d",
335 arg_tok->conf.if_missing);
336 }
337 }
338
339 static int find_same_and_apply_arg(struct list_head *head,
340 struct arg_item *arg_tok)
341 {
342 struct list_head *pos;
343 struct trailer_item *in_tok;
344 struct trailer_item *on_tok;
345
346 enum trailer_where where = arg_tok->conf.where;
347 int middle = (where == WHERE_AFTER) || (where == WHERE_BEFORE);
348 int backwards = after_or_end(where);
349 struct trailer_item *start_tok;
350
351 if (list_empty(head))
352 return 0;
353
354 start_tok = list_entry(backwards ? head->prev : head->next,
355 struct trailer_item,
356 list);
357
358 list_for_each_dir(pos, head, backwards) {
359 in_tok = list_entry(pos, struct trailer_item, list);
360 if (!same_token(in_tok, arg_tok))
361 continue;
362 on_tok = middle ? in_tok : start_tok;
363 apply_arg_if_exists(in_tok, arg_tok, on_tok, head);
364 return 1;
365 }
366 return 0;
367 }
368
369 static void process_trailers_lists(struct list_head *head,
370 struct list_head *arg_head)
371 {
372 struct list_head *pos, *p;
373 struct arg_item *arg_tok;
374
375 list_for_each_safe(pos, p, arg_head) {
376 int applied = 0;
377 arg_tok = list_entry(pos, struct arg_item, list);
378
379 list_del(pos);
380
381 applied = find_same_and_apply_arg(head, arg_tok);
382
383 if (!applied)
384 apply_arg_if_missing(head, arg_tok);
385 }
386 }
387
388 int trailer_set_where(enum trailer_where *item, const char *value)
389 {
390 if (!value)
391 *item = WHERE_DEFAULT;
392 else if (!strcasecmp("after", value))
393 *item = WHERE_AFTER;
394 else if (!strcasecmp("before", value))
395 *item = WHERE_BEFORE;
396 else if (!strcasecmp("end", value))
397 *item = WHERE_END;
398 else if (!strcasecmp("start", value))
399 *item = WHERE_START;
400 else
401 return -1;
402 return 0;
403 }
404
405 int trailer_set_if_exists(enum trailer_if_exists *item, const char *value)
406 {
407 if (!value)
408 *item = EXISTS_DEFAULT;
409 else if (!strcasecmp("addIfDifferent", value))
410 *item = EXISTS_ADD_IF_DIFFERENT;
411 else if (!strcasecmp("addIfDifferentNeighbor", value))
412 *item = EXISTS_ADD_IF_DIFFERENT_NEIGHBOR;
413 else if (!strcasecmp("add", value))
414 *item = EXISTS_ADD;
415 else if (!strcasecmp("replace", value))
416 *item = EXISTS_REPLACE;
417 else if (!strcasecmp("doNothing", value))
418 *item = EXISTS_DO_NOTHING;
419 else
420 return -1;
421 return 0;
422 }
423
424 int trailer_set_if_missing(enum trailer_if_missing *item, const char *value)
425 {
426 if (!value)
427 *item = MISSING_DEFAULT;
428 else if (!strcasecmp("doNothing", value))
429 *item = MISSING_DO_NOTHING;
430 else if (!strcasecmp("add", value))
431 *item = MISSING_ADD;
432 else
433 return -1;
434 return 0;
435 }
436
437 static void duplicate_conf(struct conf_info *dst, const struct conf_info *src)
438 {
439 *dst = *src;
440 dst->name = xstrdup_or_null(src->name);
441 dst->key = xstrdup_or_null(src->key);
442 dst->command = xstrdup_or_null(src->command);
443 dst->cmd = xstrdup_or_null(src->cmd);
444 }
445
446 static struct arg_item *get_conf_item(const char *name)
447 {
448 struct list_head *pos;
449 struct arg_item *item;
450
451 /* Look up item with same name */
452 list_for_each(pos, &conf_head) {
453 item = list_entry(pos, struct arg_item, list);
454 if (!strcasecmp(item->conf.name, name))
455 return item;
456 }
457
458 /* Item does not already exists, create it */
459 CALLOC_ARRAY(item, 1);
460 duplicate_conf(&item->conf, &default_conf_info);
461 item->conf.name = xstrdup(name);
462
463 list_add_tail(&item->list, &conf_head);
464
465 return item;
466 }
467
468 enum trailer_info_type { TRAILER_KEY, TRAILER_COMMAND, TRAILER_CMD,
469 TRAILER_WHERE, TRAILER_IF_EXISTS, TRAILER_IF_MISSING };
470
471 static struct {
472 const char *name;
473 enum trailer_info_type type;
474 } trailer_config_items[] = {
475 { "key", TRAILER_KEY },
476 { "command", TRAILER_COMMAND },
477 { "cmd", TRAILER_CMD },
478 { "where", TRAILER_WHERE },
479 { "ifexists", TRAILER_IF_EXISTS },
480 { "ifmissing", TRAILER_IF_MISSING }
481 };
482
483 static int git_trailer_default_config(const char *conf_key, const char *value,
484 const struct config_context *ctx UNUSED,
485 void *cb UNUSED)
486 {
487 const char *trailer_item, *variable_name;
488
489 if (!skip_prefix(conf_key, "trailer.", &trailer_item))
490 return 0;
491
492 variable_name = strrchr(trailer_item, '.');
493 if (!variable_name) {
494 if (!strcmp(trailer_item, "where")) {
495 if (trailer_set_where(&default_conf_info.where,
496 value) < 0)
497 warning(_("unknown value '%s' for key '%s'"),
498 value, conf_key);
499 } else if (!strcmp(trailer_item, "ifexists")) {
500 if (trailer_set_if_exists(&default_conf_info.if_exists,
501 value) < 0)
502 warning(_("unknown value '%s' for key '%s'"),
503 value, conf_key);
504 } else if (!strcmp(trailer_item, "ifmissing")) {
505 if (trailer_set_if_missing(&default_conf_info.if_missing,
506 value) < 0)
507 warning(_("unknown value '%s' for key '%s'"),
508 value, conf_key);
509 } else if (!strcmp(trailer_item, "separators")) {
510 if (!value)
511 return config_error_nonbool(conf_key);
512 separators = xstrdup(value);
513 }
514 }
515 return 0;
516 }
517
518 static int git_trailer_config(const char *conf_key, const char *value,
519 const struct config_context *ctx UNUSED,
520 void *cb UNUSED)
521 {
522 const char *trailer_item, *variable_name;
523 struct arg_item *item;
524 struct conf_info *conf;
525 char *name = NULL;
526 enum trailer_info_type type;
527 int i;
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 (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 static void ensure_configured(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 git_config(git_trailer_default_config, NULL);
602 git_config(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 return c - line;
640 if (!whitespace_found && (isalnum(*c) || *c == '-'))
641 continue;
642 if (c != line && (*c == ' ' || *c == '\t')) {
643 whitespace_found = 1;
644 continue;
645 }
646 break;
647 }
648 return -1;
649 }
650
651 /*
652 * Obtain the token, value, and conf from the given trailer.
653 *
654 * separator_pos must not be 0, since the token cannot be an empty string.
655 *
656 * If separator_pos is -1, interpret the whole trailer as a token.
657 */
658 static void parse_trailer(struct strbuf *tok, struct strbuf *val,
659 const struct conf_info **conf, const char *trailer,
660 ssize_t separator_pos)
661 {
662 struct arg_item *item;
663 size_t tok_len;
664 struct list_head *pos;
665
666 if (separator_pos != -1) {
667 strbuf_add(tok, trailer, separator_pos);
668 strbuf_trim(tok);
669 strbuf_addstr(val, trailer + separator_pos + 1);
670 strbuf_trim(val);
671 } else {
672 strbuf_addstr(tok, trailer);
673 strbuf_trim(tok);
674 }
675
676 /* Lookup if the token matches something in the config */
677 tok_len = token_len_without_separator(tok->buf, tok->len);
678 if (conf)
679 *conf = &default_conf_info;
680 list_for_each(pos, &conf_head) {
681 item = list_entry(pos, struct arg_item, list);
682 if (token_matches_item(tok->buf, item, tok_len)) {
683 char *tok_buf = strbuf_detach(tok, NULL);
684 if (conf)
685 *conf = &item->conf;
686 strbuf_addstr(tok, token_from_item(item, tok_buf));
687 free(tok_buf);
688 break;
689 }
690 }
691 }
692
693 static struct trailer_item *add_trailer_item(struct list_head *head, char *tok,
694 char *val)
695 {
696 struct trailer_item *new_item = xcalloc(1, sizeof(*new_item));
697 new_item->token = tok;
698 new_item->value = val;
699 list_add_tail(&new_item->list, head);
700 return new_item;
701 }
702
703 static void add_arg_item(struct list_head *arg_head, char *tok, char *val,
704 const struct conf_info *conf,
705 const struct new_trailer_item *new_trailer_item)
706 {
707 struct arg_item *new_item = xcalloc(1, sizeof(*new_item));
708 new_item->token = tok;
709 new_item->value = val;
710 duplicate_conf(&new_item->conf, conf);
711 if (new_trailer_item) {
712 if (new_trailer_item->where != WHERE_DEFAULT)
713 new_item->conf.where = new_trailer_item->where;
714 if (new_trailer_item->if_exists != EXISTS_DEFAULT)
715 new_item->conf.if_exists = new_trailer_item->if_exists;
716 if (new_trailer_item->if_missing != MISSING_DEFAULT)
717 new_item->conf.if_missing = new_trailer_item->if_missing;
718 }
719 list_add_tail(&new_item->list, arg_head);
720 }
721
722 static void parse_trailers_from_config(struct list_head *config_head)
723 {
724 struct arg_item *item;
725 struct list_head *pos;
726
727 /* Add an arg item for each configured trailer with a command */
728 list_for_each(pos, &conf_head) {
729 item = list_entry(pos, struct arg_item, list);
730 if (item->conf.command)
731 add_arg_item(config_head,
732 xstrdup(token_from_item(item, NULL)),
733 xstrdup(""),
734 &item->conf, NULL);
735 }
736 }
737
738 static void parse_trailers_from_command_line_args(struct list_head *arg_head,
739 struct list_head *new_trailer_head)
740 {
741 struct strbuf tok = STRBUF_INIT;
742 struct strbuf val = STRBUF_INIT;
743 const struct conf_info *conf;
744 struct list_head *pos;
745
746 /*
747 * In command-line arguments, '=' is accepted (in addition to the
748 * separators that are defined).
749 */
750 char *cl_separators = xstrfmt("=%s", separators);
751
752 /* Add an arg item for each trailer on the command line */
753 list_for_each(pos, new_trailer_head) {
754 struct new_trailer_item *tr =
755 list_entry(pos, struct new_trailer_item, list);
756 ssize_t separator_pos = find_separator(tr->text, cl_separators);
757
758 if (separator_pos == 0) {
759 struct strbuf sb = STRBUF_INIT;
760 strbuf_addstr(&sb, tr->text);
761 strbuf_trim(&sb);
762 error(_("empty trailer token in trailer '%.*s'"),
763 (int) sb.len, sb.buf);
764 strbuf_release(&sb);
765 } else {
766 parse_trailer(&tok, &val, &conf, tr->text,
767 separator_pos);
768 add_arg_item(arg_head,
769 strbuf_detach(&tok, NULL),
770 strbuf_detach(&val, NULL),
771 conf, tr);
772 }
773 }
774
775 free(cl_separators);
776 }
777
778 static void read_input_file(struct strbuf *sb, const char *file)
779 {
780 if (file) {
781 if (strbuf_read_file(sb, file, 0) < 0)
782 die_errno(_("could not read input file '%s'"), file);
783 } else {
784 if (strbuf_read(sb, fileno(stdin), 0) < 0)
785 die_errno(_("could not read from stdin"));
786 }
787 }
788
789 static const char *next_line(const char *str)
790 {
791 const char *nl = strchrnul(str, '\n');
792 return nl + !!*nl;
793 }
794
795 /*
796 * Return the position of the start of the last line. If len is 0, return -1.
797 */
798 static ssize_t last_line(const char *buf, size_t len)
799 {
800 ssize_t i;
801 if (len == 0)
802 return -1;
803 if (len == 1)
804 return 0;
805 /*
806 * Skip the last character (in addition to the null terminator),
807 * because if the last character is a newline, it is considered as part
808 * of the last line anyway.
809 */
810 i = len - 2;
811
812 for (; i >= 0; i--) {
813 if (buf[i] == '\n')
814 return i + 1;
815 }
816 return 0;
817 }
818
819 /*
820 * Find the end of the log message as an offset from the start of the input
821 * (where callers of this function are interested in looking for a trailers
822 * block in the same input). We have to consider two categories of content that
823 * can come at the end of the input which we want to ignore (because they don't
824 * belong in the log message):
825 *
826 * (1) the "patch part" which begins with a "---" divider and has patch
827 * information (like the output of git-format-patch), and
828 *
829 * (2) any trailing comment lines, blank lines like in the output of "git
830 * commit -v", or stuff below the "cut" (scissor) line.
831 *
832 * As a formula, the situation looks like this:
833 *
834 * INPUT = LOG MESSAGE + IGNORED
835 *
836 * where IGNORED can be either of the two categories described above. It may be
837 * that there is nothing to ignore. Now it may be the case that the LOG MESSAGE
838 * contains a trailer block, but that's not the concern of this function.
839 */
840 static size_t find_end_of_log_message(const char *input, int no_divider)
841 {
842 size_t end;
843 const char *s;
844
845 /* Assume the naive end of the input is already what we want. */
846 end = strlen(input);
847
848 if (no_divider)
849 return end;
850
851 /* Optionally skip over any patch part ("---" line and below). */
852 for (s = input; *s; s = next_line(s)) {
853 const char *v;
854
855 if (skip_prefix(s, "---", &v) && isspace(*v)) {
856 end = s - input;
857 break;
858 }
859 }
860
861 /* Skip over other ignorable bits. */
862 return end - ignored_log_message_bytes(input, end);
863 }
864
865 /*
866 * Return the position of the first trailer line or len if there are no
867 * trailers.
868 */
869 static size_t find_trailer_block_start(const char *buf, size_t len)
870 {
871 const char *s;
872 ssize_t end_of_title, l;
873 int only_spaces = 1;
874 int recognized_prefix = 0, trailer_lines = 0, non_trailer_lines = 0;
875 /*
876 * Number of possible continuation lines encountered. This will be
877 * reset to 0 if we encounter a trailer (since those lines are to be
878 * considered continuations of that trailer), and added to
879 * non_trailer_lines if we encounter a non-trailer (since those lines
880 * are to be considered non-trailers).
881 */
882 int possible_continuation_lines = 0;
883
884 /* The first paragraph is the title and cannot be trailers */
885 for (s = buf; s < buf + len; s = next_line(s)) {
886 if (s[0] == comment_line_char)
887 continue;
888 if (is_blank_line(s))
889 break;
890 }
891 end_of_title = s - buf;
892
893 /*
894 * Get the start of the trailers by looking starting from the end for a
895 * blank line before a set of non-blank lines that (i) are all
896 * trailers, or (ii) contains at least one Git-generated trailer and
897 * consists of at least 25% trailers.
898 */
899 for (l = last_line(buf, len);
900 l >= end_of_title;
901 l = last_line(buf, l)) {
902 const char *bol = buf + l;
903 const char **p;
904 ssize_t separator_pos;
905
906 if (bol[0] == comment_line_char) {
907 non_trailer_lines += possible_continuation_lines;
908 possible_continuation_lines = 0;
909 continue;
910 }
911 if (is_blank_line(bol)) {
912 if (only_spaces)
913 continue;
914 non_trailer_lines += possible_continuation_lines;
915 if (recognized_prefix &&
916 trailer_lines * 3 >= non_trailer_lines)
917 return next_line(bol) - buf;
918 else if (trailer_lines && !non_trailer_lines)
919 return next_line(bol) - buf;
920 return len;
921 }
922 only_spaces = 0;
923
924 for (p = git_generated_prefixes; *p; p++) {
925 if (starts_with(bol, *p)) {
926 trailer_lines++;
927 possible_continuation_lines = 0;
928 recognized_prefix = 1;
929 goto continue_outer_loop;
930 }
931 }
932
933 separator_pos = find_separator(bol, separators);
934 if (separator_pos >= 1 && !isspace(bol[0])) {
935 struct list_head *pos;
936
937 trailer_lines++;
938 possible_continuation_lines = 0;
939 if (recognized_prefix)
940 continue;
941 list_for_each(pos, &conf_head) {
942 struct arg_item *item;
943 item = list_entry(pos, struct arg_item, list);
944 if (token_matches_item(bol, item,
945 separator_pos)) {
946 recognized_prefix = 1;
947 break;
948 }
949 }
950 } else if (isspace(bol[0]))
951 possible_continuation_lines++;
952 else {
953 non_trailer_lines++;
954 non_trailer_lines += possible_continuation_lines;
955 possible_continuation_lines = 0;
956 }
957 continue_outer_loop:
958 ;
959 }
960
961 return len;
962 }
963
964 static int ends_with_blank_line(const char *buf, size_t len)
965 {
966 ssize_t ll = last_line(buf, len);
967 if (ll < 0)
968 return 0;
969 return is_blank_line(buf + ll);
970 }
971
972 static void unfold_value(struct strbuf *val)
973 {
974 struct strbuf out = STRBUF_INIT;
975 size_t i;
976
977 strbuf_grow(&out, val->len);
978 i = 0;
979 while (i < val->len) {
980 char c = val->buf[i++];
981 if (c == '\n') {
982 /* Collapse continuation down to a single space. */
983 while (i < val->len && isspace(val->buf[i]))
984 i++;
985 strbuf_addch(&out, ' ');
986 } else {
987 strbuf_addch(&out, c);
988 }
989 }
990
991 /* Empty lines may have left us with whitespace cruft at the edges */
992 strbuf_trim(&out);
993
994 /* output goes back to val as if we modified it in-place */
995 strbuf_swap(&out, val);
996 strbuf_release(&out);
997 }
998
999 /*
1000 * Parse trailers in "str", populating the trailer info and "head"
1001 * linked list structure.
1002 */
1003 static void parse_trailers(struct trailer_info *info,
1004 const char *str,
1005 struct list_head *head,
1006 const struct process_trailer_options *opts)
1007 {
1008 struct strbuf tok = STRBUF_INIT;
1009 struct strbuf val = STRBUF_INIT;
1010 size_t i;
1011
1012 trailer_info_get(info, str, opts);
1013
1014 for (i = 0; i < info->trailer_nr; i++) {
1015 int separator_pos;
1016 char *trailer = info->trailers[i];
1017 if (trailer[0] == comment_line_char)
1018 continue;
1019 separator_pos = find_separator(trailer, separators);
1020 if (separator_pos >= 1) {
1021 parse_trailer(&tok, &val, NULL, trailer,
1022 separator_pos);
1023 if (opts->unfold)
1024 unfold_value(&val);
1025 add_trailer_item(head,
1026 strbuf_detach(&tok, NULL),
1027 strbuf_detach(&val, NULL));
1028 } else if (!opts->only_trailers) {
1029 strbuf_addstr(&val, trailer);
1030 strbuf_strip_suffix(&val, "\n");
1031 add_trailer_item(head,
1032 NULL,
1033 strbuf_detach(&val, NULL));
1034 }
1035 }
1036 }
1037
1038 static void free_all(struct list_head *head)
1039 {
1040 struct list_head *pos, *p;
1041 list_for_each_safe(pos, p, head) {
1042 list_del(pos);
1043 free_trailer_item(list_entry(pos, struct trailer_item, list));
1044 }
1045 }
1046
1047 static struct tempfile *trailers_tempfile;
1048
1049 static FILE *create_in_place_tempfile(const char *file)
1050 {
1051 struct stat st;
1052 struct strbuf filename_template = STRBUF_INIT;
1053 const char *tail;
1054 FILE *outfile;
1055
1056 if (stat(file, &st))
1057 die_errno(_("could not stat %s"), file);
1058 if (!S_ISREG(st.st_mode))
1059 die(_("file %s is not a regular file"), file);
1060 if (!(st.st_mode & S_IWUSR))
1061 die(_("file %s is not writable by user"), file);
1062
1063 /* Create temporary file in the same directory as the original */
1064 tail = strrchr(file, '/');
1065 if (tail)
1066 strbuf_add(&filename_template, file, tail - file + 1);
1067 strbuf_addstr(&filename_template, "git-interpret-trailers-XXXXXX");
1068
1069 trailers_tempfile = xmks_tempfile_m(filename_template.buf, st.st_mode);
1070 strbuf_release(&filename_template);
1071 outfile = fdopen_tempfile(trailers_tempfile, "w");
1072 if (!outfile)
1073 die_errno(_("could not open temporary file"));
1074
1075 return outfile;
1076 }
1077
1078 void process_trailers(const char *file,
1079 const struct process_trailer_options *opts,
1080 struct list_head *new_trailer_head)
1081 {
1082 LIST_HEAD(head);
1083 struct strbuf sb = STRBUF_INIT;
1084 struct trailer_info info;
1085 FILE *outfile = stdout;
1086
1087 ensure_configured();
1088
1089 read_input_file(&sb, file);
1090
1091 if (opts->in_place)
1092 outfile = create_in_place_tempfile(file);
1093
1094 parse_trailers(&info, sb.buf, &head, opts);
1095
1096 /* Print the lines before the trailers */
1097 if (!opts->only_trailers)
1098 fwrite(sb.buf, 1, info.trailer_block_start, outfile);
1099
1100 if (!opts->only_trailers && !info.blank_line_before_trailer)
1101 fprintf(outfile, "\n");
1102
1103
1104 if (!opts->only_input) {
1105 LIST_HEAD(config_head);
1106 LIST_HEAD(arg_head);
1107 parse_trailers_from_config(&config_head);
1108 parse_trailers_from_command_line_args(&arg_head, new_trailer_head);
1109 list_splice(&config_head, &arg_head);
1110 process_trailers_lists(&head, &arg_head);
1111 }
1112
1113 print_all(outfile, &head, opts);
1114
1115 free_all(&head);
1116 trailer_info_release(&info);
1117
1118 /* Print the lines after the trailers as is */
1119 if (!opts->only_trailers)
1120 fwrite(sb.buf + info.trailer_block_end, 1, sb.len - info.trailer_block_end, outfile);
1121
1122 if (opts->in_place)
1123 if (rename_tempfile(&trailers_tempfile, file))
1124 die_errno(_("could not rename temporary file to %s"), file);
1125
1126 strbuf_release(&sb);
1127 }
1128
1129 void trailer_info_get(struct trailer_info *info, const char *str,
1130 const struct process_trailer_options *opts)
1131 {
1132 size_t end_of_log_message = 0, trailer_block_start = 0;
1133 struct strbuf **trailer_lines, **ptr;
1134 char **trailer_strings = NULL;
1135 size_t nr = 0, alloc = 0;
1136 char **last = NULL;
1137
1138 ensure_configured();
1139
1140 end_of_log_message = find_end_of_log_message(str, opts->no_divider);
1141 trailer_block_start = find_trailer_block_start(str, end_of_log_message);
1142
1143 trailer_lines = strbuf_split_buf(str + trailer_block_start,
1144 end_of_log_message - trailer_block_start,
1145 '\n',
1146 0);
1147 for (ptr = trailer_lines; *ptr; ptr++) {
1148 if (last && isspace((*ptr)->buf[0])) {
1149 struct strbuf sb = STRBUF_INIT;
1150 strbuf_attach(&sb, *last, strlen(*last), strlen(*last));
1151 strbuf_addbuf(&sb, *ptr);
1152 *last = strbuf_detach(&sb, NULL);
1153 continue;
1154 }
1155 ALLOC_GROW(trailer_strings, nr + 1, alloc);
1156 trailer_strings[nr] = strbuf_detach(*ptr, NULL);
1157 last = find_separator(trailer_strings[nr], separators) >= 1
1158 ? &trailer_strings[nr]
1159 : NULL;
1160 nr++;
1161 }
1162 strbuf_list_free(trailer_lines);
1163
1164 info->blank_line_before_trailer = ends_with_blank_line(str,
1165 trailer_block_start);
1166 info->trailer_block_start = trailer_block_start;
1167 info->trailer_block_end = end_of_log_message;
1168 info->trailers = trailer_strings;
1169 info->trailer_nr = nr;
1170 }
1171
1172 void trailer_info_release(struct trailer_info *info)
1173 {
1174 size_t i;
1175 for (i = 0; i < info->trailer_nr; i++)
1176 free(info->trailers[i]);
1177 free(info->trailers);
1178 }
1179
1180 static void format_trailer_info(struct strbuf *out,
1181 const struct trailer_info *info,
1182 const char *msg,
1183 const struct process_trailer_options *opts)
1184 {
1185 size_t origlen = out->len;
1186 size_t i;
1187
1188 /* If we want the whole block untouched, we can take the fast path. */
1189 if (!opts->only_trailers && !opts->unfold && !opts->filter &&
1190 !opts->separator && !opts->key_only && !opts->value_only &&
1191 !opts->key_value_separator) {
1192 strbuf_add(out, msg + info->trailer_block_start,
1193 info->trailer_block_end - info->trailer_block_start);
1194 return;
1195 }
1196
1197 for (i = 0; i < info->trailer_nr; i++) {
1198 char *trailer = info->trailers[i];
1199 ssize_t separator_pos = find_separator(trailer, separators);
1200
1201 if (separator_pos >= 1) {
1202 struct strbuf tok = STRBUF_INIT;
1203 struct strbuf val = STRBUF_INIT;
1204
1205 parse_trailer(&tok, &val, NULL, trailer, separator_pos);
1206 if (!opts->filter || opts->filter(&tok, opts->filter_data)) {
1207 if (opts->unfold)
1208 unfold_value(&val);
1209
1210 if (opts->separator && out->len != origlen)
1211 strbuf_addbuf(out, opts->separator);
1212 if (!opts->value_only)
1213 strbuf_addbuf(out, &tok);
1214 if (!opts->key_only && !opts->value_only) {
1215 if (opts->key_value_separator)
1216 strbuf_addbuf(out, opts->key_value_separator);
1217 else
1218 strbuf_addstr(out, ": ");
1219 }
1220 if (!opts->key_only)
1221 strbuf_addbuf(out, &val);
1222 if (!opts->separator)
1223 strbuf_addch(out, '\n');
1224 }
1225 strbuf_release(&tok);
1226 strbuf_release(&val);
1227
1228 } else if (!opts->only_trailers) {
1229 if (opts->separator && out->len != origlen) {
1230 strbuf_addbuf(out, opts->separator);
1231 }
1232 strbuf_addstr(out, trailer);
1233 if (opts->separator) {
1234 strbuf_rtrim(out);
1235 }
1236 }
1237 }
1238
1239 }
1240
1241 void format_trailers_from_commit(struct strbuf *out, const char *msg,
1242 const struct process_trailer_options *opts)
1243 {
1244 struct trailer_info info;
1245
1246 trailer_info_get(&info, msg, opts);
1247 format_trailer_info(out, &info, msg, opts);
1248 trailer_info_release(&info);
1249 }
1250
1251 void trailer_iterator_init(struct trailer_iterator *iter, const char *msg)
1252 {
1253 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
1254 strbuf_init(&iter->key, 0);
1255 strbuf_init(&iter->val, 0);
1256 opts.no_divider = 1;
1257 trailer_info_get(&iter->internal.info, msg, &opts);
1258 iter->internal.cur = 0;
1259 }
1260
1261 int trailer_iterator_advance(struct trailer_iterator *iter)
1262 {
1263 while (iter->internal.cur < iter->internal.info.trailer_nr) {
1264 char *trailer = iter->internal.info.trailers[iter->internal.cur++];
1265 int separator_pos = find_separator(trailer, separators);
1266
1267 if (separator_pos < 1)
1268 continue; /* not a real trailer */
1269
1270 strbuf_reset(&iter->key);
1271 strbuf_reset(&iter->val);
1272 parse_trailer(&iter->key, &iter->val, NULL,
1273 trailer, separator_pos);
1274 unfold_value(&iter->val);
1275 return 1;
1276 }
1277 return 0;
1278 }
1279
1280 void trailer_iterator_release(struct trailer_iterator *iter)
1281 {
1282 trailer_info_release(&iter->internal.info);
1283 strbuf_release(&iter->val);
1284 strbuf_release(&iter->key);
1285 }