Merge branch 'jc/cvsserver' into maint-2.10
[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 /*
8  * Copyright (c) 2013, 2014 Christian Couder <chriscool@tuxfamily.org>
9  */
10
11 enum action_where { WHERE_END, WHERE_AFTER, WHERE_BEFORE, WHERE_START };
12 enum action_if_exists { EXISTS_ADD_IF_DIFFERENT_NEIGHBOR, EXISTS_ADD_IF_DIFFERENT,
13                         EXISTS_ADD, EXISTS_REPLACE, EXISTS_DO_NOTHING };
14 enum action_if_missing { MISSING_ADD, MISSING_DO_NOTHING };
15
16 struct conf_info {
17         char *name;
18         char *key;
19         char *command;
20         enum action_where where;
21         enum action_if_exists if_exists;
22         enum action_if_missing if_missing;
23 };
24
25 static struct conf_info default_conf_info;
26
27 struct trailer_item {
28         struct trailer_item *previous;
29         struct trailer_item *next;
30         const char *token;
31         const char *value;
32         struct conf_info conf;
33 };
34
35 static struct trailer_item *first_conf_item;
36
37 static char *separators = ":";
38
39 #define TRAILER_ARG_STRING "$ARG"
40
41 static int after_or_end(enum action_where where)
42 {
43         return (where == WHERE_AFTER) || (where == WHERE_END);
44 }
45
46 /*
47  * Return the length of the string not including any final
48  * punctuation. E.g., the input "Signed-off-by:" would return
49  * 13, stripping the trailing punctuation but retaining
50  * internal punctuation.
51  */
52 static size_t token_len_without_separator(const char *token, size_t len)
53 {
54         while (len > 0 && !isalnum(token[len - 1]))
55                 len--;
56         return len;
57 }
58
59 static int same_token(struct trailer_item *a, struct trailer_item *b)
60 {
61         size_t a_len = token_len_without_separator(a->token, strlen(a->token));
62         size_t b_len = token_len_without_separator(b->token, strlen(b->token));
63         size_t min_len = (a_len > b_len) ? b_len : a_len;
64
65         return !strncasecmp(a->token, b->token, min_len);
66 }
67
68 static int same_value(struct trailer_item *a, struct trailer_item *b)
69 {
70         return !strcasecmp(a->value, b->value);
71 }
72
73 static int same_trailer(struct trailer_item *a, struct trailer_item *b)
74 {
75         return same_token(a, b) && same_value(a, b);
76 }
77
78 static inline int contains_only_spaces(const char *str)
79 {
80         const char *s = str;
81         while (*s && isspace(*s))
82                 s++;
83         return !*s;
84 }
85
86 static inline void strbuf_replace(struct strbuf *sb, const char *a, const char *b)
87 {
88         const char *ptr = strstr(sb->buf, a);
89         if (ptr)
90                 strbuf_splice(sb, ptr - sb->buf, strlen(a), b, strlen(b));
91 }
92
93 static void free_trailer_item(struct trailer_item *item)
94 {
95         free(item->conf.name);
96         free(item->conf.key);
97         free(item->conf.command);
98         free((char *)item->token);
99         free((char *)item->value);
100         free(item);
101 }
102
103 static char last_non_space_char(const char *s)
104 {
105         int i;
106         for (i = strlen(s) - 1; i >= 0; i--)
107                 if (!isspace(s[i]))
108                         return s[i];
109         return '\0';
110 }
111
112 static void print_tok_val(FILE *outfile, const char *tok, const char *val)
113 {
114         char c = last_non_space_char(tok);
115         if (!c)
116                 return;
117         if (strchr(separators, c))
118                 fprintf(outfile, "%s%s\n", tok, val);
119         else
120                 fprintf(outfile, "%s%c %s\n", tok, separators[0], val);
121 }
122
123 static void print_all(FILE *outfile, struct trailer_item *first, int trim_empty)
124 {
125         struct trailer_item *item;
126         for (item = first; item; item = item->next) {
127                 if (!trim_empty || strlen(item->value) > 0)
128                         print_tok_val(outfile, item->token, item->value);
129         }
130 }
131
132 static void update_last(struct trailer_item **last)
133 {
134         if (*last)
135                 while ((*last)->next != NULL)
136                         *last = (*last)->next;
137 }
138
139 static void update_first(struct trailer_item **first)
140 {
141         if (*first)
142                 while ((*first)->previous != NULL)
143                         *first = (*first)->previous;
144 }
145
146 static void add_arg_to_input_list(struct trailer_item *on_tok,
147                                   struct trailer_item *arg_tok,
148                                   struct trailer_item **first,
149                                   struct trailer_item **last)
150 {
151         if (after_or_end(arg_tok->conf.where)) {
152                 arg_tok->next = on_tok->next;
153                 on_tok->next = arg_tok;
154                 arg_tok->previous = on_tok;
155                 if (arg_tok->next)
156                         arg_tok->next->previous = arg_tok;
157                 update_last(last);
158         } else {
159                 arg_tok->previous = on_tok->previous;
160                 on_tok->previous = arg_tok;
161                 arg_tok->next = on_tok;
162                 if (arg_tok->previous)
163                         arg_tok->previous->next = arg_tok;
164                 update_first(first);
165         }
166 }
167
168 static int check_if_different(struct trailer_item *in_tok,
169                               struct trailer_item *arg_tok,
170                               int check_all)
171 {
172         enum action_where where = arg_tok->conf.where;
173         do {
174                 if (!in_tok)
175                         return 1;
176                 if (same_trailer(in_tok, arg_tok))
177                         return 0;
178                 /*
179                  * if we want to add a trailer after another one,
180                  * we have to check those before this one
181                  */
182                 in_tok = after_or_end(where) ? in_tok->previous : in_tok->next;
183         } while (check_all);
184         return 1;
185 }
186
187 static void remove_from_list(struct trailer_item *item,
188                              struct trailer_item **first,
189                              struct trailer_item **last)
190 {
191         struct trailer_item *next = item->next;
192         struct trailer_item *previous = item->previous;
193
194         if (next) {
195                 item->next->previous = previous;
196                 item->next = NULL;
197         } else if (last)
198                 *last = previous;
199
200         if (previous) {
201                 item->previous->next = next;
202                 item->previous = NULL;
203         } else if (first)
204                 *first = next;
205 }
206
207 static struct trailer_item *remove_first(struct trailer_item **first)
208 {
209         struct trailer_item *item = *first;
210         *first = item->next;
211         if (item->next) {
212                 item->next->previous = NULL;
213                 item->next = NULL;
214         }
215         return item;
216 }
217
218 static const char *apply_command(const char *command, const char *arg)
219 {
220         struct strbuf cmd = STRBUF_INIT;
221         struct strbuf buf = STRBUF_INIT;
222         struct child_process cp = CHILD_PROCESS_INIT;
223         const char *argv[] = {NULL, NULL};
224         const char *result;
225
226         strbuf_addstr(&cmd, command);
227         if (arg)
228                 strbuf_replace(&cmd, TRAILER_ARG_STRING, arg);
229
230         argv[0] = cmd.buf;
231         cp.argv = argv;
232         cp.env = local_repo_env;
233         cp.no_stdin = 1;
234         cp.use_shell = 1;
235
236         if (capture_command(&cp, &buf, 1024)) {
237                 error(_("running trailer command '%s' failed"), cmd.buf);
238                 strbuf_release(&buf);
239                 result = xstrdup("");
240         } else {
241                 strbuf_trim(&buf);
242                 result = strbuf_detach(&buf, NULL);
243         }
244
245         strbuf_release(&cmd);
246         return result;
247 }
248
249 static void apply_item_command(struct trailer_item *in_tok, struct trailer_item *arg_tok)
250 {
251         if (arg_tok->conf.command) {
252                 const char *arg;
253                 if (arg_tok->value && arg_tok->value[0]) {
254                         arg = arg_tok->value;
255                 } else {
256                         if (in_tok && in_tok->value)
257                                 arg = xstrdup(in_tok->value);
258                         else
259                                 arg = xstrdup("");
260                 }
261                 arg_tok->value = apply_command(arg_tok->conf.command, arg);
262                 free((char *)arg);
263         }
264 }
265
266 static void apply_arg_if_exists(struct trailer_item *in_tok,
267                                 struct trailer_item *arg_tok,
268                                 struct trailer_item *on_tok,
269                                 struct trailer_item **in_tok_first,
270                                 struct trailer_item **in_tok_last)
271 {
272         switch (arg_tok->conf.if_exists) {
273         case EXISTS_DO_NOTHING:
274                 free_trailer_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                                       in_tok_first, in_tok_last);
280                 remove_from_list(in_tok, in_tok_first, in_tok_last);
281                 free_trailer_item(in_tok);
282                 break;
283         case EXISTS_ADD:
284                 apply_item_command(in_tok, arg_tok);
285                 add_arg_to_input_list(on_tok, arg_tok,
286                                       in_tok_first, in_tok_last);
287                 break;
288         case EXISTS_ADD_IF_DIFFERENT:
289                 apply_item_command(in_tok, arg_tok);
290                 if (check_if_different(in_tok, arg_tok, 1))
291                         add_arg_to_input_list(on_tok, arg_tok,
292                                               in_tok_first, in_tok_last);
293                 else
294                         free_trailer_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))
299                         add_arg_to_input_list(on_tok, arg_tok,
300                                               in_tok_first, in_tok_last);
301                 else
302                         free_trailer_item(arg_tok);
303                 break;
304         }
305 }
306
307 static void apply_arg_if_missing(struct trailer_item **in_tok_first,
308                                  struct trailer_item **in_tok_last,
309                                  struct trailer_item *arg_tok)
310 {
311         struct trailer_item **in_tok;
312         enum action_where where;
313
314         switch (arg_tok->conf.if_missing) {
315         case MISSING_DO_NOTHING:
316                 free_trailer_item(arg_tok);
317                 break;
318         case MISSING_ADD:
319                 where = arg_tok->conf.where;
320                 in_tok = after_or_end(where) ? in_tok_last : in_tok_first;
321                 apply_item_command(NULL, arg_tok);
322                 if (*in_tok) {
323                         add_arg_to_input_list(*in_tok, arg_tok,
324                                               in_tok_first, in_tok_last);
325                 } else {
326                         *in_tok_first = arg_tok;
327                         *in_tok_last = arg_tok;
328                 }
329                 break;
330         }
331 }
332
333 static int find_same_and_apply_arg(struct trailer_item **in_tok_first,
334                                    struct trailer_item **in_tok_last,
335                                    struct trailer_item *arg_tok)
336 {
337         struct trailer_item *in_tok;
338         struct trailer_item *on_tok;
339         struct trailer_item *following_tok;
340
341         enum action_where where = arg_tok->conf.where;
342         int middle = (where == WHERE_AFTER) || (where == WHERE_BEFORE);
343         int backwards = after_or_end(where);
344         struct trailer_item *start_tok = backwards ? *in_tok_last : *in_tok_first;
345
346         for (in_tok = start_tok; in_tok; in_tok = following_tok) {
347                 following_tok = backwards ? in_tok->previous : in_tok->next;
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,
352                                     in_tok_first, in_tok_last);
353                 return 1;
354         }
355         return 0;
356 }
357
358 static void process_trailers_lists(struct trailer_item **in_tok_first,
359                                    struct trailer_item **in_tok_last,
360                                    struct trailer_item **arg_tok_first)
361 {
362         struct trailer_item *arg_tok;
363         struct trailer_item *next_arg;
364
365         if (!*arg_tok_first)
366                 return;
367
368         for (arg_tok = *arg_tok_first; arg_tok; arg_tok = next_arg) {
369                 int applied = 0;
370
371                 next_arg = arg_tok->next;
372                 remove_from_list(arg_tok, arg_tok_first, NULL);
373
374                 applied = find_same_and_apply_arg(in_tok_first,
375                                                   in_tok_last,
376                                                   arg_tok);
377
378                 if (!applied)
379                         apply_arg_if_missing(in_tok_first,
380                                              in_tok_last,
381                                              arg_tok);
382         }
383 }
384
385 static int set_where(struct conf_info *item, const char *value)
386 {
387         if (!strcasecmp("after", value))
388                 item->where = WHERE_AFTER;
389         else if (!strcasecmp("before", value))
390                 item->where = WHERE_BEFORE;
391         else if (!strcasecmp("end", value))
392                 item->where = WHERE_END;
393         else if (!strcasecmp("start", value))
394                 item->where = WHERE_START;
395         else
396                 return -1;
397         return 0;
398 }
399
400 static int set_if_exists(struct conf_info *item, const char *value)
401 {
402         if (!strcasecmp("addIfDifferent", value))
403                 item->if_exists = EXISTS_ADD_IF_DIFFERENT;
404         else if (!strcasecmp("addIfDifferentNeighbor", value))
405                 item->if_exists = EXISTS_ADD_IF_DIFFERENT_NEIGHBOR;
406         else if (!strcasecmp("add", value))
407                 item->if_exists = EXISTS_ADD;
408         else if (!strcasecmp("replace", value))
409                 item->if_exists = EXISTS_REPLACE;
410         else if (!strcasecmp("doNothing", value))
411                 item->if_exists = EXISTS_DO_NOTHING;
412         else
413                 return -1;
414         return 0;
415 }
416
417 static int set_if_missing(struct conf_info *item, const char *value)
418 {
419         if (!strcasecmp("doNothing", value))
420                 item->if_missing = MISSING_DO_NOTHING;
421         else if (!strcasecmp("add", value))
422                 item->if_missing = MISSING_ADD;
423         else
424                 return -1;
425         return 0;
426 }
427
428 static void duplicate_conf(struct conf_info *dst, struct conf_info *src)
429 {
430         *dst = *src;
431         dst->name = xstrdup_or_null(src->name);
432         dst->key = xstrdup_or_null(src->key);
433         dst->command = xstrdup_or_null(src->command);
434 }
435
436 static struct trailer_item *get_conf_item(const char *name)
437 {
438         struct trailer_item *item;
439         struct trailer_item *previous;
440
441         /* Look up item with same name */
442         for (previous = NULL, item = first_conf_item;
443              item;
444              previous = item, item = item->next) {
445                 if (!strcasecmp(item->conf.name, name))
446                         return item;
447         }
448
449         /* Item does not already exists, create it */
450         item = xcalloc(sizeof(struct trailer_item), 1);
451         duplicate_conf(&item->conf, &default_conf_info);
452         item->conf.name = xstrdup(name);
453
454         if (!previous)
455                 first_conf_item = item;
456         else {
457                 previous->next = item;
458                 item->previous = previous;
459         }
460
461         return item;
462 }
463
464 enum trailer_info_type { TRAILER_KEY, TRAILER_COMMAND, TRAILER_WHERE,
465                          TRAILER_IF_EXISTS, TRAILER_IF_MISSING };
466
467 static struct {
468         const char *name;
469         enum trailer_info_type type;
470 } trailer_config_items[] = {
471         { "key", TRAILER_KEY },
472         { "command", TRAILER_COMMAND },
473         { "where", TRAILER_WHERE },
474         { "ifexists", TRAILER_IF_EXISTS },
475         { "ifmissing", TRAILER_IF_MISSING }
476 };
477
478 static int git_trailer_default_config(const char *conf_key, const char *value, void *cb)
479 {
480         const char *trailer_item, *variable_name;
481
482         if (!skip_prefix(conf_key, "trailer.", &trailer_item))
483                 return 0;
484
485         variable_name = strrchr(trailer_item, '.');
486         if (!variable_name) {
487                 if (!strcmp(trailer_item, "where")) {
488                         if (set_where(&default_conf_info, value) < 0)
489                                 warning(_("unknown value '%s' for key '%s'"),
490                                         value, conf_key);
491                 } else if (!strcmp(trailer_item, "ifexists")) {
492                         if (set_if_exists(&default_conf_info, value) < 0)
493                                 warning(_("unknown value '%s' for key '%s'"),
494                                         value, conf_key);
495                 } else if (!strcmp(trailer_item, "ifmissing")) {
496                         if (set_if_missing(&default_conf_info, value) < 0)
497                                 warning(_("unknown value '%s' for key '%s'"),
498                                         value, conf_key);
499                 } else if (!strcmp(trailer_item, "separators")) {
500                         separators = xstrdup(value);
501                 }
502         }
503         return 0;
504 }
505
506 static int git_trailer_config(const char *conf_key, const char *value, void *cb)
507 {
508         const char *trailer_item, *variable_name;
509         struct trailer_item *item;
510         struct conf_info *conf;
511         char *name = NULL;
512         enum trailer_info_type type;
513         int i;
514
515         if (!skip_prefix(conf_key, "trailer.", &trailer_item))
516                 return 0;
517
518         variable_name = strrchr(trailer_item, '.');
519         if (!variable_name)
520                 return 0;
521
522         variable_name++;
523         for (i = 0; i < ARRAY_SIZE(trailer_config_items); i++) {
524                 if (strcmp(trailer_config_items[i].name, variable_name))
525                         continue;
526                 name = xstrndup(trailer_item,  variable_name - trailer_item - 1);
527                 type = trailer_config_items[i].type;
528                 break;
529         }
530
531         if (!name)
532                 return 0;
533
534         item = get_conf_item(name);
535         conf = &item->conf;
536         free(name);
537
538         switch (type) {
539         case TRAILER_KEY:
540                 if (conf->key)
541                         warning(_("more than one %s"), conf_key);
542                 conf->key = xstrdup(value);
543                 break;
544         case TRAILER_COMMAND:
545                 if (conf->command)
546                         warning(_("more than one %s"), conf_key);
547                 conf->command = xstrdup(value);
548                 break;
549         case TRAILER_WHERE:
550                 if (set_where(conf, value))
551                         warning(_("unknown value '%s' for key '%s'"), value, conf_key);
552                 break;
553         case TRAILER_IF_EXISTS:
554                 if (set_if_exists(conf, value))
555                         warning(_("unknown value '%s' for key '%s'"), value, conf_key);
556                 break;
557         case TRAILER_IF_MISSING:
558                 if (set_if_missing(conf, value))
559                         warning(_("unknown value '%s' for key '%s'"), value, conf_key);
560                 break;
561         default:
562                 die("BUG: trailer.c: unhandled type %d", type);
563         }
564         return 0;
565 }
566
567 static int parse_trailer(struct strbuf *tok, struct strbuf *val, const char *trailer)
568 {
569         size_t len;
570         struct strbuf seps = STRBUF_INIT;
571         strbuf_addstr(&seps, separators);
572         strbuf_addch(&seps, '=');
573         len = strcspn(trailer, seps.buf);
574         strbuf_release(&seps);
575         if (len == 0) {
576                 int l = strlen(trailer);
577                 while (l > 0 && isspace(trailer[l - 1]))
578                         l--;
579                 return error(_("empty trailer token in trailer '%.*s'"), l, trailer);
580         }
581         if (len < strlen(trailer)) {
582                 strbuf_add(tok, trailer, len);
583                 strbuf_trim(tok);
584                 strbuf_addstr(val, trailer + len + 1);
585                 strbuf_trim(val);
586         } else {
587                 strbuf_addstr(tok, trailer);
588                 strbuf_trim(tok);
589         }
590         return 0;
591 }
592
593 static const char *token_from_item(struct trailer_item *item, char *tok)
594 {
595         if (item->conf.key)
596                 return item->conf.key;
597         if (tok)
598                 return tok;
599         return item->conf.name;
600 }
601
602 static struct trailer_item *new_trailer_item(struct trailer_item *conf_item,
603                                              char *tok, char *val)
604 {
605         struct trailer_item *new = xcalloc(sizeof(*new), 1);
606         new->value = val ? val : xstrdup("");
607
608         if (conf_item) {
609                 duplicate_conf(&new->conf, &conf_item->conf);
610                 new->token = xstrdup(token_from_item(conf_item, tok));
611                 free(tok);
612         } else {
613                 duplicate_conf(&new->conf, &default_conf_info);
614                 new->token = tok;
615         }
616
617         return new;
618 }
619
620 static int token_matches_item(const char *tok, struct trailer_item *item, int tok_len)
621 {
622         if (!strncasecmp(tok, item->conf.name, tok_len))
623                 return 1;
624         return item->conf.key ? !strncasecmp(tok, item->conf.key, tok_len) : 0;
625 }
626
627 static struct trailer_item *create_trailer_item(const char *string)
628 {
629         struct strbuf tok = STRBUF_INIT;
630         struct strbuf val = STRBUF_INIT;
631         struct trailer_item *item;
632         int tok_len;
633
634         if (parse_trailer(&tok, &val, string))
635                 return NULL;
636
637         tok_len = token_len_without_separator(tok.buf, tok.len);
638
639         /* Lookup if the token matches something in the config */
640         for (item = first_conf_item; item; item = item->next) {
641                 if (token_matches_item(tok.buf, item, tok_len))
642                         return new_trailer_item(item,
643                                                 strbuf_detach(&tok, NULL),
644                                                 strbuf_detach(&val, NULL));
645         }
646
647         return new_trailer_item(NULL,
648                                 strbuf_detach(&tok, NULL),
649                                 strbuf_detach(&val, NULL));
650 }
651
652 static void add_trailer_item(struct trailer_item **first,
653                              struct trailer_item **last,
654                              struct trailer_item *new)
655 {
656         if (!new)
657                 return;
658         if (!*last) {
659                 *first = new;
660                 *last = new;
661         } else {
662                 (*last)->next = new;
663                 new->previous = *last;
664                 *last = new;
665         }
666 }
667
668 static struct trailer_item *process_command_line_args(struct string_list *trailers)
669 {
670         struct trailer_item *arg_tok_first = NULL;
671         struct trailer_item *arg_tok_last = NULL;
672         struct string_list_item *tr;
673         struct trailer_item *item;
674
675         /* Add a trailer item for each configured trailer with a command */
676         for (item = first_conf_item; item; item = item->next) {
677                 if (item->conf.command) {
678                         struct trailer_item *new = new_trailer_item(item, NULL, NULL);
679                         add_trailer_item(&arg_tok_first, &arg_tok_last, new);
680                 }
681         }
682
683         /* Add a trailer item for each trailer on the command line */
684         for_each_string_list_item(tr, trailers) {
685                 struct trailer_item *new = create_trailer_item(tr->string);
686                 add_trailer_item(&arg_tok_first, &arg_tok_last, new);
687         }
688
689         return arg_tok_first;
690 }
691
692 static struct strbuf **read_input_file(const char *file)
693 {
694         struct strbuf **lines;
695         struct strbuf sb = STRBUF_INIT;
696
697         if (file) {
698                 if (strbuf_read_file(&sb, file, 0) < 0)
699                         die_errno(_("could not read input file '%s'"), file);
700         } else {
701                 if (strbuf_read(&sb, fileno(stdin), 0) < 0)
702                         die_errno(_("could not read from stdin"));
703         }
704
705         lines = strbuf_split(&sb, '\n');
706
707         strbuf_release(&sb);
708
709         return lines;
710 }
711
712 /*
713  * Return the (0 based) index of the start of the patch or the line
714  * count if there is no patch in the message.
715  */
716 static int find_patch_start(struct strbuf **lines, int count)
717 {
718         int i;
719
720         /* Get the start of the patch part if any */
721         for (i = 0; i < count; i++) {
722                 if (starts_with(lines[i]->buf, "---"))
723                         return i;
724         }
725
726         return count;
727 }
728
729 /*
730  * Return the (0 based) index of the first trailer line or count if
731  * there are no trailers. Trailers are searched only in the lines from
732  * index (count - 1) down to index 0.
733  */
734 static int find_trailer_start(struct strbuf **lines, int count)
735 {
736         int start, end_of_title, only_spaces = 1;
737
738         /* The first paragraph is the title and cannot be trailers */
739         for (start = 0; start < count; start++) {
740                 if (lines[start]->buf[0] == comment_line_char)
741                         continue;
742                 if (contains_only_spaces(lines[start]->buf))
743                         break;
744         }
745         end_of_title = start;
746
747         /*
748          * Get the start of the trailers by looking starting from the end
749          * for a line with only spaces before lines with one separator.
750          */
751         for (start = count - 1; start >= end_of_title; start--) {
752                 if (lines[start]->buf[0] == comment_line_char)
753                         continue;
754                 if (contains_only_spaces(lines[start]->buf)) {
755                         if (only_spaces)
756                                 continue;
757                         return start + 1;
758                 }
759                 if (strcspn(lines[start]->buf, separators) < lines[start]->len) {
760                         if (only_spaces)
761                                 only_spaces = 0;
762                         continue;
763                 }
764                 return count;
765         }
766
767         return only_spaces ? count : 0;
768 }
769
770 /* Get the index of the end of the trailers */
771 static int find_trailer_end(struct strbuf **lines, int patch_start)
772 {
773         struct strbuf sb = STRBUF_INIT;
774         int i, ignore_bytes;
775
776         for (i = 0; i < patch_start; i++)
777                 strbuf_addbuf(&sb, lines[i]);
778         ignore_bytes = ignore_non_trailer(&sb);
779         strbuf_release(&sb);
780         for (i = patch_start - 1; i >= 0 && ignore_bytes > 0; i--)
781                 ignore_bytes -= lines[i]->len;
782
783         return i + 1;
784 }
785
786 static int has_blank_line_before(struct strbuf **lines, int start)
787 {
788         for (;start >= 0; start--) {
789                 if (lines[start]->buf[0] == comment_line_char)
790                         continue;
791                 return contains_only_spaces(lines[start]->buf);
792         }
793         return 0;
794 }
795
796 static void print_lines(FILE *outfile, struct strbuf **lines, int start, int end)
797 {
798         int i;
799         for (i = start; lines[i] && i < end; i++)
800                 fprintf(outfile, "%s", lines[i]->buf);
801 }
802
803 static int process_input_file(FILE *outfile,
804                               struct strbuf **lines,
805                               struct trailer_item **in_tok_first,
806                               struct trailer_item **in_tok_last)
807 {
808         int count = 0;
809         int patch_start, trailer_start, trailer_end, i;
810
811         /* Get the line count */
812         while (lines[count])
813                 count++;
814
815         patch_start = find_patch_start(lines, count);
816         trailer_end = find_trailer_end(lines, patch_start);
817         trailer_start = find_trailer_start(lines, trailer_end);
818
819         /* Print lines before the trailers as is */
820         print_lines(outfile, lines, 0, trailer_start);
821
822         if (!has_blank_line_before(lines, trailer_start - 1))
823                 fprintf(outfile, "\n");
824
825         /* Parse trailer lines */
826         for (i = trailer_start; i < trailer_end; i++) {
827                 if (lines[i]->buf[0] != comment_line_char) {
828                         struct trailer_item *new = create_trailer_item(lines[i]->buf);
829                         add_trailer_item(in_tok_first, in_tok_last, new);
830                 }
831         }
832
833         return trailer_end;
834 }
835
836 static void free_all(struct trailer_item **first)
837 {
838         while (*first) {
839                 struct trailer_item *item = remove_first(first);
840                 free_trailer_item(item);
841         }
842 }
843
844 static struct tempfile trailers_tempfile;
845
846 static FILE *create_in_place_tempfile(const char *file)
847 {
848         struct stat st;
849         struct strbuf template = STRBUF_INIT;
850         const char *tail;
851         FILE *outfile;
852
853         if (stat(file, &st))
854                 die_errno(_("could not stat %s"), file);
855         if (!S_ISREG(st.st_mode))
856                 die(_("file %s is not a regular file"), file);
857         if (!(st.st_mode & S_IWUSR))
858                 die(_("file %s is not writable by user"), file);
859
860         /* Create temporary file in the same directory as the original */
861         tail = strrchr(file, '/');
862         if (tail != NULL)
863                 strbuf_add(&template, file, tail - file + 1);
864         strbuf_addstr(&template, "git-interpret-trailers-XXXXXX");
865
866         xmks_tempfile_m(&trailers_tempfile, template.buf, st.st_mode);
867         strbuf_release(&template);
868         outfile = fdopen_tempfile(&trailers_tempfile, "w");
869         if (!outfile)
870                 die_errno(_("could not open temporary file"));
871
872         return outfile;
873 }
874
875 void process_trailers(const char *file, int in_place, int trim_empty, struct string_list *trailers)
876 {
877         struct trailer_item *in_tok_first = NULL;
878         struct trailer_item *in_tok_last = NULL;
879         struct trailer_item *arg_tok_first;
880         struct strbuf **lines;
881         int trailer_end;
882         FILE *outfile = stdout;
883
884         /* Default config must be setup first */
885         git_config(git_trailer_default_config, NULL);
886         git_config(git_trailer_config, NULL);
887
888         lines = read_input_file(file);
889
890         if (in_place)
891                 outfile = create_in_place_tempfile(file);
892
893         /* Print the lines before the trailers */
894         trailer_end = process_input_file(outfile, lines, &in_tok_first, &in_tok_last);
895
896         arg_tok_first = process_command_line_args(trailers);
897
898         process_trailers_lists(&in_tok_first, &in_tok_last, &arg_tok_first);
899
900         print_all(outfile, in_tok_first, trim_empty);
901
902         free_all(&in_tok_first);
903
904         /* Print the lines after the trailers as is */
905         print_lines(outfile, lines, trailer_end, INT_MAX);
906
907         if (in_place)
908                 if (rename_tempfile(&trailers_tempfile, file))
909                         die_errno(_("could not rename temporary file to %s"), file);
910
911         strbuf_list_free(lines);
912 }