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