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