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