trailer: support values folded to multiple lines
[git] / trailer.c
1 #include "cache.h"
2 #include "string-list.h"
3 #include "run-command.h"
4 #include "commit.h"
5 #include "tempfile.h"
6 #include "trailer.h"
7 #include "list.h"
8 /*
9  * Copyright (c) 2013, 2014 Christian Couder <chriscool@tuxfamily.org>
10  */
11
12 enum action_where { WHERE_END, WHERE_AFTER, WHERE_BEFORE, WHERE_START };
13 enum action_if_exists { EXISTS_ADD_IF_DIFFERENT_NEIGHBOR, EXISTS_ADD_IF_DIFFERENT,
14                         EXISTS_ADD, EXISTS_REPLACE, EXISTS_DO_NOTHING };
15 enum action_if_missing { MISSING_ADD, MISSING_DO_NOTHING };
16
17 struct 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
26 static struct conf_info default_conf_info;
27
28 struct trailer_item {
29         struct list_head list;
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          */
34         char *token;
35         char *value;
36 };
37
38 struct arg_item {
39         struct list_head list;
40         char *token;
41         char *value;
42         struct conf_info conf;
43 };
44
45 static LIST_HEAD(conf_head);
46
47 static char *separators = ":";
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 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  */
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 contains_only_spaces(const char *str)
106 {
107         const char *s = str;
108         while (*s && isspace(*s))
109                 s++;
110         return !*s;
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->token);
133         free(item->value);
134         free(item);
135 }
136
137 static 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
146 static void print_tok_val(FILE *outfile, const char *tok, const char *val)
147 {
148         char c;
149
150         if (!tok) {
151                 fprintf(outfile, "%s\n", val);
152                 return;
153         }
154
155         c = last_non_space_char(tok);
156         if (!c)
157                 return;
158         if (strchr(separators, c))
159                 fprintf(outfile, "%s%s\n", tok, val);
160         else
161                 fprintf(outfile, "%s%c %s\n", tok, separators[0], val);
162 }
163
164 static void print_all(FILE *outfile, struct list_head *head, int trim_empty)
165 {
166         struct list_head *pos;
167         struct trailer_item *item;
168         list_for_each(pos, head) {
169                 item = list_entry(pos, struct trailer_item, list);
170                 if (!trim_empty || strlen(item->value) > 0)
171                         print_tok_val(outfile, item->token, item->value);
172         }
173 }
174
175 static struct trailer_item *trailer_from_arg(struct arg_item *arg_tok)
176 {
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;
183 }
184
185 static void add_arg_to_input_list(struct trailer_item *on_tok,
186                                   struct arg_item *arg_tok)
187 {
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);
192         else
193                 list_add_tail(&to_add->list, &on_tok->list);
194 }
195
196 static int check_if_different(struct trailer_item *in_tok,
197                               struct arg_item *arg_tok,
198                               int check_all,
199                               struct list_head *head)
200 {
201         enum action_where where = arg_tok->conf.where;
202         struct list_head *next_head;
203         do {
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                  */
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);
215         } while (check_all);
216         return 1;
217 }
218
219 static char *apply_command(const char *command, const char *arg)
220 {
221         struct strbuf cmd = STRBUF_INIT;
222         struct strbuf buf = STRBUF_INIT;
223         struct child_process cp = CHILD_PROCESS_INIT;
224         const char *argv[] = {NULL, NULL};
225         char *result;
226
227         strbuf_addstr(&cmd, command);
228         if (arg)
229                 strbuf_replace(&cmd, TRAILER_ARG_STRING, arg);
230
231         argv[0] = cmd.buf;
232         cp.argv = argv;
233         cp.env = local_repo_env;
234         cp.no_stdin = 1;
235         cp.use_shell = 1;
236
237         if (capture_command(&cp, &buf, 1024)) {
238                 error(_("running trailer command '%s' failed"), cmd.buf);
239                 strbuf_release(&buf);
240                 result = xstrdup("");
241         } else {
242                 strbuf_trim(&buf);
243                 result = strbuf_detach(&buf, NULL);
244         }
245
246         strbuf_release(&cmd);
247         return result;
248 }
249
250 static void apply_item_command(struct trailer_item *in_tok, struct arg_item *arg_tok)
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
267 static void apply_arg_if_exists(struct trailer_item *in_tok,
268                                 struct arg_item *arg_tok,
269                                 struct trailer_item *on_tok,
270                                 struct list_head *head)
271 {
272         switch (arg_tok->conf.if_exists) {
273         case EXISTS_DO_NOTHING:
274                 free_arg_item(arg_tok);
275                 break;
276         case EXISTS_REPLACE:
277                 apply_item_command(in_tok, arg_tok);
278                 add_arg_to_input_list(on_tok, arg_tok);
279                 list_del(&in_tok->list);
280                 free_trailer_item(in_tok);
281                 break;
282         case EXISTS_ADD:
283                 apply_item_command(in_tok, arg_tok);
284                 add_arg_to_input_list(on_tok, arg_tok);
285                 break;
286         case EXISTS_ADD_IF_DIFFERENT:
287                 apply_item_command(in_tok, arg_tok);
288                 if (check_if_different(in_tok, arg_tok, 1, head))
289                         add_arg_to_input_list(on_tok, arg_tok);
290                 else
291                         free_arg_item(arg_tok);
292                 break;
293         case EXISTS_ADD_IF_DIFFERENT_NEIGHBOR:
294                 apply_item_command(in_tok, arg_tok);
295                 if (check_if_different(on_tok, arg_tok, 0, head))
296                         add_arg_to_input_list(on_tok, arg_tok);
297                 else
298                         free_arg_item(arg_tok);
299                 break;
300         }
301 }
302
303 static void apply_arg_if_missing(struct list_head *head,
304                                  struct arg_item *arg_tok)
305 {
306         enum action_where where;
307         struct trailer_item *to_add;
308
309         switch (arg_tok->conf.if_missing) {
310         case MISSING_DO_NOTHING:
311                 free_arg_item(arg_tok);
312                 break;
313         case MISSING_ADD:
314                 where = arg_tok->conf.where;
315                 apply_item_command(NULL, arg_tok);
316                 to_add = trailer_from_arg(arg_tok);
317                 if (after_or_end(where))
318                         list_add_tail(&to_add->list, head);
319                 else
320                         list_add(&to_add->list, head);
321         }
322 }
323
324 static int find_same_and_apply_arg(struct list_head *head,
325                                    struct arg_item *arg_tok)
326 {
327         struct list_head *pos;
328         struct trailer_item *in_tok;
329         struct trailer_item *on_tok;
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);
334         struct trailer_item *start_tok;
335
336         if (list_empty(head))
337                 return 0;
338
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);
345                 if (!same_token(in_tok, arg_tok))
346                         continue;
347                 on_tok = middle ? in_tok : start_tok;
348                 apply_arg_if_exists(in_tok, arg_tok, on_tok, head);
349                 return 1;
350         }
351         return 0;
352 }
353
354 static void process_trailers_lists(struct list_head *head,
355                                    struct list_head *arg_head)
356 {
357         struct list_head *pos, *p;
358         struct arg_item *arg_tok;
359
360         list_for_each_safe(pos, p, arg_head) {
361                 int applied = 0;
362                 arg_tok = list_entry(pos, struct arg_item, list);
363
364                 list_del(pos);
365
366                 applied = find_same_and_apply_arg(head, arg_tok);
367
368                 if (!applied)
369                         apply_arg_if_missing(head, arg_tok);
370         }
371 }
372
373 static 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
388 static 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
405 static 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
416 static void duplicate_conf(struct conf_info *dst, const struct conf_info *src)
417 {
418         *dst = *src;
419         if (src->name)
420                 dst->name = xstrdup(src->name);
421         if (src->key)
422                 dst->key = xstrdup(src->key);
423         if (src->command)
424                 dst->command = xstrdup(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 const char *token_from_item(struct arg_item *item, char *tok)
553 {
554         if (item->conf.key)
555                 return item->conf.key;
556         if (tok)
557                 return tok;
558         return item->conf.name;
559 }
560
561 static int token_matches_item(const char *tok, struct arg_item *item, int tok_len)
562 {
563         if (!strncasecmp(tok, item->conf.name, tok_len))
564                 return 1;
565         return item->conf.key ? !strncasecmp(tok, item->conf.key, tok_len) : 0;
566 }
567
568 /*
569  * Return the location of the first separator in line, or -1 if there is no
570  * separator.
571  */
572 static int find_separator(const char *line, const char *separators)
573 {
574         int loc = strcspn(line, separators);
575         if (!line[loc])
576                 return -1;
577         return loc;
578 }
579
580 /*
581  * Obtain the token, value, and conf from the given trailer.
582  *
583  * separator_pos must not be 0, since the token cannot be an empty string.
584  *
585  * If separator_pos is -1, interpret the whole trailer as a token.
586  */
587 static void parse_trailer(struct strbuf *tok, struct strbuf *val,
588                          const struct conf_info **conf, const char *trailer,
589                          int separator_pos)
590 {
591         struct arg_item *item;
592         int tok_len;
593         struct list_head *pos;
594
595         if (separator_pos != -1) {
596                 strbuf_add(tok, trailer, separator_pos);
597                 strbuf_trim(tok);
598                 strbuf_addstr(val, trailer + separator_pos + 1);
599                 strbuf_trim(val);
600         } else {
601                 strbuf_addstr(tok, trailer);
602                 strbuf_trim(tok);
603         }
604
605         /* Lookup if the token matches something in the config */
606         tok_len = token_len_without_separator(tok->buf, tok->len);
607         if (conf)
608                 *conf = &default_conf_info;
609         list_for_each(pos, &conf_head) {
610                 item = list_entry(pos, struct arg_item, list);
611                 if (token_matches_item(tok->buf, item, tok_len)) {
612                         char *tok_buf = strbuf_detach(tok, NULL);
613                         if (conf)
614                                 *conf = &item->conf;
615                         strbuf_addstr(tok, token_from_item(item, tok_buf));
616                         free(tok_buf);
617                         break;
618                 }
619         }
620 }
621
622 static struct trailer_item *add_trailer_item(struct list_head *head, char *tok,
623                                              char *val)
624 {
625         struct trailer_item *new = xcalloc(sizeof(*new), 1);
626         new->token = tok;
627         new->value = val;
628         list_add_tail(&new->list, head);
629         return new;
630 }
631
632 static void add_arg_item(struct list_head *arg_head, char *tok, char *val,
633                          const struct conf_info *conf)
634 {
635         struct arg_item *new = xcalloc(sizeof(*new), 1);
636         new->token = tok;
637         new->value = val;
638         duplicate_conf(&new->conf, conf);
639         list_add_tail(&new->list, arg_head);
640 }
641
642 static void process_command_line_args(struct list_head *arg_head,
643                                       struct string_list *trailers)
644 {
645         struct string_list_item *tr;
646         struct arg_item *item;
647         struct strbuf tok = STRBUF_INIT;
648         struct strbuf val = STRBUF_INIT;
649         const struct conf_info *conf;
650         struct list_head *pos;
651
652         /*
653          * In command-line arguments, '=' is accepted (in addition to the
654          * separators that are defined).
655          */
656         char *cl_separators = xstrfmt("=%s", separators);
657
658         /* Add an arg item for each configured trailer with a command */
659         list_for_each(pos, &conf_head) {
660                 item = list_entry(pos, struct arg_item, list);
661                 if (item->conf.command)
662                         add_arg_item(arg_head,
663                                      xstrdup(token_from_item(item, NULL)),
664                                      xstrdup(""),
665                                      &item->conf);
666         }
667
668         /* Add an arg item for each trailer on the command line */
669         for_each_string_list_item(tr, trailers) {
670                 int separator_pos = find_separator(tr->string, cl_separators);
671                 if (separator_pos == 0) {
672                         struct strbuf sb = STRBUF_INIT;
673                         strbuf_addstr(&sb, tr->string);
674                         strbuf_trim(&sb);
675                         error(_("empty trailer token in trailer '%.*s'"),
676                               (int) sb.len, sb.buf);
677                         strbuf_release(&sb);
678                 } else {
679                         parse_trailer(&tok, &val, &conf, tr->string,
680                                       separator_pos);
681                         add_arg_item(arg_head,
682                                      strbuf_detach(&tok, NULL),
683                                      strbuf_detach(&val, NULL),
684                                      conf);
685                 }
686         }
687
688         free(cl_separators);
689 }
690
691 static struct strbuf **read_input_file(const char *file)
692 {
693         struct strbuf **lines;
694         struct strbuf sb = STRBUF_INIT;
695
696         if (file) {
697                 if (strbuf_read_file(&sb, file, 0) < 0)
698                         die_errno(_("could not read input file '%s'"), file);
699         } else {
700                 if (strbuf_read(&sb, fileno(stdin), 0) < 0)
701                         die_errno(_("could not read from stdin"));
702         }
703
704         lines = strbuf_split(&sb, '\n');
705
706         strbuf_release(&sb);
707
708         return lines;
709 }
710
711 /*
712  * Return the (0 based) index of the start of the patch or the line
713  * count if there is no patch in the message.
714  */
715 static int find_patch_start(struct strbuf **lines, int count)
716 {
717         int i;
718
719         /* Get the start of the patch part if any */
720         for (i = 0; i < count; i++) {
721                 if (starts_with(lines[i]->buf, "---"))
722                         return i;
723         }
724
725         return count;
726 }
727
728 /*
729  * Return the (0 based) index of the first trailer line or count if
730  * there are no trailers. Trailers are searched only in the lines from
731  * index (count - 1) down to index 0.
732  */
733 static int find_trailer_start(struct strbuf **lines, int count)
734 {
735         int start, end_of_title, only_spaces = 1;
736         int recognized_prefix = 0, trailer_lines = 0, non_trailer_lines = 0;
737         /*
738          * Number of possible continuation lines encountered. This will be
739          * reset to 0 if we encounter a trailer (since those lines are to be
740          * considered continuations of that trailer), and added to
741          * non_trailer_lines if we encounter a non-trailer (since those lines
742          * are to be considered non-trailers).
743          */
744         int possible_continuation_lines = 0;
745
746         /* The first paragraph is the title and cannot be trailers */
747         for (start = 0; start < count; start++) {
748                 if (lines[start]->buf[0] == comment_line_char)
749                         continue;
750                 if (contains_only_spaces(lines[start]->buf))
751                         break;
752         }
753         end_of_title = start;
754
755         /*
756          * Get the start of the trailers by looking starting from the end for a
757          * blank line before a set of non-blank lines that (i) are all
758          * trailers, or (ii) contains at least one Git-generated trailer and
759          * consists of at least 25% trailers.
760          */
761         for (start = count - 1; start >= end_of_title; start--) {
762                 const char **p;
763                 int separator_pos;
764
765                 if (lines[start]->buf[0] == comment_line_char) {
766                         non_trailer_lines += possible_continuation_lines;
767                         possible_continuation_lines = 0;
768                         continue;
769                 }
770                 if (contains_only_spaces(lines[start]->buf)) {
771                         if (only_spaces)
772                                 continue;
773                         non_trailer_lines += possible_continuation_lines;
774                         if (recognized_prefix &&
775                             trailer_lines * 3 >= non_trailer_lines)
776                                 return start + 1;
777                         if (trailer_lines && !non_trailer_lines)
778                                 return start + 1;
779                         return count;
780                 }
781                 only_spaces = 0;
782
783                 for (p = git_generated_prefixes; *p; p++) {
784                         if (starts_with(lines[start]->buf, *p)) {
785                                 trailer_lines++;
786                                 possible_continuation_lines = 0;
787                                 recognized_prefix = 1;
788                                 goto continue_outer_loop;
789                         }
790                 }
791
792                 separator_pos = find_separator(lines[start]->buf, separators);
793                 if (separator_pos >= 1 && !isspace(lines[start]->buf[0])) {
794                         struct list_head *pos;
795
796                         trailer_lines++;
797                         possible_continuation_lines = 0;
798                         if (recognized_prefix)
799                                 continue;
800                         list_for_each(pos, &conf_head) {
801                                 struct arg_item *item;
802                                 item = list_entry(pos, struct arg_item, list);
803                                 if (token_matches_item(lines[start]->buf, item,
804                                                        separator_pos)) {
805                                         recognized_prefix = 1;
806                                         break;
807                                 }
808                         }
809                 } else if (isspace(lines[start]->buf[0]))
810                         possible_continuation_lines++;
811                 else {
812                         non_trailer_lines++;
813                         non_trailer_lines += possible_continuation_lines;
814                         possible_continuation_lines = 0;
815                 }
816 continue_outer_loop:
817                 ;
818         }
819
820         return count;
821 }
822
823 /* Get the index of the end of the trailers */
824 static int find_trailer_end(struct strbuf **lines, int patch_start)
825 {
826         struct strbuf sb = STRBUF_INIT;
827         int i, ignore_bytes;
828
829         for (i = 0; i < patch_start; i++)
830                 strbuf_addbuf(&sb, lines[i]);
831         ignore_bytes = ignore_non_trailer(&sb);
832         strbuf_release(&sb);
833         for (i = patch_start - 1; i >= 0 && ignore_bytes > 0; i--)
834                 ignore_bytes -= lines[i]->len;
835
836         return i + 1;
837 }
838
839 static int has_blank_line_before(struct strbuf **lines, int start)
840 {
841         for (;start >= 0; start--) {
842                 if (lines[start]->buf[0] == comment_line_char)
843                         continue;
844                 return contains_only_spaces(lines[start]->buf);
845         }
846         return 0;
847 }
848
849 static void print_lines(FILE *outfile, struct strbuf **lines, int start, int end)
850 {
851         int i;
852         for (i = start; lines[i] && i < end; i++)
853                 fprintf(outfile, "%s", lines[i]->buf);
854 }
855
856 static int process_input_file(FILE *outfile,
857                               struct strbuf **lines,
858                               struct list_head *head)
859 {
860         int count = 0;
861         int patch_start, trailer_start, trailer_end, i;
862         struct strbuf tok = STRBUF_INIT;
863         struct strbuf val = STRBUF_INIT;
864         struct trailer_item *last = NULL;
865
866         /* Get the line count */
867         while (lines[count])
868                 count++;
869
870         patch_start = find_patch_start(lines, count);
871         trailer_end = find_trailer_end(lines, patch_start);
872         trailer_start = find_trailer_start(lines, trailer_end);
873
874         /* Print lines before the trailers as is */
875         print_lines(outfile, lines, 0, trailer_start);
876
877         if (!has_blank_line_before(lines, trailer_start - 1))
878                 fprintf(outfile, "\n");
879
880         /* Parse trailer lines */
881         for (i = trailer_start; i < trailer_end; i++) {
882                 int separator_pos;
883                 if (lines[i]->buf[0] == comment_line_char)
884                         continue;
885                 if (last && isspace(lines[i]->buf[0])) {
886                         struct strbuf sb = STRBUF_INIT;
887                         strbuf_addf(&sb, "%s\n%s", last->value, lines[i]->buf);
888                         strbuf_strip_suffix(&sb, "\n");
889                         free(last->value);
890                         last->value = strbuf_detach(&sb, NULL);
891                         continue;
892                 }
893                 separator_pos = find_separator(lines[i]->buf, separators);
894                 if (separator_pos >= 1) {
895                         parse_trailer(&tok, &val, NULL, lines[i]->buf,
896                                       separator_pos);
897                         last = add_trailer_item(head,
898                                                 strbuf_detach(&tok, NULL),
899                                                 strbuf_detach(&val, NULL));
900                 } else {
901                         strbuf_addbuf(&val, lines[i]);
902                         strbuf_strip_suffix(&val, "\n");
903                         add_trailer_item(head,
904                                          NULL,
905                                          strbuf_detach(&val, NULL));
906                         last = NULL;
907                 }
908         }
909
910         return trailer_end;
911 }
912
913 static void free_all(struct list_head *head)
914 {
915         struct list_head *pos, *p;
916         list_for_each_safe(pos, p, head) {
917                 list_del(pos);
918                 free_trailer_item(list_entry(pos, struct trailer_item, list));
919         }
920 }
921
922 static struct tempfile trailers_tempfile;
923
924 static FILE *create_in_place_tempfile(const char *file)
925 {
926         struct stat st;
927         struct strbuf template = STRBUF_INIT;
928         const char *tail;
929         FILE *outfile;
930
931         if (stat(file, &st))
932                 die_errno(_("could not stat %s"), file);
933         if (!S_ISREG(st.st_mode))
934                 die(_("file %s is not a regular file"), file);
935         if (!(st.st_mode & S_IWUSR))
936                 die(_("file %s is not writable by user"), file);
937
938         /* Create temporary file in the same directory as the original */
939         tail = strrchr(file, '/');
940         if (tail != NULL)
941                 strbuf_add(&template, file, tail - file + 1);
942         strbuf_addstr(&template, "git-interpret-trailers-XXXXXX");
943
944         xmks_tempfile_m(&trailers_tempfile, template.buf, st.st_mode);
945         strbuf_release(&template);
946         outfile = fdopen_tempfile(&trailers_tempfile, "w");
947         if (!outfile)
948                 die_errno(_("could not open temporary file"));
949
950         return outfile;
951 }
952
953 void process_trailers(const char *file, int in_place, int trim_empty, struct string_list *trailers)
954 {
955         LIST_HEAD(head);
956         LIST_HEAD(arg_head);
957         struct strbuf **lines;
958         int trailer_end;
959         FILE *outfile = stdout;
960
961         /* Default config must be setup first */
962         git_config(git_trailer_default_config, NULL);
963         git_config(git_trailer_config, NULL);
964
965         lines = read_input_file(file);
966
967         if (in_place)
968                 outfile = create_in_place_tempfile(file);
969
970         /* Print the lines before the trailers */
971         trailer_end = process_input_file(outfile, lines, &head);
972
973         process_command_line_args(&arg_head, trailers);
974
975         process_trailers_lists(&head, &arg_head);
976
977         print_all(outfile, &head, trim_empty);
978
979         free_all(&head);
980
981         /* Print the lines after the trailers as is */
982         print_lines(outfile, lines, trailer_end, INT_MAX);
983
984         if (in_place)
985                 if (rename_tempfile(&trailers_tempfile, file))
986                         die_errno(_("could not rename temporary file to %s"), file);
987
988         strbuf_list_free(lines);
989 }