builtin-commit.con commit Port git commit to C. (f5bbc32)
   1/*
   2 * Builtin "git commit"
   3 *
   4 * Copyright (c) 2007 Kristian Høgsberg <krh@redhat.com>
   5 * Based on git-commit.sh by Junio C Hamano and Linus Torvalds
   6 */
   7
   8#include "cache.h"
   9#include "cache-tree.h"
  10#include "builtin.h"
  11#include "diff.h"
  12#include "diffcore.h"
  13#include "commit.h"
  14#include "revision.h"
  15#include "wt-status.h"
  16#include "run-command.h"
  17#include "refs.h"
  18#include "log-tree.h"
  19#include "strbuf.h"
  20#include "utf8.h"
  21#include "parse-options.h"
  22
  23static const char * const builtin_commit_usage[] = {
  24        "git-commit [options] [--] <filepattern>...",
  25        NULL
  26};
  27
  28static unsigned char head_sha1[20], merge_head_sha1[20];
  29static char *use_message_buffer;
  30static const char commit_editmsg[] = "COMMIT_EDITMSG";
  31static struct lock_file lock_file;
  32
  33static char *logfile, *force_author, *message, *template_file;
  34static char *edit_message, *use_message;
  35static int all, edit_flag, also, interactive, only, amend, signoff;
  36static int quiet, verbose, untracked_files, no_verify;
  37
  38static int no_edit, initial_commit, in_merge;
  39const char *only_include_assumed;
  40
  41static struct option builtin_commit_options[] = {
  42        OPT__QUIET(&quiet),
  43        OPT__VERBOSE(&verbose),
  44        OPT_GROUP("Commit message options"),
  45
  46        OPT_STRING('F', "file", &logfile, "FILE", "read log from file"),
  47        OPT_STRING(0, "author", &force_author, "AUTHOR", "override author for commit"),
  48        OPT_STRING('m', "message", &message, "MESSAGE", "specify commit message"),
  49        OPT_STRING('c', "reedit-message", &edit_message, "COMMIT", "reuse and edit message from specified commit "),
  50        OPT_STRING('C', "reuse-message", &use_message, "COMMIT", "reuse message from specified commit"),
  51        OPT_BOOLEAN('s', "signoff", &signoff, "add Signed-off-by: header"),
  52        OPT_STRING('t', "template", &template_file, "FILE", "use specified template file"),
  53        OPT_BOOLEAN('e', "edit", &edit_flag, "force edit of commit"),
  54
  55        OPT_GROUP("Commit contents options"),
  56        OPT_BOOLEAN('a', "all", &all, "commit all changed files"),
  57        OPT_BOOLEAN('i', "include", &also, "add specified files to index for commit"),
  58        OPT_BOOLEAN(0, "interactive", &interactive, "interactively add files"),
  59        OPT_BOOLEAN('o', "only", &only, ""),
  60        OPT_BOOLEAN('n', "no-verify", &no_verify, "bypass pre-commit hook"),
  61        OPT_BOOLEAN(0, "amend", &amend, "amend previous commit"),
  62        OPT_BOOLEAN(0, "untracked-files", &untracked_files, "show all untracked files"),
  63
  64        OPT_END()
  65};
  66
  67static char *prepare_index(const char **files, const char *prefix)
  68{
  69        int fd;
  70        struct tree *tree;
  71        struct lock_file *next_index_lock;
  72
  73        if (interactive) {
  74                interactive_add();
  75                return get_index_file();
  76        }
  77
  78        fd = hold_locked_index(&lock_file, 1);
  79        if (read_cache() < 0)
  80                die("index file corrupt");
  81
  82        if (all || also) {
  83                add_files_to_cache(verbose, also ? prefix : NULL, files);
  84                if (write_cache(fd, active_cache, active_nr) || close(fd))
  85                        die("unable to write new_index file");
  86                return lock_file.filename;
  87        }
  88
  89        if (*files == NULL) {
  90                /* Commit index as-is. */
  91                rollback_lock_file(&lock_file);
  92                return get_index_file();
  93        }
  94
  95        /* update the user index file */
  96        add_files_to_cache(verbose, prefix, files);
  97        if (write_cache(fd, active_cache, active_nr) || close(fd))
  98                die("unable to write new_index file");
  99
 100        if (!initial_commit) {
 101                tree = parse_tree_indirect(head_sha1);
 102                if (!tree)
 103                        die("failed to unpack HEAD tree object");
 104                if (read_tree(tree, 0, NULL))
 105                        die("failed to read HEAD tree object");
 106        }
 107
 108        /* Use a lock file to garbage collect the temporary index file. */
 109        next_index_lock = xmalloc(sizeof(*next_index_lock));
 110        fd = hold_lock_file_for_update(next_index_lock,
 111                                       git_path("next-index-%d", getpid()), 1);
 112        add_files_to_cache(verbose, prefix, files);
 113        if (write_cache(fd, active_cache, active_nr) || close(fd))
 114                die("unable to write new_index file");
 115
 116        return next_index_lock->filename;
 117}
 118
 119static int run_status(FILE *fp, const char *index_file)
 120{
 121        struct wt_status s;
 122
 123        wt_status_prepare(&s);
 124
 125        if (amend) {
 126                s.amend = 1;
 127                s.reference = "HEAD^1";
 128        }
 129        s.verbose = verbose;
 130        s.untracked = untracked_files;
 131        s.index_file = index_file;
 132        s.fp = fp;
 133
 134        wt_status_print(&s);
 135
 136        return s.commitable;
 137}
 138
 139static const char sign_off_header[] = "Signed-off-by: ";
 140
 141static int prepare_log_message(const char *index_file)
 142{
 143        struct stat statbuf;
 144        int commitable;
 145        struct strbuf sb;
 146        char *buffer;
 147        FILE *fp;
 148
 149        strbuf_init(&sb, 0);
 150        if (message) {
 151                strbuf_add(&sb, message, strlen(message));
 152        } else if (logfile && !strcmp(logfile, "-")) {
 153                if (isatty(0))
 154                        fprintf(stderr, "(reading log message from standard input)\n");
 155                if (strbuf_read(&sb, 0, 0) < 0)
 156                        die("could not read log from standard input");
 157        } else if (logfile) {
 158                if (strbuf_read_file(&sb, logfile, 0) < 0)
 159                        die("could not read log file '%s': %s",
 160                            logfile, strerror(errno));
 161        } else if (use_message) {
 162                buffer = strstr(use_message_buffer, "\n\n");
 163                if (!buffer || buffer[2] == '\0')
 164                        die("commit has empty message");
 165                strbuf_add(&sb, buffer + 2, strlen(buffer + 2));
 166        } else if (!stat(git_path("MERGE_MSG"), &statbuf)) {
 167                if (strbuf_read_file(&sb, git_path("MERGE_MSG"), 0) < 0)
 168                        die("could not read MERGE_MSG: %s", strerror(errno));
 169        } else if (!stat(git_path("SQUASH_MSG"), &statbuf)) {
 170                if (strbuf_read_file(&sb, git_path("SQUASH_MSG"), 0) < 0)
 171                        die("could not read SQUASH_MSG: %s", strerror(errno));
 172        } else if (template_file && !stat(template_file, &statbuf)) {
 173                if (strbuf_read_file(&sb, template_file, 0) < 0)
 174                        die("could not read %s: %s",
 175                            template_file, strerror(errno));
 176        }
 177
 178        fp = fopen(git_path(commit_editmsg), "w");
 179        if (fp == NULL)
 180                die("could not open %s\n", git_path(commit_editmsg));
 181
 182        stripspace(&sb, 0);
 183        if (fwrite(sb.buf, 1, sb.len, fp) < sb.len)
 184                die("could not write commit template: %s\n",
 185                    strerror(errno));
 186
 187        if (signoff) {
 188                const char *info, *bol;
 189
 190                info = git_committer_info(1);
 191                strbuf_addch(&sb, '\0');
 192                bol = strrchr(sb.buf + sb.len - 1, '\n');
 193                if (!bol || prefixcmp(bol, sign_off_header))
 194                        fprintf(fp, "\n");
 195                fprintf(fp, "%s%s\n", sign_off_header, git_committer_info(1));
 196        }
 197
 198        strbuf_release(&sb);
 199
 200        if (in_merge && !no_edit)
 201                fprintf(fp,
 202                        "#\n"
 203                        "# It looks like you may be committing a MERGE.\n"
 204                        "# If this is not correct, please remove the file\n"
 205                        "#      %s\n"
 206                        "# and try again.\n"
 207                        "#\n",
 208                        git_path("MERGE_HEAD"));
 209
 210        fprintf(fp,
 211                "\n"
 212                "# Please enter the commit message for your changes.\n"
 213                "# (Comment lines starting with '#' will not be included)\n");
 214        if (only_include_assumed)
 215                fprintf(fp, "# %s\n", only_include_assumed);
 216
 217        commitable = run_status(fp, index_file);
 218
 219        fclose(fp);
 220
 221        return commitable;
 222}
 223
 224/*
 225 * Find out if the message starting at position 'start' in the strbuf
 226 * contains only whitespace and Signed-off-by lines.
 227 */
 228static int message_is_empty(struct strbuf *sb, int start)
 229{
 230        struct strbuf tmpl;
 231        const char *nl;
 232        int eol, i;
 233
 234        /* See if the template is just a prefix of the message. */
 235        strbuf_init(&tmpl, 0);
 236        if (template_file && strbuf_read_file(&tmpl, template_file, 0) > 0) {
 237                stripspace(&tmpl, 1);
 238                if (start + tmpl.len <= sb->len &&
 239                    memcmp(tmpl.buf, sb->buf + start, tmpl.len) == 0)
 240                        start += tmpl.len;
 241        }
 242        strbuf_release(&tmpl);
 243
 244        /* Check if the rest is just whitespace and Signed-of-by's. */
 245        for (i = start; i < sb->len; i++) {
 246                nl = memchr(sb->buf + i, '\n', sb->len - i);
 247                if (nl)
 248                        eol = nl - sb->buf;
 249                else
 250                        eol = sb->len;
 251
 252                if (strlen(sign_off_header) <= eol - i &&
 253                    !prefixcmp(sb->buf + i, sign_off_header)) {
 254                        i = eol;
 255                        continue;
 256                }
 257                while (i < eol)
 258                        if (!isspace(sb->buf[i++]))
 259                                return 0;
 260        }
 261
 262        return 1;
 263}
 264
 265static void determine_author_info(struct strbuf *sb)
 266{
 267        char *name, *email, *date;
 268
 269        name = getenv("GIT_AUTHOR_NAME");
 270        email = getenv("GIT_AUTHOR_EMAIL");
 271        date = getenv("GIT_AUTHOR_DATE");
 272
 273        if (use_message) {
 274                const char *a, *lb, *rb, *eol;
 275
 276                a = strstr(use_message_buffer, "\nauthor ");
 277                if (!a)
 278                        die("invalid commit: %s\n", use_message);
 279
 280                lb = strstr(a + 8, " <");
 281                rb = strstr(a + 8, "> ");
 282                eol = strchr(a + 8, '\n');
 283                if (!lb || !rb || !eol)
 284                        die("invalid commit: %s\n", use_message);
 285
 286                name = xstrndup(a + 8, lb - (a + 8));
 287                email = xstrndup(lb + 2, rb - (lb + 2));
 288                date = xstrndup(rb + 2, eol - (rb + 2));
 289        }
 290
 291        if (force_author) {
 292                const char *lb = strstr(force_author, " <");
 293                const char *rb = strchr(force_author, '>');
 294
 295                if (!lb || !rb)
 296                        die("malformed --author parameter\n");
 297                name = xstrndup(force_author, lb - force_author);
 298                email = xstrndup(lb + 2, rb - (lb + 2));
 299        }
 300
 301        strbuf_addf(sb, "author %s\n", fmt_ident(name, email, date, 1));
 302}
 303
 304static int parse_and_validate_options(int argc, const char *argv[])
 305{
 306        int f = 0;
 307
 308        argc = parse_options(argc, argv, builtin_commit_options,
 309                             builtin_commit_usage, 0);
 310
 311        if (logfile || message || use_message)
 312                no_edit = 1;
 313        if (edit_flag)
 314                no_edit = 0;
 315
 316        if (get_sha1("HEAD", head_sha1))
 317                initial_commit = 1;
 318
 319        if (!get_sha1("MERGE_HEAD", merge_head_sha1))
 320                in_merge = 1;
 321
 322        /* Sanity check options */
 323        if (amend && initial_commit)
 324                die("You have nothing to amend.");
 325        if (amend && in_merge)
 326                die("You are in the middle of a merger -- cannot amend.");
 327
 328        if (use_message)
 329                f++;
 330        if (edit_message)
 331                f++;
 332        if (logfile)
 333                f++;
 334        if (f > 1)
 335                die("Only one of -c/-C/-F can be used.");
 336        if (message && f > 0)
 337                die("Option -m cannot be combined with -c/-C/-F.");
 338        if (edit_message)
 339                use_message = edit_message;
 340        if (amend)
 341                use_message = "HEAD";
 342        if (use_message) {
 343                unsigned char sha1[20];
 344                static char utf8[] = "UTF-8";
 345                const char *out_enc;
 346                char *enc, *end;
 347                struct commit *commit;
 348
 349                if (get_sha1(use_message, sha1))
 350                        die("could not lookup commit %s", use_message);
 351                commit = lookup_commit(sha1);
 352                if (!commit || parse_commit(commit))
 353                        die("could not parse commit %s", use_message);
 354
 355                enc = strstr(commit->buffer, "\nencoding");
 356                if (enc) {
 357                        end = strchr(enc + 10, '\n');
 358                        enc = xstrndup(enc + 10, end - (enc + 10));
 359                } else {
 360                        enc = utf8;
 361                }
 362                out_enc = git_commit_encoding ? git_commit_encoding : utf8;
 363
 364                if (strcmp(out_enc, enc))
 365                        use_message_buffer =
 366                                reencode_string(commit->buffer, out_enc, enc);
 367
 368                /*
 369                 * If we failed to reencode the buffer, just copy it
 370                 * byte for byte so the user can try to fix it up.
 371                 * This also handles the case where input and output
 372                 * encodings are identical.
 373                 */
 374                if (use_message_buffer == NULL)
 375                        use_message_buffer = xstrdup(commit->buffer);
 376                if (enc != utf8)
 377                        free(enc);
 378        }
 379
 380        if (!!also + !!only + !!all + !!interactive > 1)
 381                die("Only one of --include/--only/--all/--interactive can be used.");
 382        if (argc == 0 && (also || (only && !amend)))
 383                die("No paths with --include/--only does not make sense.");
 384        if (argc == 0 && only && amend)
 385                only_include_assumed = "Clever... amending the last one with dirty index.";
 386        if (argc > 0 && !also && !only) {
 387                only_include_assumed = "Explicit paths specified without -i nor -o; assuming --only paths...";
 388                also = 0;
 389        }
 390
 391        if (all && argc > 0)
 392                die("Paths with -a does not make sense.");
 393        else if (interactive && argc > 0)
 394                die("Paths with --interactive does not make sense.");
 395
 396        return argc;
 397}
 398
 399int cmd_status(int argc, const char **argv, const char *prefix)
 400{
 401        const char *index_file;
 402        int commitable;
 403
 404        git_config(git_status_config);
 405
 406        argc = parse_and_validate_options(argc, argv);
 407
 408        index_file = prepare_index(argv, prefix);
 409
 410        commitable = run_status(stdout, index_file);
 411
 412        rollback_lock_file(&lock_file);
 413
 414        return commitable ? 0 : 1;
 415}
 416
 417static int run_hook(const char *index_file, const char *name, const char *arg)
 418{
 419        struct child_process hook;
 420        const char *argv[3], *env[2];
 421        char index[PATH_MAX];
 422
 423        argv[0] = git_path("hooks/%s", name);
 424        argv[1] = arg;
 425        argv[2] = NULL;
 426        snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
 427        env[0] = index;
 428        env[1] = NULL;
 429
 430        if (access(argv[0], X_OK) < 0)
 431                return 0;
 432
 433        memset(&hook, 0, sizeof(hook));
 434        hook.argv = argv;
 435        hook.no_stdin = 1;
 436        hook.stdout_to_stderr = 1;
 437        hook.env = env;
 438
 439        return run_command(&hook);
 440}
 441
 442static void print_summary(const char *prefix, const unsigned char *sha1)
 443{
 444        struct rev_info rev;
 445        struct commit *commit;
 446
 447        commit = lookup_commit(sha1);
 448        if (!commit)
 449                die("couldn't look up newly created commit\n");
 450        if (!commit || parse_commit(commit))
 451                die("could not parse newly created commit");
 452
 453        init_revisions(&rev, prefix);
 454        setup_revisions(0, NULL, &rev, NULL);
 455
 456        rev.abbrev = 0;
 457        rev.diff = 1;
 458        rev.diffopt.output_format =
 459                DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
 460
 461        rev.verbose_header = 1;
 462        rev.show_root_diff = 1;
 463        rev.commit_format = get_commit_format("format:%h: %s");
 464        rev.always_show_header = 1;
 465
 466        printf("Created %scommit ", initial_commit ? "initial " : "");
 467
 468        log_tree_commit(&rev, commit);
 469}
 470
 471int git_commit_config(const char *k, const char *v)
 472{
 473        if (!strcmp(k, "commit.template")) {
 474                template_file = xstrdup(v);
 475                return 0;
 476        }
 477
 478        return git_status_config(k, v);
 479}
 480
 481static const char commit_utf8_warn[] =
 482"Warning: commit message does not conform to UTF-8.\n"
 483"You may want to amend it after fixing the message, or set the config\n"
 484"variable i18n.commitencoding to the encoding your project uses.\n";
 485
 486int cmd_commit(int argc, const char **argv, const char *prefix)
 487{
 488        int header_len, parent_count = 0;
 489        struct strbuf sb;
 490        const char *index_file, *reflog_msg;
 491        char *nl, *header_line;
 492        unsigned char commit_sha1[20];
 493        struct ref_lock *ref_lock;
 494
 495        git_config(git_commit_config);
 496
 497        argc = parse_and_validate_options(argc, argv);
 498
 499        index_file = prepare_index(argv, prefix);
 500
 501        if (!no_verify && run_hook(index_file, "pre-commit", NULL))
 502                exit(1);
 503
 504        if (!prepare_log_message(index_file) && !in_merge) {
 505                run_status(stdout, index_file);
 506                unlink(commit_editmsg);
 507                return 1;
 508        }
 509
 510        strbuf_init(&sb, 0);
 511
 512        /* Start building up the commit header */
 513        read_cache_from(index_file);
 514        active_cache_tree = cache_tree();
 515        if (cache_tree_update(active_cache_tree,
 516                              active_cache, active_nr, 0, 0) < 0)
 517                die("Error building trees");
 518        strbuf_addf(&sb, "tree %s\n",
 519                    sha1_to_hex(active_cache_tree->sha1));
 520
 521        /* Determine parents */
 522        if (initial_commit) {
 523                reflog_msg = "commit (initial)";
 524                parent_count = 0;
 525        } else if (amend) {
 526                struct commit_list *c;
 527                struct commit *commit;
 528
 529                reflog_msg = "commit (amend)";
 530                commit = lookup_commit(head_sha1);
 531                if (!commit || parse_commit(commit))
 532                        die("could not parse HEAD commit");
 533
 534                for (c = commit->parents; c; c = c->next)
 535                        strbuf_addf(&sb, "parent %s\n",
 536                                      sha1_to_hex(c->item->object.sha1));
 537        } else if (in_merge) {
 538                struct strbuf m;
 539                FILE *fp;
 540
 541                reflog_msg = "commit (merge)";
 542                strbuf_addf(&sb, "parent %s\n", sha1_to_hex(head_sha1));
 543                strbuf_init(&m, 0);
 544                fp = fopen(git_path("MERGE_HEAD"), "r");
 545                if (fp == NULL)
 546                        die("could not open %s for reading: %s",
 547                            git_path("MERGE_HEAD"), strerror(errno));
 548                while (strbuf_getline(&m, fp, '\n') != EOF)
 549                        strbuf_addf(&sb, "parent %s\n", m.buf);
 550                fclose(fp);
 551                strbuf_release(&m);
 552        } else {
 553                reflog_msg = "commit";
 554                strbuf_addf(&sb, "parent %s\n", sha1_to_hex(head_sha1));
 555        }
 556
 557        determine_author_info(&sb);
 558        strbuf_addf(&sb, "committer %s\n", git_committer_info(1));
 559        if (!is_encoding_utf8(git_commit_encoding))
 560                strbuf_addf(&sb, "encoding %s\n", git_commit_encoding);
 561        strbuf_addch(&sb, '\n');
 562
 563        /* Get the commit message and validate it */
 564        header_len = sb.len;
 565        if (!no_edit) {
 566                fprintf(stderr, "launching editor, log %s\n", logfile);
 567                launch_editor(git_path(commit_editmsg), &sb);
 568        } else if (strbuf_read_file(&sb, git_path(commit_editmsg), 0) < 0)
 569                die("could not read commit message\n");
 570        if (run_hook(index_file, "commit-msg", commit_editmsg))
 571                exit(1);
 572        stripspace(&sb, 1);
 573        if (sb.len < header_len ||
 574            message_is_empty(&sb, header_len))
 575                die("* no commit message?  aborting commit.");
 576        strbuf_addch(&sb, '\0');
 577        if (is_encoding_utf8(git_commit_encoding) && !is_utf8(sb.buf))
 578                fprintf(stderr, commit_utf8_warn);
 579
 580        if (write_sha1_file(sb.buf, sb.len - 1, commit_type, commit_sha1))
 581                die("failed to write commit object");
 582
 583        ref_lock = lock_any_ref_for_update("HEAD",
 584                                           initial_commit ? NULL : head_sha1,
 585                                           0);
 586
 587        nl = strchr(sb.buf + header_len, '\n');
 588        header_line = xstrndup(sb.buf + header_len,
 589                               nl - (sb.buf + header_len));
 590        strbuf_release(&sb);
 591        strbuf_addf(&sb, "%s: %s\n", reflog_msg, header_line);
 592        strbuf_addch(&sb, '\0');
 593        free(header_line);
 594
 595        if (!ref_lock)
 596                die("cannot lock HEAD ref");
 597        if (write_ref_sha1(ref_lock, commit_sha1, sb.buf) < 0)
 598                die("cannot update HEAD ref");
 599
 600        unlink(git_path("MERGE_HEAD"));
 601        unlink(git_path("MERGE_MSG"));
 602
 603        if (lock_file.filename[0] && commit_locked_index(&lock_file))
 604                die("failed to write new index");
 605
 606        rerere();
 607
 608        run_hook(index_file, "post-commit", NULL);
 609
 610        if (!quiet)
 611                print_summary(prefix, commit_sha1);
 612
 613        return 0;
 614}