trailer: avoid unnecessary splitting on lines
[git/git.git] / trailer.c
CommitLineData
9385b5d7 1#include "cache.h"
f0a90b4e 2#include "string-list.h"
85039fb6 3#include "run-command.h"
61cfef4c 4#include "commit.h"
e1f89863 5#include "tempfile.h"
b1d78d77 6#include "trailer.h"
8966a394 7#include "list.h"
9385b5d7
CC
8/*
9 * Copyright (c) 2013, 2014 Christian Couder <chriscool@tuxfamily.org>
10 */
11
12enum action_where { WHERE_END, WHERE_AFTER, WHERE_BEFORE, WHERE_START };
13enum action_if_exists { EXISTS_ADD_IF_DIFFERENT_NEIGHBOR, EXISTS_ADD_IF_DIFFERENT,
14 EXISTS_ADD, EXISTS_REPLACE, EXISTS_DO_NOTHING };
15enum action_if_missing { MISSING_ADD, MISSING_DO_NOTHING };
16
17struct conf_info {
18 char *name;
19 char *key;
20 char *command;
21 enum action_where where;
22 enum action_if_exists if_exists;
23 enum action_if_missing if_missing;
24};
25
26static struct conf_info default_conf_info;
27
28struct trailer_item {
8966a394 29 struct list_head list;
14624506
JT
30 /*
31 * If this is not a trailer line, the line is stored in value
32 * (excluding the terminating newline) and token is NULL.
33 */
d65fd424
JT
34 char *token;
35 char *value;
cc71b0de
JT
36};
37
38struct arg_item {
39 struct list_head list;
40 char *token;
41 char *value;
9385b5d7
CC
42 struct conf_info conf;
43};
44
8966a394 45static LIST_HEAD(conf_head);
9385b5d7
CC
46
47static char *separators = ":";
48
85039fb6
CC
49#define TRAILER_ARG_STRING "$ARG"
50
14624506
JT
51static const char *git_generated_prefixes[] = {
52 "Signed-off-by: ",
53 "(cherry picked from commit ",
54 NULL
55};
56
8966a394
JT
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
9385b5d7
CC
63static int after_or_end(enum action_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 */
74static 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
cc71b0de 81static int same_token(struct trailer_item *a, struct arg_item *b)
9385b5d7 82{
14624506
JT
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;
9385b5d7
CC
91
92 return !strncasecmp(a->token, b->token, min_len);
93}
94
cc71b0de 95static int same_value(struct trailer_item *a, struct arg_item *b)
9385b5d7
CC
96{
97 return !strcasecmp(a->value, b->value);
98}
99
cc71b0de 100static int same_trailer(struct trailer_item *a, struct arg_item *b)
9385b5d7
CC
101{
102 return same_token(a, b) && same_value(a, b);
103}
4103818d 104
022349c3 105static inline int is_blank_line(const char *str)
2013d850
CC
106{
107 const char *s = str;
022349c3 108 while (*s && *s != '\n' && isspace(*s))
2013d850 109 s++;
022349c3 110 return !*s || *s == '\n';
2013d850
CC
111}
112
85039fb6
CC
113static 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
4103818d 120static void free_trailer_item(struct trailer_item *item)
cc71b0de
JT
121{
122 free(item->token);
123 free(item->value);
124 free(item);
125}
126
127static void free_arg_item(struct arg_item *item)
4103818d
CC
128{
129 free(item->conf.name);
130 free(item->conf.key);
131 free(item->conf.command);
d65fd424
JT
132 free(item->token);
133 free(item->value);
4103818d
CC
134 free(item);
135}
136
b1d78d77
CC
137static char last_non_space_char(const char *s)
138{
139 int i;
140 for (i = strlen(s) - 1; i >= 0; i--)
141 if (!isspace(s[i]))
142 return s[i];
143 return '\0';
144}
145
d0d2344a 146static void print_tok_val(FILE *outfile, const char *tok, const char *val)
b1d78d77 147{
14624506
JT
148 char c;
149
150 if (!tok) {
151 fprintf(outfile, "%s\n", val);
152 return;
153 }
154
155 c = last_non_space_char(tok);
b1d78d77
CC
156 if (!c)
157 return;
158 if (strchr(separators, c))
d0d2344a 159 fprintf(outfile, "%s%s\n", tok, val);
b1d78d77 160 else
d0d2344a 161 fprintf(outfile, "%s%c %s\n", tok, separators[0], val);
b1d78d77
CC
162}
163
8966a394 164static void print_all(FILE *outfile, struct list_head *head, int trim_empty)
b1d78d77 165{
8966a394 166 struct list_head *pos;
b1d78d77 167 struct trailer_item *item;
8966a394
JT
168 list_for_each(pos, head) {
169 item = list_entry(pos, struct trailer_item, list);
b1d78d77 170 if (!trim_empty || strlen(item->value) > 0)
d0d2344a 171 print_tok_val(outfile, item->token, item->value);
b1d78d77
CC
172 }
173}
174
cc71b0de 175static struct trailer_item *trailer_from_arg(struct arg_item *arg_tok)
4103818d 176{
cc71b0de
JT
177 struct trailer_item *new = xcalloc(sizeof(*new), 1);
178 new->token = arg_tok->token;
179 new->value = arg_tok->value;
180 arg_tok->token = arg_tok->value = NULL;
181 free_arg_item(arg_tok);
182 return new;
4103818d
CC
183}
184
185static void add_arg_to_input_list(struct trailer_item *on_tok,
cc71b0de 186 struct arg_item *arg_tok)
8966a394 187{
cc71b0de
JT
188 int aoe = after_or_end(arg_tok->conf.where);
189 struct trailer_item *to_add = trailer_from_arg(arg_tok);
190 if (aoe)
191 list_add(&to_add->list, &on_tok->list);
8966a394 192 else
cc71b0de 193 list_add_tail(&to_add->list, &on_tok->list);
4103818d
CC
194}
195
196static int check_if_different(struct trailer_item *in_tok,
cc71b0de 197 struct arg_item *arg_tok,
8966a394
JT
198 int check_all,
199 struct list_head *head)
4103818d
CC
200{
201 enum action_where where = arg_tok->conf.where;
8966a394 202 struct list_head *next_head;
4103818d 203 do {
4103818d
CC
204 if (same_trailer(in_tok, arg_tok))
205 return 0;
206 /*
207 * if we want to add a trailer after another one,
208 * we have to check those before this one
209 */
8966a394
JT
210 next_head = after_or_end(where) ? in_tok->list.prev
211 : in_tok->list.next;
212 if (next_head == head)
213 break;
214 in_tok = list_entry(next_head, struct trailer_item, list);
4103818d
CC
215 } while (check_all);
216 return 1;
217}
218
d65fd424 219static char *apply_command(const char *command, const char *arg)
85039fb6
CC
220{
221 struct strbuf cmd = STRBUF_INIT;
222 struct strbuf buf = STRBUF_INIT;
b226293b 223 struct child_process cp = CHILD_PROCESS_INIT;
85039fb6 224 const char *argv[] = {NULL, NULL};
d65fd424 225 char *result;
85039fb6
CC
226
227 strbuf_addstr(&cmd, command);
228 if (arg)
229 strbuf_replace(&cmd, TRAILER_ARG_STRING, arg);
230
231 argv[0] = cmd.buf;
85039fb6
CC
232 cp.argv = argv;
233 cp.env = local_repo_env;
234 cp.no_stdin = 1;
85039fb6
CC
235 cp.use_shell = 1;
236
c5eadcaa 237 if (capture_command(&cp, &buf, 1024)) {
13ad56f8 238 error(_("running trailer command '%s' failed"), cmd.buf);
85039fb6
CC
239 strbuf_release(&buf);
240 result = xstrdup("");
c5eadcaa
JK
241 } else {
242 strbuf_trim(&buf);
85039fb6 243 result = strbuf_detach(&buf, NULL);
c5eadcaa 244 }
85039fb6
CC
245
246 strbuf_release(&cmd);
247 return result;
248}
249
cc71b0de 250static void apply_item_command(struct trailer_item *in_tok, struct arg_item *arg_tok)
85039fb6
CC
251{
252 if (arg_tok->conf.command) {
253 const char *arg;
254 if (arg_tok->value && arg_tok->value[0]) {
255 arg = arg_tok->value;
256 } else {
257 if (in_tok && in_tok->value)
258 arg = xstrdup(in_tok->value);
259 else
260 arg = xstrdup("");
261 }
262 arg_tok->value = apply_command(arg_tok->conf.command, arg);
263 free((char *)arg);
264 }
265}
266
4103818d 267static void apply_arg_if_exists(struct trailer_item *in_tok,
cc71b0de 268 struct arg_item *arg_tok,
4103818d 269 struct trailer_item *on_tok,
8966a394 270 struct list_head *head)
4103818d
CC
271{
272 switch (arg_tok->conf.if_exists) {
273 case EXISTS_DO_NOTHING:
cc71b0de 274 free_arg_item(arg_tok);
4103818d
CC
275 break;
276 case EXISTS_REPLACE:
85039fb6 277 apply_item_command(in_tok, arg_tok);
8966a394
JT
278 add_arg_to_input_list(on_tok, arg_tok);
279 list_del(&in_tok->list);
4103818d
CC
280 free_trailer_item(in_tok);
281 break;
282 case EXISTS_ADD:
85039fb6 283 apply_item_command(in_tok, arg_tok);
8966a394 284 add_arg_to_input_list(on_tok, arg_tok);
4103818d
CC
285 break;
286 case EXISTS_ADD_IF_DIFFERENT:
85039fb6 287 apply_item_command(in_tok, arg_tok);
8966a394
JT
288 if (check_if_different(in_tok, arg_tok, 1, head))
289 add_arg_to_input_list(on_tok, arg_tok);
4103818d 290 else
cc71b0de 291 free_arg_item(arg_tok);
4103818d
CC
292 break;
293 case EXISTS_ADD_IF_DIFFERENT_NEIGHBOR:
85039fb6 294 apply_item_command(in_tok, arg_tok);
8966a394
JT
295 if (check_if_different(on_tok, arg_tok, 0, head))
296 add_arg_to_input_list(on_tok, arg_tok);
4103818d 297 else
cc71b0de 298 free_arg_item(arg_tok);
4103818d
CC
299 break;
300 }
301}
302
8966a394 303static void apply_arg_if_missing(struct list_head *head,
cc71b0de 304 struct arg_item *arg_tok)
4103818d 305{
4103818d 306 enum action_where where;
cc71b0de 307 struct trailer_item *to_add;
4103818d
CC
308
309 switch (arg_tok->conf.if_missing) {
310 case MISSING_DO_NOTHING:
cc71b0de 311 free_arg_item(arg_tok);
4103818d
CC
312 break;
313 case MISSING_ADD:
314 where = arg_tok->conf.where;
85039fb6 315 apply_item_command(NULL, arg_tok);
cc71b0de 316 to_add = trailer_from_arg(arg_tok);
8966a394 317 if (after_or_end(where))
cc71b0de 318 list_add_tail(&to_add->list, head);
8966a394 319 else
cc71b0de 320 list_add(&to_add->list, head);
4103818d
CC
321 }
322}
323
8966a394 324static int find_same_and_apply_arg(struct list_head *head,
cc71b0de 325 struct arg_item *arg_tok)
4103818d 326{
8966a394 327 struct list_head *pos;
4103818d
CC
328 struct trailer_item *in_tok;
329 struct trailer_item *on_tok;
4103818d
CC
330
331 enum action_where where = arg_tok->conf.where;
332 int middle = (where == WHERE_AFTER) || (where == WHERE_BEFORE);
333 int backwards = after_or_end(where);
8966a394 334 struct trailer_item *start_tok;
4103818d 335
8966a394
JT
336 if (list_empty(head))
337 return 0;
4103818d 338
8966a394
JT
339 start_tok = list_entry(backwards ? head->prev : head->next,
340 struct trailer_item,
341 list);
342
343 list_for_each_dir(pos, head, backwards) {
344 in_tok = list_entry(pos, struct trailer_item, list);
4103818d
CC
345 if (!same_token(in_tok, arg_tok))
346 continue;
347 on_tok = middle ? in_tok : start_tok;
8966a394 348 apply_arg_if_exists(in_tok, arg_tok, on_tok, head);
4103818d
CC
349 return 1;
350 }
351 return 0;
352}
353
8966a394
JT
354static void process_trailers_lists(struct list_head *head,
355 struct list_head *arg_head)
4103818d 356{
8966a394 357 struct list_head *pos, *p;
cc71b0de 358 struct arg_item *arg_tok;
4103818d 359
8966a394 360 list_for_each_safe(pos, p, arg_head) {
4103818d 361 int applied = 0;
cc71b0de 362 arg_tok = list_entry(pos, struct arg_item, list);
4103818d 363
8966a394 364 list_del(pos);
4103818d 365
8966a394 366 applied = find_same_and_apply_arg(head, arg_tok);
4103818d
CC
367
368 if (!applied)
8966a394 369 apply_arg_if_missing(head, arg_tok);
4103818d
CC
370 }
371}
46a0613f
CC
372
373static int set_where(struct conf_info *item, const char *value)
374{
375 if (!strcasecmp("after", value))
376 item->where = WHERE_AFTER;
377 else if (!strcasecmp("before", value))
378 item->where = WHERE_BEFORE;
379 else if (!strcasecmp("end", value))
380 item->where = WHERE_END;
381 else if (!strcasecmp("start", value))
382 item->where = WHERE_START;
383 else
384 return -1;
385 return 0;
386}
387
388static int set_if_exists(struct conf_info *item, const char *value)
389{
390 if (!strcasecmp("addIfDifferent", value))
391 item->if_exists = EXISTS_ADD_IF_DIFFERENT;
392 else if (!strcasecmp("addIfDifferentNeighbor", value))
393 item->if_exists = EXISTS_ADD_IF_DIFFERENT_NEIGHBOR;
394 else if (!strcasecmp("add", value))
395 item->if_exists = EXISTS_ADD;
396 else if (!strcasecmp("replace", value))
397 item->if_exists = EXISTS_REPLACE;
398 else if (!strcasecmp("doNothing", value))
399 item->if_exists = EXISTS_DO_NOTHING;
400 else
401 return -1;
402 return 0;
403}
404
405static int set_if_missing(struct conf_info *item, const char *value)
406{
407 if (!strcasecmp("doNothing", value))
408 item->if_missing = MISSING_DO_NOTHING;
409 else if (!strcasecmp("add", value))
410 item->if_missing = MISSING_ADD;
411 else
412 return -1;
413 return 0;
414}
415
d65fd424 416static void duplicate_conf(struct conf_info *dst, const struct conf_info *src)
46a0613f
CC
417{
418 *dst = *src;
13092a91
JH
419 dst->name = xstrdup_or_null(src->name);
420 dst->key = xstrdup_or_null(src->key);
421 dst->command = xstrdup_or_null(src->command);
46a0613f
CC
422}
423
cc71b0de 424static struct arg_item *get_conf_item(const char *name)
46a0613f 425{
8966a394 426 struct list_head *pos;
cc71b0de 427 struct arg_item *item;
46a0613f
CC
428
429 /* Look up item with same name */
8966a394 430 list_for_each(pos, &conf_head) {
cc71b0de 431 item = list_entry(pos, struct arg_item, list);
46a0613f
CC
432 if (!strcasecmp(item->conf.name, name))
433 return item;
434 }
435
436 /* Item does not already exists, create it */
cc71b0de 437 item = xcalloc(sizeof(*item), 1);
46a0613f
CC
438 duplicate_conf(&item->conf, &default_conf_info);
439 item->conf.name = xstrdup(name);
440
8966a394 441 list_add_tail(&item->list, &conf_head);
46a0613f
CC
442
443 return item;
444}
445
446enum trailer_info_type { TRAILER_KEY, TRAILER_COMMAND, TRAILER_WHERE,
447 TRAILER_IF_EXISTS, TRAILER_IF_MISSING };
448
449static struct {
450 const char *name;
451 enum trailer_info_type type;
452} trailer_config_items[] = {
453 { "key", TRAILER_KEY },
454 { "command", TRAILER_COMMAND },
455 { "where", TRAILER_WHERE },
456 { "ifexists", TRAILER_IF_EXISTS },
457 { "ifmissing", TRAILER_IF_MISSING }
458};
459
460static int git_trailer_default_config(const char *conf_key, const char *value, void *cb)
461{
462 const char *trailer_item, *variable_name;
463
464 if (!skip_prefix(conf_key, "trailer.", &trailer_item))
465 return 0;
466
467 variable_name = strrchr(trailer_item, '.');
468 if (!variable_name) {
469 if (!strcmp(trailer_item, "where")) {
470 if (set_where(&default_conf_info, value) < 0)
471 warning(_("unknown value '%s' for key '%s'"),
472 value, conf_key);
473 } else if (!strcmp(trailer_item, "ifexists")) {
474 if (set_if_exists(&default_conf_info, value) < 0)
475 warning(_("unknown value '%s' for key '%s'"),
476 value, conf_key);
477 } else if (!strcmp(trailer_item, "ifmissing")) {
478 if (set_if_missing(&default_conf_info, value) < 0)
479 warning(_("unknown value '%s' for key '%s'"),
480 value, conf_key);
481 } else if (!strcmp(trailer_item, "separators")) {
482 separators = xstrdup(value);
483 }
484 }
485 return 0;
486}
487
488static int git_trailer_config(const char *conf_key, const char *value, void *cb)
489{
490 const char *trailer_item, *variable_name;
cc71b0de 491 struct arg_item *item;
46a0613f
CC
492 struct conf_info *conf;
493 char *name = NULL;
494 enum trailer_info_type type;
495 int i;
496
497 if (!skip_prefix(conf_key, "trailer.", &trailer_item))
498 return 0;
499
500 variable_name = strrchr(trailer_item, '.');
501 if (!variable_name)
502 return 0;
503
504 variable_name++;
505 for (i = 0; i < ARRAY_SIZE(trailer_config_items); i++) {
506 if (strcmp(trailer_config_items[i].name, variable_name))
507 continue;
508 name = xstrndup(trailer_item, variable_name - trailer_item - 1);
509 type = trailer_config_items[i].type;
510 break;
511 }
512
513 if (!name)
514 return 0;
515
516 item = get_conf_item(name);
517 conf = &item->conf;
518 free(name);
519
520 switch (type) {
521 case TRAILER_KEY:
522 if (conf->key)
523 warning(_("more than one %s"), conf_key);
524 conf->key = xstrdup(value);
525 break;
526 case TRAILER_COMMAND:
527 if (conf->command)
528 warning(_("more than one %s"), conf_key);
529 conf->command = xstrdup(value);
530 break;
531 case TRAILER_WHERE:
532 if (set_where(conf, value))
533 warning(_("unknown value '%s' for key '%s'"), value, conf_key);
534 break;
535 case TRAILER_IF_EXISTS:
536 if (set_if_exists(conf, value))
537 warning(_("unknown value '%s' for key '%s'"), value, conf_key);
538 break;
539 case TRAILER_IF_MISSING:
540 if (set_if_missing(conf, value))
541 warning(_("unknown value '%s' for key '%s'"), value, conf_key);
542 break;
543 default:
ef1177d1 544 die("BUG: trailer.c: unhandled type %d", type);
46a0613f
CC
545 }
546 return 0;
547}
f0a90b4e 548
cc71b0de 549static const char *token_from_item(struct arg_item *item, char *tok)
f0a90b4e
CC
550{
551 if (item->conf.key)
552 return item->conf.key;
553 if (tok)
554 return tok;
555 return item->conf.name;
556}
557
cc71b0de 558static int token_matches_item(const char *tok, struct arg_item *item, int tok_len)
f0a90b4e
CC
559{
560 if (!strncasecmp(tok, item->conf.name, tok_len))
561 return 1;
562 return item->conf.key ? !strncasecmp(tok, item->conf.key, tok_len) : 0;
563}
564
fdbf4510 565/*
e4319562
JT
566 * If the given line is of the form
567 * "<token><optional whitespace><separator>..." or "<separator>...", return the
568 * location of the separator. Otherwise, return -1. The optional whitespace
569 * is allowed there primarily to allow things like "Bug #43" where <token> is
570 * "Bug" and <separator> is "#".
571 *
572 * The separator-starts-line case (in which this function returns 0) is
573 * distinguished from the non-well-formed-line case (in which this function
574 * returns -1) because some callers of this function need such a distinction.
fdbf4510
JT
575 */
576static int find_separator(const char *line, const char *separators)
f0a90b4e 577{
e4319562
JT
578 int whitespace_found = 0;
579 const char *c;
580 for (c = line; *c; c++) {
581 if (strchr(separators, *c))
582 return c - line;
583 if (!whitespace_found && (isalnum(*c) || *c == '-'))
584 continue;
585 if (c != line && (*c == ' ' || *c == '\t')) {
586 whitespace_found = 1;
587 continue;
588 }
589 break;
590 }
591 return -1;
fdbf4510 592}
f0a90b4e 593
fdbf4510
JT
594/*
595 * Obtain the token, value, and conf from the given trailer.
596 *
597 * separator_pos must not be 0, since the token cannot be an empty string.
598 *
599 * If separator_pos is -1, interpret the whole trailer as a token.
600 */
601static void parse_trailer(struct strbuf *tok, struct strbuf *val,
602 const struct conf_info **conf, const char *trailer,
603 int separator_pos)
f0a90b4e 604{
cc71b0de 605 struct arg_item *item;
63ab3f34
JT
606 int tok_len;
607 struct list_head *pos;
f0a90b4e 608
fdbf4510
JT
609 if (separator_pos != -1) {
610 strbuf_add(tok, trailer, separator_pos);
f0a90b4e 611 strbuf_trim(tok);
fdbf4510 612 strbuf_addstr(val, trailer + separator_pos + 1);
f0a90b4e
CC
613 strbuf_trim(val);
614 } else {
615 strbuf_addstr(tok, trailer);
616 strbuf_trim(tok);
617 }
f0a90b4e
CC
618
619 /* Lookup if the token matches something in the config */
63ab3f34 620 tok_len = token_len_without_separator(tok->buf, tok->len);
cc71b0de
JT
621 if (conf)
622 *conf = &default_conf_info;
8966a394 623 list_for_each(pos, &conf_head) {
cc71b0de 624 item = list_entry(pos, struct arg_item, list);
63ab3f34
JT
625 if (token_matches_item(tok->buf, item, tok_len)) {
626 char *tok_buf = strbuf_detach(tok, NULL);
cc71b0de
JT
627 if (conf)
628 *conf = &item->conf;
63ab3f34
JT
629 strbuf_addstr(tok, token_from_item(item, tok_buf));
630 free(tok_buf);
631 break;
632 }
f0a90b4e 633 }
f0a90b4e 634}
f0a90b4e 635
60ef86a1
JT
636static struct trailer_item *add_trailer_item(struct list_head *head, char *tok,
637 char *val)
f0a90b4e 638{
63ab3f34
JT
639 struct trailer_item *new = xcalloc(sizeof(*new), 1);
640 new->token = tok;
641 new->value = val;
8966a394 642 list_add_tail(&new->list, head);
60ef86a1 643 return new;
f0a90b4e
CC
644}
645
cc71b0de
JT
646static void add_arg_item(struct list_head *arg_head, char *tok, char *val,
647 const struct conf_info *conf)
f0a90b4e 648{
cc71b0de
JT
649 struct arg_item *new = xcalloc(sizeof(*new), 1);
650 new->token = tok;
651 new->value = val;
652 duplicate_conf(&new->conf, conf);
653 list_add_tail(&new->list, arg_head);
f0a90b4e
CC
654}
655
8966a394
JT
656static void process_command_line_args(struct list_head *arg_head,
657 struct string_list *trailers)
f0a90b4e 658{
f0a90b4e 659 struct string_list_item *tr;
cc71b0de 660 struct arg_item *item;
63ab3f34
JT
661 struct strbuf tok = STRBUF_INIT;
662 struct strbuf val = STRBUF_INIT;
663 const struct conf_info *conf;
8966a394 664 struct list_head *pos;
85039fb6 665
fdbf4510
JT
666 /*
667 * In command-line arguments, '=' is accepted (in addition to the
668 * separators that are defined).
669 */
670 char *cl_separators = xstrfmt("=%s", separators);
671
cc71b0de 672 /* Add an arg item for each configured trailer with a command */
8966a394 673 list_for_each(pos, &conf_head) {
cc71b0de 674 item = list_entry(pos, struct arg_item, list);
63ab3f34 675 if (item->conf.command)
cc71b0de
JT
676 add_arg_item(arg_head,
677 xstrdup(token_from_item(item, NULL)),
678 xstrdup(""),
679 &item->conf);
85039fb6 680 }
f0a90b4e 681
cc71b0de 682 /* Add an arg item for each trailer on the command line */
f0a90b4e 683 for_each_string_list_item(tr, trailers) {
fdbf4510
JT
684 int separator_pos = find_separator(tr->string, cl_separators);
685 if (separator_pos == 0) {
686 struct strbuf sb = STRBUF_INIT;
687 strbuf_addstr(&sb, tr->string);
688 strbuf_trim(&sb);
689 error(_("empty trailer token in trailer '%.*s'"),
690 (int) sb.len, sb.buf);
691 strbuf_release(&sb);
692 } else {
693 parse_trailer(&tok, &val, &conf, tr->string,
694 separator_pos);
cc71b0de
JT
695 add_arg_item(arg_head,
696 strbuf_detach(&tok, NULL),
697 strbuf_detach(&val, NULL),
698 conf);
fdbf4510 699 }
f0a90b4e
CC
700 }
701
fdbf4510 702 free(cl_separators);
f0a90b4e 703}
2013d850 704
022349c3 705static void read_input_file(struct strbuf *sb, const char *file)
2013d850 706{
2013d850 707 if (file) {
022349c3 708 if (strbuf_read_file(sb, file, 0) < 0)
2013d850
CC
709 die_errno(_("could not read input file '%s'"), file);
710 } else {
022349c3 711 if (strbuf_read(sb, fileno(stdin), 0) < 0)
2013d850
CC
712 die_errno(_("could not read from stdin"));
713 }
022349c3 714}
2013d850 715
022349c3
JT
716static const char *next_line(const char *str)
717{
718 const char *nl = strchrnul(str, '\n');
719 return nl + !!*nl;
720}
2013d850 721
022349c3
JT
722/*
723 * Return the position of the start of the last line. If len is 0, return -1.
724 */
725static int last_line(const char *buf, size_t len)
726{
727 int i;
728 if (len == 0)
729 return -1;
730 if (len == 1)
731 return 0;
732 /*
733 * Skip the last character (in addition to the null terminator),
734 * because if the last character is a newline, it is considered as part
735 * of the last line anyway.
736 */
737 i = len - 2;
2013d850 738
022349c3
JT
739 for (; i >= 0; i--) {
740 if (buf[i] == '\n')
741 return i + 1;
742 }
743 return 0;
2013d850
CC
744}
745
746/*
022349c3
JT
747 * Return the position of the start of the patch or the length of str if there
748 * is no patch in the message.
2013d850 749 */
022349c3 750static int find_patch_start(const char *str)
2013d850 751{
022349c3 752 const char *s;
2013d850 753
022349c3
JT
754 for (s = str; *s; s = next_line(s)) {
755 if (starts_with(s, "---"))
756 return s - str;
2013d850
CC
757 }
758
022349c3 759 return s - str;
2013d850
CC
760}
761
762/*
022349c3
JT
763 * Return the position of the first trailer line or len if there are no
764 * trailers.
2013d850 765 */
022349c3 766static int find_trailer_start(const char *buf, size_t len)
2013d850 767{
022349c3
JT
768 const char *s;
769 int end_of_title, l, only_spaces = 1;
14624506 770 int recognized_prefix = 0, trailer_lines = 0, non_trailer_lines = 0;
60ef86a1
JT
771 /*
772 * Number of possible continuation lines encountered. This will be
773 * reset to 0 if we encounter a trailer (since those lines are to be
774 * considered continuations of that trailer), and added to
775 * non_trailer_lines if we encounter a non-trailer (since those lines
776 * are to be considered non-trailers).
777 */
778 int possible_continuation_lines = 0;
5c99995d
CC
779
780 /* The first paragraph is the title and cannot be trailers */
022349c3
JT
781 for (s = buf; s < buf + len; s = next_line(s)) {
782 if (s[0] == comment_line_char)
5c99995d 783 continue;
022349c3 784 if (is_blank_line(s))
5c99995d
CC
785 break;
786 }
022349c3 787 end_of_title = s - buf;
2013d850
CC
788
789 /*
14624506
JT
790 * Get the start of the trailers by looking starting from the end for a
791 * blank line before a set of non-blank lines that (i) are all
792 * trailers, or (ii) contains at least one Git-generated trailer and
793 * consists of at least 25% trailers.
2013d850 794 */
022349c3
JT
795 for (l = last_line(buf, len);
796 l >= end_of_title;
797 l = last_line(buf, l)) {
798 const char *bol = buf + l;
14624506
JT
799 const char **p;
800 int separator_pos;
801
022349c3 802 if (bol[0] == comment_line_char) {
60ef86a1
JT
803 non_trailer_lines += possible_continuation_lines;
804 possible_continuation_lines = 0;
2013d850 805 continue;
60ef86a1 806 }
022349c3 807 if (is_blank_line(bol)) {
2013d850
CC
808 if (only_spaces)
809 continue;
60ef86a1 810 non_trailer_lines += possible_continuation_lines;
14624506
JT
811 if (recognized_prefix &&
812 trailer_lines * 3 >= non_trailer_lines)
022349c3
JT
813 return next_line(bol) - buf;
814 else if (trailer_lines && !non_trailer_lines)
815 return next_line(bol) - buf;
816 return len;
2013d850 817 }
14624506
JT
818 only_spaces = 0;
819
820 for (p = git_generated_prefixes; *p; p++) {
022349c3 821 if (starts_with(bol, *p)) {
14624506 822 trailer_lines++;
60ef86a1 823 possible_continuation_lines = 0;
14624506
JT
824 recognized_prefix = 1;
825 goto continue_outer_loop;
826 }
2013d850 827 }
14624506 828
022349c3
JT
829 separator_pos = find_separator(bol, separators);
830 if (separator_pos >= 1 && !isspace(bol[0])) {
14624506
JT
831 struct list_head *pos;
832
833 trailer_lines++;
60ef86a1 834 possible_continuation_lines = 0;
14624506
JT
835 if (recognized_prefix)
836 continue;
837 list_for_each(pos, &conf_head) {
838 struct arg_item *item;
839 item = list_entry(pos, struct arg_item, list);
022349c3 840 if (token_matches_item(bol, item,
14624506
JT
841 separator_pos)) {
842 recognized_prefix = 1;
843 break;
844 }
845 }
022349c3 846 } else if (isspace(bol[0]))
60ef86a1
JT
847 possible_continuation_lines++;
848 else {
14624506 849 non_trailer_lines++;
60ef86a1
JT
850 non_trailer_lines += possible_continuation_lines;
851 possible_continuation_lines = 0;
2013d850 852 }
14624506
JT
853continue_outer_loop:
854 ;
2013d850
CC
855 }
856
022349c3 857 return len;
61cfef4c
CC
858}
859
022349c3
JT
860/* Return the position of the end of the trailers. */
861static int find_trailer_end(const char *buf, size_t len)
2013d850 862{
022349c3 863 return len - ignore_non_trailer(buf, len);
2013d850
CC
864}
865
022349c3 866static int ends_with_blank_line(const char *buf, size_t len)
2013d850 867{
022349c3
JT
868 int ll = last_line(buf, len);
869 if (ll < 0)
870 return 0;
871 return is_blank_line(buf + ll);
2013d850
CC
872}
873
d0d2344a 874static int process_input_file(FILE *outfile,
022349c3 875 const char *str,
8966a394 876 struct list_head *head)
2013d850 877{
022349c3 878 int patch_start, trailer_start, trailer_end;
63ab3f34
JT
879 struct strbuf tok = STRBUF_INIT;
880 struct strbuf val = STRBUF_INIT;
60ef86a1 881 struct trailer_item *last = NULL;
022349c3 882 struct strbuf *trailer, **trailer_lines, **ptr;
2013d850 883
022349c3
JT
884 patch_start = find_patch_start(str);
885 trailer_end = find_trailer_end(str, patch_start);
886 trailer_start = find_trailer_start(str, trailer_end);
2013d850
CC
887
888 /* Print lines before the trailers as is */
022349c3 889 fwrite(str, 1, trailer_start, outfile);
2013d850 890
022349c3 891 if (!ends_with_blank_line(str, trailer_start))
d0d2344a 892 fprintf(outfile, "\n");
2013d850
CC
893
894 /* Parse trailer lines */
022349c3
JT
895 trailer_lines = strbuf_split_buf(str + trailer_start,
896 trailer_end - trailer_start,
897 '\n',
898 0);
899 for (ptr = trailer_lines; *ptr; ptr++) {
fdbf4510 900 int separator_pos;
022349c3
JT
901 trailer = *ptr;
902 if (trailer->buf[0] == comment_line_char)
fdbf4510 903 continue;
022349c3 904 if (last && isspace(trailer->buf[0])) {
60ef86a1 905 struct strbuf sb = STRBUF_INIT;
022349c3 906 strbuf_addf(&sb, "%s\n%s", last->value, trailer->buf);
60ef86a1
JT
907 strbuf_strip_suffix(&sb, "\n");
908 free(last->value);
909 last->value = strbuf_detach(&sb, NULL);
910 continue;
911 }
022349c3 912 separator_pos = find_separator(trailer->buf, separators);
fdbf4510 913 if (separator_pos >= 1) {
022349c3 914 parse_trailer(&tok, &val, NULL, trailer->buf,
fdbf4510 915 separator_pos);
60ef86a1
JT
916 last = add_trailer_item(head,
917 strbuf_detach(&tok, NULL),
918 strbuf_detach(&val, NULL));
14624506 919 } else {
022349c3 920 strbuf_addbuf(&val, trailer);
14624506
JT
921 strbuf_strip_suffix(&val, "\n");
922 add_trailer_item(head,
923 NULL,
924 strbuf_detach(&val, NULL));
60ef86a1 925 last = NULL;
2887103b 926 }
2013d850 927 }
022349c3 928 strbuf_list_free(trailer_lines);
2013d850 929
61cfef4c 930 return trailer_end;
2013d850 931}
b1d78d77 932
8966a394 933static void free_all(struct list_head *head)
b1d78d77 934{
8966a394
JT
935 struct list_head *pos, *p;
936 list_for_each_safe(pos, p, head) {
937 list_del(pos);
938 free_trailer_item(list_entry(pos, struct trailer_item, list));
b1d78d77
CC
939 }
940}
941
e1f89863
TK
942static struct tempfile trailers_tempfile;
943
944static FILE *create_in_place_tempfile(const char *file)
945{
946 struct stat st;
947 struct strbuf template = STRBUF_INIT;
948 const char *tail;
949 FILE *outfile;
950
951 if (stat(file, &st))
952 die_errno(_("could not stat %s"), file);
953 if (!S_ISREG(st.st_mode))
954 die(_("file %s is not a regular file"), file);
955 if (!(st.st_mode & S_IWUSR))
956 die(_("file %s is not writable by user"), file);
957
958 /* Create temporary file in the same directory as the original */
959 tail = strrchr(file, '/');
960 if (tail != NULL)
961 strbuf_add(&template, file, tail - file + 1);
962 strbuf_addstr(&template, "git-interpret-trailers-XXXXXX");
963
964 xmks_tempfile_m(&trailers_tempfile, template.buf, st.st_mode);
965 strbuf_release(&template);
966 outfile = fdopen_tempfile(&trailers_tempfile, "w");
967 if (!outfile)
968 die_errno(_("could not open temporary file"));
969
970 return outfile;
971}
972
973void process_trailers(const char *file, int in_place, int trim_empty, struct string_list *trailers)
b1d78d77 974{
8966a394
JT
975 LIST_HEAD(head);
976 LIST_HEAD(arg_head);
022349c3 977 struct strbuf sb = STRBUF_INIT;
61cfef4c 978 int trailer_end;
d0d2344a 979 FILE *outfile = stdout;
b1d78d77
CC
980
981 /* Default config must be setup first */
982 git_config(git_trailer_default_config, NULL);
983 git_config(git_trailer_config, NULL);
984
022349c3 985 read_input_file(&sb, file);
b1d78d77 986
e1f89863
TK
987 if (in_place)
988 outfile = create_in_place_tempfile(file);
989
b1d78d77 990 /* Print the lines before the trailers */
022349c3 991 trailer_end = process_input_file(outfile, sb.buf, &head);
b1d78d77 992
8966a394 993 process_command_line_args(&arg_head, trailers);
b1d78d77 994
8966a394 995 process_trailers_lists(&head, &arg_head);
b1d78d77 996
8966a394 997 print_all(outfile, &head, trim_empty);
b1d78d77 998
8966a394 999 free_all(&head);
b1d78d77
CC
1000
1001 /* Print the lines after the trailers as is */
022349c3 1002 fwrite(sb.buf + trailer_end, 1, sb.len - trailer_end, outfile);
b1d78d77 1003
e1f89863
TK
1004 if (in_place)
1005 if (rename_tempfile(&trailers_tempfile, file))
1006 die_errno(_("could not rename temporary file to %s"), file);
1007
022349c3 1008 strbuf_release(&sb);
b1d78d77 1009}