Code

Merge branch 'pb/prepare-commit-msg'
authorJunio C Hamano <gitster@pobox.com>
Sun, 17 Feb 2008 01:56:59 +0000 (17:56 -0800)
committerJunio C Hamano <gitster@pobox.com>
Sun, 17 Feb 2008 01:56:59 +0000 (17:56 -0800)
* pb/prepare-commit-msg:
  git-commit: add a prepare-commit-msg hook
  git-commit: Refactor creation of log message.
  git-commit: set GIT_EDITOR=: if editor will not be launched
  git-commit: support variable number of hook arguments

Documentation/git-commit.txt
Documentation/hooks.txt
builtin-commit.c
t/t7502-commit.sh
t/t7505-prepare-commit-msg-hook.sh [new file with mode: 0755]
templates/hooks--commit-msg
templates/hooks--prepare-commit-msg [new file with mode: 0644]

index c3725b2ed9958cdc02b312895f35d016e3579d10..b4ae61ff46f4b7ff9e71e9e91a999fdc8fc17560 100644 (file)
@@ -280,8 +280,8 @@ order).
 
 HOOKS
 -----
-This command can run `commit-msg`, `pre-commit`, and
-`post-commit` hooks.  See link:hooks.html[hooks] for more
+This command can run `commit-msg`, `prepare-commit-msg`, `pre-commit`,
+and `post-commit` hooks.  See link:hooks.html[hooks] for more
 information.
 
 
index f110162b0155b3b17bc3133c5f42504290c1de4d..76b8d77460e961fda9a5505a4ce0cf20788de133 100644 (file)
@@ -61,6 +61,35 @@ The default 'pre-commit' hook, when enabled, catches introduction
 of lines with trailing whitespaces and aborts the commit when
 such a line is found.
 
+All the `git-commit` hooks are invoked with the environment
+variable `GIT_EDITOR=:` if the command will not bring up an editor
+to modify the commit message.
+
+prepare-commit-msg
+------------------
+
+This hook is invoked by `git-commit` right after preparing the
+default log message, and before the editor is started.
+
+It takes one to three parameters.  The first is the name of the file
+that the commit log message.  The second is the source of the commit
+message, and can be: `message` (if a `\-m` or `\-F` option was
+given); `template` (if a `\-t` option was given or the
+configuration option `commit.template` is set); `merge` (if the
+commit is a merge or a `.git/MERGE_MSG` file exists); `squash`
+(if a `.git/SQUASH_MSG` file exists); or `commit`, followed by
+a commit SHA1 (if a `\-c`, `\-C` or `\--amend` option was given).
+
+If the exit status is non-zero, `git-commit` will abort.
+
+The purpose of the hook is to edit the message file in place, and
+it is not suppressed by the `\--no-verify` option.  A non-zero exit
+means a failure of the hook and aborts the commit.  It should not
+be used as replacement for pre-commit hook.
+
+The sample `prepare-commit-msg` hook that comes with git comments
+out the `Conflicts:` part of a merge's commit message.
+
 commit-msg
 ----------
 
index ff6ea0d85eebdd0b815f33b9b1ef0df8d1885988..6612b4f40504fea0cd9aec4463c20d8982bfbaeb 100644 (file)
@@ -347,45 +347,107 @@ static int run_status(FILE *fp, const char *index_file, const char *prefix, int
        return s.commitable;
 }
 
+static int run_hook(const char *index_file, const char *name, ...)
+{
+       struct child_process hook;
+       const char *argv[10], *env[2];
+       char index[PATH_MAX];
+       va_list args;
+       int i;
+
+       va_start(args, name);
+       argv[0] = git_path("hooks/%s", name);
+       i = 0;
+       do {
+               if (++i >= ARRAY_SIZE(argv))
+                       die ("run_hook(): too many arguments");
+               argv[i] = va_arg(args, const char *);
+       } while (argv[i]);
+       va_end(args);
+
+       snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
+       env[0] = index;
+       env[1] = NULL;
+
+       if (access(argv[0], X_OK) < 0)
+               return 0;
+
+       memset(&hook, 0, sizeof(hook));
+       hook.argv = argv;
+       hook.no_stdin = 1;
+       hook.stdout_to_stderr = 1;
+       hook.env = env;
+
+       return run_command(&hook);
+}
+
+static int is_a_merge(const unsigned char *sha1)
+{
+       struct commit *commit = lookup_commit(sha1);
+       if (!commit || parse_commit(commit))
+               die("could not parse HEAD commit");
+       return !!(commit->parents && commit->parents->next);
+}
+
 static const char sign_off_header[] = "Signed-off-by: ";
 
