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