-static int prepare_log_message(const char *index_file, const char *prefix)
+static int prepare_to_commit(const char *index_file, const char *prefix)
 {
        struct stat statbuf;
        int commitable, saved_color_setting;
        struct strbuf sb;
        char *buffer;
        FILE *fp;
+       const char *hook_arg1 = NULL;
+       const char *hook_arg2 = NULL;
+
+       if (!no_verify && run_hook(index_file, "pre-commit", NULL))
+               return 0;
 
        strbuf_init(&sb, 0);
        if (message.len) {
                strbuf_addbuf(&sb, &message);
+               hook_arg1 = "message";
        } else if (logfile && !strcmp(logfile, "-")) {
                if (isatty(0))
                        fprintf(stderr, "(reading log message from standard input)\n");
                if (strbuf_read(&sb, 0, 0) < 0)
                        die("could not read log from standard input");
+               hook_arg1 = "message";
        } else if (logfile) {
                if (strbuf_read_file(&sb, logfile, 0) < 0)
                        die("could not read log file '%s': %s",
                            logfile, strerror(errno));
+               hook_arg1 = "message";
        } else if (use_message) {
                buffer = strstr(use_message_buffer, "\n\n");
                if (!buffer || buffer[2] == '\0')
                        die("commit has empty message");
                strbuf_add(&sb, buffer + 2, strlen(buffer + 2));
+               hook_arg1 = "commit";
+               hook_arg2 = use_message;
        } else if (!stat(git_path("MERGE_MSG"), &statbuf)) {
                if (strbuf_read_file(&sb, git_path("MERGE_MSG"), 0) < 0)
                        die("could not read MERGE_MSG: %s", strerror(errno));
+               hook_arg1 = "merge";
        } else if (!stat(git_path("SQUASH_MSG"), &statbuf)) {
                if (strbuf_read_file(&sb, git_path("SQUASH_MSG"), 0) < 0)
                        die("could not read SQUASH_MSG: %s", strerror(errno));
+               hook_arg1 = "squash";
        } else if (template_file && !stat(template_file, &statbuf)) {
                if (strbuf_read_file(&sb, template_file, 0) < 0)
                        die("could not read %s: %s",
                            template_file, strerror(errno));
+               hook_arg1 = "template";
        }
 
+       /*
+        * This final case does not modify the template message,
+        * it just sets the argument to the prepare-commit-msg hook.
+        */
+       else if (in_merge)
+               hook_arg1 = "merge";
+
        fp = fopen(git_path(commit_editmsg), "w");
        if (fp == NULL)
                die("could not open %s", git_path(commit_editmsg));
@@ -417,13 +479,38 @@ static int prepare_log_message(const char *index_file, const char *prefix)
 
        strbuf_release(&sb);
 
-       if (!use_editor) {
+       if (use_editor) {
+               if (in_merge)
+                       fprintf(fp,
+                               "#\n"
+                               "# It looks like you may be committing a MERGE.\n"
+                               "# If this is not correct, please remove the file\n"
+                               "#      %s\n"
+                               "# and try again.\n"
+                               "#\n",
+                               git_path("MERGE_HEAD"));
+
+               fprintf(fp,
+                       "\n"
+                       "# Please enter the commit message for your changes.\n"
+                       "# (Comment lines starting with '#' will ");
+               if (cleanup_mode == CLEANUP_ALL)
+                       fprintf(fp, "not be included)\n");
+               else /* CLEANUP_SPACE, that is. */
+                       fprintf(fp, "be kept.\n"
+                               "# You can remove them yourself if you want to)\n");
+               if (only_include_assumed)
+                       fprintf(fp, "# %s\n", only_include_assumed);
+
+               saved_color_setting = wt_status_use_color;
+               wt_status_use_color = 0;
+               commitable = run_status(fp, index_file, prefix, 1);
+               wt_status_use_color = saved_color_setting;
+       } else {
                struct rev_info rev;
                unsigned char sha1[20];
                const char *parent = "HEAD";
 
-               fclose(fp);
-
                if (!active_nr && read_cache() < 0)
                        die("Cannot read index");
 
@@ -431,48 +518,60 @@ static int prepare_log_message(const char *index_file, const char *prefix)
                        parent = "HEAD^1";
 
                if (get_sha1(parent, sha1))
-                       return !!active_nr;
+                       commitable = !!active_nr;
+               else {
+                       init_revisions(&rev, "");
+                       rev.abbrev = 0;
+                       setup_revisions(0, NULL, &rev, parent);
+                       DIFF_OPT_SET(&rev.diffopt, QUIET);
+                       DIFF_OPT_SET(&rev.diffopt, EXIT_WITH_STATUS);
+                       run_diff_index(&rev, 1 /* cached */);
+
+                       commitable = !!DIFF_OPT_TST(&rev.diffopt, HAS_CHANGES);
+               }
+       }
 
-               init_revisions(&rev, "");
-               rev.abbrev = 0;
-               setup_revisions(0, NULL, &rev, parent);
-               DIFF_OPT_SET(&rev.diffopt, QUIET);
-               DIFF_OPT_SET(&rev.diffopt, EXIT_WITH_STATUS);
-               run_diff_index(&rev, 1 /* cached */);
+       fclose(fp);
 
-               return !!DIFF_OPT_TST(&rev.diffopt, HAS_CHANGES);
+       if (!commitable && !in_merge && !allow_empty &&
+           !(amend && is_a_merge(head_sha1))) {
+               run_status(stdout, index_file, prefix, 0);
+               unlink(commit_editmsg);
+               return 0;
        }
 
-       if (in_merge)
-               fprintf(fp,
-                       "#\n"
-                       "# It looks like you may be committing a MERGE.\n"
-                       "# If this is not correct, please remove the file\n"
-                       "#      %s\n"
-                       "# and try again.\n"
-                       "#\n",
-                       git_path("MERGE_HEAD"));
-
-       fprintf(fp,
-               "\n"
-               "# Please enter the commit message for your changes.\n"
-               "# (Comment lines starting with '#' will ");
-       if (cleanup_mode == CLEANUP_ALL)
-               fprintf(fp, "not be included)\n");
-       else /* CLEANUP_SPACE, that is. */
-               fprintf(fp, "be kept.\n"
-                       "# You can remove them yourself if you want to)\n");
-       if (only_include_assumed)
-               fprintf(fp, "# %s\n", only_include_assumed);
-
-       saved_color_setting = wt_status_use_color;
-       wt_status_use_color = 0;
-       commitable = run_status(fp, index_file, prefix, 1);
-       wt_status_use_color = saved_color_setting;
+       /*
+        * Re-read the index as pre-commit hook could have updated it,
+        * and write it out as a tree.  We must do this before we invoke
+        * the editor and after we invoke run_status above.
+        */
+       discard_cache();
+       read_cache_from(index_file);
+       if (!active_cache_tree)
+               active_cache_tree = cache_tree();
+       if (cache_tree_update(active_cache_tree,
+                             active_cache, active_nr, 0, 0) < 0) {
+               error("Error building trees");
+               return 0;
+       }
 
-       fclose(fp);
+       if (run_hook(index_file, "prepare-commit-msg",
+                    git_path(commit_editmsg), hook_arg1, hook_arg2, NULL))
+               return 0;
 
-       return commitable;
+       if (use_editor) {
+               char index[PATH_MAX];
+               const char *env[2] = { index, NULL };
+               snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
+               launch_editor(git_path(commit_editmsg), NULL, env);
+       }
+
+       if (!no_verify &&
+           run_hook(index_file, "commit-msg", git_path(commit_editmsg), NULL)) {
+               return 0;
+       }
+
+       return 1;
 }
 
 /*
@@ -569,6 +668,8 @@ static int parse_and_validate_options(int argc, const char *argv[],
                use_editor = 0;
        if (edit_flag)
                use_editor = 1;
+       if (!use_editor)
+               setenv("GIT_EDITOR", ":", 1);
 
        if (get_sha1("HEAD", head_sha1))
                initial_commit = 1;
@@ -681,31 +782,6 @@ int cmd_status(int argc, const char **argv, const char *prefix)
        return commitable ? 0 : 1;
 }
 
-static int run_hook(const char *index_file, const char *name, const char *arg)
-{
-       struct child_process hook;
-       const char *argv[3], *env[2];
-       char index[PATH_MAX];
-
-       argv[0] = git_path("hooks/%s", name);
-       argv[1] = arg;
-       argv[2] = NULL;
-       snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
-       env[0] = index;
-       env[1] = NULL;
-
-       if (access(argv[0], X_OK) < 0)
-               return 0;
-
-       memset(&hook, 0, sizeof(hook));
-       hook.argv = argv;
-       hook.no_stdin = 1;
-       hook.stdout_to_stderr = 1;
-       hook.env = env;
-
-       return run_command(&hook);
-}
-
 static void print_summary(const char *prefix, const unsigned char *sha1)
 {
        struct rev_info rev;
@@ -756,14 +832,6 @@ int git_commit_config(const char *k, const char *v)
        return git_status_config(k, v);
 }
 
-static int is_a_merge(const unsigned char *sha1)
-{
-       struct commit *commit = lookup_commit(sha1);
-       if (!commit || parse_commit(commit))
-               die("could not parse HEAD commit");
-       return !!(commit->parents && commit->parents->next);
-}
-
 static const char commit_utf8_warn[] =
 "Warning: commit message does not conform to UTF-8.\n"
 "You may want to amend it after fixing the message, or set the config\n"
@@ -795,33 +863,13 @@ int cmd_commit(int argc, const char **argv, const char *prefix)
 
        index_file = prepare_index(argc, argv, prefix);
 
-       if (!no_verify && run_hook(index_file, "pre-commit", NULL)) {
-               rollback_index_files();
-               return 1;
-       }
-
-       if (!prepare_log_message(index_file, prefix) && !in_merge &&
-           !allow_empty && !(amend && is_a_merge(head_sha1))) {
-               run_status(stdout, index_file, prefix, 0);
+       /* Set up everything for writing the commit object.  This includes
+          running hooks, writing the trees, and interacting with the user.  */
+       if (!prepare_to_commit(index_file, prefix)) {
                rollback_index_files();
-               unlink(commit_editmsg);
                return 1;
        }
 
-       /*
-        * Re-read the index as pre-commit hook could have updated it,
-        * and write it out as a tree.
-        */
-       discard_cache();
-       read_cache_from(index_file);
-       if (!active_cache_tree)
-               active_cache_tree = cache_tree();
-       if (cache_tree_update(active_cache_tree,
-                             active_cache, active_nr, 0, 0) < 0) {
-               rollback_index_files();
-               die("Error building trees");
-       }
-
        /*
         * The commit object
         */
@@ -873,19 +921,8 @@ int cmd_commit(int argc, const char **argv, const char *prefix)
                strbuf_addf(&sb, "encoding %s\n", git_commit_encoding);
        strbuf_addch(&sb, '\n');
 
-       /* Get the commit message and validate it */
+       /* Finally, get the commit message */
        header_len = sb.len;
-       if (use_editor) {
-               char index[PATH_MAX];
-               const char *env[2] = { index, NULL };
-               snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
-               launch_editor(git_path(commit_editmsg), NULL, env);
-       }
-       if (!no_verify &&
-           run_hook(index_file, "commit-msg", git_path(commit_editmsg))) {
-               rollback_index_files();
-               exit(1);
-       }
        if (strbuf_read_file(&sb, git_path(commit_editmsg), 0) < 0) {
                rollback_index_files();
                die("could not read commit message");
index aaf497e6a5948ffa393ea07380bf577ceb5f347b..b780fddc08f9c01eaf1143b9178ab5b7ecd032db 100755 (executable)
@@ -154,4 +154,33 @@ test_expect_success 'cleanup commit messages (strip,-F,-e)' '
 
 '
 
+pwd=`pwd`
+cat >> .git/FAKE_EDITOR << EOF
+#! /bin/sh
+echo editor started > "$pwd/.git/result"
+exit 0
+EOF
+chmod +x .git/FAKE_EDITOR
+
+test_expect_success 'do not fire editor in the presence of conflicts' '
+
+       git clean
+       echo f>g
+       git add g
+       git commit -myes
+       git branch second
+       echo master>g
+       echo g>h
+       git add g h
+       git commit -mmaster
+       git checkout second
+       echo second>g
+       git add g
+       git commit -msecond
+       git cherry-pick -n master
+       echo "editor not started" > .git/result
+       GIT_EDITOR=`pwd`/.git/FAKE_EDITOR git commit && exit 1  # should fail
+       test "`cat .git/result`" = "editor not started"
+'
+
 test_done
diff --git a/t/t7505-prepare-commit-msg-hook.sh b/t/t7505-prepare-commit-msg-hook.sh
new file mode 100755 (executable)
index 0000000..7ddec99
--- /dev/null
@@ -0,0 +1,155 @@
+#!/bin/sh
+
+test_description='prepare-commit-msg hook'
+
+. ./test-lib.sh
+
+test_expect_success 'with no hook' '
+
+       echo "foo" > file &&
+       git add file &&
+       git commit -m "first"
+
+'
+
+# set up fake editor for interactive editing
+cat > fake-editor <<'EOF'
+#!/bin/sh
+exit 0
+EOF
+chmod +x fake-editor
+FAKE_EDITOR="$(pwd)/fake-editor"
+export FAKE_EDITOR
+
+# now install hook that always succeeds and adds a message
+HOOKDIR="$(git rev-parse --git-dir)/hooks"
+HOOK="$HOOKDIR/prepare-commit-msg"
+mkdir -p "$HOOKDIR"
+cat > "$HOOK" <<'EOF'
+#!/bin/sh
+if test "$2" = commit; then
+  source=$(git-rev-parse "$3")
+else
+  source=${2-default}
+fi
+if test "$GIT_EDITOR" = :; then
+  sed -e "1s/.*/$source (no editor)/" "$1" > msg.tmp
+else
+  sed -e "1s/.*/$source/" "$1" > msg.tmp
+fi
+mv msg.tmp "$1"
+exit 0
+EOF
+chmod +x "$HOOK"
+
+echo dummy template > "$(git rev-parse --git-dir)/template"
+
+test_expect_success 'with hook (-m)' '
+
+       echo "more" >> file &&
+       git add file &&
+       git commit -m "more" &&
+       test "`git log -1 --pretty=format:%s`" = "message (no editor)"
+
+'
+
+test_expect_success 'with hook (-m editor)' '
+
+       echo "more" >> file &&
+       git add file &&
+       GIT_EDITOR="$FAKE_EDITOR" git commit -e -m "more more" &&
+       test "`git log -1 --pretty=format:%s`" = message
+
+'
+
+test_expect_success 'with hook (-t)' '
+
+       echo "more" >> file &&
+       git add file &&
+       git commit -t "$(git rev-parse --git-dir)/template" &&
+       test "`git log -1 --pretty=format:%s`" = template
+
+'
+
+test_expect_success 'with hook (-F)' '
+
+       echo "more" >> file &&
+       git add file &&
+       (echo more | git commit -F -) &&
+       test "`git log -1 --pretty=format:%s`" = "message (no editor)"
+
+'
+
+test_expect_success 'with hook (-F editor)' '
+
+       echo "more" >> file &&
+       git add file &&
+       (echo more more | GIT_EDITOR="$FAKE_EDITOR" git commit -e -F -) &&
+       test "`git log -1 --pretty=format:%s`" = message
+
+'
+
+test_expect_success 'with hook (-C)' '
+
+       head=`git rev-parse HEAD` &&
+       echo "more" >> file &&
+       git add file &&
+       git commit -C $head &&
+       test "`git log -1 --pretty=format:%s`" = "$head (no editor)"
+
+'
+
+test_expect_success 'with hook (editor)' '
+
+       echo "more more" >> file &&
+       git add file &&
+       GIT_EDITOR="$FAKE_EDITOR" git commit &&
+       test "`git log -1 --pretty=format:%s`" = default
+
+'
+
+test_expect_success 'with hook (--amend)' '
+
+       head=`git rev-parse HEAD` &&
+       echo "more" >> file &&
+       git add file &&
+       GIT_EDITOR="$FAKE_EDITOR" git commit --amend &&
+       test "`git log -1 --pretty=format:%s`" = "$head"
+
+'
+
+test_expect_success 'with hook (-c)' '
+
+       head=`git rev-parse HEAD` &&
+       echo "more" >> file &&
+       git add file &&
+       GIT_EDITOR="$FAKE_EDITOR" git commit -c $head &&
+       test "`git log -1 --pretty=format:%s`" = "$head"
+
+'
+
+cat > "$HOOK" <<'EOF'
+#!/bin/sh
+exit 1
+EOF
+
+test_expect_success 'with failing hook' '
+
+       head=`git rev-parse HEAD` &&
+       echo "more" >> file &&
+       git add file &&
+       ! GIT_EDITOR="$FAKE_EDITOR" git commit -c $head
+
+'
+
+test_expect_success 'with failing hook (--no-verify)' '
+
+       head=`git rev-parse HEAD` &&
+       echo "more" >> file &&
+       git add file &&
+       ! GIT_EDITOR="$FAKE_EDITOR" git commit --no-verify -c $head
+
+'
+
+
+test_done
index c5cdb9d7eeebab7edf048e77eb92437de24751bf..4ef86eb244bbbde9b793fd8cfab92042adb51485 100644 (file)
@@ -9,6 +9,9 @@
 # To enable this hook, make this file executable.
 
 # Uncomment the below to add a Signed-off-by line to the message.
+# Doing this in a hook is a bad idea in general, but the prepare-commit-msg
+# hook is more suited to it.
+#
 # SOB=$(git var GIT_AUTHOR_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p')
 # grep -qs "^$SOB" "$1" || echo "$SOB" >> "$1"
 
diff --git a/templates/hooks--prepare-commit-msg b/templates/hooks--prepare-commit-msg
new file mode 100644 (file)
index 0000000..ff0f42a
--- /dev/null
@@ -0,0 +1,36 @@
+#!/bin/sh
+#
+# An example hook script to prepare the commit log message.
+# Called by git-commit with the name of the file that has the
+# commit message, followed by the description of the commit
+# message's source.  The hook's purpose is to edit the commit
+# message file.  If the hook fails with a non-zero status,
+# the commit is aborted.
+#
+# To enable this hook, make this file executable.
+
+# This hook includes three examples.  The first comments out the
+# "Conflicts:" part of a merge commit.
+#
+# The second includes the output of "git diff --name-status -r"
+# into the message, just before the "git status" output.  It is
+# commented because it doesn't cope with --amend or with squashed
+# commits.
+#
+# The third example adds a Signed-off-by line to the message, that can
+# still be edited.  This is rarely a good idea.
+
+case "$2 $3" in
+  merge)
+    sed -i '/^Conflicts:/,/#/!b;s/^/# &/;s/^# #/#/' "$1" ;;
+
+# ""|template)
+#   perl -i -pe '
+#      print "\n" . `git diff --cached --name-status -r`
+#       if /^#/ && $first++ == 0' "$1" ;;
+
+  *) ;;
+esac
+
+# SOB=$(git var GIT_AUTHOR_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p')
+# grep -qs "^$SOB" "$1" || echo "$SOB" >> "$1"