summaryrefslogtreecommitdiff
path: root/contrib
diff options
context:
space:
mode:
Diffstat (limited to 'contrib')
-rwxr-xr-xcontrib/completion/git-completion.bash1551
-rw-r--r--contrib/convert-objects/convert-objects.c329
-rw-r--r--contrib/convert-objects/git-convert-objects.txt28
-rw-r--r--contrib/emacs/Makefile2
-rw-r--r--contrib/emacs/README39
-rw-r--r--contrib/emacs/git-blame.el12
-rw-r--r--contrib/emacs/git.el895
-rw-r--r--contrib/emacs/vc-git.el216
-rw-r--r--contrib/examples/README3
-rwxr-xr-xcontrib/examples/git-checkout.sh302
-rwxr-xr-xcontrib/examples/git-clean.sh118
-rwxr-xr-xcontrib/examples/git-clone.sh525
-rwxr-xr-xcontrib/examples/git-commit.sh639
-rwxr-xr-xcontrib/examples/git-fetch.sh377
-rwxr-xr-xcontrib/examples/git-gc.sh2
-rwxr-xr-xcontrib/examples/git-ls-remote.sh142
-rwxr-xr-xcontrib/examples/git-merge-ours.sh14
-rwxr-xr-xcontrib/examples/git-merge.sh554
-rwxr-xr-xcontrib/examples/git-remote.perl474
-rwxr-xr-xcontrib/examples/git-rerere.perl284
-rwxr-xr-xcontrib/examples/git-reset.sh106
-rwxr-xr-xcontrib/examples/git-revert.sh197
-rwxr-xr-xcontrib/examples/git-svnimport.perl976
-rw-r--r--contrib/examples/git-svnimport.txt179
-rwxr-xr-xcontrib/examples/git-tag.sh6
-rwxr-xr-xcontrib/examples/git-verify-tag.sh2
-rwxr-xr-xcontrib/fast-import/git-import.perl64
-rwxr-xr-xcontrib/fast-import/git-import.sh38
-rwxr-xr-xcontrib/fast-import/git-p4626
-rw-r--r--contrib/fast-import/git-p4.txt133
-rwxr-xr-xcontrib/fast-import/import-tars.perl16
-rwxr-xr-xcontrib/fast-import/import-zips.py73
-rwxr-xr-xcontrib/git-resurrect.sh180
-rwxr-xr-xcontrib/gitview/gitview56
-rwxr-xr-xcontrib/hg-to-git/hg-to-git.py99
-rw-r--r--contrib/hooks/post-receive-email318
-rw-r--r--contrib/hooks/pre-auto-gc-battery43
-rw-r--r--contrib/hooks/setgitperms.perl214
-rw-r--r--contrib/hooks/update-paranoid16
-rwxr-xr-x[-rw-r--r--]contrib/remotes2config.sh8
-rwxr-xr-xcontrib/rerere-train.sh52
-rwxr-xr-xcontrib/stats/packinfo.pl16
-rw-r--r--contrib/thunderbird-patch-inline/README20
-rwxr-xr-xcontrib/thunderbird-patch-inline/appp.sh55
-rw-r--r--contrib/vim/README40
-rw-r--r--contrib/vim/syntax/gitcommit.vim18
-rwxr-xr-xcontrib/workdir/git-new-workdir4
47 files changed, 8774 insertions, 1287 deletions
diff --git a/contrib/completion/git-completion.bash b/contrib/completion/git-completion.bash
index cad842af45..1683e6d7b8 100755
--- a/contrib/completion/git-completion.bash
+++ b/contrib/completion/git-completion.bash
@@ -1,3 +1,4 @@
+#!bash
#
# bash completion support for core Git.
#
@@ -33,6 +34,12 @@
# are currently in a git repository. The %s token will be
# the name of the current branch.
#
+# In addition, if you set GIT_PS1_SHOWDIRTYSTATE to a nonempty
+# value, unstaged (*) and staged (+) changes will be shown next
+# to the branch name. You can configure this per-repository
+# with the bash.showDirtyState variable, which defaults to true
+# once GIT_PS1_SHOWDIRTYSTATE is enabled.
+#
# To submit patches:
#
# *) Read Documentation/SubmittingPatches
@@ -45,10 +52,17 @@
# git@vger.kernel.org
#
+case "$COMP_WORDBREAKS" in
+*:*) : great ;;
+*) COMP_WORDBREAKS="$COMP_WORDBREAKS:"
+esac
+
+# __gitdir accepts 0 or 1 arguments (i.e., location)
+# returns location of .git repo
__gitdir ()
{
- if [ -z "$1" ]; then
- if [ -n "$__git_dir" ]; then
+ if [ -z "${1-}" ]; then
+ if [ -n "${__git_dir-}" ]; then
echo "$__git_dir"
elif [ -d .git ]; then
echo .git
@@ -62,49 +76,124 @@ __gitdir ()
fi
}
+# __git_ps1 accepts 0 or 1 arguments (i.e., format string)
+# returns text to add to bash PS1 prompt (includes branch name)
__git_ps1 ()
{
- local b="$(git symbolic-ref HEAD 2>/dev/null)"
- if [ -n "$b" ]; then
- if [ -n "$1" ]; then
- printf "$1" "${b##refs/heads/}"
+ local g="$(__gitdir)"
+ if [ -n "$g" ]; then
+ local r
+ local b
+ if [ -d "$g/rebase-apply" ]; then
+ if [ -f "$g/rebase-apply/rebasing" ]; then
+ r="|REBASE"
+ elif [ -f "$g/rebase-apply/applying" ]; then
+ r="|AM"
+ else
+ r="|AM/REBASE"
+ fi
+ b="$(git symbolic-ref HEAD 2>/dev/null)"
+ elif [ -f "$g/rebase-merge/interactive" ]; then
+ r="|REBASE-i"
+ b="$(cat "$g/rebase-merge/head-name")"
+ elif [ -d "$g/rebase-merge" ]; then
+ r="|REBASE-m"
+ b="$(cat "$g/rebase-merge/head-name")"
+ elif [ -f "$g/MERGE_HEAD" ]; then
+ r="|MERGING"
+ b="$(git symbolic-ref HEAD 2>/dev/null)"
else
- printf " (%s)" "${b##refs/heads/}"
+ if [ -f "$g/BISECT_LOG" ]; then
+ r="|BISECTING"
+ fi
+ if ! b="$(git symbolic-ref HEAD 2>/dev/null)"; then
+ if ! b="$(git describe --exact-match HEAD 2>/dev/null)"; then
+ if [ -r "$g/HEAD" ]; then
+ b="$(cut -c1-7 "$g/HEAD")..."
+ fi
+ fi
+ fi
+ fi
+
+ local w
+ local i
+ local c
+
+ if [ "true" = "$(git rev-parse --is-inside-git-dir 2>/dev/null)" ]; then
+ if [ "true" = "$(git config --bool core.bare 2>/dev/null)" ]; then
+ c="BARE:"
+ else
+ b="GIT_DIR!"
+ fi
+ elif [ "true" = "$(git rev-parse --is-inside-work-tree 2>/dev/null)" ]; then
+ if [ -n "${GIT_PS1_SHOWDIRTYSTATE-}" ]; then
+ if [ "$(git config --bool bash.showDirtyState)" != "false" ]; then
+ git diff --no-ext-diff --ignore-submodules \
+ --quiet --exit-code || w="*"
+ if git rev-parse --quiet --verify HEAD >/dev/null; then
+ git diff-index --cached --quiet \
+ --ignore-submodules HEAD -- || i="+"
+ else
+ i="#"
+ fi
+ fi
+ fi
+ fi
+
+ if [ -n "$b" ]; then
+ if [ -n "${1-}" ]; then
+ printf "$1" "$c${b##refs/heads/}$w$i$r"
+ else
+ printf " (%s)" "$c${b##refs/heads/}$w$i$r"
+ fi
fi
fi
}
+# __gitcomp_1 requires 2 arguments
+__gitcomp_1 ()
+{
+ local c IFS=' '$'\t'$'\n'
+ for c in $1; do
+ case "$c$2" in
+ --*=*) printf %s$'\n' "$c$2" ;;
+ *.) printf %s$'\n' "$c$2" ;;
+ *) printf %s$'\n' "$c$2 " ;;
+ esac
+ done
+}
+
+# __gitcomp accepts 1, 2, 3, or 4 arguments
+# generates completion reply with compgen
__gitcomp ()
{
- local all c s=$'\n' IFS=' '$'\t'$'\n'
local cur="${COMP_WORDS[COMP_CWORD]}"
if [ $# -gt 2 ]; then
cur="$3"
fi
- for c in $1; do
- case "$c$4" in
- --*=*) all="$all$c$4$s" ;;
- *.) all="$all$c$4$s" ;;
- *) all="$all$c$4 $s" ;;
- esac
- done
- IFS=$s
- COMPREPLY=($(compgen -P "$2" -W "$all" -- "$cur"))
- return
+ case "$cur" in
+ --*=)
+ COMPREPLY=()
+ ;;
+ *)
+ local IFS=$'\n'
+ COMPREPLY=($(compgen -P "${2-}" \
+ -W "$(__gitcomp_1 "${1-}" "${4-}")" \
+ -- "$cur"))
+ ;;
+ esac
}
+# __git_heads accepts 0 or 1 arguments (to pass to __gitdir)
__git_heads ()
{
- local cmd i is_hash=y dir="$(__gitdir "$1")"
+ local cmd i is_hash=y dir="$(__gitdir "${1-}")"
if [ -d "$dir" ]; then
- for i in $(git --git-dir="$dir" \
- for-each-ref --format='%(refname)' \
- refs/heads ); do
- echo "${i#refs/heads/}"
- done
+ git --git-dir="$dir" for-each-ref --format='%(refname:short)' \
+ refs/heads
return
fi
- for i in $(git-ls-remote "$1" 2>/dev/null); do
+ for i in $(git ls-remote "${1-}" 2>/dev/null); do
case "$is_hash,$i" in
y,*) is_hash=n ;;
n,*^{}) is_hash=y ;;
@@ -114,18 +203,16 @@ __git_heads ()
done
}
+# __git_tags accepts 0 or 1 arguments (to pass to __gitdir)
__git_tags ()
{
- local cmd i is_hash=y dir="$(__gitdir "$1")"
+ local cmd i is_hash=y dir="$(__gitdir "${1-}")"
if [ -d "$dir" ]; then
- for i in $(git --git-dir="$dir" \
- for-each-ref --format='%(refname)' \
- refs/tags ); do
- echo "${i#refs/tags/}"
- done
+ git --git-dir="$dir" for-each-ref --format='%(refname:short)' \
+ refs/tags
return
fi
- for i in $(git-ls-remote "$1" 2>/dev/null); do
+ for i in $(git ls-remote "${1-}" 2>/dev/null); do
case "$is_hash,$i" in
y,*) is_hash=n ;;
n,*^{}) is_hash=y ;;
@@ -135,24 +222,28 @@ __git_tags ()
done
}
+# __git_refs accepts 0 or 1 arguments (to pass to __gitdir)
__git_refs ()
{
- local cmd i is_hash=y dir="$(__gitdir "$1")"
+ local i is_hash=y dir="$(__gitdir "${1-}")"
+ local cur="${COMP_WORDS[COMP_CWORD]}" format refs
if [ -d "$dir" ]; then
- if [ -e "$dir/HEAD" ]; then echo HEAD; fi
- for i in $(git --git-dir="$dir" \
- for-each-ref --format='%(refname)' \
- refs/tags refs/heads refs/remotes); do
- case "$i" in
- refs/tags/*) echo "${i#refs/tags/}" ;;
- refs/heads/*) echo "${i#refs/heads/}" ;;
- refs/remotes/*) echo "${i#refs/remotes/}" ;;
- *) echo "$i" ;;
- esac
- done
+ case "$cur" in
+ refs|refs/*)
+ format="refname"
+ refs="${cur%/*}"
+ ;;
+ *)
+ if [ -e "$dir/HEAD" ]; then echo HEAD; fi
+ format="refname:short"
+ refs="refs/tags refs/heads refs/remotes"
+ ;;
+ esac
+ git --git-dir="$dir" for-each-ref --format="%($format)" \
+ $refs
return
fi
- for i in $(git-ls-remote "$dir" 2>/dev/null); do
+ for i in $(git ls-remote "$dir" 2>/dev/null); do
case "$is_hash,$i" in
y,*) is_hash=n ;;
n,*^{}) is_hash=y ;;
@@ -164,6 +255,7 @@ __git_refs ()
done
}
+# __git_refs2 requires 1 argument (to pass to __git_refs)
__git_refs2 ()
{
local i
@@ -172,10 +264,11 @@ __git_refs2 ()
done
}
+# __git_refs_remotes requires 1 argument (to pass to ls-remote)
__git_refs_remotes ()
{
local cmd i is_hash=y
- for i in $(git-ls-remote "$1" 2>/dev/null); do
+ for i in $(git ls-remote "$1" 2>/dev/null); do
case "$is_hash,$i" in
n,refs/heads/*)
is_hash=y
@@ -210,19 +303,21 @@ __git_remotes ()
__git_merge_strategies ()
{
- if [ -n "$__git_merge_strategylist" ]; then
+ if [ -n "${__git_merge_strategylist-}" ]; then
echo "$__git_merge_strategylist"
return
fi
- sed -n "/^all_strategies='/{
- s/^all_strategies='//
- s/'//
+ git merge -s help 2>&1 |
+ sed -n -e '/[Aa]vailable strategies are: /,/^$/{
+ s/\.$//
+ s/.*://
+ s/^[ ]*//
+ s/[ ]*$//
p
- q
- }" "$(git --exec-path)/git-merge"
+ }'
}
__git_merge_strategylist=
-__git_merge_strategylist="$(__git_merge_strategies 2>/dev/null)"
+__git_merge_strategylist=$(__git_merge_strategies 2>/dev/null)
__git_complete_file ()
{
@@ -242,9 +337,23 @@ __git_complete_file ()
ls="$ref"
;;
esac
+
+ case "$COMP_WORDBREAKS" in
+ *:*) : great ;;
+ *) pfx="$ref:$pfx" ;;
+ esac
+
+ local IFS=$'\n'
COMPREPLY=($(compgen -P "$pfx" \
-W "$(git --git-dir="$(__gitdir)" ls-tree "$ls" \
- | sed '/^100... blob /s,^.* ,,
+ | sed '/^100... blob /{
+ s,^.* ,,
+ s,$, ,
+ }
+ /^120000 blob /{
+ s,^.* ,,
+ s,$, ,
+ }
/^040000 tree /{
s,^.* ,,
s,$,/,
@@ -272,34 +381,129 @@ __git_complete_revlist ()
cur="${cur#*..}"
__gitcomp "$(__git_refs)" "$pfx" "$cur"
;;
- *.)
- __gitcomp "$cur."
- ;;
*)
__gitcomp "$(__git_refs)"
;;
esac
}
-__git_commands ()
+__git_complete_remote_or_refspec ()
+{
+ local cmd="${COMP_WORDS[1]}"
+ local cur="${COMP_WORDS[COMP_CWORD]}"
+ local i c=2 remote="" pfx="" lhs=1 no_complete_refspec=0
+ while [ $c -lt $COMP_CWORD ]; do
+ i="${COMP_WORDS[c]}"
+ case "$i" in
+ --all|--mirror) [ "$cmd" = "push" ] && no_complete_refspec=1 ;;
+ -*) ;;
+ *) remote="$i"; break ;;
+ esac
+ c=$((++c))
+ done
+ if [ -z "$remote" ]; then
+ __gitcomp "$(__git_remotes)"
+ return
+ fi
+ if [ $no_complete_refspec = 1 ]; then
+ COMPREPLY=()
+ return
+ fi
+ [ "$remote" = "." ] && remote=
+ case "$cur" in
+ *:*)
+ case "$COMP_WORDBREAKS" in
+ *:*) : great ;;
+ *) pfx="${cur%%:*}:" ;;
+ esac
+ cur="${cur#*:}"
+ lhs=0
+ ;;
+ +*)
+ pfx="+"
+ cur="${cur#+}"
+ ;;
+ esac
+ case "$cmd" in
+ fetch)
+ if [ $lhs = 1 ]; then
+ __gitcomp "$(__git_refs2 "$remote")" "$pfx" "$cur"
+ else
+ __gitcomp "$(__git_refs)" "$pfx" "$cur"
+ fi
+ ;;
+ pull)
+ if [ $lhs = 1 ]; then
+ __gitcomp "$(__git_refs "$remote")" "$pfx" "$cur"
+ else
+ __gitcomp "$(__git_refs)" "$pfx" "$cur"
+ fi
+ ;;
+ push)
+ if [ $lhs = 1 ]; then
+ __gitcomp "$(__git_refs)" "$pfx" "$cur"
+ else
+ __gitcomp "$(__git_refs "$remote")" "$pfx" "$cur"
+ fi
+ ;;
+ esac
+}
+
+__git_complete_strategy ()
+{
+ case "${COMP_WORDS[COMP_CWORD-1]}" in
+ -s|--strategy)
+ __gitcomp "$(__git_merge_strategies)"
+ return 0
+ esac
+ local cur="${COMP_WORDS[COMP_CWORD]}"
+ case "$cur" in
+ --strategy=*)
+ __gitcomp "$(__git_merge_strategies)" "" "${cur##--strategy=}"
+ return 0
+ ;;
+ esac
+ return 1
+}
+
+__git_all_commands ()
{
- if [ -n "$__git_commandlist" ]; then
- echo "$__git_commandlist"
+ if [ -n "${__git_all_commandlist-}" ]; then
+ echo "$__git_all_commandlist"
return
fi
local i IFS=" "$'\n'
for i in $(git help -a|egrep '^ ')
do
case $i in
- add--interactive) : plumbing;;
+ *--*) : helper pattern;;
+ *) echo $i;;
+ esac
+ done
+}
+__git_all_commandlist=
+__git_all_commandlist="$(__git_all_commands 2>/dev/null)"
+
+__git_porcelain_commands ()
+{
+ if [ -n "${__git_porcelain_commandlist-}" ]; then
+ echo "$__git_porcelain_commandlist"
+ return
+ fi
+ local i IFS=" "$'\n'
+ for i in "help" $(__git_all_commands)
+ do
+ case $i in
+ *--*) : helper pattern;;
applymbox) : ask gittus;;
applypatch) : ask gittus;;
archimport) : import;;
cat-file) : plumbing;;
check-attr) : plumbing;;
check-ref-format) : plumbing;;
+ checkout-index) : plumbing;;
commit-tree) : plumbing;;
- convert-objects) : plumbing;;
+ count-objects) : infrequent;;
cvsexportcommit) : export;;
cvsimport) : import;;
cvsserver) : daemon;;
@@ -308,8 +512,8 @@ __git_commands ()
diff-index) : plumbing;;
diff-tree) : plumbing;;
fast-import) : import;;
+ fast-export) : export;;
fsck-objects) : plumbing;;
- fetch--tool) : plumbing;;
fetch-pack) : plumbing;;
fmt-merge-msg) : plumbing;;
for-each-ref) : plumbing;;
@@ -318,6 +522,10 @@ __git_commands ()
index-pack) : plumbing;;
init-db) : deprecated;;
local-fetch) : plumbing;;
+ lost-found) : infrequent;;
+ ls-files) : plumbing;;
+ ls-remote) : plumbing;;
+ ls-tree) : plumbing;;
mailinfo) : plumbing;;
mailsplit) : plumbing;;
merge-*) : plumbing;;
@@ -335,19 +543,18 @@ __git_commands ()
read-tree) : plumbing;;
receive-pack) : plumbing;;
reflog) : plumbing;;
- repo-config) : plumbing;;
+ repo-config) : deprecated;;
rerere) : plumbing;;
rev-list) : plumbing;;
rev-parse) : plumbing;;
runstatus) : plumbing;;
sh-setup) : internal;;
shell) : daemon;;
+ show-ref) : plumbing;;
send-pack) : plumbing;;
show-index) : plumbing;;
ssh-*) : transport;;
stripspace) : plumbing;;
- svn) : import export;;
- svnimport) : import;;
symbolic-ref) : plumbing;;
tar-tree) : deprecated;;
unpack-file) : plumbing;;
@@ -358,13 +565,15 @@ __git_commands ()
upload-archive) : plumbing;;
upload-pack) : plumbing;;
write-tree) : plumbing;;
+ var) : infrequent;;
+ verify-pack) : infrequent;;
verify-tag) : plumbing;;
*) echo $i;;
esac
done
}
-__git_commandlist=
-__git_commandlist="$(__git_commands 2>/dev/null)"
+__git_porcelain_commandlist=
+__git_porcelain_commandlist="$(__git_porcelain_commands 2>/dev/null)"
__git_aliases ()
{
@@ -379,6 +588,7 @@ __git_aliases ()
done
}
+# __git_aliased_command requires 1 argument
__git_aliased_command ()
{
local word cmdline=$(git --git-dir="$(__gitdir)" \
@@ -391,13 +601,42 @@ __git_aliased_command ()
done
}
-__git_whitespacelist="nowarn warn error error-all strip"
+# __git_find_subcommand requires 1 argument
+__git_find_subcommand ()
+{
+ local word subcommand c=1
+
+ while [ $c -lt $COMP_CWORD ]; do
+ word="${COMP_WORDS[c]}"
+ for subcommand in $1; do
+ if [ "$subcommand" = "$word" ]; then
+ echo "$subcommand"
+ return
+ fi
+ done
+ c=$((++c))
+ done
+}
+
+__git_has_doubledash ()
+{
+ local c=1
+ while [ $c -lt $COMP_CWORD ]; do
+ if [ "--" = "${COMP_WORDS[c]}" ]; then
+ return 0
+ fi
+ c=$((++c))
+ done
+ return 1
+}
+
+__git_whitespacelist="nowarn warn error error-all fix"
_git_am ()
{
- local cur="${COMP_WORDS[COMP_CWORD]}"
- if [ -d .dotest ]; then
- __gitcomp "--skip --resolved"
+ local cur="${COMP_WORDS[COMP_CWORD]}" dir="$(__gitdir)"
+ if [ -d "$dir"/rebase-apply ]; then
+ __gitcomp "--skip --resolved --abort"
return
fi
case "$cur" in
@@ -407,7 +646,8 @@ _git_am ()
;;
--*)
__gitcomp "
- --signoff --utf8 --binary --3way --interactive
+ --3way --committer-date-is-author-date --ignore-date
+ --interactive --keep --no-utf8 --signoff --utf8
--whitespace=
"
return
@@ -437,36 +677,56 @@ _git_apply ()
_git_add ()
{
+ __git_has_doubledash && return
+
local cur="${COMP_WORDS[COMP_CWORD]}"
case "$cur" in
--*)
- __gitcomp "--interactive --refresh"
+ __gitcomp "
+ --interactive --refresh --patch --update --dry-run
+ --ignore-errors --intent-to-add
+ "
return
esac
COMPREPLY=()
}
+_git_archive ()
+{
+ local cur="${COMP_WORDS[COMP_CWORD]}"
+ case "$cur" in
+ --format=*)
+ __gitcomp "$(git archive --list)" "" "${cur##--format=}"
+ return
+ ;;
+ --remote=*)
+ __gitcomp "$(__git_remotes)" "" "${cur##--remote=}"
+ return
+ ;;
+ --*)
+ __gitcomp "
+ --format= --list --verbose
+ --prefix= --remote= --exec=
+ "
+ return
+ ;;
+ esac
+ __git_complete_file
+}
+
_git_bisect ()
{
- local i c=1 command
- while [ $c -lt $COMP_CWORD ]; do
- i="${COMP_WORDS[c]}"
- case "$i" in
- start|bad|good|reset|visualize|replay|log)
- command="$i"
- break
- ;;
- esac
- c=$((++c))
- done
+ __git_has_doubledash && return
- if [ $c -eq $COMP_CWORD -a -z "$command" ]; then
- __gitcomp "start bad good reset visualize replay log"
+ local subcommands="start bad good skip reset visualize replay log run"
+ local subcommand="$(__git_find_subcommand "$subcommands")"
+ if [ -z "$subcommand" ]; then
+ __gitcomp "$subcommands"
return
fi
- case "$command" in
- bad|good|reset)
+ case "$subcommand" in
+ bad|good|reset|skip)
__gitcomp "$(__git_refs)"
;;
*)
@@ -477,26 +737,42 @@ _git_bisect ()
_git_branch ()
{
- __gitcomp "$(__git_refs)"
-}
+ local i c=1 only_local_ref="n" has_r="n"
-_git_bundle ()
-{
- local mycword="$COMP_CWORD"
- case "${COMP_WORDS[0]}" in
- git)
- local cmd="${COMP_WORDS[2]}"
- mycword="$((mycword-1))"
+ while [ $c -lt $COMP_CWORD ]; do
+ i="${COMP_WORDS[c]}"
+ case "$i" in
+ -d|-m) only_local_ref="y" ;;
+ -r) has_r="y" ;;
+ esac
+ c=$((++c))
+ done
+
+ case "${COMP_WORDS[COMP_CWORD]}" in
+ --*)
+ __gitcomp "
+ --color --no-color --verbose --abbrev= --no-abbrev
+ --track --no-track --contains --merged --no-merged
+ "
;;
- git-bundle*)
- local cmd="${COMP_WORDS[1]}"
+ *)
+ if [ $only_local_ref = "y" -a $has_r = "n" ]; then
+ __gitcomp "$(__git_heads)"
+ else
+ __gitcomp "$(__git_refs)"
+ fi
;;
esac
- case "$mycword" in
- 1)
+}
+
+_git_bundle ()
+{
+ local cmd="${COMP_WORDS[2]}"
+ case "$COMP_CWORD" in
+ 2)
__gitcomp "create list-heads verify unbundle"
;;
- 2)
+ 3)
# looking for a file
;;
*)
@@ -511,6 +787,8 @@ _git_bundle ()
_git_checkout ()
{
+ __git_has_doubledash && return
+
__gitcomp "$(__git_refs)"
}
@@ -532,14 +810,55 @@ _git_cherry_pick ()
esac
}
+_git_clean ()
+{
+ __git_has_doubledash && return
+
+ local cur="${COMP_WORDS[COMP_CWORD]}"
+ case "$cur" in
+ --*)
+ __gitcomp "--dry-run --quiet"
+ return
+ ;;
+ esac
+ COMPREPLY=()
+}
+
+_git_clone ()
+{
+ local cur="${COMP_WORDS[COMP_CWORD]}"
+ case "$cur" in
+ --*)
+ __gitcomp "
+ --local
+ --no-hardlinks
+ --shared
+ --reference
+ --quiet
+ --no-checkout
+ --bare
+ --mirror
+ --origin
+ --upload-pack
+ --template=
+ --depth
+ "
+ return
+ ;;
+ esac
+ COMPREPLY=()
+}
+
_git_commit ()
{
+ __git_has_doubledash && return
+
local cur="${COMP_WORDS[COMP_CWORD]}"
case "$cur" in
--*)
__gitcomp "
--all --author= --signoff --verify --no-verify
- --edit --amend --include --only
+ --edit --amend --include --only --interactive
"
return
esac
@@ -548,63 +867,111 @@ _git_commit ()
_git_describe ()
{
+ local cur="${COMP_WORDS[COMP_CWORD]}"
+ case "$cur" in
+ --*)
+ __gitcomp "
+ --all --tags --contains --abbrev= --candidates=
+ --exact-match --debug --long --match --always
+ "
+ return
+ esac
__gitcomp "$(__git_refs)"
}
+__git_diff_common_options="--stat --numstat --shortstat --summary
+ --patch-with-stat --name-only --name-status --color
+ --no-color --color-words --no-renames --check
+ --full-index --binary --abbrev --diff-filter=
+ --find-copies-harder
+ --text --ignore-space-at-eol --ignore-space-change
+ --ignore-all-space --exit-code --quiet --ext-diff
+ --no-ext-diff
+ --no-prefix --src-prefix= --dst-prefix=
+ --inter-hunk-context=
+ --patience
+ --raw
+"
+
_git_diff ()
{
+ __git_has_doubledash && return
+
+ local cur="${COMP_WORDS[COMP_CWORD]}"
+ case "$cur" in
+ --*)
+ __gitcomp "--cached --staged --pickaxe-all --pickaxe-regex
+ --base --ours --theirs
+ $__git_diff_common_options
+ "
+ return
+ ;;
+ esac
__git_complete_file
}
-_git_diff_tree ()
+__git_mergetools_common="diffuse ecmerge emerge kdiff3 meld opendiff
+ tkdiff vimdiff gvimdiff xxdiff
+"
+
+_git_difftool ()
{
- __gitcomp "$(__git_refs)"
+ local cur="${COMP_WORDS[COMP_CWORD]}"
+ case "$cur" in
+ --tool=*)
+ __gitcomp "$__git_mergetools_common kompare" "" "${cur##--tool=}"
+ return
+ ;;
+ --*)
+ __gitcomp "--tool="
+ return
+ ;;
+ esac
+ COMPREPLY=()
}
+__git_fetch_options="
+ --quiet --verbose --append --upload-pack --force --keep --depth=
+ --tags --no-tags
+"
+
_git_fetch ()
{
local cur="${COMP_WORDS[COMP_CWORD]}"
-
- case "${COMP_WORDS[0]},$COMP_CWORD" in
- git-fetch*,1)
- __gitcomp "$(__git_remotes)"
- ;;
- git,2)
- __gitcomp "$(__git_remotes)"
- ;;
- *)
- case "$cur" in
- *:*)
- __gitcomp "$(__git_refs)" "" "${cur#*:}"
- ;;
- *)
- local remote
- case "${COMP_WORDS[0]}" in
- git-fetch) remote="${COMP_WORDS[1]}" ;;
- git) remote="${COMP_WORDS[2]}" ;;
- esac
- __gitcomp "$(__git_refs2 "$remote")"
- ;;
- esac
+ case "$cur" in
+ --*)
+ __gitcomp "$__git_fetch_options"
+ return
;;
esac
+ __git_complete_remote_or_refspec
}
_git_format_patch ()
{
local cur="${COMP_WORDS[COMP_CWORD]}"
case "$cur" in
+ --thread=*)
+ __gitcomp "
+ deep shallow
+ " "" "${cur##--thread=}"
+ return
+ ;;
--*)
__gitcomp "
- --stdout --attach --thread
+ --stdout --attach --no-attach --thread --thread=
--output-directory
--numbered --start-number
--numbered-files
--keep-subject
--signoff
- --in-reply-to=
+ --in-reply-to= --cc=
--full-index --binary
--not --all
+ --cover-letter
+ --no-prefix --src-prefix= --dst-prefix=
+ --inline --suffix= --ignore-if-in-upstream
+ --subject-prefix=
"
return
;;
@@ -612,6 +979,21 @@ _git_format_patch ()
__git_complete_revlist
}
+_git_fsck ()
+{
+ local cur="${COMP_WORDS[COMP_CWORD]}"
+ case "$cur" in
+ --*)
+ __gitcomp "
+ --tags --root --unreachable --cache --no-reflogs --full
+ --strict --verbose --lost-found
+ "
+ return
+ ;;
+ esac
+ COMPREPLY=()
+}
+
_git_gc ()
{
local cur="${COMP_WORDS[COMP_CWORD]}"
@@ -624,6 +1006,84 @@ _git_gc ()
COMPREPLY=()
}
+_git_grep ()
+{
+ __git_has_doubledash && return
+
+ local cur="${COMP_WORDS[COMP_CWORD]}"
+ case "$cur" in
+ --*)
+ __gitcomp "
+ --cached
+ --text --ignore-case --word-regexp --invert-match
+ --full-name
+ --extended-regexp --basic-regexp --fixed-strings
+ --files-with-matches --name-only
+ --files-without-match
+ --count
+ --and --or --not --all-match
+ "
+ return
+ ;;
+ esac
+ COMPREPLY=()
+}
+
+_git_help ()
+{
+ local cur="${COMP_WORDS[COMP_CWORD]}"
+ case "$cur" in
+ --*)
+ __gitcomp "--all --info --man --web"
+ return
+ ;;
+ esac
+ __gitcomp "$(__git_all_commands)
+ attributes cli core-tutorial cvs-migration
+ diffcore gitk glossary hooks ignore modules
+ repository-layout tutorial tutorial-2
+ workflows
+ "
+}
+
+_git_init ()
+{
+ local cur="${COMP_WORDS[COMP_CWORD]}"
+ case "$cur" in
+ --shared=*)
+ __gitcomp "
+ false true umask group all world everybody
+ " "" "${cur##--shared=}"
+ return
+ ;;
+ --*)
+ __gitcomp "--quiet --bare --template= --shared --shared="
+ return
+ ;;
+ esac
+ COMPREPLY=()
+}
+
+_git_ls_files ()
+{
+ __git_has_doubledash && return
+
+ local cur="${COMP_WORDS[COMP_CWORD]}"
+ case "$cur" in
+ --*)
+ __gitcomp "--cached --deleted --modified --others --ignored
+ --stage --directory --no-empty-directory --unmerged
+ --killed --exclude= --exclude-from=
+ --exclude-per-directory= --exclude-standard
+ --error-unmatch --with-tree= --full-name
+ --abbrev --ignored --exclude-per-directory
+ "
+ return
+ ;;
+ esac
+ COMPREPLY=()
+}
+
_git_ls_remote ()
{
__gitcomp "$(__git_remotes)"
@@ -634,35 +1094,73 @@ _git_ls_tree ()
__git_complete_file
}
+# Options that go well for log, shortlog and gitk
+__git_log_common_options="
+ --not --all
+ --branches --tags --remotes
+ --first-parent --no-merges
+ --max-count=
+ --max-age= --since= --after=
+ --min-age= --until= --before=
+"
+# Options that go well for log and gitk (not shortlog)
+__git_log_gitk_options="
+ --dense --sparse --full-history
+ --simplify-merges --simplify-by-decoration
+ --left-right
+"
+# Options that go well for log and shortlog (not gitk)
+__git_log_shortlog_options="
+ --author= --committer= --grep=
+ --all-match
+"
+
+__git_log_pretty_formats="oneline short medium full fuller email raw format:"
+__git_log_date_formats="relative iso8601 rfc2822 short local default raw"
+
_git_log ()
{
+ __git_has_doubledash && return
+
local cur="${COMP_WORDS[COMP_CWORD]}"
+ local g="$(git rev-parse --git-dir 2>/dev/null)"
+ local merge=""
+ if [ -f "$g/MERGE_HEAD" ]; then
+ merge="--merge"
+ fi
case "$cur" in
--pretty=*)
- __gitcomp "
- oneline short medium full fuller email raw
+ __gitcomp "$__git_log_pretty_formats
" "" "${cur##--pretty=}"
return
;;
+ --format=*)
+ __gitcomp "$__git_log_pretty_formats
+ " "" "${cur##--format=}"
+ return
+ ;;
--date=*)
- __gitcomp "
- relative iso8601 rfc2822 short local default
- " "" "${cur##--date=}"
+ __gitcomp "$__git_log_date_formats" "" "${cur##--date=}"
return
;;
--*)
__gitcomp "
- --max-count= --max-age= --since= --after=
- --min-age= --before= --until=
+ $__git_log_common_options
+ $__git_log_shortlog_options
+ $__git_log_gitk_options
--root --topo-order --date-order --reverse
- --no-merges --follow
+ --follow
--abbrev-commit --abbrev=
--relative-date --date=
- --author= --committer= --grep=
- --all-match
- --pretty= --name-status --name-only --raw
- --not --all
- --left-right --cherry-pick
+ --pretty= --format= --oneline
+ --cherry-pick
+ --graph
+ --decorate
+ --walk-reflogs
+ --parents --children
+ $merge
+ $__git_diff_common_options
+ --pickaxe-all --pickaxe-regex
"
return
;;
@@ -670,26 +1168,38 @@ _git_log ()
__git_complete_revlist
}
+__git_merge_options="
+ --no-commit --no-stat --log --no-log --squash --strategy
+ --commit --stat --no-squash --ff --no-ff
+"
+
_git_merge ()
{
+ __git_complete_strategy && return
+
local cur="${COMP_WORDS[COMP_CWORD]}"
- case "${COMP_WORDS[COMP_CWORD-1]}" in
- -s|--strategy)
- __gitcomp "$(__git_merge_strategies)"
+ case "$cur" in
+ --*)
+ __gitcomp "$__git_merge_options"
return
esac
+ __gitcomp "$(__git_refs)"
+}
+
+_git_mergetool ()
+{
+ local cur="${COMP_WORDS[COMP_CWORD]}"
case "$cur" in
- --strategy=*)
- __gitcomp "$(__git_merge_strategies)" "" "${cur##--strategy=}"
+ --tool=*)
+ __gitcomp "$__git_mergetools_common tortoisemerge" "" "${cur##--tool=}"
return
;;
--*)
- __gitcomp "
- --no-commit --no-summary --squash --strategy
- "
+ __gitcomp "--tool="
return
+ ;;
esac
- __gitcomp "$(__git_refs)"
+ COMPREPLY=()
}
_git_merge_base ()
@@ -697,6 +1207,18 @@ _git_merge_base ()
__gitcomp "$(__git_refs)"
}
+_git_mv ()
+{
+ local cur="${COMP_WORDS[COMP_CWORD]}"
+ case "$cur" in
+ --*)
+ __gitcomp "--dry-run"
+ return
+ ;;
+ esac
+ COMPREPLY=()
+}
+
_git_name_rev ()
{
__gitcomp "--tags --all --stdin"
@@ -704,80 +1226,100 @@ _git_name_rev ()
_git_pull ()
{
- local cur="${COMP_WORDS[COMP_CWORD]}"
+ __git_complete_strategy && return
- case "${COMP_WORDS[0]},$COMP_CWORD" in
- git-pull*,1)
- __gitcomp "$(__git_remotes)"
- ;;
- git,2)
- __gitcomp "$(__git_remotes)"
- ;;
- *)
- local remote
- case "${COMP_WORDS[0]}" in
- git-pull) remote="${COMP_WORDS[1]}" ;;
- git) remote="${COMP_WORDS[2]}" ;;
- esac
- __gitcomp "$(__git_refs "$remote")"
+ local cur="${COMP_WORDS[COMP_CWORD]}"
+ case "$cur" in
+ --*)
+ __gitcomp "
+ --rebase --no-rebase
+ $__git_merge_options
+ $__git_fetch_options
+ "
+ return
;;
esac
+ __git_complete_remote_or_refspec
}
_git_push ()
{
local cur="${COMP_WORDS[COMP_CWORD]}"
-
- case "${COMP_WORDS[0]},$COMP_CWORD" in
- git-push*,1)
- __gitcomp "$(__git_remotes)"
- ;;
- git,2)
+ case "${COMP_WORDS[COMP_CWORD-1]}" in
+ --repo)
__gitcomp "$(__git_remotes)"
+ return
+ esac
+ case "$cur" in
+ --repo=*)
+ __gitcomp "$(__git_remotes)" "" "${cur##--repo=}"
+ return
;;
- *)
- case "$cur" in
- *:*)
- local remote
- case "${COMP_WORDS[0]}" in
- git-push) remote="${COMP_WORDS[1]}" ;;
- git) remote="${COMP_WORDS[2]}" ;;
- esac
- __gitcomp "$(__git_refs "$remote")" "" "${cur#*:}"
- ;;
- +*)
- __gitcomp "$(__git_refs)" + "${cur#+}"
- ;;
- *)
- __gitcomp "$(__git_refs)"
- ;;
- esac
+ --*)
+ __gitcomp "
+ --all --mirror --tags --dry-run --force --verbose
+ --receive-pack= --repo=
+ "
+ return
;;
esac
+ __git_complete_remote_or_refspec
}
_git_rebase ()
{
- local cur="${COMP_WORDS[COMP_CWORD]}"
- if [ -d .dotest ] || [ -d .git/.dotest-merge ]; then
+ local cur="${COMP_WORDS[COMP_CWORD]}" dir="$(__gitdir)"
+ if [ -d "$dir"/rebase-apply ] || [ -d "$dir"/rebase-merge ]; then
__gitcomp "--continue --skip --abort"
return
fi
- case "${COMP_WORDS[COMP_CWORD-1]}" in
- -s|--strategy)
- __gitcomp "$(__git_merge_strategies)"
+ __git_complete_strategy && return
+ case "$cur" in
+ --*)
+ __gitcomp "--onto --merge --strategy --interactive"
return
esac
+ __gitcomp "$(__git_refs)"
+}
+
+__git_send_email_confirm_options="always never auto cc compose"
+__git_send_email_suppresscc_options="author self cc ccbody sob cccmd body all"
+
+_git_send_email ()
+{
+ local cur="${COMP_WORDS[COMP_CWORD]}"
case "$cur" in
- --strategy=*)
- __gitcomp "$(__git_merge_strategies)" "" "${cur##--strategy=}"
+ --confirm=*)
+ __gitcomp "
+ $__git_send_email_confirm_options
+ " "" "${cur##--confirm=}"
+ return
+ ;;
+ --suppress-cc=*)
+ __gitcomp "
+ $__git_send_email_suppresscc_options
+ " "" "${cur##--suppress-cc=}"
+
+ return
+ ;;
+ --smtp-encryption=*)
+ __gitcomp "ssl tls" "" "${cur##--smtp-encryption=}"
return
;;
--*)
- __gitcomp "--onto --merge --strategy"
+ __gitcomp "--annotate --bcc --cc --cc-cmd --chain-reply-to
+ --compose --confirm= --dry-run --envelope-sender
+ --from --identity
+ --in-reply-to --no-chain-reply-to --no-signed-off-by-cc
+ --no-suppress-from --no-thread --quiet
+ --signed-off-by-cc --smtp-pass --smtp-server
+ --smtp-server-port --smtp-encryption= --smtp-user
+ --subject --suppress-cc= --suppress-from --thread --to
+ --validate --no-validate"
return
+ ;;
esac
- __gitcomp "$(__git_refs)"
+ COMPREPLY=()
}
_git_config ()
@@ -811,17 +1353,41 @@ _git_config ()
__gitcomp "$(__git_merge_strategies)"
return
;;
- color.branch|color.diff|color.status)
+ color.branch|color.diff|color.interactive|color.status|color.ui)
__gitcomp "always never auto"
return
;;
+ color.pager)
+ __gitcomp "false true"
+ return
+ ;;
color.*.*)
__gitcomp "
- black red green yellow blue magenta cyan white
+ normal black red green yellow blue magenta cyan white
bold dim ul blink reverse
"
return
;;
+ help.format)
+ __gitcomp "man info web html"
+ return
+ ;;
+ log.date)
+ __gitcomp "$__git_log_date_formats"
+ return
+ ;;
+ sendemail.aliasesfiletype)
+ __gitcomp "mutt mailrc pine elm gnus"
+ return
+ ;;
+ sendemail.confirm)
+ __gitcomp "$__git_send_email_confirm_options"
+ return
+ ;;
+ sendemail.suppresscc)
+ __gitcomp "$__git_send_email_suppresscc_options"
+ return
+ ;;
*.*)
COMPREPLY=()
return
@@ -841,7 +1407,7 @@ _git_config ()
branch.*.*)
local pfx="${cur%.*}."
cur="${cur##*.}"
- __gitcomp "remote merge" "$pfx" "$cur"
+ __gitcomp "remote merge mergeoptions" "$pfx" "$cur"
return
;;
branch.*)
@@ -850,11 +1416,44 @@ _git_config ()
__gitcomp "$(__git_heads)" "$pfx" "$cur" "."
return
;;
+ guitool.*.*)
+ local pfx="${cur%.*}."
+ cur="${cur##*.}"
+ __gitcomp "
+ argprompt cmd confirm needsfile noconsole norescan
+ prompt revprompt revunmerged title
+ " "$pfx" "$cur"
+ return
+ ;;
+ difftool.*.*)
+ local pfx="${cur%.*}."
+ cur="${cur##*.}"
+ __gitcomp "cmd path" "$pfx" "$cur"
+ return
+ ;;
+ man.*.*)
+ local pfx="${cur%.*}."
+ cur="${cur##*.}"
+ __gitcomp "cmd path" "$pfx" "$cur"
+ return
+ ;;
+ mergetool.*.*)
+ local pfx="${cur%.*}."
+ cur="${cur##*.}"
+ __gitcomp "cmd path trustExitCode" "$pfx" "$cur"
+ return
+ ;;
+ pager.*)
+ local pfx="${cur%.*}."
+ cur="${cur#*.}"
+ __gitcomp "$(__git_all_commands)" "$pfx" "$cur"
+ return
+ ;;
remote.*.*)
local pfx="${cur%.*}."
cur="${cur##*.}"
__gitcomp "
- url fetch push skipDefaultUpdate
+ url proxy fetch push mirror skipDefaultUpdate
receivepack uploadpack tagopt
" "$pfx" "$cur"
return
@@ -865,112 +1464,239 @@ _git_config ()
__gitcomp "$(__git_remotes)" "$pfx" "$cur" "."
return
;;
+ url.*.*)
+ local pfx="${cur%.*}."
+ cur="${cur##*.}"
+ __gitcomp "insteadof" "$pfx" "$cur"
+ return
+ ;;
esac
__gitcomp "
+ alias.
apply.whitespace
- core.fileMode
- core.gitProxy
- core.ignoreStat
- core.preferSymlinkRefs
- core.logAllRefUpdates
- core.loosecompression
- core.repositoryFormatVersion
- core.sharedRepository
- core.warnAmbiguousRefs
- core.compression
- core.legacyHeaders
- core.packedGitWindowSize
- core.packedGitLimit
+ branch.autosetupmerge
+ branch.autosetuprebase
clean.requireForce
color.branch
color.branch.current
color.branch.local
- color.branch.remote
color.branch.plain
+ color.branch.remote
color.diff
- color.diff.plain
- color.diff.meta
+ color.diff.commit
color.diff.frag
- color.diff.old
+ color.diff.meta
color.diff.new
- color.diff.commit
+ color.diff.old
+ color.diff.plain
color.diff.whitespace
+ color.grep
+ color.grep.external
+ color.grep.match
+ color.interactive
+ color.interactive.header
+ color.interactive.help
+ color.interactive.prompt
color.pager
color.status
- color.status.header
color.status.added
color.status.changed
+ color.status.header
+ color.status.nobranch
color.status.untracked
+ color.status.updated
+ color.ui
+ commit.template
+ core.autocrlf
+ core.bare
+ core.compression
+ core.createObject
+ core.deltaBaseCacheLimit
+ core.editor
+ core.excludesfile
+ core.fileMode
+ core.fsyncobjectfiles
+ core.gitProxy
+ core.ignoreCygwinFSTricks
+ core.ignoreStat
+ core.logAllRefUpdates
+ core.loosecompression
+ core.packedGitLimit
+ core.packedGitWindowSize
+ core.pager
+ core.preferSymlinkRefs
+ core.preloadindex
+ core.quotepath
+ core.repositoryFormatVersion
+ core.safecrlf
+ core.sharedRepository
+ core.symlinks
+ core.trustctime
+ core.warnAmbiguousRefs
+ core.whitespace
+ core.worktree
+ diff.autorefreshindex
+ diff.external
+ diff.mnemonicprefix
diff.renameLimit
+ diff.renameLimit.
diff.renames
+ diff.suppressBlankEmpty
+ diff.tool
+ diff.wordRegex
+ difftool.
+ difftool.prompt
fetch.unpackLimit
+ format.attach
+ format.cc
format.headers
+ format.numbered
+ format.pretty
+ format.signoff
format.subjectprefix
- gitcvs.enabled
- gitcvs.logfile
- gitcvs.allbinary
- gitcvs.dbname gitcvs.dbdriver gitcvs.dbuser gitcvs.dvpass
+ format.suffix
+ format.thread
+ gc.aggressiveWindow
+ gc.auto
+ gc.autopacklimit
gc.packrefs
+ gc.pruneexpire
gc.reflogexpire
gc.reflogexpireunreachable
gc.rerereresolved
gc.rerereunresolved
- http.sslVerify
- http.sslCert
- http.sslKey
- http.sslCAInfo
- http.sslCAPath
- http.maxRequests
+ gitcvs.allbinary
+ gitcvs.commitmsgannotation
+ gitcvs.dbTableNamePrefix
+ gitcvs.dbdriver
+ gitcvs.dbname
+ gitcvs.dbpass
+ gitcvs.dbuser
+ gitcvs.enabled
+ gitcvs.logfile
+ gitcvs.usecrlfattr
+ guitool.
+ gui.blamehistoryctx
+ gui.commitmsgwidth
+ gui.copyblamethreshold
+ gui.diffcontext
+ gui.encoding
+ gui.fastcopyblame
+ gui.matchtrackingbranch
+ gui.newbranchtemplate
+ gui.pruneduringfetch
+ gui.spellingdictionary
+ gui.trustmtime
+ help.autocorrect
+ help.browser
+ help.format
http.lowSpeedLimit
http.lowSpeedTime
+ http.maxRequests
http.noEPSV
+ http.proxy
+ http.sslCAInfo
+ http.sslCAPath
+ http.sslCert
+ http.sslKey
+ http.sslVerify
i18n.commitEncoding
i18n.logOutputEncoding
+ imap.folder
+ imap.host
+ imap.pass
+ imap.port
+ imap.preformattedHTML
+ imap.sslverify
+ imap.tunnel
+ imap.user
+ instaweb.browser
+ instaweb.httpd
+ instaweb.local
+ instaweb.modulepath
+ instaweb.port
+ interactive.singlekey
+ log.date
log.showroot
+ mailmap.file
+ man.
+ man.viewer
+ merge.conflictstyle
+ merge.log
+ merge.renameLimit
+ merge.stat
merge.tool
- merge.summary
merge.verbosity
- pack.window
- pack.depth
- pack.windowMemory
+ mergetool.
+ mergetool.keepBackup
+ mergetool.prompt
pack.compression
- pack.deltaCacheSize
pack.deltaCacheLimit
+ pack.deltaCacheSize
+ pack.depth
+ pack.indexVersion
+ pack.packSizeLimit
+ pack.threads
+ pack.window
+ pack.windowMemory
+ pager.
pull.octopus
pull.twohead
- repack.useDeltaBaseOffset
- show.difftree
+ push.default
+ rebase.stat
+ receive.denyCurrentBranch
+ receive.denyDeletes
+ receive.denyNonFastForwards
+ receive.fsckObjects
+ receive.unpackLimit
+ repack.usedeltabaseoffset
+ rerere.autoupdate
+ rerere.enabled
+ sendemail.aliasesfile
+ sendemail.aliasesfiletype
+ sendemail.bcc
+ sendemail.cc
+ sendemail.cccmd
+ sendemail.chainreplyto
+ sendemail.confirm
+ sendemail.envelopesender
+ sendemail.multiedit
+ sendemail.signedoffbycc
+ sendemail.smtpencryption
+ sendemail.smtppass
+ sendemail.smtpserver
+ sendemail.smtpserverport
+ sendemail.smtpuser
+ sendemail.suppresscc
+ sendemail.suppressfrom
+ sendemail.thread
+ sendemail.to
+ sendemail.validate
showbranch.default
+ status.relativePaths
+ status.showUntrackedFiles
tar.umask
transfer.unpackLimit
- receive.unpackLimit
- receive.denyNonFastForwards
- user.name
+ url.
user.email
+ user.name
user.signingkey
- whatchanged.difftree
+ web.browser
branch. remote.
"
}
_git_remote ()
{
- local i c=1 command
- while [ $c -lt $COMP_CWORD ]; do
- i="${COMP_WORDS[c]}"
- case "$i" in
- add|show|prune|update) command="$i"; break ;;
- esac
- c=$((++c))
- done
-
- if [ $c -eq $COMP_CWORD -a -z "$command" ]; then
- __gitcomp "add show prune update"
+ local subcommands="add rename rm show prune update set-head"
+ local subcommand="$(__git_find_subcommand "$subcommands")"
+ if [ -z "$subcommand" ]; then
+ __gitcomp "$subcommands"
return
fi
- case "$command" in
- show|prune)
+ case "$subcommand" in
+ rename|rm|show|prune)
__gitcomp "$(__git_remotes)"
;;
update)
@@ -993,28 +1719,54 @@ _git_remote ()
_git_reset ()
{
+ __git_has_doubledash && return
+
+ local cur="${COMP_WORDS[COMP_CWORD]}"
+ case "$cur" in
+ --*)
+ __gitcomp "--merge --mixed --hard --soft"
+ return
+ ;;
+ esac
+ __gitcomp "$(__git_refs)"
+}
+
+_git_revert ()
+{
local cur="${COMP_WORDS[COMP_CWORD]}"
case "$cur" in
--*)
- __gitcomp "--mixed --hard --soft"
+ __gitcomp "--edit --mainline --no-edit --no-commit --signoff"
return
;;
esac
__gitcomp "$(__git_refs)"
}
+_git_rm ()
+{
+ __git_has_doubledash && return
+
+ local cur="${COMP_WORDS[COMP_CWORD]}"
+ case "$cur" in
+ --*)
+ __gitcomp "--cached --dry-run --ignore-unmatch --quiet"
+ return
+ ;;
+ esac
+ COMPREPLY=()
+}
+
_git_shortlog ()
{
+ __git_has_doubledash && return
+
local cur="${COMP_WORDS[COMP_CWORD]}"
case "$cur" in
--*)
__gitcomp "
- --max-count= --max-age= --since= --after=
- --min-age= --before= --until=
- --no-merges
- --author= --committer= --grep=
- --all-match
- --not --all
+ $__git_log_common_options
+ $__git_log_shortlog_options
--numbered --summary
"
return
@@ -1025,52 +1777,191 @@ _git_shortlog ()
_git_show ()
{
+ __git_has_doubledash && return
+
local cur="${COMP_WORDS[COMP_CWORD]}"
case "$cur" in
--pretty=*)
- __gitcomp "
- oneline short medium full fuller email raw
+ __gitcomp "$__git_log_pretty_formats
" "" "${cur##--pretty=}"
return
;;
+ --format=*)
+ __gitcomp "$__git_log_pretty_formats
+ " "" "${cur##--format=}"
+ return
+ ;;
--*)
- __gitcomp "--pretty="
+ __gitcomp "--pretty= --format=
+ $__git_diff_common_options
+ "
return
;;
esac
__git_complete_file
}
+_git_show_branch ()
+{
+ local cur="${COMP_WORDS[COMP_CWORD]}"
+ case "$cur" in
+ --*)
+ __gitcomp "
+ --all --remotes --topo-order --current --more=
+ --list --independent --merge-base --no-name
+ --sha1-name --topics --reflog
+ "
+ return
+ ;;
+ esac
+ __git_complete_revlist
+}
+
_git_stash ()
{
- __gitcomp 'list show apply clear'
+ local subcommands='save list show apply clear drop pop create branch'
+ local subcommand="$(__git_find_subcommand "$subcommands")"
+ if [ -z "$subcommand" ]; then
+ __gitcomp "$subcommands"
+ else
+ local cur="${COMP_WORDS[COMP_CWORD]}"
+ case "$subcommand,$cur" in
+ save,--*)
+ __gitcomp "--keep-index"
+ ;;
+ apply,--*)
+ __gitcomp "--index"
+ ;;
+ show,--*|drop,--*|pop,--*|branch,--*)
+ COMPREPLY=()
+ ;;
+ show,*|apply,*|drop,*|pop,*|branch,*)
+ __gitcomp "$(git --git-dir="$(__gitdir)" stash list \
+ | sed -n -e 's/:.*//p')"
+ ;;
+ *)
+ COMPREPLY=()
+ ;;
+ esac
+ fi
}
_git_submodule ()
{
- local i c=1 command
- while [ $c -lt $COMP_CWORD ]; do
- i="${COMP_WORDS[c]}"
- case "$i" in
- add|status|init|update) command="$i"; break ;;
- esac
- c=$((++c))
- done
+ __git_has_doubledash && return
- if [ $c -eq $COMP_CWORD -a -z "$command" ]; then
+ local subcommands="add status init update summary foreach sync"
+ if [ -z "$(__git_find_subcommand "$subcommands")" ]; then
local cur="${COMP_WORDS[COMP_CWORD]}"
case "$cur" in
--*)
__gitcomp "--quiet --cached"
;;
*)
- __gitcomp "add status init update"
+ __gitcomp "$subcommands"
;;
esac
return
fi
}
+_git_svn ()
+{
+ local subcommands="
+ init fetch clone rebase dcommit log find-rev
+ set-tree commit-diff info create-ignore propget
+ proplist show-ignore show-externals branch tag blame
+ migrate
+ "
+ local subcommand="$(__git_find_subcommand "$subcommands")"
+ if [ -z "$subcommand" ]; then
+ __gitcomp "$subcommands"
+ else
+ local remote_opts="--username= --config-dir= --no-auth-cache"
+ local fc_opts="
+ --follow-parent --authors-file= --repack=
+ --no-metadata --use-svm-props --use-svnsync-props
+ --log-window-size= --no-checkout --quiet
+ --repack-flags --use-log-author --localtime
+ --ignore-paths= $remote_opts
+ "
+ local init_opts="
+ --template= --shared= --trunk= --tags=
+ --branches= --stdlayout --minimize-url
+ --no-metadata --use-svm-props --use-svnsync-props
+ --rewrite-root= --prefix= --use-log-author
+ --add-author-from $remote_opts
+ "
+ local cmt_opts="
+ --edit --rmdir --find-copies-harder --copy-similarity=
+ "
+
+ local cur="${COMP_WORDS[COMP_CWORD]}"
+ case "$subcommand,$cur" in
+ fetch,--*)
+ __gitcomp "--revision= --fetch-all $fc_opts"
+ ;;
+ clone,--*)
+ __gitcomp "--revision= $fc_opts $init_opts"
+ ;;
+ init,--*)
+ __gitcomp "$init_opts"
+ ;;
+ dcommit,--*)
+ __gitcomp "
+ --merge --strategy= --verbose --dry-run
+ --fetch-all --no-rebase --commit-url
+ --revision $cmt_opts $fc_opts
+ "
+ ;;
+ set-tree,--*)
+ __gitcomp "--stdin $cmt_opts $fc_opts"
+ ;;
+ create-ignore,--*|propget,--*|proplist,--*|show-ignore,--*|\
+ show-externals,--*)
+ __gitcomp "--revision="
+ ;;
+ log,--*)
+ __gitcomp "
+ --limit= --revision= --verbose --incremental
+ --oneline --show-commit --non-recursive
+ --authors-file= --color
+ "
+ ;;
+ rebase,--*)
+ __gitcomp "
+ --merge --verbose --strategy= --local
+ --fetch-all --dry-run $fc_opts
+ "
+ ;;
+ commit-diff,--*)
+ __gitcomp "--message= --file= --revision= $cmt_opts"
+ ;;
+ info,--*)
+ __gitcomp "--url"
+ ;;
+ branch,--*)
+ __gitcomp "--dry-run --message --tag"
+ ;;
+ tag,--*)
+ __gitcomp "--dry-run --message"
+ ;;
+ blame,--*)
+ __gitcomp "--git-format"
+ ;;
+ migrate,--*)
+ __gitcomp "
+ --config-dir= --ignore-paths= --minimize
+ --no-auth-cache --username=
+ "
+ ;;
+ *)
+ COMPREPLY=()
+ ;;
+ esac
+ fi
+}
+
_git_tag ()
{
local i c=1 f=0
@@ -1092,7 +1983,7 @@ _git_tag ()
-m|-F)
COMPREPLY=()
;;
- -*|tag|git-tag)
+ -*|tag)
if [ $f = 1 ]; then
__gitcomp "$(__git_tags)"
else
@@ -1114,24 +2005,28 @@ _git ()
case "$i" in
--git-dir=*) __git_dir="${i#--git-dir=}" ;;
--bare) __git_dir="." ;;
- --version|--help|-p|--paginate) ;;
+ --version|-p|--paginate) ;;
+ --help) command="help"; break ;;
*) command="$i"; break ;;
esac
c=$((++c))
done
- if [ $c -eq $COMP_CWORD -a -z "$command" ]; then
+ if [ -z "$command" ]; then
case "${COMP_WORDS[COMP_CWORD]}" in
- --*=*) COMPREPLY=() ;;
--*) __gitcomp "
+ --paginate
--no-pager
--git-dir=
--bare
--version
--exec-path
+ --html-path
+ --work-tree=
+ --help
"
;;
- *) __gitcomp "$(__git_commands) $(__git_aliases)" ;;
+ *) __gitcomp "$(__git_porcelain_commands) $(__git_aliases)" ;;
esac
return
fi
@@ -1143,35 +2038,51 @@ _git ()
am) _git_am ;;
add) _git_add ;;
apply) _git_apply ;;
+ archive) _git_archive ;;
bisect) _git_bisect ;;
bundle) _git_bundle ;;
branch) _git_branch ;;
checkout) _git_checkout ;;
cherry) _git_cherry ;;
cherry-pick) _git_cherry_pick ;;
+ clean) _git_clean ;;
+ clone) _git_clone ;;
commit) _git_commit ;;
config) _git_config ;;
describe) _git_describe ;;
diff) _git_diff ;;
+ difftool) _git_difftool ;;
fetch) _git_fetch ;;
format-patch) _git_format_patch ;;
+ fsck) _git_fsck ;;
gc) _git_gc ;;
+ grep) _git_grep ;;
+ help) _git_help ;;
+ init) _git_init ;;
log) _git_log ;;
+ ls-files) _git_ls_files ;;
ls-remote) _git_ls_remote ;;
ls-tree) _git_ls_tree ;;
merge) _git_merge;;
+ mergetool) _git_mergetool;;
merge-base) _git_merge_base ;;
+ mv) _git_mv ;;
name-rev) _git_name_rev ;;
pull) _git_pull ;;
push) _git_push ;;
rebase) _git_rebase ;;
remote) _git_remote ;;
reset) _git_reset ;;
+ revert) _git_revert ;;
+ rm) _git_rm ;;
+ send-email) _git_send_email ;;
shortlog) _git_shortlog ;;
show) _git_show ;;
- show-branch) _git_log ;;
+ show-branch) _git_show_branch ;;
stash) _git_stash ;;
+ stage) _git_add ;;
submodule) _git_submodule ;;
+ svn) _git_svn ;;
tag) _git_tag ;;
whatchanged) _git_log ;;
*) COMPREPLY=() ;;
@@ -1180,75 +2091,37 @@ _git ()
_gitk ()
{
+ __git_has_doubledash && return
+
local cur="${COMP_WORDS[COMP_CWORD]}"
+ local g="$(__gitdir)"
+ local merge=""
+ if [ -f "$g/MERGE_HEAD" ]; then
+ merge="--merge"
+ fi
case "$cur" in
--*)
- __gitcomp "--not --all"
+ __gitcomp "
+ $__git_log_common_options
+ $__git_log_gitk_options
+ $merge
+ "
return
;;
esac
__git_complete_revlist
}
-complete -o default -o nospace -F _git git
-complete -o default -o nospace -F _gitk gitk
-complete -o default -o nospace -F _git_am git-am
-complete -o default -o nospace -F _git_apply git-apply
-complete -o default -o nospace -F _git_bisect git-bisect
-complete -o default -o nospace -F _git_branch git-branch
-complete -o default -o nospace -F _git_bundle git-bundle
-complete -o default -o nospace -F _git_checkout git-checkout
-complete -o default -o nospace -F _git_cherry git-cherry
-complete -o default -o nospace -F _git_cherry_pick git-cherry-pick
-complete -o default -o nospace -F _git_commit git-commit
-complete -o default -o nospace -F _git_describe git-describe
-complete -o default -o nospace -F _git_diff git-diff
-complete -o default -o nospace -F _git_fetch git-fetch
-complete -o default -o nospace -F _git_format_patch git-format-patch
-complete -o default -o nospace -F _git_gc git-gc
-complete -o default -o nospace -F _git_log git-log
-complete -o default -o nospace -F _git_ls_remote git-ls-remote
-complete -o default -o nospace -F _git_ls_tree git-ls-tree
-complete -o default -o nospace -F _git_merge git-merge
-complete -o default -o nospace -F _git_merge_base git-merge-base
-complete -o default -o nospace -F _git_name_rev git-name-rev
-complete -o default -o nospace -F _git_pull git-pull
-complete -o default -o nospace -F _git_push git-push
-complete -o default -o nospace -F _git_rebase git-rebase
-complete -o default -o nospace -F _git_config git-config
-complete -o default -o nospace -F _git_remote git-remote
-complete -o default -o nospace -F _git_reset git-reset
-complete -o default -o nospace -F _git_shortlog git-shortlog
-complete -o default -o nospace -F _git_show git-show
-complete -o default -o nospace -F _git_stash git-stash
-complete -o default -o nospace -F _git_submodule git-submodule
-complete -o default -o nospace -F _git_log git-show-branch
-complete -o default -o nospace -F _git_tag git-tag
-complete -o default -o nospace -F _git_log git-whatchanged
+complete -o bashdefault -o default -o nospace -F _git git 2>/dev/null \
+ || complete -o default -o nospace -F _git git
+complete -o bashdefault -o default -o nospace -F _gitk gitk 2>/dev/null \
+ || complete -o default -o nospace -F _gitk gitk
# The following are necessary only for Cygwin, and only are needed
# when the user has tab-completed the executable name and consequently
# included the '.exe' suffix.
#
if [ Cygwin = "$(uname -o 2>/dev/null)" ]; then
-complete -o default -o nospace -F _git_add git-add.exe
-complete -o default -o nospace -F _git_apply git-apply.exe
-complete -o default -o nospace -F _git git.exe
-complete -o default -o nospace -F _git_branch git-branch.exe
-complete -o default -o nospace -F _git_bundle git-bundle.exe
-complete -o default -o nospace -F _git_cherry git-cherry.exe
-complete -o default -o nospace -F _git_describe git-describe.exe
-complete -o default -o nospace -F _git_diff git-diff.exe
-complete -o default -o nospace -F _git_format_patch git-format-patch.exe
-complete -o default -o nospace -F _git_log git-log.exe
-complete -o default -o nospace -F _git_ls_tree git-ls-tree.exe
-complete -o default -o nospace -F _git_merge_base git-merge-base.exe
-complete -o default -o nospace -F _git_name_rev git-name-rev.exe
-complete -o default -o nospace -F _git_push git-push.exe
-complete -o default -o nospace -F _git_config git-config
-complete -o default -o nospace -F _git_shortlog git-shortlog.exe
-complete -o default -o nospace -F _git_show git-show.exe
-complete -o default -o nospace -F _git_log git-show-branch.exe
-complete -o default -o nospace -F _git_tag git-tag.exe
-complete -o default -o nospace -F _git_log git-whatchanged.exe
+complete -o bashdefault -o default -o nospace -F _git git.exe 2>/dev/null \
+ || complete -o default -o nospace -F _git git.exe
fi
diff --git a/contrib/convert-objects/convert-objects.c b/contrib/convert-objects/convert-objects.c
new file mode 100644
index 0000000000..f3b57bf1d2
--- /dev/null
+++ b/contrib/convert-objects/convert-objects.c
@@ -0,0 +1,329 @@
+#include "cache.h"
+#include "blob.h"
+#include "commit.h"
+#include "tree.h"
+
+struct entry {
+ unsigned char old_sha1[20];
+ unsigned char new_sha1[20];
+ int converted;
+};
+
+#define MAXOBJECTS (1000000)
+
+static struct entry *convert[MAXOBJECTS];
+static int nr_convert;
+
+static struct entry * convert_entry(unsigned char *sha1);
+
+static struct entry *insert_new(unsigned char *sha1, int pos)
+{
+ struct entry *new = xcalloc(1, sizeof(struct entry));
+ hashcpy(new->old_sha1, sha1);
+ memmove(convert + pos + 1, convert + pos, (nr_convert - pos) * sizeof(struct entry *));
+ convert[pos] = new;
+ nr_convert++;
+ if (nr_convert == MAXOBJECTS)
+ die("you're kidding me - hit maximum object limit");
+ return new;
+}
+
+static struct entry *lookup_entry(unsigned char *sha1)
+{
+ int low = 0, high = nr_convert;
+
+ while (low < high) {
+ int next = (low + high) / 2;
+ struct entry *n = convert[next];
+ int cmp = hashcmp(sha1, n->old_sha1);
+ if (!cmp)
+ return n;
+ if (cmp < 0) {
+ high = next;
+ continue;
+ }
+ low = next+1;
+ }
+ return insert_new(sha1, low);
+}
+
+static void convert_binary_sha1(void *buffer)
+{
+ struct entry *entry = convert_entry(buffer);
+ hashcpy(buffer, entry->new_sha1);
+}
+
+static void convert_ascii_sha1(void *buffer)
+{
+ unsigned char sha1[20];
+ struct entry *entry;
+
+ if (get_sha1_hex(buffer, sha1))
+ die("expected sha1, got '%s'", (char *) buffer);
+ entry = convert_entry(sha1);
+ memcpy(buffer, sha1_to_hex(entry->new_sha1), 40);
+}
+
+static unsigned int convert_mode(unsigned int mode)
+{
+ unsigned int newmode;
+
+ newmode = mode & S_IFMT;
+ if (S_ISREG(mode))
+ newmode |= (mode & 0100) ? 0755 : 0644;
+ return newmode;
+}
+
+static int write_subdirectory(void *buffer, unsigned long size, const char *base, int baselen, unsigned char *result_sha1)
+{
+ char *new = xmalloc(size);
+ unsigned long newlen = 0;
+ unsigned long used;
+
+ used = 0;
+ while (size) {
+ int len = 21 + strlen(buffer);
+ char *path = strchr(buffer, ' ');
+ unsigned char *sha1;
+ unsigned int mode;
+ char *slash, *origpath;
+
+ if (!path || strtoul_ui(buffer, 8, &mode))
+ die("bad tree conversion");
+ mode = convert_mode(mode);
+ path++;
+ if (memcmp(path, base, baselen))
+ break;
+ origpath = path;
+ path += baselen;
+ slash = strchr(path, '/');
+ if (!slash) {
+ newlen += sprintf(new + newlen, "%o %s", mode, path);
+ new[newlen++] = '\0';
+ hashcpy((unsigned char *)new + newlen, (unsigned char *) buffer + len - 20);
+ newlen += 20;
+
+ used += len;
+ size -= len;
+ buffer = (char *) buffer + len;
+ continue;
+ }
+
+ newlen += sprintf(new + newlen, "%o %.*s", S_IFDIR, (int)(slash - path), path);
+ new[newlen++] = 0;
+ sha1 = (unsigned char *)(new + newlen);
+ newlen += 20;
+
+ len = write_subdirectory(buffer, size, origpath, slash-origpath+1, sha1);
+
+ used += len;
+ size -= len;
+ buffer = (char *) buffer + len;
+ }
+
+ write_sha1_file(new, newlen, tree_type, result_sha1);
+ free(new);
+ return used;
+}
+
+static void convert_tree(void *buffer, unsigned long size, unsigned char *result_sha1)
+{
+ void *orig_buffer = buffer;
+ unsigned long orig_size = size;
+
+ while (size) {
+ size_t len = 1+strlen(buffer);
+
+ convert_binary_sha1((char *) buffer + len);
+
+ len += 20;
+ if (len > size)
+ die("corrupt tree object");
+ size -= len;
+ buffer = (char *) buffer + len;
+ }
+
+ write_subdirectory(orig_buffer, orig_size, "", 0, result_sha1);
+}
+
+static unsigned long parse_oldstyle_date(const char *buf)
+{
+ char c, *p;
+ char buffer[100];
+ struct tm tm;
+ const char *formats[] = {
+ "%c",
+ "%a %b %d %T",
+ "%Z",
+ "%Y",
+ " %Y",
+ NULL
+ };
+ /* We only ever did two timezones in the bad old format .. */
+ const char *timezones[] = {
+ "PDT", "PST", "CEST", NULL
+ };
+ const char **fmt = formats;
+
+ p = buffer;
+ while (isspace(c = *buf))
+ buf++;
+ while ((c = *buf++) != '\n')
+ *p++ = c;
+ *p++ = 0;
+ buf = buffer;
+ memset(&tm, 0, sizeof(tm));
+ do {
+ const char *next = strptime(buf, *fmt, &tm);
+ if (next) {
+ if (!*next)
+ return mktime(&tm);
+ buf = next;
+ } else {
+ const char **p = timezones;
+ while (isspace(*buf))
+ buf++;
+ while (*p) {
+ if (!memcmp(buf, *p, strlen(*p))) {
+ buf += strlen(*p);
+ break;
+ }
+ p++;
+ }
+ }
+ fmt++;
+ } while (*buf && *fmt);
+ printf("left: %s\n", buf);
+ return mktime(&tm);
+}
+
+static int convert_date_line(char *dst, void **buf, unsigned long *sp)
+{
+ unsigned long size = *sp;
+ char *line = *buf;
+ char *next = strchr(line, '\n');
+ char *date = strchr(line, '>');
+ int len;
+
+ if (!next || !date)
+ die("missing or bad author/committer line %s", line);
+ next++; date += 2;
+
+ *buf = next;
+ *sp = size - (next - line);
+
+ len = date - line;
+ memcpy(dst, line, len);
+ dst += len;
+
+ /* Is it already in new format? */
+ if (isdigit(*date)) {
+ int datelen = next - date;
+ memcpy(dst, date, datelen);
+ return len + datelen;
+ }
+
+ /*
+ * Hacky hacky: one of the sparse old-style commits does not have
+ * any date at all, but we can fake it by using the committer date.
+ */
+ if (*date == '\n' && strchr(next, '>'))
+ date = strchr(next, '>')+2;
+
+ return len + sprintf(dst, "%lu -0700\n", parse_oldstyle_date(date));
+}
+
+static void convert_date(void *buffer, unsigned long size, unsigned char *result_sha1)
+{
+ char *new = xmalloc(size + 100);
+ unsigned long newlen = 0;
+
+ /* "tree <sha1>\n" */
+ memcpy(new + newlen, buffer, 46);
+ newlen += 46;
+ buffer = (char *) buffer + 46;
+ size -= 46;
+
+ /* "parent <sha1>\n" */
+ while (!memcmp(buffer, "parent ", 7)) {
+ memcpy(new + newlen, buffer, 48);
+ newlen += 48;
+ buffer = (char *) buffer + 48;
+ size -= 48;
+ }
+
+ /* "author xyz <xyz> date" */
+ newlen += convert_date_line(new + newlen, &buffer, &size);
+ /* "committer xyz <xyz> date" */
+ newlen += convert_date_line(new + newlen, &buffer, &size);
+
+ /* Rest */
+ memcpy(new + newlen, buffer, size);
+ newlen += size;
+
+ write_sha1_file(new, newlen, commit_type, result_sha1);
+ free(new);
+}
+
+static void convert_commit(void *buffer, unsigned long size, unsigned char *result_sha1)
+{
+ void *orig_buffer = buffer;
+ unsigned long orig_size = size;
+
+ if (memcmp(buffer, "tree ", 5))
+ die("Bad commit '%s'", (char *) buffer);
+ convert_ascii_sha1((char *) buffer + 5);
+ buffer = (char *) buffer + 46; /* "tree " + "hex sha1" + "\n" */
+ while (!memcmp(buffer, "parent ", 7)) {
+ convert_ascii_sha1((char *) buffer + 7);
+ buffer = (char *) buffer + 48;
+ }
+ convert_date(orig_buffer, orig_size, result_sha1);
+}
+
+static struct entry * convert_entry(unsigned char *sha1)
+{
+ struct entry *entry = lookup_entry(sha1);
+ enum object_type type;
+ void *buffer, *data;
+ unsigned long size;
+
+ if (entry->converted)
+ return entry;
+ data = read_sha1_file(sha1, &type, &size);
+ if (!data)
+ die("unable to read object %s", sha1_to_hex(sha1));
+
+ buffer = xmalloc(size);
+ memcpy(buffer, data, size);
+
+ if (type == OBJ_BLOB) {
+ write_sha1_file(buffer, size, blob_type, entry->new_sha1);
+ } else if (type == OBJ_TREE)
+ convert_tree(buffer, size, entry->new_sha1);
+ else if (type == OBJ_COMMIT)
+ convert_commit(buffer, size, entry->new_sha1);
+ else
+ die("unknown object type %d in %s", type, sha1_to_hex(sha1));
+ entry->converted = 1;
+ free(buffer);
+ free(data);
+ return entry;
+}
+
+int main(int argc, char **argv)
+{
+ unsigned char sha1[20];
+ struct entry *entry;
+
+ setup_git_directory();
+
+ if (argc != 2)
+ usage("git-convert-objects <sha1>");
+ if (get_sha1(argv[1], sha1))
+ die("Not a valid object name %s", argv[1]);
+
+ entry = convert_entry(sha1);
+ printf("new sha1: %s\n", sha1_to_hex(entry->new_sha1));
+ return 0;
+}
diff --git a/contrib/convert-objects/git-convert-objects.txt b/contrib/convert-objects/git-convert-objects.txt
new file mode 100644
index 0000000000..9718abf86d
--- /dev/null
+++ b/contrib/convert-objects/git-convert-objects.txt
@@ -0,0 +1,28 @@
+git-convert-objects(1)
+======================
+
+NAME
+----
+git-convert-objects - Converts old-style git repository
+
+
+SYNOPSIS
+--------
+'git-convert-objects'
+
+DESCRIPTION
+-----------
+Converts old-style git repository to the latest format
+
+
+Author
+------
+Written by Linus Torvalds <torvalds@osdl.org>
+
+Documentation
+--------------
+Documentation by David Greaves, Junio C Hamano and the git-list <git@vger.kernel.org>.
+
+GIT
+---
+Part of the gitlink:git[7] suite
diff --git a/contrib/emacs/Makefile b/contrib/emacs/Makefile
index a48540a92b..24d9312941 100644
--- a/contrib/emacs/Makefile
+++ b/contrib/emacs/Makefile
@@ -2,7 +2,7 @@
EMACS = emacs
-ELC = git.elc vc-git.elc git-blame.elc
+ELC = git.elc git-blame.elc
INSTALL ?= install
INSTALL_ELC = $(INSTALL) -m 644
prefix ?= $(HOME)
diff --git a/contrib/emacs/README b/contrib/emacs/README
new file mode 100644
index 0000000000..82368bdbff
--- /dev/null
+++ b/contrib/emacs/README
@@ -0,0 +1,39 @@
+This directory contains various modules for Emacs support.
+
+To make the modules available to Emacs, you should add this directory
+to your load-path, and then require the modules you want. This can be
+done by adding to your .emacs something like this:
+
+ (add-to-list 'load-path ".../git/contrib/emacs")
+ (require 'git)
+ (require 'git-blame)
+
+
+The following modules are available:
+
+* git.el:
+
+ Status manager that displays the state of all the files of the
+ project, and provides easy access to the most frequently used git
+ commands. The user interface is as far as possible compatible with
+ the pcl-cvs mode. It can be started with `M-x git-status'.
+
+* git-blame.el:
+
+ Emacs implementation of incremental git-blame. When you turn it on
+ while viewing a file, the editor buffer will be updated by setting
+ the background of individual lines to a color that reflects which
+ commit it comes from. And when you move around the buffer, a
+ one-line summary will be shown in the echo area.
+
+* vc-git.el:
+
+ This file used to contain the VC-mode backend for git, but it is no
+ longer distributed with git. It is now maintained as part of Emacs
+ and included in standard Emacs distributions starting from version
+ 22.2.
+
+ If you have an earlier Emacs version, upgrading to Emacs 22 is
+ recommended, since the VC mode in older Emacs is not generic enough
+ to be able to support git in a reasonable manner, and no attempt has
+ been made to backport vc-git.el.
diff --git a/contrib/emacs/git-blame.el b/contrib/emacs/git-blame.el
index bb671d561e..4fa70c5ad4 100644
--- a/contrib/emacs/git-blame.el
+++ b/contrib/emacs/git-blame.el
@@ -105,6 +105,13 @@ selected element from l."
(setq ,l (remove e ,l))
e))
+(defvar git-blame-log-oneline-format
+ "format:[%cr] %cn: %s"
+ "*Formatting option used for describing current line in the minibuffer.
+
+This option is used to pass to git log --pretty= command-line option,
+and describe which commit the current line was made.")
+
(defvar git-blame-dark-colors
(git-blame-color-scale "0c" "04" "24" "1c" "2c" "34" "14" "3c")
"*List of colors (format #RGB) to use in a dark environment.
@@ -371,9 +378,10 @@ See also function `git-blame-mode'."
(defun git-describe-commit (hash)
(with-temp-buffer
(call-process "git" nil t nil
- "log" "-1" "--pretty=oneline"
+ "log" "-1"
+ (concat "--pretty=" git-blame-log-oneline-format)
hash)
- (buffer-substring (point-min) (1- (point-max)))))
+ (buffer-substring (point-min) (point-max))))
(defvar git-blame-last-identification nil)
(make-variable-buffer-local 'git-blame-last-identification)
diff --git a/contrib/emacs/git.el b/contrib/emacs/git.el
index 280557ecd4..eace9c18eb 100644
--- a/contrib/emacs/git.el
+++ b/contrib/emacs/git.el
@@ -1,6 +1,6 @@
;;; git.el --- A user interface for git
-;; Copyright (C) 2005, 2006, 2007 Alexandre Julliard <julliard@winehq.org>
+;; Copyright (C) 2005, 2006, 2007, 2008, 2009 Alexandre Julliard <julliard@winehq.org>
;; Version: 1.0
@@ -34,22 +34,27 @@
;; To start: `M-x git-status'
;;
;; TODO
-;; - portability to XEmacs
-;; - better handling of subprocess errors
-;; - hook into file save (after-save-hook)
;; - diff against other branch
;; - renaming files from the status buffer
;; - creating tags
;; - fetch/pull
-;; - switching branches
;; - revlist browser
;; - git-show-branch browser
-;; - menus
+;;
+
+;;; Compatibility:
+;;
+;; This file works on GNU Emacs 21 or later. It may work on older
+;; versions but this is not guaranteed.
+;;
+;; It may work on XEmacs 21, provided that you first install the ewoc
+;; and log-edit packages.
;;
(eval-when-compile (require 'cl))
(require 'ewoc)
(require 'log-edit)
+(require 'easymenu)
;;;; Customizations
@@ -97,6 +102,21 @@ if there is already one that displays the same directory."
:group 'git
:type 'string)
+(defcustom git-show-uptodate nil
+ "Whether to display up-to-date files."
+ :group 'git
+ :type 'boolean)
+
+(defcustom git-show-ignored nil
+ "Whether to display ignored files."
+ :group 'git
+ :type 'boolean)
+
+(defcustom git-show-unknown t
+ "Whether to display unknown files."
+ :group 'git
+ :type 'boolean)
+
(defface git-status-face
'((((class color) (background light)) (:foreground "purple"))
@@ -159,7 +179,7 @@ if there is already one that displays the same directory."
(defconst git-log-msg-separator "--- log message follows this line ---")
(defvar git-log-edit-font-lock-keywords
- `(("^\\(Author:\\|Date:\\|Parent:\\|Signed-off-by:\\)\\(.*\\)$"
+ `(("^\\(Author:\\|Date:\\|Merge:\\|Signed-off-by:\\)\\(.*\\)$"
(1 font-lock-keyword-face)
(2 font-lock-function-name-face))
(,(concat "^\\(" (regexp-quote git-log-msg-separator) "\\)$")
@@ -169,20 +189,38 @@ if there is already one that displays the same directory."
"Build a list of NAME=VALUE strings from a list of environment strings."
(mapcar (lambda (entry) (concat (car entry) "=" (cdr entry))) env))
-(defun git-call-process-env (buffer env &rest args)
+(defun git-call-process (buffer &rest args)
"Wrapper for call-process that sets environment strings."
- (if env
- (apply #'call-process "env" nil buffer nil
- (append (git-get-env-strings env) (list "git") args))
- (apply #'call-process "git" nil buffer nil args)))
-
-(defun git-call-process-env-string (env &rest args)
- "Wrapper for call-process that sets environment strings,
-and returns the process output as a string."
+ (apply #'call-process "git" nil buffer nil args))
+
+(defun git-call-process-display-error (&rest args)
+ "Wrapper for call-process that displays error messages."
+ (let* ((dir default-directory)
+ (buffer (get-buffer-create "*Git Command Output*"))
+ (ok (with-current-buffer buffer
+ (let ((default-directory dir)
+ (buffer-read-only nil))
+ (erase-buffer)
+ (eq 0 (apply #'git-call-process (list buffer t) args))))))
+ (unless ok (display-message-or-buffer buffer))
+ ok))
+
+(defun git-call-process-string (&rest args)
+ "Wrapper for call-process that returns the process output as a string,
+or nil if the git command failed."
(with-temp-buffer
- (and (eq 0 (apply #' git-call-process-env t env args))
+ (and (eq 0 (apply #'git-call-process t args))
(buffer-string))))
+(defun git-call-process-string-display-error (&rest args)
+ "Wrapper for call-process that displays error message and returns
+the process output as a string, or nil if the git command failed."
+ (with-temp-buffer
+ (if (eq 0 (apply #'git-call-process (list t t) args))
+ (buffer-string)
+ (display-message-or-buffer (current-buffer))
+ nil)))
+
(defun git-run-process-region (buffer start end program args)
"Run a git process with a buffer region as input."
(let ((output-buffer (current-buffer))
@@ -190,7 +228,7 @@ and returns the process output as a string."
(with-current-buffer buffer
(cd dir)
(apply #'call-process-region start end program
- nil (list output-buffer nil) nil args))))
+ nil (list output-buffer t) nil args))))
(defun git-run-command-buffer (buffer-name &rest args)
"Run a git command, sending the output to a buffer named BUFFER-NAME."
@@ -201,26 +239,21 @@ and returns the process output as a string."
(let ((default-directory dir)
(buffer-read-only nil))
(erase-buffer)
- (apply #'git-call-process-env buffer nil args)))
+ (apply #'git-call-process buffer args)))
(message "Running git %s...done" (car args))
buffer))
-(defun git-run-command (buffer env &rest args)
- (message "Running git %s..." (car args))
- (apply #'git-call-process-env buffer env args)
- (message "Running git %s...done" (car args)))
-
(defun git-run-command-region (buffer start end env &rest args)
"Run a git command with specified buffer region as input."
- (message "Running git %s..." (car args))
- (unless (eq 0 (if env
- (git-run-process-region
- buffer start end "env"
- (append (git-get-env-strings env) (list "git") args))
+ (with-temp-buffer
+ (if (eq 0 (if env
(git-run-process-region
- buffer start end "git" args)))
- (error "Failed to run \"git %s\":\n%s" (mapconcat (lambda (x) x) args " ") (buffer-string)))
- (message "Running git %s...done" (car args)))
+ buffer start end "env"
+ (append (git-get-env-strings env) (list "git") args))
+ (git-run-process-region buffer start end "git" args)))
+ (buffer-string)
+ (display-message-or-buffer (current-buffer))
+ nil)))
(defun git-run-hook (hook env &rest args)
"Run a git hook and display its output if any."
@@ -297,12 +330,19 @@ and returns the process output as a string."
"\"")
name))
+(defun git-success-message (text files)
+ "Print a success message after having handled FILES."
+ (let ((n (length files)))
+ (if (equal n 1)
+ (message "%s %s" text (car files))
+ (message "%s %d files" text n))))
+
(defun git-get-top-dir (dir)
"Retrieve the top-level directory of a git tree."
(let ((cdup (with-output-to-string
(with-current-buffer standard-output
(cd dir)
- (unless (eq 0 (call-process "git" nil t nil "rev-parse" "--show-cdup"))
+ (unless (eq 0 (git-call-process t "rev-parse" "--show-cdup"))
(error "cannot find top-level git tree for %s." dir))))))
(expand-file-name (concat (file-name-as-directory dir)
(car (split-string cdup "\n"))))))
@@ -323,8 +363,8 @@ and returns the process output as a string."
(sort-lines nil (point-min) (point-max))
(save-buffer))
(when created
- (git-run-command nil nil "update-index" "--add" "--" (file-relative-name ignore-name)))
- (git-update-status-files (list (file-relative-name ignore-name)) 'unknown)))
+ (git-call-process nil "update-index" "--add" "--" (file-relative-name ignore-name)))
+ (git-update-status-files (list (file-relative-name ignore-name)))))
; propertize definition for XEmacs, stolen from erc-compat
(eval-when-compile
@@ -342,38 +382,52 @@ and returns the process output as a string."
(defun git-rev-parse (rev)
"Parse a revision name and return its SHA1."
(git-get-string-sha1
- (git-call-process-env-string nil "rev-parse" rev)))
+ (git-call-process-string "rev-parse" rev)))
(defun git-config (key)
"Retrieve the value associated to KEY in the git repository config file."
- (let ((str (git-call-process-env-string nil "config" key)))
+ (let ((str (git-call-process-string "config" key)))
(and str (car (split-string str "\n")))))
(defun git-symbolic-ref (ref)
"Wrapper for the git-symbolic-ref command."
- (let ((str (git-call-process-env-string nil "symbolic-ref" ref)))
+ (let ((str (git-call-process-string "symbolic-ref" ref)))
(and str (car (split-string str "\n")))))
(defun git-update-ref (ref newval &optional oldval reason)
"Update a reference by calling git-update-ref."
(let ((args (and oldval (list oldval))))
- (push newval args)
+ (when newval (push newval args))
(push ref args)
(when reason
(push reason args)
(push "-m" args))
- (eq 0 (apply #'git-call-process-env nil nil "update-ref" args))))
+ (unless newval (push "-d" args))
+ (apply 'git-call-process-display-error "update-ref" args)))
+
+(defun git-for-each-ref (&rest specs)
+ "Return a list of refs using git-for-each-ref.
+Each entry is a cons of (SHORT-NAME . FULL-NAME)."
+ (let (refs)
+ (with-temp-buffer
+ (apply #'git-call-process t "for-each-ref" "--format=%(refname)" specs)
+ (goto-char (point-min))
+ (while (re-search-forward "^[^/\n]+/[^/\n]+/\\(.+\\)$" nil t)
+ (push (cons (match-string 1) (match-string 0)) refs)))
+ (nreverse refs)))
(defun git-read-tree (tree &optional index-file)
"Read a tree into the index file."
- (apply #'git-call-process-env nil
- (if index-file `(("GIT_INDEX_FILE" . ,index-file)) nil)
- "read-tree" (if tree (list tree))))
+ (let ((process-environment
+ (append (and index-file (list (concat "GIT_INDEX_FILE=" index-file))) process-environment)))
+ (apply 'git-call-process-display-error "read-tree" (if tree (list tree)))))
(defun git-write-tree (&optional index-file)
"Call git-write-tree and return the resulting tree SHA1 as a string."
- (git-get-string-sha1
- (git-call-process-env-string (and index-file `(("GIT_INDEX_FILE" . ,index-file))) "write-tree")))
+ (let ((process-environment
+ (append (and index-file (list (concat "GIT_INDEX_FILE=" index-file))) process-environment)))
+ (git-get-string-sha1
+ (git-call-process-string-display-error "write-tree"))))
(defun git-commit-tree (buffer tree head)
"Call git-commit-tree with buffer as input and return the resulting commit SHA1."
@@ -399,11 +453,11 @@ and returns the process output as a string."
(when (re-search-forward "^Date: +\\(.*\\)$" nil t)
(setq author-date (match-string 1)))
(goto-char (point-min))
- (while (re-search-forward "^Parent: +\\([0-9a-f]+\\)" nil t)
- (unless (string-equal head (match-string 1))
- (setq subject "commit (merge): ")
+ (when (re-search-forward "^Merge: +\\(.*\\)" nil t)
+ (setq subject "commit (merge): ")
+ (dolist (parent (split-string (match-string 1) " +" t))
(push "-p" args)
- (push (match-string 1) args))))
+ (push parent args))))
(setq log-start (point-min)))
(setq log-end (point-max))
(goto-char log-start)
@@ -412,22 +466,20 @@ and returns the process output as a string."
(setq coding-system-for-write buffer-file-coding-system))
(let ((commit
(git-get-string-sha1
- (with-output-to-string
- (with-current-buffer standard-output
- (let ((env `(("GIT_AUTHOR_NAME" . ,author-name)
- ("GIT_AUTHOR_EMAIL" . ,author-email)
- ("GIT_COMMITTER_NAME" . ,(git-get-committer-name))
- ("GIT_COMMITTER_EMAIL" . ,(git-get-committer-email)))))
- (when author-date (push `("GIT_AUTHOR_DATE" . ,author-date) env))
- (apply #'git-run-command-region
- buffer log-start log-end env
- "commit-tree" tree (nreverse args))))))))
- (and (git-update-ref "HEAD" commit head subject)
- commit))))
+ (let ((env `(("GIT_AUTHOR_NAME" . ,author-name)
+ ("GIT_AUTHOR_EMAIL" . ,author-email)
+ ("GIT_COMMITTER_NAME" . ,(git-get-committer-name))
+ ("GIT_COMMITTER_EMAIL" . ,(git-get-committer-email)))))
+ (when author-date (push `("GIT_AUTHOR_DATE" . ,author-date) env))
+ (apply #'git-run-command-region
+ buffer log-start log-end env
+ "commit-tree" tree (nreverse args))))))
+ (when commit (git-update-ref "HEAD" commit head subject))
+ commit)))
(defun git-empty-db-p ()
"Check if the git db is empty (no commit done yet)."
- (not (eq 0 (call-process "git" nil nil nil "rev-parse" "--verify" "HEAD"))))
+ (not (eq 0 (git-call-process nil "rev-parse" "--verify" "HEAD"))))
(defun git-get-merge-heads ()
"Retrieve the merge heads from the MERGE_HEAD file if present."
@@ -443,7 +495,7 @@ and returns the process output as a string."
(defun git-get-commit-description (commit)
"Get a one-line description of COMMIT."
(let ((coding-system-for-read (git-get-logoutput-coding-system)))
- (let ((descr (git-call-process-env-string nil "log" "--max-count=1" "--pretty=oneline" commit)))
+ (let ((descr (git-call-process-string "log" "--max-count=1" "--pretty=oneline" commit)))
(if (and descr (string-match "\\`\\([0-9a-f]\\{40\\}\\) *\\(.*\\)$" descr))
(concat (substring (match-string 1 descr) 0 10) " - " (match-string 2 descr))
descr))))
@@ -462,22 +514,42 @@ and returns the process output as a string."
old-perm new-perm ;; permission flags
rename-state ;; rename or copy state
orig-name ;; original name for renames or copies
+ needs-update ;; whether file needs to be updated
needs-refresh) ;; whether file needs to be refreshed
(defvar git-status nil)
-(defun git-clear-status (status)
- "Remove everything from the status list."
- (ewoc-filter status (lambda (info) nil)))
-
-(defun git-set-files-state (files state)
- "Set the state of a list of files."
- (dolist (info files)
- (unless (eq (git-fileinfo->state info) state)
- (setf (git-fileinfo->state info) state)
- (setf (git-fileinfo->rename-state info) nil)
- (setf (git-fileinfo->orig-name info) nil)
- (setf (git-fileinfo->needs-refresh info) t))))
+(defun git-set-fileinfo-state (info state)
+ "Set the state of a file info."
+ (unless (eq (git-fileinfo->state info) state)
+ (setf (git-fileinfo->state info) state
+ (git-fileinfo->new-perm info) (git-fileinfo->old-perm info)
+ (git-fileinfo->rename-state info) nil
+ (git-fileinfo->orig-name info) nil
+ (git-fileinfo->needs-update info) nil
+ (git-fileinfo->needs-refresh info) t)))
+
+(defun git-status-filenames-map (status func files &rest args)
+ "Apply FUNC to the status files names in the FILES list.
+The list must be sorted."
+ (when files
+ (let ((file (pop files))
+ (node (ewoc-nth status 0)))
+ (while (and file node)
+ (let* ((info (ewoc-data node))
+ (name (git-fileinfo->name info)))
+ (if (string-lessp name file)
+ (setq node (ewoc-next status node))
+ (if (string-equal name file)
+ (apply func info args))
+ (setq file (pop files))))))))
+
+(defun git-set-filenames-state (status files state)
+ "Set the state of a list of named files. The list must be sorted"
+ (when files
+ (git-status-filenames-map status #'git-set-fileinfo-state files state)
+ (unless state ;; delete files whose state has been set to nil
+ (ewoc-filter status (lambda (info) (git-fileinfo->state info))))))
(defun git-state-code (code)
"Convert from a string to a added/deleted/modified state."
@@ -487,6 +559,7 @@ and returns the process output as a string."
(?A 'added)
(?D 'deleted)
(?U 'unmerged)
+ (?T 'modified)
(t nil)))
(defun git-status-code-as-string (code)
@@ -501,6 +574,36 @@ and returns the process output as a string."
('ignored (propertize "Ignored " 'face 'git-ignored-face))
(t "? ")))
+(defun git-file-type-as-string (old-perm new-perm)
+ "Return a string describing the file type based on its permissions."
+ (let* ((old-type (lsh (or old-perm 0) -9))
+ (new-type (lsh (or new-perm 0) -9))
+ (str (case new-type
+ (64 ;; file
+ (case old-type
+ (64 nil)
+ (80 " (type change symlink -> file)")
+ (112 " (type change subproject -> file)")))
+ (80 ;; symlink
+ (case old-type
+ (64 " (type change file -> symlink)")
+ (112 " (type change subproject -> symlink)")
+ (t " (symlink)")))
+ (112 ;; subproject
+ (case old-type
+ (64 " (type change file -> subproject)")
+ (80 " (type change symlink -> subproject)")
+ (t " (subproject)")))
+ (72 nil) ;; directory (internal, not a real git state)
+ (0 ;; deleted or unknown
+ (case old-type
+ (80 " (symlink)")
+ (112 " (subproject)")))
+ (t (format " (unknown type %o)" new-type)))))
+ (cond (str (propertize str 'face 'git-status-face))
+ ((eq new-type 72) "/")
+ (t ""))))
+
(defun git-rename-as-string (info)
"Return a string describing the copy or rename associated with INFO, or an empty string if none."
(let ((state (git-fileinfo->rename-state info)))
@@ -526,30 +629,64 @@ and returns the process output as a string."
(defun git-fileinfo-prettyprint (info)
"Pretty-printer for the git-fileinfo structure."
- (insert (concat " " (if (git-fileinfo->marked info) (propertize "*" 'face 'git-mark-face) " ")
- " " (git-status-code-as-string (git-fileinfo->state info))
- " " (git-permissions-as-string (git-fileinfo->old-perm info) (git-fileinfo->new-perm info))
- " " (git-escape-file-name (git-fileinfo->name info))
- (git-rename-as-string info))))
-
-(defun git-insert-fileinfo (status info &optional refresh)
- "Insert INFO in the status buffer, optionally refreshing an existing one."
- (let ((node (and refresh
- (git-find-status-file status (git-fileinfo->name info)))))
- (setf (git-fileinfo->needs-refresh info) t)
- (when node ;preserve the marked flag
- (setf (git-fileinfo->marked info) (git-fileinfo->marked (ewoc-data node))))
- (if node (setf (ewoc-data node) info) (ewoc-enter-last status info))))
+ (let ((old-perm (git-fileinfo->old-perm info))
+ (new-perm (git-fileinfo->new-perm info)))
+ (insert (concat " " (if (git-fileinfo->marked info) (propertize "*" 'face 'git-mark-face) " ")
+ " " (git-status-code-as-string (git-fileinfo->state info))
+ " " (git-permissions-as-string old-perm new-perm)
+ " " (git-escape-file-name (git-fileinfo->name info))
+ (git-file-type-as-string old-perm new-perm)
+ (git-rename-as-string info)))))
+
+(defun git-update-node-fileinfo (node info)
+ "Update the fileinfo of the specified node. The names are assumed to match already."
+ (let ((data (ewoc-data node)))
+ (setf
+ ;; preserve the marked flag
+ (git-fileinfo->marked info) (git-fileinfo->marked data)
+ (git-fileinfo->needs-update data) nil)
+ (when (not (equal info data))
+ (setf (git-fileinfo->needs-refresh info) t
+ (ewoc-data node) info))))
+
+(defun git-insert-info-list (status infolist files)
+ "Insert a sorted list of file infos in the status buffer, replacing existing ones if any."
+ (let* ((info (pop infolist))
+ (node (ewoc-nth status 0))
+ (name (and info (git-fileinfo->name info)))
+ remaining)
+ (while info
+ (let ((nodename (and node (git-fileinfo->name (ewoc-data node)))))
+ (while (and files (string-lessp (car files) name))
+ (push (pop files) remaining))
+ (when (and files (string-equal (car files) name))
+ (setq files (cdr files)))
+ (cond ((not nodename)
+ (setq node (ewoc-enter-last status info))
+ (setq info (pop infolist))
+ (setq name (and info (git-fileinfo->name info))))
+ ((string-lessp nodename name)
+ (setq node (ewoc-next status node)))
+ ((string-equal nodename name)
+ ;; preserve the marked flag
+ (git-update-node-fileinfo node info)
+ (setq info (pop infolist))
+ (setq name (and info (git-fileinfo->name info))))
+ (t
+ (setq node (ewoc-enter-before status node info))
+ (setq info (pop infolist))
+ (setq name (and info (git-fileinfo->name info)))))))
+ (nconc (nreverse remaining) files)))
(defun git-run-diff-index (status files)
"Run git-diff-index on FILES and parse the results into STATUS.
Return the list of files that haven't been handled."
- (let ((refresh files))
+ (let (infolist)
(with-temp-buffer
- (apply #'git-run-command t nil "diff-index" "-z" "-M" "HEAD" "--" files)
+ (apply #'git-call-process t "diff-index" "-z" "-M" "HEAD" "--" files)
(goto-char (point-min))
(while (re-search-forward
- ":\\([0-7]\\{6\\}\\) \\([0-7]\\{6\\}\\) [0-9a-f]\\{40\\} [0-9a-f]\\{40\\} \\(\\([ADMU]\\)\0\\([^\0]+\\)\\|\\([CR]\\)[0-9]*\0\\([^\0]+\\)\0\\([^\0]+\\)\\)\0"
+ ":\\([0-7]\\{6\\}\\) \\([0-7]\\{6\\}\\) [0-9a-f]\\{40\\} [0-9a-f]\\{40\\} \\(\\([ADMUT]\\)\0\\([^\0]+\\)\\|\\([CR]\\)[0-9]*\0\\([^\0]+\\)\0\\([^\0]+\\)\\)\0"
nil t 1)
(let ((old-perm (string-to-number (match-string 1) 8))
(new-perm (string-to-number (match-string 2) 8))
@@ -558,13 +695,15 @@ Return the list of files that haven't been handled."
(new-name (match-string 8)))
(if new-name ; copy or rename
(if (eq ?C (string-to-char state))
- (git-insert-fileinfo status (git-create-fileinfo 'added new-name old-perm new-perm 'copy name) refresh)
- (git-insert-fileinfo status (git-create-fileinfo 'deleted name 0 0 'rename new-name) refresh)
- (git-insert-fileinfo status (git-create-fileinfo 'added new-name old-perm new-perm 'rename name)) refresh)
- (git-insert-fileinfo status (git-create-fileinfo (git-state-code state) name old-perm new-perm) refresh))
- (setq files (delete name files))
- (when new-name (setq files (delete new-name files)))))))
- files)
+ (push (git-create-fileinfo 'added new-name old-perm new-perm 'copy name) infolist)
+ (push (git-create-fileinfo 'deleted name 0 0 'rename new-name) infolist)
+ (push (git-create-fileinfo 'added new-name old-perm new-perm 'rename name) infolist))
+ (push (git-create-fileinfo (git-state-code state) name old-perm new-perm) infolist)))))
+ (setq infolist (sort (nreverse infolist)
+ (lambda (info1 info2)
+ (string-lessp (git-fileinfo->name info1)
+ (git-fileinfo->name info2)))))
+ (git-insert-info-list status infolist files)))
(defun git-find-status-file (status file)
"Find a given file in the status ewoc and return its node."
@@ -576,27 +715,43 @@ Return the list of files that haven't been handled."
(defun git-run-ls-files (status files default-state &rest options)
"Run git-ls-files on FILES and parse the results into STATUS.
Return the list of files that haven't been handled."
- (let ((refresh files))
+ (let (infolist)
(with-temp-buffer
- (apply #'git-run-command t nil "ls-files" "-z" "-t" (append options (list "--") files))
+ (apply #'git-call-process t "ls-files" "-z" (append options (list "--") files))
(goto-char (point-min))
- (while (re-search-forward "\\([HMRCK?]\\) \\([^\0]*\\)\0" nil t 1)
- (let ((state (match-string 1))
- (name (match-string 2)))
- (git-insert-fileinfo status (git-create-fileinfo (or (git-state-code state) default-state) name) refresh)
- (setq files (delete name files))))))
- files)
+ (while (re-search-forward "\\([^\0]*?\\)\\(/?\\)\0" nil t 1)
+ (let ((name (match-string 1)))
+ (push (git-create-fileinfo default-state name 0
+ (if (string-equal "/" (match-string 2)) (lsh ?\110 9) 0))
+ infolist))))
+ (setq infolist (nreverse infolist)) ;; assume it is sorted already
+ (git-insert-info-list status infolist files)))
+
+(defun git-run-ls-files-cached (status files default-state)
+ "Run git-ls-files -c on FILES and parse the results into STATUS.
+Return the list of files that haven't been handled."
+ (let (infolist)
+ (with-temp-buffer
+ (apply #'git-call-process t "ls-files" "-z" "-s" "-c" "--" files)
+ (goto-char (point-min))
+ (while (re-search-forward "\\([0-7]\\{6\\}\\) [0-9a-f]\\{40\\} 0\t\\([^\0]+\\)\0" nil t)
+ (let* ((new-perm (string-to-number (match-string 1) 8))
+ (old-perm (if (eq default-state 'added) 0 new-perm))
+ (name (match-string 2)))
+ (push (git-create-fileinfo default-state name old-perm new-perm) infolist))))
+ (setq infolist (nreverse infolist)) ;; assume it is sorted already
+ (git-insert-info-list status infolist files)))
(defun git-run-ls-unmerged (status files)
"Run git-ls-files -u on FILES and parse the results into STATUS."
(with-temp-buffer
- (apply #'git-run-command t nil "ls-files" "-z" "-u" "--" files)
+ (apply #'git-call-process t "ls-files" "-z" "-u" "--" files)
(goto-char (point-min))
(let (unmerged-files)
(while (re-search-forward "[0-7]\\{6\\} [0-9a-f]\\{40\\} [123]\t\\([^\0]+\\)\0" nil t)
- (let ((node (git-find-status-file status (match-string 1))))
- (when node (push (ewoc-data node) unmerged-files))))
- (git-set-files-state unmerged-files 'unmerged))))
+ (push (match-string 1) unmerged-files))
+ (setq unmerged-files (nreverse unmerged-files)) ;; assume it is sorted already
+ (git-set-filenames-state status unmerged-files 'unmerged))))
(defun git-get-exclude-files ()
"Get the list of exclude files to pass to git-ls-files."
@@ -608,34 +763,62 @@ Return the list of files that haven't been handled."
(push config files))
files))
-(defun git-update-status-files (files &optional default-state)
- "Update the status of FILES from the index."
+(defun git-run-ls-files-with-excludes (status files default-state &rest options)
+ "Run git-ls-files on FILES with appropriate --exclude-from options."
+ (let ((exclude-files (git-get-exclude-files)))
+ (apply #'git-run-ls-files status files default-state "--directory" "--no-empty-directory"
+ (concat "--exclude-per-directory=" git-per-dir-ignore-file)
+ (append options (mapcar (lambda (f) (concat "--exclude-from=" f)) exclude-files)))))
+
+(defun git-update-status-files (&optional files mark-files)
+ "Update the status of FILES from the index.
+The FILES list must be sorted."
(unless git-status (error "Not in git-status buffer."))
- (let* ((status git-status)
- (remaining-files
+ ;; set the needs-update flag on existing files
+ (if files
+ (git-status-filenames-map
+ git-status (lambda (info) (setf (git-fileinfo->needs-update info) t)) files)
+ (ewoc-map (lambda (info) (setf (git-fileinfo->needs-update info) t) nil) git-status)
+ (git-call-process nil "update-index" "--refresh")
+ (when git-show-uptodate
+ (git-run-ls-files-cached git-status nil 'uptodate)))
+ (let ((remaining-files
(if (git-empty-db-p) ; we need some special handling for an empty db
- (git-run-ls-files status files 'added "-c")
- (git-run-diff-index status files))))
- (git-run-ls-unmerged status files)
- (when (or (not files) remaining-files)
- (let ((exclude-files (git-get-exclude-files)))
- (setq remaining-files (apply #'git-run-ls-files status remaining-files 'unknown "-o"
- (concat "--exclude-per-directory=" git-per-dir-ignore-file)
- (mapcar (lambda (f) (concat "--exclude-from=" f)) exclude-files)))))
- ; mark remaining files with the default state (or remove them if nil)
+ (git-run-ls-files-cached git-status files 'added)
+ (git-run-diff-index git-status files))))
+ (git-run-ls-unmerged git-status files)
+ (when (or remaining-files (and git-show-unknown (not files)))
+ (setq remaining-files (git-run-ls-files-with-excludes git-status remaining-files 'unknown "-o")))
+ (when (or remaining-files (and git-show-ignored (not files)))
+ (setq remaining-files (git-run-ls-files-with-excludes git-status remaining-files 'ignored "-o" "-i")))
+ (unless files
+ (setq remaining-files (git-get-filenames (ewoc-collect git-status #'git-fileinfo->needs-update))))
(when remaining-files
- (if default-state
- (ewoc-map (lambda (info)
- (when (member (git-fileinfo->name info) remaining-files)
- (git-set-files-state (list info) default-state))
- nil)
- status)
- (ewoc-filter status
- (lambda (info files)
- (not (member (git-fileinfo->name info) files)))
- remaining-files)))
+ (setq remaining-files (git-run-ls-files-cached git-status remaining-files 'uptodate)))
+ (git-set-filenames-state git-status remaining-files nil)
+ (when mark-files (git-mark-files git-status files))
(git-refresh-files)
- (git-refresh-ewoc-hf status)))
+ (git-refresh-ewoc-hf git-status)))
+
+(defun git-mark-files (status files)
+ "Mark all the specified FILES, and unmark the others."
+ (let ((file (and files (pop files)))
+ (node (ewoc-nth status 0)))
+ (while node
+ (let ((info (ewoc-data node)))
+ (if (and file (string-equal (git-fileinfo->name info) file))
+ (progn
+ (unless (git-fileinfo->marked info)
+ (setf (git-fileinfo->marked info) t)
+ (setf (git-fileinfo->needs-refresh info) t))
+ (setq file (pop files))
+ (setq node (ewoc-next status node)))
+ (when (git-fileinfo->marked info)
+ (setf (git-fileinfo->marked info) nil)
+ (setf (git-fileinfo->needs-refresh info) t))
+ (if (and file (string-lessp file (git-fileinfo->name info)))
+ (setq file (pop files))
+ (setq node (ewoc-next status node))))))))
(defun git-marked-files ()
"Return a list of all marked files, or if none a list containing just the file at cursor position."
@@ -644,13 +827,13 @@ Return the list of files that haven't been handled."
(list (ewoc-data (ewoc-locate git-status)))))
(defun git-marked-files-state (&rest states)
- "Return marked files that are in the specified states."
+ "Return a sorted list of marked files that are in the specified states."
(let ((files (git-marked-files))
result)
(dolist (info files)
(when (memq (git-fileinfo->state info) states)
(push info result)))
- result))
+ (nreverse result)))
(defun git-refresh-files ()
"Refresh all files that need it and clear the needs-refresh flag."
@@ -690,19 +873,18 @@ Return the list of files that haven't been handled."
(defun git-update-index (index-file files)
"Run git-update-index on a list of files."
- (let ((env (and index-file `(("GIT_INDEX_FILE" . ,index-file))))
+ (let ((process-environment (append (and index-file (list (concat "GIT_INDEX_FILE=" index-file)))
+ process-environment))
added deleted modified)
(dolist (info files)
(case (git-fileinfo->state info)
('added (push info added))
('deleted (push info deleted))
('modified (push info modified))))
- (when added
- (apply #'git-run-command nil env "update-index" "--add" "--" (git-get-filenames added)))
- (when deleted
- (apply #'git-run-command nil env "update-index" "--remove" "--" (git-get-filenames deleted)))
- (when modified
- (apply #'git-run-command nil env "update-index" "--" (git-get-filenames modified)))))
+ (and
+ (or (not added) (apply #'git-call-process-display-error "update-index" "--add" "--" (git-get-filenames added)))
+ (or (not deleted) (apply #'git-call-process-display-error "update-index" "--remove" "--" (git-get-filenames deleted)))
+ (or (not modified) (apply #'git-call-process-display-error "update-index" "--" (git-get-filenames modified))))))
(defun git-run-pre-commit-hook ()
"Run the pre-commit hook if any."
@@ -728,30 +910,30 @@ Return the list of files that haven't been handled."
(message "You cannot commit unmerged files, resolve them first.")
(unwind-protect
(let ((files (git-marked-files-state 'added 'deleted 'modified))
- head head-tree)
+ head tree head-tree)
(unless (git-empty-db-p)
(setq head (git-rev-parse "HEAD")
head-tree (git-rev-parse "HEAD^{tree}")))
- (if files
- (progn
- (git-read-tree head-tree index-file)
- (git-update-index nil files) ;update both the default index
- (git-update-index index-file files) ;and the temporary one
- (let ((tree (git-write-tree index-file)))
- (if (or (not (string-equal tree head-tree))
- (yes-or-no-p "The tree was not modified, do you really want to perform an empty commit? "))
- (let ((commit (git-commit-tree buffer tree head)))
- (condition-case nil (delete-file ".git/MERGE_HEAD") (error nil))
- (condition-case nil (delete-file ".git/MERGE_MSG") (error nil))
- (with-current-buffer buffer (erase-buffer))
- (git-set-files-state files 'uptodate)
- (git-run-command nil nil "rerere")
- (git-refresh-files)
- (git-refresh-ewoc-hf git-status)
- (message "Committed %s." commit)
- (git-run-hook "post-commit" nil))
- (message "Commit aborted."))))
- (message "No files to commit.")))
+ (message "Running git commit...")
+ (when
+ (and
+ (git-read-tree head-tree index-file)
+ (git-update-index nil files) ;update both the default index
+ (git-update-index index-file files) ;and the temporary one
+ (setq tree (git-write-tree index-file)))
+ (if (or (not (string-equal tree head-tree))
+ (yes-or-no-p "The tree was not modified, do you really want to perform an empty commit? "))
+ (let ((commit (git-commit-tree buffer tree head)))
+ (when commit
+ (condition-case nil (delete-file ".git/MERGE_HEAD") (error nil))
+ (condition-case nil (delete-file ".git/MERGE_MSG") (error nil))
+ (with-current-buffer buffer (erase-buffer))
+ (git-update-status-files (git-get-filenames files))
+ (git-call-process nil "rerere")
+ (git-call-process nil "gc" "--auto")
+ (message "Committed %s." commit)
+ (git-run-hook "post-commit" nil)))
+ (message "Commit aborted."))))
(delete-file index-file))))))
@@ -792,7 +974,8 @@ Return the list of files that haven't been handled."
"Mark all files."
(interactive)
(unless git-status (error "Not in git-status buffer."))
- (ewoc-map (lambda (info) (setf (git-fileinfo->marked info) t) t) git-status)
+ (ewoc-map (lambda (info) (unless (git-fileinfo->marked info)
+ (setf (git-fileinfo->marked info) t))) git-status)
; move back to goal column after invalidate
(when goal-column (move-to-column goal-column)))
@@ -800,7 +983,9 @@ Return the list of files that haven't been handled."
"Unmark all files."
(interactive)
(unless git-status (error "Not in git-status buffer."))
- (ewoc-map (lambda (info) (setf (git-fileinfo->marked info) nil) t) git-status)
+ (ewoc-map (lambda (info) (when (git-fileinfo->marked info)
+ (setf (git-fileinfo->marked info) nil)
+ t)) git-status)
; move back to goal column after invalidate
(when goal-column (move-to-column goal-column)))
@@ -850,14 +1035,21 @@ Return the list of files that haven't been handled."
(setq node (ewoc-prev git-status node)))
(ewoc-goto-node git-status last)))
+(defun git-insert-file (file)
+ "Insert file(s) into the git-status buffer."
+ (interactive "fInsert file: ")
+ (git-update-status-files (list (file-relative-name file))))
+
(defun git-add-file ()
"Add marked file(s) to the index cache."
(interactive)
- (let ((files (git-get-filenames (git-marked-files-state 'unknown))))
+ (let ((files (git-get-filenames (git-marked-files-state 'unknown 'ignored))))
+ ;; FIXME: add support for directories
(unless files
(push (file-relative-name (read-file-name "File to add: " nil nil t)) files))
- (apply #'git-run-command nil nil "update-index" "--add" "--" files)
- (git-update-status-files files 'uptodate)))
+ (when (apply 'git-call-process-display-error "update-index" "--add" "--" files)
+ (git-update-status-files files)
+ (git-success-message "Added" files))))
(defun git-ignore-file ()
"Add marked file(s) to the ignore list."
@@ -866,61 +1058,127 @@ Return the list of files that haven't been handled."
(unless files
(push (file-relative-name (read-file-name "File to ignore: " nil nil t)) files))
(dolist (f files) (git-append-to-ignore f))
- (git-update-status-files files 'ignored)))
+ (git-update-status-files files)
+ (git-success-message "Ignored" files)))
(defun git-remove-file ()
"Remove the marked file(s)."
(interactive)
- (let ((files (git-get-filenames (git-marked-files-state 'added 'modified 'unknown 'uptodate))))
+ (let ((files (git-get-filenames (git-marked-files-state 'added 'modified 'unknown 'uptodate 'ignored))))
(unless files
(push (file-relative-name (read-file-name "File to remove: " nil nil t)) files))
(if (yes-or-no-p
- (format "Remove %d file%s? " (length files) (if (> (length files) 1) "s" "")))
+ (if (cdr files)
+ (format "Remove %d files? " (length files))
+ (format "Remove %s? " (car files))))
(progn
(dolist (name files)
- (when (file-exists-p name) (delete-file name)))
- (apply #'git-run-command nil nil "update-index" "--remove" "--" files)
- (git-update-status-files files nil))
+ (ignore-errors
+ (if (file-directory-p name)
+ (delete-directory name)
+ (delete-file name))))
+ (when (apply 'git-call-process-display-error "update-index" "--remove" "--" files)
+ (git-update-status-files files)
+ (git-success-message "Removed" files)))
(message "Aborting"))))
(defun git-revert-file ()
"Revert changes to the marked file(s)."
(interactive)
- (let ((files (git-marked-files))
+ (let ((files (git-marked-files-state 'added 'deleted 'modified 'unmerged))
added modified)
(when (and files
(yes-or-no-p
- (format "Revert %d file%s? " (length files) (if (> (length files) 1) "s" ""))))
+ (if (cdr files)
+ (format "Revert %d files? " (length files))
+ (format "Revert %s? " (git-fileinfo->name (car files))))))
(dolist (info files)
(case (git-fileinfo->state info)
('added (push (git-fileinfo->name info) added))
('deleted (push (git-fileinfo->name info) modified))
('unmerged (push (git-fileinfo->name info) modified))
('modified (push (git-fileinfo->name info) modified))))
- (when added
- (apply #'git-run-command nil nil "update-index" "--force-remove" "--" added))
- (when modified
- (apply #'git-run-command nil nil "checkout" "HEAD" modified))
- (git-update-status-files (append added modified) 'uptodate))))
+ ;; check if a buffer contains one of the files and isn't saved
+ (dolist (file modified)
+ (let ((buffer (get-file-buffer file)))
+ (when (and buffer (buffer-modified-p buffer))
+ (error "Buffer %s is modified. Please kill or save modified buffers before reverting." (buffer-name buffer)))))
+ (let ((ok (and
+ (or (not added)
+ (apply 'git-call-process-display-error "update-index" "--force-remove" "--" added))
+ (or (not modified)
+ (apply 'git-call-process-display-error "checkout" "HEAD" modified))))
+ (names (git-get-filenames files)))
+ (git-update-status-files names)
+ (when ok
+ (dolist (file modified)
+ (let ((buffer (get-file-buffer file)))
+ (when buffer (with-current-buffer buffer (revert-buffer t t t)))))
+ (git-success-message "Reverted" names))))))
(defun git-resolve-file ()
"Resolve conflicts in marked file(s)."
(interactive)
(let ((files (git-get-filenames (git-marked-files-state 'unmerged))))
(when files
- (apply #'git-run-command nil nil "update-index" "--" files)
- (git-update-status-files files 'uptodate))))
+ (when (apply 'git-call-process-display-error "update-index" "--" files)
+ (git-update-status-files files)
+ (git-success-message "Resolved" files)))))
(defun git-remove-handled ()
"Remove handled files from the status list."
(interactive)
(ewoc-filter git-status
(lambda (info)
- (not (or (eq (git-fileinfo->state info) 'ignored)
- (eq (git-fileinfo->state info) 'uptodate)))))
+ (case (git-fileinfo->state info)
+ ('ignored git-show-ignored)
+ ('uptodate git-show-uptodate)
+ ('unknown git-show-unknown)
+ (t t))))
(unless (ewoc-nth git-status 0) ; refresh header if list is empty
(git-refresh-ewoc-hf git-status)))
+(defun git-toggle-show-uptodate ()
+ "Toogle the option for showing up-to-date files."
+ (interactive)
+ (if (setq git-show-uptodate (not git-show-uptodate))
+ (git-refresh-status)
+ (git-remove-handled)))
+
+(defun git-toggle-show-ignored ()
+ "Toogle the option for showing ignored files."
+ (interactive)
+ (if (setq git-show-ignored (not git-show-ignored))
+ (progn
+ (message "Inserting ignored files...")
+ (git-run-ls-files-with-excludes git-status nil 'ignored "-o" "-i")
+ (git-refresh-files)
+ (git-refresh-ewoc-hf git-status)
+ (message "Inserting ignored files...done"))
+ (git-remove-handled)))
+
+(defun git-toggle-show-unknown ()
+ "Toogle the option for showing unknown files."
+ (interactive)
+ (if (setq git-show-unknown (not git-show-unknown))
+ (progn
+ (message "Inserting unknown files...")
+ (git-run-ls-files-with-excludes git-status nil 'unknown "-o")
+ (git-refresh-files)
+ (git-refresh-ewoc-hf git-status)
+ (message "Inserting unknown files...done"))
+ (git-remove-handled)))
+
+(defun git-expand-directory (info)
+ "Expand the directory represented by INFO to list its files."
+ (when (eq (lsh (git-fileinfo->new-perm info) -9) ?\110)
+ (let ((dir (git-fileinfo->name info)))
+ (git-set-filenames-state git-status (list dir) nil)
+ (git-run-ls-files-with-excludes git-status (list (concat dir "/")) 'unknown "-o")
+ (git-refresh-files)
+ (git-refresh-ewoc-hf git-status)
+ t)))
+
(defun git-setup-diff-buffer (buffer)
"Setup a buffer for displaying a diff."
(let ((dir default-directory))
@@ -930,7 +1188,9 @@ Return the list of files that haven't been handled."
(setq default-directory dir)
(setq buffer-read-only t)))
(display-buffer buffer)
- (shrink-window-if-larger-than-buffer))
+ ; shrink window only if it displays the status buffer
+ (when (eq (window-buffer) (current-buffer))
+ (shrink-window-if-larger-than-buffer)))
(defun git-diff-file ()
"Diff the marked file(s) against HEAD."
@@ -1003,6 +1263,11 @@ Return the list of files that haven't been handled."
(with-current-buffer log-edit-parent-buffer
(git-get-filenames (git-marked-files-state 'added 'deleted 'modified))))
+(defun git-log-edit-diff ()
+ "Run a diff of the current files being committed from a log-edit buffer."
+ (with-current-buffer log-edit-parent-buffer
+ (git-diff-file)))
+
(defun git-append-sign-off (name email)
"Append a Signed-off-by entry to the current buffer, avoiding duplicates."
(let ((sign-off (format "Signed-off-by: %s <%s>" name email))
@@ -1015,11 +1280,10 @@ Return the list of files that haven't been handled."
(goto-char (point-max))
(insert sign-off "\n"))))
-(defun git-setup-log-buffer (buffer &optional author-name author-email subject date msg)
+(defun git-setup-log-buffer (buffer &optional merge-heads author-name author-email subject date msg)
"Setup the log buffer for a commit."
(unless git-status (error "Not in git-status buffer."))
- (let ((merge-heads (git-get-merge-heads))
- (dir default-directory)
+ (let ((dir default-directory)
(committer-name (git-get-committer-name))
(committer-email (git-get-committer-email))
(sign-off git-append-signed-off-by))
@@ -1033,24 +1297,24 @@ Return the list of files that haven't been handled."
(or author-email committer-email)
(if date (format "Date: %s\n" date) "")
(if merge-heads
- (format "Parent: %s\n%s\n"
- (git-rev-parse "HEAD")
- (mapconcat (lambda (str) (concat "Parent: " str)) merge-heads "\n"))
+ (format "Merge: %s\n"
+ (mapconcat 'identity merge-heads " "))
""))
'face 'git-header-face)
(propertize git-log-msg-separator 'face 'git-separator-face)
"\n")
(when subject (insert subject "\n\n"))
(cond (msg (insert msg "\n"))
- ((file-readable-p ".dotest/msg")
- (insert-file-contents ".dotest/msg"))
+ ((file-readable-p ".git/rebase-apply/msg")
+ (insert-file-contents ".git/rebase-apply/msg"))
((file-readable-p ".git/MERGE_MSG")
(insert-file-contents ".git/MERGE_MSG")))
; delete empty lines at end
(goto-char (point-min))
(when (re-search-forward "\n+\\'" nil t)
(replace-match "\n" t t))
- (when sign-off (git-append-sign-off committer-name committer-email)))))
+ (when sign-off (git-append-sign-off committer-name committer-email)))
+ buffer))
(defun git-commit-file ()
"Commit the marked file(s), asking for a commit message."
@@ -1061,9 +1325,9 @@ Return the list of files that haven't been handled."
(coding-system (git-get-commits-coding-system))
author-name author-email subject date)
(when (eq 0 (buffer-size buffer))
- (when (file-readable-p ".dotest/info")
+ (when (file-readable-p ".git/rebase-apply/info")
(with-temp-buffer
- (insert-file-contents ".dotest/info")
+ (insert-file-contents ".git/rebase-apply/info")
(goto-char (point-min))
(when (re-search-forward "^Author: \\(.*\\)\nEmail: \\(.*\\)$" nil t)
(setq author-name (match-string 1))
@@ -1074,20 +1338,142 @@ Return the list of files that haven't been handled."
(goto-char (point-min))
(when (re-search-forward "^Date: \\(.*\\)$" nil t)
(setq date (match-string 1)))))
- (git-setup-log-buffer buffer author-name author-email subject date))
- (log-edit #'git-do-commit nil #'git-log-edit-files buffer)
+ (git-setup-log-buffer buffer (git-get-merge-heads) author-name author-email subject date))
+ (if (boundp 'log-edit-diff-function)
+ (log-edit 'git-do-commit nil '((log-edit-listfun . git-log-edit-files)
+ (log-edit-diff-function . git-log-edit-diff)) buffer)
+ (log-edit 'git-do-commit nil 'git-log-edit-files buffer))
(setq font-lock-keywords (font-lock-compile-keywords git-log-edit-font-lock-keywords))
+ (setq paragraph-separate (concat (regexp-quote git-log-msg-separator) "$\\|Author: \\|Date: \\|Merge: \\|Signed-off-by: \\|\f\\|[ ]*$"))
(setq buffer-file-coding-system coding-system)
(re-search-forward (regexp-quote (concat git-log-msg-separator "\n")) nil t))))
+(defun git-setup-commit-buffer (commit)
+ "Setup the commit buffer with the contents of COMMIT."
+ (let (parents author-name author-email subject date msg)
+ (with-temp-buffer
+ (let ((coding-system (git-get-logoutput-coding-system)))
+ (git-call-process t "log" "-1" "--pretty=medium" "--abbrev=40" commit)
+ (goto-char (point-min))
+ (when (re-search-forward "^Merge: *\\(.*\\)$" nil t)
+ (setq parents (cdr (split-string (match-string 1) " +"))))
+ (when (re-search-forward "^Author: *\\(.*\\) <\\(.*\\)>$" nil t)
+ (setq author-name (match-string 1))
+ (setq author-email (match-string 2)))
+ (when (re-search-forward "^Date: *\\(.*\\)$" nil t)
+ (setq date (match-string 1)))
+ (while (re-search-forward "^ \\(.*\\)$" nil t)
+ (push (match-string 1) msg))
+ (setq msg (nreverse msg))
+ (setq subject (pop msg))
+ (while (and msg (zerop (length (car msg))) (pop msg)))))
+ (git-setup-log-buffer (get-buffer-create "*git-commit*")
+ parents author-name author-email subject date
+ (mapconcat #'identity msg "\n"))))
+
+(defun git-get-commit-files (commit)
+ "Retrieve a sorted list of files modified by COMMIT."
+ (let (files)
+ (with-temp-buffer
+ (git-call-process t "diff-tree" "-m" "-r" "-z" "--name-only" "--no-commit-id" "--root" commit)
+ (goto-char (point-min))
+ (while (re-search-forward "\\([^\0]*\\)\0" nil t 1)
+ (push (match-string 1) files)))
+ (sort files #'string-lessp)))
+
+(defun git-read-commit-name (prompt &optional default)
+ "Ask for a commit name, with completion for local branch, remote branch and tag."
+ (completing-read prompt
+ (list* "HEAD" "ORIG_HEAD" "FETCH_HEAD" (mapcar #'car (git-for-each-ref)))
+ nil nil nil nil default))
+
+(defun git-checkout (branch &optional merge)
+ "Checkout a branch, tag, or any commit.
+Use a prefix arg if git should merge while checking out."
+ (interactive
+ (list (git-read-commit-name "Checkout: ")
+ current-prefix-arg))
+ (unless git-status (error "Not in git-status buffer."))
+ (let ((args (list branch "--")))
+ (when merge (push "-m" args))
+ (when (apply #'git-call-process-display-error "checkout" args)
+ (git-update-status-files))))
+
+(defun git-branch (branch)
+ "Create a branch from the current HEAD and switch to it."
+ (interactive (list (git-read-commit-name "Branch: ")))
+ (unless git-status (error "Not in git-status buffer."))
+ (if (git-rev-parse (concat "refs/heads/" branch))
+ (if (yes-or-no-p (format "Branch %s already exists, replace it? " branch))
+ (and (git-call-process-display-error "branch" "-f" branch)
+ (git-call-process-display-error "checkout" branch))
+ (message "Canceled."))
+ (git-call-process-display-error "checkout" "-b" branch))
+ (git-refresh-ewoc-hf git-status))
+
+(defun git-amend-commit ()
+ "Undo the last commit on HEAD, and set things up to commit an
+amended version of it."
+ (interactive)
+ (unless git-status (error "Not in git-status buffer."))
+ (when (git-empty-db-p) (error "No commit to amend."))
+ (let* ((commit (git-rev-parse "HEAD"))
+ (files (git-get-commit-files commit)))
+ (when (if (git-rev-parse "HEAD^")
+ (git-call-process-display-error "reset" "--soft" "HEAD^")
+ (and (git-update-ref "ORIG_HEAD" commit)
+ (git-update-ref "HEAD" nil commit)))
+ (git-update-status-files files t)
+ (git-setup-commit-buffer commit)
+ (git-commit-file))))
+
+(defun git-cherry-pick-commit (arg)
+ "Cherry-pick a commit."
+ (interactive (list (git-read-commit-name "Cherry-pick commit: ")))
+ (unless git-status (error "Not in git-status buffer."))
+ (let ((commit (git-rev-parse (concat arg "^0"))))
+ (unless commit (error "Not a valid commit '%s'." arg))
+ (when (git-rev-parse (concat commit "^2"))
+ (error "Cannot cherry-pick a merge commit."))
+ (let ((files (git-get-commit-files commit))
+ (ok (git-call-process-display-error "cherry-pick" "-n" commit)))
+ (git-update-status-files files ok)
+ (with-current-buffer (git-setup-commit-buffer commit)
+ (goto-char (point-min))
+ (if (re-search-forward "^\n*Signed-off-by:" nil t 1)
+ (goto-char (match-beginning 0))
+ (goto-char (point-max)))
+ (insert "(cherry picked from commit " commit ")\n"))
+ (when ok (git-commit-file)))))
+
+(defun git-revert-commit (arg)
+ "Revert a commit."
+ (interactive (list (git-read-commit-name "Revert commit: ")))
+ (unless git-status (error "Not in git-status buffer."))
+ (let ((commit (git-rev-parse (concat arg "^0"))))
+ (unless commit (error "Not a valid commit '%s'." arg))
+ (when (git-rev-parse (concat commit "^2"))
+ (error "Cannot revert a merge commit."))
+ (let ((files (git-get-commit-files commit))
+ (subject (git-get-commit-description commit))
+ (ok (git-call-process-display-error "revert" "-n" commit)))
+ (git-update-status-files files ok)
+ (when (string-match "^[0-9a-f]+ - \\(.*\\)$" subject)
+ (setq subject (match-string 1 subject)))
+ (git-setup-log-buffer (get-buffer-create "*git-commit*")
+ (git-get-merge-heads) nil nil (format "Revert \"%s\"" subject) nil
+ (format "This reverts commit %s.\n" commit))
+ (when ok (git-commit-file)))))
+
(defun git-find-file ()
"Visit the current file in its own buffer."
(interactive)
(unless git-status (error "Not in git-status buffer."))
(let ((info (ewoc-data (ewoc-locate git-status))))
- (find-file (git-fileinfo->name info))
- (when (eq 'unmerged (git-fileinfo->state info))
- (smerge-mode 1))))
+ (unless (git-expand-directory info)
+ (find-file (git-fileinfo->name info))
+ (when (eq 'unmerged (git-fileinfo->state info))
+ (smerge-mode 1)))))
(defun git-find-file-other-window ()
"Visit the current file in its own buffer in another window."
@@ -1116,16 +1502,10 @@ Return the list of files that haven't been handled."
(defun git-refresh-status ()
"Refresh the git status buffer."
(interactive)
- (let* ((status git-status)
- (pos (ewoc-locate status))
- (cur-name (and pos (git-fileinfo->name (ewoc-data pos)))))
- (unless status (error "Not in git-status buffer."))
- (git-run-command nil nil "update-index" "--refresh")
- (git-clear-status status)
- (git-update-status-files nil)
- ; move point to the current file name if any
- (let ((node (and cur-name (git-find-status-file status cur-name))))
- (when node (ewoc-goto-node status node)))))
+ (unless git-status (error "Not in git-status buffer."))
+ (message "Refreshing git status...")
+ (git-update-status-files)
+ (message "Refreshing git status...done"))
(defun git-status-quit ()
"Quit git-status mode."
@@ -1146,19 +1526,23 @@ Return the list of files that haven't been handled."
(unless git-status-mode-map
(let ((map (make-keymap))
- (diff-map (make-sparse-keymap)))
+ (commit-map (make-sparse-keymap))
+ (diff-map (make-sparse-keymap))
+ (toggle-map (make-sparse-keymap)))
(suppress-keymap map)
(define-key map "?" 'git-help)
(define-key map "h" 'git-help)
(define-key map " " 'git-next-file)
(define-key map "a" 'git-add-file)
(define-key map "c" 'git-commit-file)
+ (define-key map "\C-c" commit-map)
(define-key map "d" diff-map)
(define-key map "=" 'git-diff-file)
(define-key map "f" 'git-find-file)
(define-key map "\r" 'git-find-file)
(define-key map "g" 'git-refresh-status)
(define-key map "i" 'git-ignore-file)
+ (define-key map "I" 'git-insert-file)
(define-key map "l" 'git-log-file)
(define-key map "m" 'git-mark-file)
(define-key map "M" 'git-mark-all)
@@ -1170,6 +1554,7 @@ Return the list of files that haven't been handled."
(define-key map "q" 'git-status-quit)
(define-key map "r" 'git-remove-file)
(define-key map "R" 'git-resolve-file)
+ (define-key map "t" toggle-map)
(define-key map "T" 'git-toggle-all-marks)
(define-key map "u" 'git-unmark-file)
(define-key map "U" 'git-revert-file)
@@ -1177,6 +1562,12 @@ Return the list of files that haven't been handled."
(define-key map "x" 'git-remove-handled)
(define-key map "\C-?" 'git-unmark-file-up)
(define-key map "\M-\C-?" 'git-unmark-all)
+ ; the commit submap
+ (define-key commit-map "\C-a" 'git-amend-commit)
+ (define-key commit-map "\C-b" 'git-branch)
+ (define-key commit-map "\C-o" 'git-checkout)
+ (define-key commit-map "\C-p" 'git-cherry-pick-commit)
+ (define-key commit-map "\C-v" 'git-revert-commit)
; the diff submap
(define-key diff-map "b" 'git-diff-file-base)
(define-key diff-map "c" 'git-diff-file-combined)
@@ -1186,7 +1577,57 @@ Return the list of files that haven't been handled."
(define-key diff-map "h" 'git-diff-file-merge-head)
(define-key diff-map "m" 'git-diff-file-mine)
(define-key diff-map "o" 'git-diff-file-other)
- (setq git-status-mode-map map)))
+ ; the toggle submap
+ (define-key toggle-map "u" 'git-toggle-show-uptodate)
+ (define-key toggle-map "i" 'git-toggle-show-ignored)
+ (define-key toggle-map "k" 'git-toggle-show-unknown)
+ (define-key toggle-map "m" 'git-toggle-all-marks)
+ (setq git-status-mode-map map))
+ (easy-menu-define git-menu git-status-mode-map
+ "Git Menu"
+ `("Git"
+ ["Refresh" git-refresh-status t]
+ ["Commit" git-commit-file t]
+ ["Checkout..." git-checkout t]
+ ["New Branch..." git-branch t]
+ ["Cherry-pick Commit..." git-cherry-pick-commit t]
+ ["Revert Commit..." git-revert-commit t]
+ ("Merge"
+ ["Next Unmerged File" git-next-unmerged-file t]
+ ["Prev Unmerged File" git-prev-unmerged-file t]
+ ["Mark as Resolved" git-resolve-file t]
+ ["Interactive Merge File" git-find-file-imerge t]
+ ["Diff Against Common Base File" git-diff-file-base t]
+ ["Diff Combined" git-diff-file-combined t]
+ ["Diff Against Merge Head" git-diff-file-merge-head t]
+ ["Diff Against Mine" git-diff-file-mine t]
+ ["Diff Against Other" git-diff-file-other t])
+ "--------"
+ ["Add File" git-add-file t]
+ ["Revert File" git-revert-file t]
+ ["Ignore File" git-ignore-file t]
+ ["Remove File" git-remove-file t]
+ ["Insert File" git-insert-file t]
+ "--------"
+ ["Find File" git-find-file t]
+ ["View File" git-view-file t]
+ ["Diff File" git-diff-file t]
+ ["Interactive Diff File" git-diff-file-idiff t]
+ ["Log" git-log-file t]
+ "--------"
+ ["Mark" git-mark-file t]
+ ["Mark All" git-mark-all t]
+ ["Unmark" git-unmark-file t]
+ ["Unmark All" git-unmark-all t]
+ ["Toggle All Marks" git-toggle-all-marks t]
+ ["Hide Handled Files" git-remove-handled t]
+ "--------"
+ ["Show Uptodate Files" git-toggle-show-uptodate :style toggle :selected git-show-uptodate]
+ ["Show Ignored Files" git-toggle-show-ignored :style toggle :selected git-show-ignored]
+ ["Show Unknown Files" git-toggle-show-unknown :style toggle :selected git-show-unknown]
+ "--------"
+ ["Quit" git-status-quit t])))
+
;; git mode should only run in the *git status* buffer
(put 'git-status-mode 'mode-class 'special)
@@ -1207,6 +1648,9 @@ Commands:
(let ((status (ewoc-create 'git-fileinfo-prettyprint "" "")))
(set (make-local-variable 'git-status) status))
(set (make-local-variable 'list-buffers-directory) default-directory)
+ (make-local-variable 'git-show-uptodate)
+ (make-local-variable 'git-show-ignored)
+ (make-local-variable 'git-show-unknown)
(run-hooks 'git-status-mode-hook)))
(defun git-find-status-buffer (dir)
@@ -1219,7 +1663,7 @@ Commands:
(with-current-buffer buffer
(when (and list-buffers-directory
(string-equal fulldir (expand-file-name list-buffers-directory))
- (string-match "\\*git-status\\*$" (buffer-name buffer)))
+ (eq major-mode 'git-status-mode))
(setq found buffer))))
(setq list (cdr list)))
found))
@@ -1235,9 +1679,24 @@ Commands:
(cd dir)
(git-status-mode)
(git-refresh-status)
- (goto-char (point-min)))
+ (goto-char (point-min))
+ (add-hook 'after-save-hook 'git-update-saved-file))
(message "%s is not a git working tree." dir)))
+(defun git-update-saved-file ()
+ "Update the corresponding git-status buffer when a file is saved.
+Meant to be used in `after-save-hook'."
+ (let* ((file (expand-file-name buffer-file-name))
+ (dir (condition-case nil (git-get-top-dir (file-name-directory file)) (error nil)))
+ (buffer (and dir (git-find-status-buffer dir))))
+ (when buffer
+ (with-current-buffer buffer
+ (let ((filename (file-relative-name file dir)))
+ ; skip files located inside the .git directory
+ (unless (string-match "^\\.git/" filename)
+ (git-call-process nil "add" "--refresh" "--" filename)
+ (git-update-status-files (list filename))))))))
+
(defun git-help ()
"Display help for Git mode."
(interactive)
diff --git a/contrib/emacs/vc-git.el b/contrib/emacs/vc-git.el
deleted file mode 100644
index b8f6be5c0a..0000000000
--- a/contrib/emacs/vc-git.el
+++ /dev/null
@@ -1,216 +0,0 @@
-;;; vc-git.el --- VC backend for the git version control system
-
-;; Copyright (C) 2006 Alexandre Julliard
-
-;; This program is free software; you can redistribute it and/or
-;; modify it under the terms of the GNU General Public License as
-;; published by the Free Software Foundation; either version 2 of
-;; the License, or (at your option) any later version.
-;;
-;; This program is distributed in the hope that it will be
-;; useful, but WITHOUT ANY WARRANTY; without even the implied
-;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
-;; PURPOSE. See the GNU General Public License for more details.
-;;
-;; You should have received a copy of the GNU General Public
-;; License along with this program; if not, write to the Free
-;; Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
-;; MA 02111-1307 USA
-
-;;; Commentary:
-
-;; This file contains a VC backend for the git version control
-;; system.
-;;
-;; To install: put this file on the load-path and add GIT to the list
-;; of supported backends in `vc-handled-backends'; the following line,
-;; placed in your ~/.emacs, will accomplish this:
-;;
-;; (add-to-list 'vc-handled-backends 'GIT)
-;;
-;; TODO
-;; - changelog generation
-;; - working with revisions other than HEAD
-;;
-
-(eval-when-compile (require 'cl))
-
-(defvar git-commits-coding-system 'utf-8
- "Default coding system for git commits.")
-
-(defun vc-git--run-command-string (file &rest args)
- "Run a git command on FILE and return its output as string."
- (let* ((ok t)
- (str (with-output-to-string
- (with-current-buffer standard-output
- (unless (eq 0 (apply #'call-process "git" nil '(t nil) nil
- (append args (list (file-relative-name file)))))
- (setq ok nil))))))
- (and ok str)))
-
-(defun vc-git--run-command (file &rest args)
- "Run a git command on FILE, discarding any output."
- (let ((name (file-relative-name file)))
- (eq 0 (apply #'call-process "git" nil (get-buffer "*Messages") nil (append args (list name))))))
-
-(defun vc-git-registered (file)
- "Check whether FILE is registered with git."
- (with-temp-buffer
- (let* ((dir (file-name-directory file))
- (name (file-relative-name file dir)))
- (and (ignore-errors
- (when dir (cd dir))
- (eq 0 (call-process "git" nil '(t nil) nil "ls-files" "-c" "-z" "--" name)))
- (let ((str (buffer-string)))
- (and (> (length str) (length name))
- (string= (substring str 0 (1+ (length name))) (concat name "\0"))))))))
-
-(defun vc-git-state (file)
- "git-specific version of `vc-state'."
- (let ((diff (vc-git--run-command-string file "diff-index" "-z" "HEAD" "--")))
- (if (and diff (string-match ":[0-7]\\{6\\} [0-7]\\{6\\} [0-9a-f]\\{40\\} [0-9a-f]\\{40\\} [ADMU]\0[^\0]+\0" diff))
- 'edited
- 'up-to-date)))
-
-(defun vc-git-workfile-version (file)
- "git-specific version of `vc-workfile-version'."
- (let ((str (with-output-to-string
- (with-current-buffer standard-output
- (call-process "git" nil '(t nil) nil "symbolic-ref" "HEAD")))))
- (if (string-match "^\\(refs/heads/\\)?\\(.+\\)$" str)
- (match-string 2 str)
- str)))
-
-(defun vc-git-symbolic-commit (commit)
- "Translate COMMIT string into symbolic form.
-Returns nil if not possible."
- (and commit
- (with-temp-buffer
- (and
- (zerop
- (call-process "git" nil '(t nil) nil "name-rev"
- "--name-only" "--tags"
- commit))
- (goto-char (point-min))
- (= (forward-line 2) 1)
- (bolp)
- (buffer-substring-no-properties (point-min) (1- (point-max)))))))
-
-(defun vc-git-previous-version (file rev)
- "git-specific version of `vc-previous-version'."
- (let ((default-directory (file-name-directory (expand-file-name file)))
- (file (file-name-nondirectory file)))
- (vc-git-symbolic-commit
- (with-temp-buffer
- (and
- (zerop
- (call-process "git" nil '(t nil) nil "rev-list"
- "-2" rev "--" file))
- (goto-char (point-max))
- (bolp)
- (zerop (forward-line -1))
- (not (bobp))
- (buffer-substring-no-properties
- (point)
- (1- (point-max))))))))
-
-(defun vc-git-next-version (file rev)
- "git-specific version of `vc-next-version'."
- (let* ((default-directory (file-name-directory
- (expand-file-name file)))
- (file (file-name-nondirectory file))
- (current-rev
- (with-temp-buffer
- (and
- (zerop
- (call-process "git" nil '(t nil) nil "rev-list"
- "-1" rev "--" file))
- (goto-char (point-max))
- (bolp)
- (zerop (forward-line -1))
- (bobp)
- (buffer-substring-no-properties
- (point)
- (1- (point-max)))))))
- (and current-rev
- (vc-git-symbolic-commit
- (with-temp-buffer
- (and
- (zerop
- (call-process "git" nil '(t nil) nil "rev-list"
- "HEAD" "--" file))
- (goto-char (point-min))
- (search-forward current-rev nil t)
- (zerop (forward-line -1))
- (buffer-substring-no-properties
- (point)
- (progn (forward-line 1) (1- (point))))))))))
-
-(defun vc-git-revert (file &optional contents-done)
- "Revert FILE to the version stored in the git repository."
- (if contents-done
- (vc-git--run-command file "update-index" "--")
- (vc-git--run-command file "checkout" "HEAD")))
-
-(defun vc-git-checkout-model (file)
- 'implicit)
-
-(defun vc-git-workfile-unchanged-p (file)
- (let ((sha1 (vc-git--run-command-string file "hash-object" "--"))
- (head (vc-git--run-command-string file "ls-tree" "-z" "HEAD" "--")))
- (and head
- (string-match "[0-7]\\{6\\} blob \\([0-9a-f]\\{40\\}\\)\t[^\0]+\0" head)
- (string= (car (split-string sha1 "\n")) (match-string 1 head)))))
-
-(defun vc-git-register (file &optional rev comment)
- "Register FILE into the git version-control system."
- (vc-git--run-command file "update-index" "--add" "--"))
-
-(defun vc-git-print-log (file &optional buffer)
- (let ((name (file-relative-name file))
- (coding-system-for-read git-commits-coding-system))
- (vc-do-command buffer 'async "git" name "rev-list" "--pretty" "HEAD" "--")))
-
-(defun vc-git-diff (file &optional rev1 rev2 buffer)
- (let ((name (file-relative-name file))
- (buf (or buffer "*vc-diff*")))
- (if (and rev1 rev2)
- (vc-do-command buf 0 "git" name "diff-tree" "-p" rev1 rev2 "--")
- (vc-do-command buf 0 "git" name "diff-index" "-p" (or rev1 "HEAD") "--"))
- ; git-diff-index doesn't set exit status like diff does
- (if (vc-git-workfile-unchanged-p file) 0 1)))
-
-(defun vc-git-checkin (file rev comment)
- (let ((coding-system-for-write git-commits-coding-system))
- (vc-git--run-command file "commit" "-m" comment "--only" "--")))
-
-(defun vc-git-checkout (file &optional editable rev destfile)
- (if destfile
- (let ((fullname (substring
- (vc-git--run-command-string file "ls-files" "-z" "--full-name" "--")
- 0 -1))
- (coding-system-for-read 'no-conversion)
- (coding-system-for-write 'no-conversion))
- (with-temp-file destfile
- (eq 0 (call-process "git" nil t nil "cat-file" "blob"
- (concat (or rev "HEAD") ":" fullname)))))
- (vc-git--run-command file "checkout" (or rev "HEAD"))))
-
-(defun vc-git-annotate-command (file buf &optional rev)
- ; FIXME: rev is ignored
- (let ((name (file-relative-name file)))
- (call-process "git" nil buf nil "blame" name)))
-
-(defun vc-git-annotate-time ()
- (and (re-search-forward "[0-9a-f]+ (.* \\([0-9]+\\)-\\([0-9]+\\)-\\([0-9]+\\) \\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\) \\([-+0-9]+\\) +[0-9]+)" nil t)
- (vc-annotate-convert-time
- (apply #'encode-time (mapcar (lambda (match) (string-to-number (match-string match))) '(6 5 4 3 2 1 7))))))
-
-;; Not really useful since we can't do anything with the revision yet
-;;(defun vc-annotate-extract-revision-at-line ()
-;; (save-excursion
-;; (move-beginning-of-line 1)
-;; (and (looking-at "[0-9a-f]+")
-;; (buffer-substring (match-beginning 0) (match-end 0)))))
-
-(provide 'vc-git)
diff --git a/contrib/examples/README b/contrib/examples/README
new file mode 100644
index 0000000000..6946f3dd2a
--- /dev/null
+++ b/contrib/examples/README
@@ -0,0 +1,3 @@
+These are original scripted implementations, kept primarily for their
+reference value to any aspiring plumbing users who want to learn how
+pieces can be fit together.
diff --git a/contrib/examples/git-checkout.sh b/contrib/examples/git-checkout.sh
new file mode 100755
index 0000000000..1a7689a48f
--- /dev/null
+++ b/contrib/examples/git-checkout.sh
@@ -0,0 +1,302 @@
+#!/bin/sh
+
+OPTIONS_KEEPDASHDASH=t
+OPTIONS_SPEC="\
+git-checkout [options] [<branch>] [<paths>...]
+--
+b= create a new branch started at <branch>
+l create the new branch's reflog
+track arrange that the new branch tracks the remote branch
+f proceed even if the index or working tree is not HEAD
+m merge local modifications into the new branch
+q,quiet be quiet
+"
+SUBDIRECTORY_OK=Sometimes
+. git-sh-setup
+require_work_tree
+
+old_name=HEAD
+old=$(git rev-parse --verify $old_name 2>/dev/null)
+oldbranch=$(git symbolic-ref $old_name 2>/dev/null)
+new=
+new_name=
+force=
+branch=
+track=
+newbranch=
+newbranch_log=
+merge=
+quiet=
+v=-v
+LF='
+'
+
+while test $# != 0; do
+ case "$1" in
+ -b)
+ shift
+ newbranch="$1"
+ [ -z "$newbranch" ] &&
+ die "git checkout: -b needs a branch name"
+ git show-ref --verify --quiet -- "refs/heads/$newbranch" &&
+ die "git checkout: branch $newbranch already exists"
+ git check-ref-format "heads/$newbranch" ||
+ die "git checkout: we do not like '$newbranch' as a branch name."
+ ;;
+ -l)
+ newbranch_log=-l
+ ;;
+ --track|--no-track)
+ track="$1"
+ ;;
+ -f)
+ force=1
+ ;;
+ -m)
+ merge=1
+ ;;
+ -q|--quiet)
+ quiet=1
+ v=
+ ;;
+ --)
+ shift
+ break
+ ;;
+ *)
+ usage
+ ;;
+ esac
+ shift
+done
+
+arg="$1"
+rev=$(git rev-parse --verify "$arg" 2>/dev/null)
+if rev=$(git rev-parse --verify "$rev^0" 2>/dev/null)
+then
+ [ -z "$rev" ] && die "unknown flag $arg"
+ new_name="$arg"
+ if git show-ref --verify --quiet -- "refs/heads/$arg"
+ then
+ rev=$(git rev-parse --verify "refs/heads/$arg^0")
+ branch="$arg"
+ fi
+ new="$rev"
+ shift
+elif rev=$(git rev-parse --verify "$rev^{tree}" 2>/dev/null)
+then
+ # checking out selected paths from a tree-ish.
+ new="$rev"
+ new_name="$rev^{tree}"
+ shift
+fi
+[ "$1" = "--" ] && shift
+
+case "$newbranch,$track" in
+,--*)
+ die "git checkout: --track and --no-track require -b"
+esac
+
+case "$force$merge" in
+11)
+ die "git checkout: -f and -m are incompatible"
+esac
+
+# The behaviour of the command with and without explicit path
+# parameters is quite different.
+#
+# Without paths, we are checking out everything in the work tree,
+# possibly switching branches. This is the traditional behaviour.
+#
+# With paths, we are _never_ switching branch, but checking out
+# the named paths from either index (when no rev is given),
+# or the named tree-ish (when rev is given).
+
+if test "$#" -ge 1
+then
+ hint=
+ if test "$#" -eq 1
+ then
+ hint="
+Did you intend to checkout '$@' which can not be resolved as commit?"
+ fi
+ if test '' != "$newbranch$force$merge"
+ then
+ die "git checkout: updating paths is incompatible with switching branches/forcing$hint"
+ fi
+ if test '' != "$new"
+ then
+ # from a specific tree-ish; note that this is for
+ # rescuing paths and is never meant to remove what
+ # is not in the named tree-ish.
+ git ls-tree --full-name -r "$new" "$@" |
+ git update-index --index-info || exit $?
+ fi
+
+ # Make sure the request is about existing paths.
+ git ls-files --full-name --error-unmatch -- "$@" >/dev/null || exit
+ git ls-files --full-name -- "$@" |
+ (cd_to_toplevel && git checkout-index -f -u --stdin)
+
+ # Run a post-checkout hook -- the HEAD does not change so the
+ # current HEAD is passed in for both args
+ if test -x "$GIT_DIR"/hooks/post-checkout; then
+ "$GIT_DIR"/hooks/post-checkout $old $old 0
+ fi
+
+ exit $?
+else
+ # Make sure we did not fall back on $arg^{tree} codepath
+ # since we are not checking out from an arbitrary tree-ish,
+ # but switching branches.
+ if test '' != "$new"
+ then
+ git rev-parse --verify "$new^{commit}" >/dev/null 2>&1 ||
+ die "Cannot switch branch to a non-commit."
+ fi
+fi
+
+# We are switching branches and checking out trees, so
+# we *NEED* to be at the toplevel.
+cd_to_toplevel
+
+[ -z "$new" ] && new=$old && new_name="$old_name"
+
+# If we don't have an existing branch that we're switching to,
+# and we don't have a new branch name for the target we
+# are switching to, then we are detaching our HEAD from any
+# branch. However, if "git checkout HEAD" detaches the HEAD
+# from the current branch, even though that may be logically
+# correct, it feels somewhat funny. More importantly, we do not
+# want "git checkout" nor "git checkout -f" to detach HEAD.
+
+detached=
+detach_warn=
+
+describe_detached_head () {
+ test -n "$quiet" || {
+ printf >&2 "$1 "
+ GIT_PAGER= git log >&2 -1 --pretty=oneline --abbrev-commit "$2" --
+ }
+}
+
+if test -z "$branch$newbranch" && test "$new_name" != "$old_name"
+then
+ detached="$new"
+ if test -n "$oldbranch" && test -z "$quiet"
+ then
+ detach_warn="Note: moving to \"$new_name\" which isn't a local branch
+If you want to create a new branch from this checkout, you may do so
+(now or later) by using -b with the checkout command again. Example:
+ git checkout -b <new_branch_name>"
+ fi
+elif test -z "$oldbranch" && test "$new" != "$old"
+then
+ describe_detached_head 'Previous HEAD position was' "$old"
+fi
+
+if [ "X$old" = X ]
+then
+ if test -z "$quiet"
+ then
+ echo >&2 "warning: You appear to be on a branch yet to be born."
+ echo >&2 "warning: Forcing checkout of $new_name."
+ fi
+ force=1
+fi
+
+if [ "$force" ]
+then
+ git read-tree $v --reset -u $new
+else
+ git update-index --refresh >/dev/null
+ git read-tree $v -m -u --exclude-per-directory=.gitignore $old $new || (
+ case "$merge,$v" in
+ ,*)
+ exit 1 ;;
+ 1,)
+ ;; # quiet
+ *)
+ echo >&2 "Falling back to 3-way merge..." ;;
+ esac
+
+ # Match the index to the working tree, and do a three-way.
+ git diff-files --name-only | git update-index --remove --stdin &&
+ work=`git write-tree` &&
+ git read-tree $v --reset -u $new || exit
+
+ eval GITHEAD_$new='${new_name:-${branch:-$new}}' &&
+ eval GITHEAD_$work=local &&
+ export GITHEAD_$new GITHEAD_$work &&
+ git merge-recursive $old -- $new $work
+
+ # Do not register the cleanly merged paths in the index yet.
+ # this is not a real merge before committing, but just carrying
+ # the working tree changes along.
+ unmerged=`git ls-files -u`
+ git read-tree $v --reset $new
+ case "$unmerged" in
+ '') ;;
+ *)
+ (
+ z40=0000000000000000000000000000000000000000
+ echo "$unmerged" |
+ sed -e 's/^[0-7]* [0-9a-f]* /'"0 $z40 /"
+ echo "$unmerged"
+ ) | git update-index --index-info
+ ;;
+ esac
+ exit 0
+ )
+ saved_err=$?
+ if test "$saved_err" = 0 && test -z "$quiet"
+ then
+ git diff-index --name-status "$new"
+ fi
+ (exit $saved_err)
+fi
+
+#
+# Switch the HEAD pointer to the new branch if we
+# checked out a branch head, and remove any potential
+# old MERGE_HEAD's (subsequent commits will clearly not
+# be based on them, since we re-set the index)
+#
+if [ "$?" -eq 0 ]; then
+ if [ "$newbranch" ]; then
+ git branch $track $newbranch_log "$newbranch" "$new_name" || exit
+ branch="$newbranch"
+ fi
+ if test -n "$branch"
+ then
+ old_branch_name=`expr "z$oldbranch" : 'zrefs/heads/\(.*\)'`
+ GIT_DIR="$GIT_DIR" git symbolic-ref -m "checkout: moving from ${old_branch_name:-$old} to $branch" HEAD "refs/heads/$branch"
+ if test -n "$quiet"
+ then
+ true # nothing
+ elif test "refs/heads/$branch" = "$oldbranch"
+ then
+ echo >&2 "Already on branch \"$branch\""
+ else
+ echo >&2 "Switched to${newbranch:+ a new} branch \"$branch\""
+ fi
+ elif test -n "$detached"
+ then
+ old_branch_name=`expr "z$oldbranch" : 'zrefs/heads/\(.*\)'`
+ git update-ref --no-deref -m "checkout: moving from ${old_branch_name:-$old} to $arg" HEAD "$detached" ||
+ die "Cannot detach HEAD"
+ if test -n "$detach_warn"
+ then
+ echo >&2 "$detach_warn"
+ fi
+ describe_detached_head 'HEAD is now at' HEAD
+ fi
+ rm -f "$GIT_DIR/MERGE_HEAD"
+else
+ exit 1
+fi
+
+# Run a post-checkout hook
+if test -x "$GIT_DIR"/hooks/post-checkout; then
+ "$GIT_DIR"/hooks/post-checkout $old $new 1
+fi
diff --git a/contrib/examples/git-clean.sh b/contrib/examples/git-clean.sh
new file mode 100755
index 0000000000..01c95e9fe8
--- /dev/null
+++ b/contrib/examples/git-clean.sh
@@ -0,0 +1,118 @@
+#!/bin/sh
+#
+# Copyright (c) 2005-2006 Pavel Roskin
+#
+
+OPTIONS_KEEPDASHDASH=
+OPTIONS_SPEC="\
+git-clean [options] <paths>...
+
+Clean untracked files from the working directory
+
+When optional <paths>... arguments are given, the paths
+affected are further limited to those that match them.
+--
+d remove directories as well
+f override clean.requireForce and clean anyway
+n don't remove anything, just show what would be done
+q be quiet, only report errors
+x remove ignored files as well
+X remove only ignored files"
+
+SUBDIRECTORY_OK=Yes
+. git-sh-setup
+require_work_tree
+
+ignored=
+ignoredonly=
+cleandir=
+rmf="rm -f --"
+rmrf="rm -rf --"
+rm_refuse="echo Not removing"
+echo1="echo"
+
+disabled=$(git config --bool clean.requireForce)
+
+while test $# != 0
+do
+ case "$1" in
+ -d)
+ cleandir=1
+ ;;
+ -f)
+ disabled=false
+ ;;
+ -n)
+ disabled=false
+ rmf="echo Would remove"
+ rmrf="echo Would remove"
+ rm_refuse="echo Would not remove"
+ echo1=":"
+ ;;
+ -q)
+ echo1=":"
+ ;;
+ -x)
+ ignored=1
+ ;;
+ -X)
+ ignoredonly=1
+ ;;
+ --)
+ shift
+ break
+ ;;
+ *)
+ usage # should not happen
+ ;;
+ esac
+ shift
+done
+
+# requireForce used to default to false but now it defaults to true.
+# IOW, lack of explicit "clean.requireForce = false" is taken as
+# "clean.requireForce = true".
+case "$disabled" in
+"")
+ die "clean.requireForce not set and -n or -f not given; refusing to clean"
+ ;;
+"true")
+ die "clean.requireForce set and -n or -f not given; refusing to clean"
+ ;;
+esac
+
+if [ "$ignored,$ignoredonly" = "1,1" ]; then
+ die "-x and -X cannot be set together"
+fi
+
+if [ -z "$ignored" ]; then
+ excl="--exclude-per-directory=.gitignore"
+ excl_info= excludes_file=
+ if [ -f "$GIT_DIR/info/exclude" ]; then
+ excl_info="--exclude-from=$GIT_DIR/info/exclude"
+ fi
+ if cfg_excl=$(git config core.excludesfile) && test -f "$cfg_excl"
+ then
+ excludes_file="--exclude-from=$cfg_excl"
+ fi
+ if [ "$ignoredonly" ]; then
+ excl="$excl --ignored"
+ fi
+fi
+
+git ls-files --others --directory \
+ $excl ${excl_info:+"$excl_info"} ${excludes_file:+"$excludes_file"} \
+ -- "$@" |
+while read -r file; do
+ if [ -d "$file" -a ! -L "$file" ]; then
+ if [ -z "$cleandir" ]; then
+ $rm_refuse "$file"
+ continue
+ fi
+ $echo1 "Removing $file"
+ $rmrf "$file"
+ else
+ $echo1 "Removing $file"
+ $rmf "$file"
+ fi
+done
diff --git a/contrib/examples/git-clone.sh b/contrib/examples/git-clone.sh
new file mode 100755
index 0000000000..547228e13c
--- /dev/null
+++ b/contrib/examples/git-clone.sh
@@ -0,0 +1,525 @@
+#!/bin/sh
+#
+# Copyright (c) 2005, Linus Torvalds
+# Copyright (c) 2005, Junio C Hamano
+#
+# Clone a repository into a different directory that does not yet exist.
+
+# See git-sh-setup why.
+unset CDPATH
+
+OPTIONS_SPEC="\
+git-clone [options] [--] <repo> [<dir>]
+--
+n,no-checkout don't create a checkout
+bare create a bare repository
+naked create a bare repository
+l,local to clone from a local repository
+no-hardlinks don't use local hardlinks, always copy
+s,shared setup as a shared repository
+template= path to the template directory
+q,quiet be quiet
+reference= reference repository
+o,origin= use <name> instead of 'origin' to track upstream
+u,upload-pack= path to git-upload-pack on the remote
+depth= create a shallow clone of that depth
+
+use-separate-remote compatibility, do not use
+no-separate-remote compatibility, do not use"
+
+die() {
+ echo >&2 "$@"
+ exit 1
+}
+
+usage() {
+ exec "$0" -h
+}
+
+eval "$(echo "$OPTIONS_SPEC" | git rev-parse --parseopt -- "$@" || echo exit $?)"
+
+get_repo_base() {
+ (
+ cd "`/bin/pwd`" &&
+ cd "$1" || cd "$1.git" &&
+ {
+ cd .git
+ pwd
+ }
+ ) 2>/dev/null
+}
+
+if [ -n "$GIT_SSL_NO_VERIFY" -o \
+ "`git config --bool http.sslVerify`" = false ]; then
+ curl_extra_args="-k"
+fi
+
+http_fetch () {
+ # $1 = Remote, $2 = Local
+ curl -nsfL $curl_extra_args "$1" >"$2"
+ curl_exit_status=$?
+ case $curl_exit_status in
+ 126|127) exit ;;
+ *) return $curl_exit_status ;;
+ esac
+}
+
+clone_dumb_http () {
+ # $1 - remote, $2 - local
+ cd "$2" &&
+ clone_tmp="$GIT_DIR/clone-tmp" &&
+ mkdir -p "$clone_tmp" || exit 1
+ if [ -n "$GIT_CURL_FTP_NO_EPSV" -o \
+ "`git config --bool http.noEPSV`" = true ]; then
+ curl_extra_args="${curl_extra_args} --disable-epsv"
+ fi
+ http_fetch "$1/info/refs" "$clone_tmp/refs" ||
+ die "Cannot get remote repository information.
+Perhaps git-update-server-info needs to be run there?"
+ test "z$quiet" = z && v=-v || v=
+ while read sha1 refname
+ do
+ name=`expr "z$refname" : 'zrefs/\(.*\)'` &&
+ case "$name" in
+ *^*) continue;;
+ esac
+ case "$bare,$name" in
+ yes,* | ,heads/* | ,tags/*) ;;
+ *) continue ;;
+ esac
+ if test -n "$use_separate_remote" &&
+ branch_name=`expr "z$name" : 'zheads/\(.*\)'`
+ then
+ tname="remotes/$origin/$branch_name"
+ else
+ tname=$name
+ fi
+ git-http-fetch $v -a -w "$tname" "$sha1" "$1" || exit 1
+ done <"$clone_tmp/refs"
+ rm -fr "$clone_tmp"
+ http_fetch "$1/HEAD" "$GIT_DIR/REMOTE_HEAD" ||
+ rm -f "$GIT_DIR/REMOTE_HEAD"
+ if test -f "$GIT_DIR/REMOTE_HEAD"; then
+ head_sha1=`cat "$GIT_DIR/REMOTE_HEAD"`
+ case "$head_sha1" in
+ 'ref: refs/'*)
+ ;;
+ *)
+ git-http-fetch $v -a "$head_sha1" "$1" ||
+ rm -f "$GIT_DIR/REMOTE_HEAD"
+ ;;
+ esac
+ fi
+}
+
+quiet=
+local=no
+use_local_hardlink=yes
+local_shared=no
+unset template
+no_checkout=
+upload_pack=
+bare=
+reference=
+origin=
+origin_override=
+use_separate_remote=t
+depth=
+no_progress=
+local_explicitly_asked_for=
+test -t 1 || no_progress=--no-progress
+
+while test $# != 0
+do
+ case "$1" in
+ -n|--no-checkout)
+ no_checkout=yes ;;
+ --naked|--bare)
+ bare=yes ;;
+ -l|--local)
+ local_explicitly_asked_for=yes
+ use_local_hardlink=yes
+ ;;
+ --no-hardlinks)
+ use_local_hardlink=no ;;
+ -s|--shared)
+ local_shared=yes ;;
+ --template)
+ shift; template="--template=$1" ;;
+ -q|--quiet)
+ quiet=-q ;;
+ --use-separate-remote|--no-separate-remote)
+ die "clones are always made with separate-remote layout" ;;
+ --reference)
+ shift; reference="$1" ;;
+ -o|--origin)
+ shift;
+ case "$1" in
+ '')
+ usage ;;
+ */*)
+ die "'$1' is not suitable for an origin name"
+ esac
+ git check-ref-format "heads/$1" ||
+ die "'$1' is not suitable for a branch name"
+ test -z "$origin_override" ||
+ die "Do not give more than one --origin options."
+ origin_override=yes
+ origin="$1"
+ ;;
+ -u|--upload-pack)
+ shift
+ upload_pack="--upload-pack=$1" ;;
+ --depth)
+ shift
+ depth="--depth=$1" ;;
+ --)
+ shift
+ break ;;
+ *)
+ usage ;;
+ esac
+ shift
+done
+
+repo="$1"
+test -n "$repo" ||
+ die 'you must specify a repository to clone.'
+
+# --bare implies --no-checkout and --no-separate-remote
+if test yes = "$bare"
+then
+ if test yes = "$origin_override"
+ then
+ die '--bare and --origin $origin options are incompatible.'
+ fi
+ no_checkout=yes
+ use_separate_remote=
+fi
+
+if test -z "$origin"
+then
+ origin=origin
+fi
+
+# Turn the source into an absolute path if
+# it is local
+if base=$(get_repo_base "$repo"); then
+ repo="$base"
+ if test -z "$depth"
+ then
+ local=yes
+ fi
+elif test -f "$repo"
+then
+ case "$repo" in /*) ;; *) repo="$PWD/$repo" ;; esac
+fi
+
+# Decide the directory name of the new repository
+if test -n "$2"
+then
+ dir="$2"
+ test $# = 2 || die "excess parameter to git-clone"
+else
+ # Derive one from the repository name
+ # Try using "humanish" part of source repo if user didn't specify one
+ if test -f "$repo"
+ then
+ # Cloning from a bundle
+ dir=$(echo "$repo" | sed -e 's|/*\.bundle$||' -e 's|.*/||g')
+ else
+ dir=$(echo "$repo" |
+ sed -e 's|/$||' -e 's|:*/*\.git$||' -e 's|.*[/:]||g')
+ fi
+fi
+
+[ -e "$dir" ] && die "destination directory '$dir' already exists."
+[ yes = "$bare" ] && unset GIT_WORK_TREE
+[ -n "$GIT_WORK_TREE" ] && [ -e "$GIT_WORK_TREE" ] &&
+die "working tree '$GIT_WORK_TREE' already exists."
+D=
+W=
+cleanup() {
+ test -z "$D" && rm -rf "$dir"
+ test -z "$W" && test -n "$GIT_WORK_TREE" && rm -rf "$GIT_WORK_TREE"
+ cd ..
+ test -n "$D" && rm -rf "$D"
+ test -n "$W" && rm -rf "$W"
+ exit $err
+}
+trap 'err=$?; cleanup' 0
+mkdir -p "$dir" && D=$(cd "$dir" && pwd) || usage
+test -n "$GIT_WORK_TREE" && mkdir -p "$GIT_WORK_TREE" &&
+W=$(cd "$GIT_WORK_TREE" && pwd) && GIT_WORK_TREE="$W" && export GIT_WORK_TREE
+if test yes = "$bare" || test -n "$GIT_WORK_TREE"; then
+ GIT_DIR="$D"
+else
+ GIT_DIR="$D/.git"
+fi &&
+export GIT_DIR &&
+GIT_CONFIG="$GIT_DIR/config" git-init $quiet ${template+"$template"} || usage
+
+if test -n "$bare"
+then
+ GIT_CONFIG="$GIT_DIR/config" git config core.bare true
+fi
+
+if test -n "$reference"
+then
+ ref_git=
+ if test -d "$reference"
+ then
+ if test -d "$reference/.git/objects"
+ then
+ ref_git="$reference/.git"
+ elif test -d "$reference/objects"
+ then
+ ref_git="$reference"
+ fi
+ fi
+ if test -n "$ref_git"
+ then
+ ref_git=$(cd "$ref_git" && pwd)
+ echo "$ref_git/objects" >"$GIT_DIR/objects/info/alternates"
+ (
+ GIT_DIR="$ref_git" git for-each-ref \
+ --format='%(objectname) %(*objectname)'
+ ) |
+ while read a b
+ do
+ test -z "$a" ||
+ git update-ref "refs/reference-tmp/$a" "$a"
+ test -z "$b" ||
+ git update-ref "refs/reference-tmp/$b" "$b"
+ done
+ else
+ die "reference repository '$reference' is not a local directory."
+ fi
+fi
+
+rm -f "$GIT_DIR/CLONE_HEAD"
+
+# We do local magic only when the user tells us to.
+case "$local" in
+yes)
+ ( cd "$repo/objects" ) ||
+ die "cannot chdir to local '$repo/objects'."
+
+ if test "$local_shared" = yes
+ then
+ mkdir -p "$GIT_DIR/objects/info"
+ echo "$repo/objects" >>"$GIT_DIR/objects/info/alternates"
+ else
+ cpio_quiet_flag=""
+ cpio --help 2>&1 | grep -- --quiet >/dev/null && \
+ cpio_quiet_flag=--quiet
+ l= &&
+ if test "$use_local_hardlink" = yes
+ then
+ # See if we can hardlink and drop "l" if not.
+ sample_file=$(cd "$repo" && \
+ find objects -type f -print | sed -e 1q)
+ # objects directory should not be empty because
+ # we are cloning!
+ test -f "$repo/$sample_file" ||
+ die "fatal: cannot clone empty repository"
+ if ln "$repo/$sample_file" "$GIT_DIR/objects/sample" 2>/dev/null
+ then
+ rm -f "$GIT_DIR/objects/sample"
+ l=l
+ elif test -n "$local_explicitly_asked_for"
+ then
+ echo >&2 "Warning: -l asked but cannot hardlink to $repo"
+ fi
+ fi &&
+ cd "$repo" &&
+ # Create dirs using umask and permissions and destination
+ find objects -type d -print | (cd "$GIT_DIR" && xargs mkdir -p) &&
+ # Copy existing 0444 permissions on content
+ find objects ! -type d -print | cpio $cpio_quiet_flag -pumd$l "$GIT_DIR/" || \
+ exit 1
+ fi
+ git-ls-remote "$repo" >"$GIT_DIR/CLONE_HEAD" || exit 1
+ ;;
+*)
+ case "$repo" in
+ rsync://*)
+ case "$depth" in
+ "") ;;
+ *) die "shallow over rsync not supported" ;;
+ esac
+ rsync $quiet -av --ignore-existing \
+ --exclude info "$repo/objects/" "$GIT_DIR/objects/" ||
+ exit
+ # Look at objects/info/alternates for rsync -- http will
+ # support it natively and git native ones will do it on the
+ # remote end. Not having that file is not a crime.
+ rsync -q "$repo/objects/info/alternates" \
+ "$GIT_DIR/TMP_ALT" 2>/dev/null ||
+ rm -f "$GIT_DIR/TMP_ALT"
+ if test -f "$GIT_DIR/TMP_ALT"
+ then
+ ( cd "$D" &&
+ . git-parse-remote &&
+ resolve_alternates "$repo" <"$GIT_DIR/TMP_ALT" ) |
+ while read alt
+ do
+ case "$alt" in 'bad alternate: '*) die "$alt";; esac
+ case "$quiet" in
+ '') echo >&2 "Getting alternate: $alt" ;;
+ esac
+ rsync $quiet -av --ignore-existing \
+ --exclude info "$alt" "$GIT_DIR/objects" || exit
+ done
+ rm -f "$GIT_DIR/TMP_ALT"
+ fi
+ git-ls-remote "$repo" >"$GIT_DIR/CLONE_HEAD" || exit 1
+ ;;
+ https://*|http://*|ftp://*)
+ case "$depth" in
+ "") ;;
+ *) die "shallow over http or ftp not supported" ;;
+ esac
+ if test -z "@@NO_CURL@@"
+ then
+ clone_dumb_http "$repo" "$D"
+ else
+ die "http transport not supported, rebuild Git with curl support"
+ fi
+ ;;
+ *)
+ if [ -f "$repo" ] ; then
+ git bundle unbundle "$repo" > "$GIT_DIR/CLONE_HEAD" ||
+ die "unbundle from '$repo' failed."
+ else
+ case "$upload_pack" in
+ '') git-fetch-pack --all -k $quiet $depth $no_progress "$repo";;
+ *) git-fetch-pack --all -k \
+ $quiet "$upload_pack" $depth $no_progress "$repo" ;;
+ esac >"$GIT_DIR/CLONE_HEAD" ||
+ die "fetch-pack from '$repo' failed."
+ fi
+ ;;
+ esac
+ ;;
+esac
+test -d "$GIT_DIR/refs/reference-tmp" && rm -fr "$GIT_DIR/refs/reference-tmp"
+
+if test -f "$GIT_DIR/CLONE_HEAD"
+then
+ # Read git-fetch-pack -k output and store the remote branches.
+ if [ -n "$use_separate_remote" ]
+ then
+ branch_top="remotes/$origin"
+ else
+ branch_top="heads"
+ fi
+ tag_top="tags"
+ while read sha1 name
+ do
+ case "$name" in
+ *'^{}')
+ continue ;;
+ HEAD)
+ destname="REMOTE_HEAD" ;;
+ refs/heads/*)
+ destname="refs/$branch_top/${name#refs/heads/}" ;;
+ refs/tags/*)
+ destname="refs/$tag_top/${name#refs/tags/}" ;;
+ *)
+ continue ;;
+ esac
+ git update-ref -m "clone: from $repo" "$destname" "$sha1" ""
+ done < "$GIT_DIR/CLONE_HEAD"
+fi
+
+if test -n "$W"; then
+ cd "$W" || exit
+else
+ cd "$D" || exit
+fi
+
+if test -z "$bare"
+then
+ # a non-bare repository is always in separate-remote layout
+ remote_top="refs/remotes/$origin"
+ head_sha1=
+ test ! -r "$GIT_DIR/REMOTE_HEAD" || head_sha1=`cat "$GIT_DIR/REMOTE_HEAD"`
+ case "$head_sha1" in
+ 'ref: refs/'*)
+ # Uh-oh, the remote told us (http transport done against
+ # new style repository with a symref HEAD).
+ # Ideally we should skip the guesswork but for now
+ # opt for minimum change.
+ head_sha1=`expr "z$head_sha1" : 'zref: refs/heads/\(.*\)'`
+ head_sha1=`cat "$GIT_DIR/$remote_top/$head_sha1"`
+ ;;
+ esac
+
+ # The name under $remote_top the remote HEAD seems to point at.
+ head_points_at=$(
+ (
+ test -f "$GIT_DIR/$remote_top/master" && echo "master"
+ cd "$GIT_DIR/$remote_top" &&
+ find . -type f -print | sed -e 's/^\.\///'
+ ) | (
+ done=f
+ while read name
+ do
+ test t = $done && continue
+ branch_tip=`cat "$GIT_DIR/$remote_top/$name"`
+ if test "$head_sha1" = "$branch_tip"
+ then
+ echo "$name"
+ done=t
+ fi
+ done
+ )
+ )
+
+ # Upstream URL
+ git config remote."$origin".url "$repo" &&
+
+ # Set up the mappings to track the remote branches.
+ git config remote."$origin".fetch \
+ "+refs/heads/*:$remote_top/*" '^$' &&
+
+ # Write out remote.$origin config, and update our "$head_points_at".
+ case "$head_points_at" in
+ ?*)
+ # Local default branch
+ git symbolic-ref HEAD "refs/heads/$head_points_at" &&
+
+ # Tracking branch for the primary branch at the remote.
+ git update-ref HEAD "$head_sha1" &&
+
+ rm -f "refs/remotes/$origin/HEAD"
+ git symbolic-ref "refs/remotes/$origin/HEAD" \
+ "refs/remotes/$origin/$head_points_at" &&
+
+ git config branch."$head_points_at".remote "$origin" &&
+ git config branch."$head_points_at".merge "refs/heads/$head_points_at"
+ ;;
+ '')
+ if test -z "$head_sha1"
+ then
+ # Source had nonexistent ref in HEAD
+ echo >&2 "Warning: Remote HEAD refers to nonexistent ref, unable to checkout."
+ no_checkout=t
+ else
+ # Source had detached HEAD pointing nowhere
+ git update-ref --no-deref HEAD "$head_sha1" &&
+ rm -f "refs/remotes/$origin/HEAD"
+ fi
+ ;;
+ esac
+
+ case "$no_checkout" in
+ '')
+ test "z$quiet" = z -a "z$no_progress" = z && v=-v || v=
+ git read-tree -m -u $v HEAD HEAD
+ esac
+fi
+rm -f "$GIT_DIR/CLONE_HEAD" "$GIT_DIR/REMOTE_HEAD"
+
+trap - 0
diff --git a/contrib/examples/git-commit.sh b/contrib/examples/git-commit.sh
new file mode 100755
index 0000000000..5c72f655c7
--- /dev/null
+++ b/contrib/examples/git-commit.sh
@@ -0,0 +1,639 @@
+#!/bin/sh
+#
+# Copyright (c) 2005 Linus Torvalds
+# Copyright (c) 2006 Junio C Hamano
+
+USAGE='[-a | --interactive] [-s] [-v] [--no-verify] [-m <message> | -F <logfile> | (-C|-c) <commit> | --amend] [-u] [-e] [--author <author>] [--template <file>] [[-i | -o] <path>...]'
+SUBDIRECTORY_OK=Yes
+OPTIONS_SPEC=
+. git-sh-setup
+require_work_tree
+
+git rev-parse --verify HEAD >/dev/null 2>&1 || initial_commit=t
+
+case "$0" in
+*status)
+ status_only=t
+ ;;
+*commit)
+ status_only=
+ ;;
+esac
+
+refuse_partial () {
+ echo >&2 "$1"
+ echo >&2 "You might have meant to say 'git commit -i paths...', perhaps?"
+ exit 1
+}
+
+TMP_INDEX=
+THIS_INDEX="${GIT_INDEX_FILE:-$GIT_DIR/index}"
+NEXT_INDEX="$GIT_DIR/next-index$$"
+rm -f "$NEXT_INDEX"
+save_index () {
+ cp -p "$THIS_INDEX" "$NEXT_INDEX"
+}
+
+run_status () {
+ # If TMP_INDEX is defined, that means we are doing
+ # "--only" partial commit, and that index file is used
+ # to build the tree for the commit. Otherwise, if
+ # NEXT_INDEX exists, that is the index file used to
+ # make the commit. Otherwise we are using as-is commit
+ # so the regular index file is what we use to compare.
+ if test '' != "$TMP_INDEX"
+ then
+ GIT_INDEX_FILE="$TMP_INDEX"
+ export GIT_INDEX_FILE
+ elif test -f "$NEXT_INDEX"
+ then
+ GIT_INDEX_FILE="$NEXT_INDEX"
+ export GIT_INDEX_FILE
+ fi
+
+ if test "$status_only" = "t" -o "$use_status_color" = "t"; then
+ color=
+ else
+ color=--nocolor
+ fi
+ git runstatus ${color} \
+ ${verbose:+--verbose} \
+ ${amend:+--amend} \
+ ${untracked_files:+--untracked}
+}
+
+trap '
+ test -z "$TMP_INDEX" || {
+ test -f "$TMP_INDEX" && rm -f "$TMP_INDEX"
+ }
+ rm -f "$NEXT_INDEX"
+' 0
+
+################################################################
+# Command line argument parsing and sanity checking
+
+all=
+also=
+allow_empty=f
+interactive=
+only=
+logfile=
+use_commit=
+amend=
+edit_flag=
+no_edit=
+log_given=
+log_message=
+verify=t
+quiet=
+verbose=
+signoff=
+force_author=
+only_include_assumed=
+untracked_files=
+templatefile="`git config commit.template`"
+while test $# != 0
+do
+ case "$1" in
+ -F|--F|-f|--f|--fi|--fil|--file)
+ case "$#" in 1) usage ;; esac
+ shift
+ no_edit=t
+ log_given=t$log_given
+ logfile="$1"
+ ;;
+ -F*|-f*)
+ no_edit=t
+ log_given=t$log_given
+ logfile="${1#-[Ff]}"
+ ;;
+ --F=*|--f=*|--fi=*|--fil=*|--file=*)
+ no_edit=t
+ log_given=t$log_given
+ logfile="${1#*=}"
+ ;;
+ -a|--a|--al|--all)
+ all=t
+ ;;
+ --allo|--allow|--allow-|--allow-e|--allow-em|--allow-emp|\
+ --allow-empt|--allow-empty)
+ allow_empty=t
+ ;;
+ --au=*|--aut=*|--auth=*|--autho=*|--author=*)
+ force_author="${1#*=}"
+ ;;
+ --au|--aut|--auth|--autho|--author)
+ case "$#" in 1) usage ;; esac
+ shift
+ force_author="$1"
+ ;;
+ -e|--e|--ed|--edi|--edit)
+ edit_flag=t
+ ;;
+ -i|--i|--in|--inc|--incl|--inclu|--includ|--include)
+ also=t
+ ;;
+ --int|--inte|--inter|--intera|--interac|--interact|--interacti|\
+ --interactiv|--interactive)
+ interactive=t
+ ;;
+ -o|--o|--on|--onl|--only)
+ only=t
+ ;;
+ -m|--m|--me|--mes|--mess|--messa|--messag|--message)
+ case "$#" in 1) usage ;; esac
+ shift
+ log_given=m$log_given
+ log_message="${log_message:+${log_message}
+
+}$1"
+ no_edit=t
+ ;;
+ -m*)
+ log_given=m$log_given
+ log_message="${log_message:+${log_message}
+
+}${1#-m}"
+ no_edit=t
+ ;;
+ --m=*|--me=*|--mes=*|--mess=*|--messa=*|--messag=*|--message=*)
+ log_given=m$log_given
+ log_message="${log_message:+${log_message}
+
+}${1#*=}"
+ no_edit=t
+ ;;
+ -n|--n|--no|--no-|--no-v|--no-ve|--no-ver|--no-veri|--no-verif|\
+ --no-verify)
+ verify=
+ ;;
+ --a|--am|--ame|--amen|--amend)
+ amend=t
+ use_commit=HEAD
+ ;;
+ -c)
+ case "$#" in 1) usage ;; esac
+ shift
+ log_given=t$log_given
+ use_commit="$1"
+ no_edit=
+ ;;
+ --ree=*|--reed=*|--reedi=*|--reedit=*|--reedit-=*|--reedit-m=*|\
+ --reedit-me=*|--reedit-mes=*|--reedit-mess=*|--reedit-messa=*|\
+ --reedit-messag=*|--reedit-message=*)
+ log_given=t$log_given
+ use_commit="${1#*=}"
+ no_edit=
+ ;;
+ --ree|--reed|--reedi|--reedit|--reedit-|--reedit-m|--reedit-me|\
+ --reedit-mes|--reedit-mess|--reedit-messa|--reedit-messag|\
+ --reedit-message)
+ case "$#" in 1) usage ;; esac
+ shift
+ log_given=t$log_given
+ use_commit="$1"
+ no_edit=
+ ;;
+ -C)
+ case "$#" in 1) usage ;; esac
+ shift
+ log_given=t$log_given
+ use_commit="$1"
+ no_edit=t
+ ;;
+ --reu=*|--reus=*|--reuse=*|--reuse-=*|--reuse-m=*|--reuse-me=*|\
+ --reuse-mes=*|--reuse-mess=*|--reuse-messa=*|--reuse-messag=*|\
+ --reuse-message=*)
+ log_given=t$log_given
+ use_commit="${1#*=}"
+ no_edit=t
+ ;;
+ --reu|--reus|--reuse|--reuse-|--reuse-m|--reuse-me|--reuse-mes|\
+ --reuse-mess|--reuse-messa|--reuse-messag|--reuse-message)
+ case "$#" in 1) usage ;; esac
+ shift
+ log_given=t$log_given
+ use_commit="$1"
+ no_edit=t
+ ;;
+ -s|--s|--si|--sig|--sign|--signo|--signof|--signoff)
+ signoff=t
+ ;;
+ -t|--t|--te|--tem|--temp|--templ|--templa|--templat|--template)
+ case "$#" in 1) usage ;; esac
+ shift
+ templatefile="$1"
+ no_edit=
+ ;;
+ -q|--q|--qu|--qui|--quie|--quiet)
+ quiet=t
+ ;;
+ -v|--v|--ve|--ver|--verb|--verbo|--verbos|--verbose)
+ verbose=t
+ ;;
+ -u|--u|--un|--unt|--untr|--untra|--untrac|--untrack|--untracke|\
+ --untracked|--untracked-|--untracked-f|--untracked-fi|--untracked-fil|\
+ --untracked-file|--untracked-files)
+ untracked_files=t
+ ;;
+ --)
+ shift
+ break
+ ;;
+ -*)
+ usage
+ ;;
+ *)
+ break
+ ;;
+ esac
+ shift
+done
+case "$edit_flag" in t) no_edit= ;; esac
+
+################################################################
+# Sanity check options
+
+case "$amend,$initial_commit" in
+t,t)
+ die "You do not have anything to amend." ;;
+t,)
+ if [ -f "$GIT_DIR/MERGE_HEAD" ]; then
+ die "You are in the middle of a merge -- cannot amend."
+ fi ;;
+esac
+
+case "$log_given" in
+tt*)
+ die "Only one of -c/-C/-F can be used." ;;
+*tm*|*mt*)
+ die "Option -m cannot be combined with -c/-C/-F." ;;
+esac
+
+case "$#,$also,$only,$amend" in
+*,t,t,*)
+ die "Only one of --include/--only can be used." ;;
+0,t,,* | 0,,t,)
+ die "No paths with --include/--only does not make sense." ;;
+0,,t,t)
+ only_include_assumed="# Clever... amending the last one with dirty index." ;;
+0,,,*)
+ ;;
+*,,,*)
+ only_include_assumed="# Explicit paths specified without -i nor -o; assuming --only paths..."
+ also=
+ ;;
+esac
+unset only
+case "$all,$interactive,$also,$#" in
+*t,*t,*)
+ die "Cannot use -a, --interactive or -i at the same time." ;;
+t,,,[1-9]*)
+ die "Paths with -a does not make sense." ;;
+,t,,[1-9]*)
+ die "Paths with --interactive does not make sense." ;;
+,,t,0)
+ die "No paths with -i does not make sense." ;;
+esac
+
+if test ! -z "$templatefile" -a -z "$log_given"
+then
+ if test ! -f "$templatefile"
+ then
+ die "Commit template file does not exist."
+ fi
+fi
+
+################################################################
+# Prepare index to have a tree to be committed
+
+case "$all,$also" in
+t,)
+ if test ! -f "$THIS_INDEX"
+ then
+ die 'nothing to commit (use "git add file1 file2" to include for commit)'
+ fi
+ save_index &&
+ (
+ cd_to_toplevel &&
+ GIT_INDEX_FILE="$NEXT_INDEX" &&
+ export GIT_INDEX_FILE &&
+ git diff-files --name-only -z |
+ git update-index --remove -z --stdin
+ ) || exit
+ ;;
+,t)
+ save_index &&
+ git ls-files --error-unmatch -- "$@" >/dev/null || exit
+
+ git diff-files --name-only -z -- "$@" |
+ (
+ cd_to_toplevel &&
+ GIT_INDEX_FILE="$NEXT_INDEX" &&
+ export GIT_INDEX_FILE &&
+ git update-index --remove -z --stdin
+ ) || exit
+ ;;
+,)
+ if test "$interactive" = t; then
+ git add --interactive || exit
+ fi
+ case "$#" in
+ 0)
+ ;; # commit as-is
+ *)
+ if test -f "$GIT_DIR/MERGE_HEAD"
+ then
+ refuse_partial "Cannot do a partial commit during a merge."
+ fi
+
+ TMP_INDEX="$GIT_DIR/tmp-index$$"
+ W=
+ test -z "$initial_commit" && W=--with-tree=HEAD
+ commit_only=`git ls-files --error-unmatch $W -- "$@"` || exit
+
+ # Build a temporary index and update the real index
+ # the same way.
+ if test -z "$initial_commit"
+ then
+ GIT_INDEX_FILE="$THIS_INDEX" \
+ git read-tree --index-output="$TMP_INDEX" -i -m HEAD
+ else
+ rm -f "$TMP_INDEX"
+ fi || exit
+
+ printf '%s\n' "$commit_only" |
+ GIT_INDEX_FILE="$TMP_INDEX" \
+ git update-index --add --remove --stdin &&
+
+ save_index &&
+ printf '%s\n' "$commit_only" |
+ (
+ GIT_INDEX_FILE="$NEXT_INDEX"
+ export GIT_INDEX_FILE
+ git update-index --add --remove --stdin
+ ) || exit
+ ;;
+ esac
+ ;;
+esac
+
+################################################################
+# If we do as-is commit, the index file will be THIS_INDEX,
+# otherwise NEXT_INDEX after we make this commit. We leave
+# the index as is if we abort.
+
+if test -f "$NEXT_INDEX"
+then
+ USE_INDEX="$NEXT_INDEX"
+else
+ USE_INDEX="$THIS_INDEX"
+fi
+
+case "$status_only" in
+t)
+ # This will silently fail in a read-only repository, which is
+ # what we want.
+ GIT_INDEX_FILE="$USE_INDEX" git update-index -q --unmerged --refresh
+ run_status
+ exit $?
+ ;;
+'')
+ GIT_INDEX_FILE="$USE_INDEX" git update-index -q --refresh || exit
+ ;;
+esac
+
+################################################################
+# Grab commit message, write out tree and make commit.
+
+if test t = "$verify" && test -x "$GIT_DIR"/hooks/pre-commit
+then
+ GIT_INDEX_FILE="${TMP_INDEX:-${USE_INDEX}}" "$GIT_DIR"/hooks/pre-commit \
+ || exit
+fi
+
+if test "$log_message" != ''
+then
+ printf '%s\n' "$log_message"
+elif test "$logfile" != ""
+then
+ if test "$logfile" = -
+ then
+ test -t 0 &&
+ echo >&2 "(reading log message from standard input)"
+ cat
+ else
+ cat <"$logfile"
+ fi
+elif test "$use_commit" != ""
+then
+ encoding=$(git config i18n.commitencoding || echo UTF-8)
+ git show -s --pretty=raw --encoding="$encoding" "$use_commit" |
+ sed -e '1,/^$/d' -e 's/^ //'
+elif test -f "$GIT_DIR/MERGE_MSG"
+then
+ cat "$GIT_DIR/MERGE_MSG"
+elif test -f "$GIT_DIR/SQUASH_MSG"
+then
+ cat "$GIT_DIR/SQUASH_MSG"
+elif test "$templatefile" != ""
+then
+ cat "$templatefile"
+fi | git stripspace >"$GIT_DIR"/COMMIT_EDITMSG
+
+case "$signoff" in
+t)
+ sign=$(git var GIT_COMMITTER_IDENT | sed -e '
+ s/>.*/>/
+ s/^/Signed-off-by: /
+ ')
+ blank_before_signoff=
+ tail -n 1 "$GIT_DIR"/COMMIT_EDITMSG |
+ grep 'Signed-off-by:' >/dev/null || blank_before_signoff='
+'
+ tail -n 1 "$GIT_DIR"/COMMIT_EDITMSG |
+ grep "$sign"$ >/dev/null ||
+ printf '%s%s\n' "$blank_before_signoff" "$sign" \
+ >>"$GIT_DIR"/COMMIT_EDITMSG
+ ;;
+esac
+
+if test -f "$GIT_DIR/MERGE_HEAD" && test -z "$no_edit"; then
+ echo "#"
+ echo "# It looks like you may be committing a MERGE."
+ echo "# If this is not correct, please remove the file"
+ printf '%s\n' "# $GIT_DIR/MERGE_HEAD"
+ echo "# and try again"
+ echo "#"
+fi >>"$GIT_DIR"/COMMIT_EDITMSG
+
+# Author
+if test '' != "$use_commit"
+then
+ eval "$(get_author_ident_from_commit "$use_commit")"
+ export GIT_AUTHOR_NAME GIT_AUTHOR_EMAIL GIT_AUTHOR_DATE
+fi
+if test '' != "$force_author"
+then
+ GIT_AUTHOR_NAME=`expr "z$force_author" : 'z\(.*[^ ]\) *<.*'` &&
+ GIT_AUTHOR_EMAIL=`expr "z$force_author" : '.*\(<.*\)'` &&
+ test '' != "$GIT_AUTHOR_NAME" &&
+ test '' != "$GIT_AUTHOR_EMAIL" ||
+ die "malformed --author parameter"
+ export GIT_AUTHOR_NAME GIT_AUTHOR_EMAIL
+fi
+
+PARENTS="-p HEAD"
+if test -z "$initial_commit"
+then
+ rloga='commit'
+ if [ -f "$GIT_DIR/MERGE_HEAD" ]; then
+ rloga='commit (merge)'
+ PARENTS="-p HEAD "`sed -e 's/^/-p /' "$GIT_DIR/MERGE_HEAD"`
+ elif test -n "$amend"; then
+ rloga='commit (amend)'
+ PARENTS=$(git cat-file commit HEAD |
+ sed -n -e '/^$/q' -e 's/^parent /-p /p')
+ fi
+ current="$(git rev-parse --verify HEAD)"
+else
+ if [ -z "$(git ls-files)" ]; then
+ echo >&2 'nothing to commit (use "git add file1 file2" to include for commit)'
+ exit 1
+ fi
+ PARENTS=""
+ rloga='commit (initial)'
+ current=''
+fi
+set_reflog_action "$rloga"
+
+if test -z "$no_edit"
+then
+ {
+ echo ""
+ echo "# Please enter the commit message for your changes."
+ echo "# (Comment lines starting with '#' will not be included)"
+ test -z "$only_include_assumed" || echo "$only_include_assumed"
+ run_status
+ } >>"$GIT_DIR"/COMMIT_EDITMSG
+else
+ # we need to check if there is anything to commit
+ run_status >/dev/null
+fi
+case "$allow_empty,$?,$PARENTS" in
+t,* | ?,0,* | ?,*,-p' '?*-p' '?*)
+ # an explicit --allow-empty, or a merge commit can record the
+ # same tree as its parent. Otherwise having commitable paths
+ # is required.
+ ;;
+*)
+ rm -f "$GIT_DIR/COMMIT_EDITMSG" "$GIT_DIR/SQUASH_MSG"
+ use_status_color=t
+ run_status
+ exit 1
+esac
+
+case "$no_edit" in
+'')
+ git var GIT_AUTHOR_IDENT > /dev/null || die
+ git var GIT_COMMITTER_IDENT > /dev/null || die
+ git_editor "$GIT_DIR/COMMIT_EDITMSG"
+ ;;
+esac
+
+case "$verify" in
+t)
+ if test -x "$GIT_DIR"/hooks/commit-msg
+ then
+ "$GIT_DIR"/hooks/commit-msg "$GIT_DIR"/COMMIT_EDITMSG || exit
+ fi
+esac
+
+if test -z "$no_edit"
+then
+ sed -e '
+ /^diff --git a\/.*/{
+ s///
+ q
+ }
+ /^#/d
+ ' "$GIT_DIR"/COMMIT_EDITMSG
+else
+ cat "$GIT_DIR"/COMMIT_EDITMSG
+fi |
+git stripspace >"$GIT_DIR"/COMMIT_MSG
+
+# Test whether the commit message has any content we didn't supply.
+have_commitmsg=
+grep -v -i '^Signed-off-by' "$GIT_DIR"/COMMIT_MSG |
+ git stripspace > "$GIT_DIR"/COMMIT_BAREMSG
+
+# Is the commit message totally empty?
+if test -s "$GIT_DIR"/COMMIT_BAREMSG
+then
+ if test "$templatefile" != ""
+ then
+ # Test whether this is just the unaltered template.
+ if cnt=`sed -e '/^#/d' < "$templatefile" |
+ git stripspace |
+ diff "$GIT_DIR"/COMMIT_BAREMSG - |
+ wc -l` &&
+ test 0 -lt $cnt
+ then
+ have_commitmsg=t
+ fi
+ else
+ # No template, so the content in the commit message must
+ # have come from the user.
+ have_commitmsg=t
+ fi
+fi
+
+rm -f "$GIT_DIR"/COMMIT_BAREMSG
+
+if test "$have_commitmsg" = "t"
+then
+ if test -z "$TMP_INDEX"
+ then
+ tree=$(GIT_INDEX_FILE="$USE_INDEX" git write-tree)
+ else
+ tree=$(GIT_INDEX_FILE="$TMP_INDEX" git write-tree) &&
+ rm -f "$TMP_INDEX"
+ fi &&
+ commit=$(git commit-tree $tree $PARENTS <"$GIT_DIR/COMMIT_MSG") &&
+ rlogm=$(sed -e 1q "$GIT_DIR"/COMMIT_MSG) &&
+ git update-ref -m "$GIT_REFLOG_ACTION: $rlogm" HEAD $commit "$current" &&
+ rm -f -- "$GIT_DIR/MERGE_HEAD" "$GIT_DIR/MERGE_MSG" &&
+ if test -f "$NEXT_INDEX"
+ then
+ mv "$NEXT_INDEX" "$THIS_INDEX"
+ else
+ : ;# happy
+ fi
+else
+ echo >&2 "* no commit message? aborting commit."
+ false
+fi
+ret="$?"
+rm -f "$GIT_DIR/COMMIT_MSG" "$GIT_DIR/COMMIT_EDITMSG" "$GIT_DIR/SQUASH_MSG"
+
+cd_to_toplevel
+
+git rerere
+
+if test "$ret" = 0
+then
+ git gc --auto
+ if test -x "$GIT_DIR"/hooks/post-commit
+ then
+ "$GIT_DIR"/hooks/post-commit
+ fi
+ if test -z "$quiet"
+ then
+ commit=`git diff-tree --always --shortstat --pretty="format:%h: %s"\
+ --summary --root HEAD --`
+ echo "Created${initial_commit:+ initial} commit $commit"
+ fi
+fi
+
+exit "$ret"
diff --git a/contrib/examples/git-fetch.sh b/contrib/examples/git-fetch.sh
new file mode 100755
index 0000000000..e44af2c86d
--- /dev/null
+++ b/contrib/examples/git-fetch.sh
@@ -0,0 +1,377 @@
+#!/bin/sh
+#
+
+USAGE='<fetch-options> <repository> <refspec>...'
+SUBDIRECTORY_OK=Yes
+. git-sh-setup
+set_reflog_action "fetch $*"
+cd_to_toplevel ;# probably unnecessary...
+
+. git-parse-remote
+_x40='[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]'
+_x40="$_x40$_x40$_x40$_x40$_x40$_x40$_x40$_x40"
+
+LF='
+'
+IFS="$LF"
+
+no_tags=
+tags=
+append=
+force=
+verbose=
+update_head_ok=
+exec=
+keep=
+shallow_depth=
+no_progress=
+test -t 1 || no_progress=--no-progress
+quiet=
+while test $# != 0
+do
+ case "$1" in
+ -a|--a|--ap|--app|--appe|--appen|--append)
+ append=t
+ ;;
+ --upl|--uplo|--uploa|--upload|--upload-|--upload-p|\
+ --upload-pa|--upload-pac|--upload-pack)
+ shift
+ exec="--upload-pack=$1"
+ ;;
+ --upl=*|--uplo=*|--uploa=*|--upload=*|\
+ --upload-=*|--upload-p=*|--upload-pa=*|--upload-pac=*|--upload-pack=*)
+ exec=--upload-pack=$(expr "z$1" : 'z-[^=]*=\(.*\)')
+ shift
+ ;;
+ -f|--f|--fo|--for|--forc|--force)
+ force=t
+ ;;
+ -t|--t|--ta|--tag|--tags)
+ tags=t
+ ;;
+ -n|--n|--no|--no-|--no-t|--no-ta|--no-tag|--no-tags)
+ no_tags=t
+ ;;
+ -u|--u|--up|--upd|--upda|--updat|--update|--update-|--update-h|\
+ --update-he|--update-hea|--update-head|--update-head-|\
+ --update-head-o|--update-head-ok)
+ update_head_ok=t
+ ;;
+ -q|--q|--qu|--qui|--quie|--quiet)
+ quiet=--quiet
+ ;;
+ -v|--verbose)
+ verbose="$verbose"Yes
+ ;;
+ -k|--k|--ke|--kee|--keep)
+ keep='-k -k'
+ ;;
+ --depth=*)
+ shallow_depth="--depth=`expr "z$1" : 'z-[^=]*=\(.*\)'`"
+ ;;
+ --depth)
+ shift
+ shallow_depth="--depth=$1"
+ ;;
+ -*)
+ usage
+ ;;
+ *)
+ break
+ ;;
+ esac
+ shift
+done
+
+case "$#" in
+0)
+ origin=$(get_default_remote)
+ test -n "$(get_remote_url ${origin})" ||
+ die "Where do you want to fetch from today?"
+ set x $origin ; shift ;;
+esac
+
+if test -z "$exec"
+then
+ # No command line override and we have configuration for the remote.
+ exec="--upload-pack=$(get_uploadpack $1)"
+fi
+
+remote_nick="$1"
+remote=$(get_remote_url "$@")
+refs=
+rref=
+rsync_slurped_objects=
+
+if test "" = "$append"
+then
+ : >"$GIT_DIR/FETCH_HEAD"
+fi
+
+# Global that is reused later
+ls_remote_result=$(git ls-remote $exec "$remote") ||
+ die "Cannot get the repository state from $remote"
+
+append_fetch_head () {
+ flags=
+ test -n "$verbose" && flags="$flags$LF-v"
+ test -n "$force$single_force" && flags="$flags$LF-f"
+ GIT_REFLOG_ACTION="$GIT_REFLOG_ACTION" \
+ git fetch--tool $flags append-fetch-head "$@"
+}
+
+# updating the current HEAD with git-fetch in a bare
+# repository is always fine.
+if test -z "$update_head_ok" && test $(is_bare_repository) = false
+then
+ orig_head=$(git rev-parse --verify HEAD 2>/dev/null)
+fi
+
+# Allow --notags from remote.$1.tagopt
+case "$tags$no_tags" in
+'')
+ case "$(git config --get "remote.$1.tagopt")" in
+ --no-tags)
+ no_tags=t ;;
+ esac
+esac
+
+# If --tags (and later --heads or --all) is specified, then we are
+# not talking about defaults stored in Pull: line of remotes or
+# branches file, and just fetch those and refspecs explicitly given.
+# Otherwise we do what we always did.
+
+reflist=$(get_remote_refs_for_fetch "$@")
+if test "$tags"
+then
+ taglist=`IFS=' ' &&
+ echo "$ls_remote_result" |
+ git show-ref --exclude-existing=refs/tags/ |
+ while read sha1 name
+ do
+ echo ".${name}:${name}"
+ done` || exit
+ if test "$#" -gt 1
+ then
+ # remote URL plus explicit refspecs; we need to merge them.
+ reflist="$reflist$LF$taglist"
+ else
+ # No explicit refspecs; fetch tags only.
+ reflist=$taglist
+ fi
+fi
+
+fetch_all_at_once () {
+
+ eval=$(echo "$1" | git fetch--tool parse-reflist "-")
+ eval "$eval"
+
+ ( : subshell because we muck with IFS
+ IFS=" $LF"
+ (
+ if test "$remote" = . ; then
+ git show-ref $rref || echo failed "$remote"
+ elif test -f "$remote" ; then
+ test -n "$shallow_depth" &&
+ die "shallow clone with bundle is not supported"
+ git bundle unbundle "$remote" $rref ||
+ echo failed "$remote"
+ else
+ if test -d "$remote" &&
+
+ # The remote might be our alternate. With
+ # this optimization we will bypass fetch-pack
+ # altogether, which means we cannot be doing
+ # the shallow stuff at all.
+ test ! -f "$GIT_DIR/shallow" &&
+ test -z "$shallow_depth" &&
+
+ # See if all of what we are going to fetch are
+ # connected to our repository's tips, in which
+ # case we do not have to do any fetch.
+ theirs=$(echo "$ls_remote_result" | \
+ git fetch--tool -s pick-rref "$rref" "-") &&
+
+ # This will barf when $theirs reach an object that
+ # we do not have in our repository. Otherwise,
+ # we already have everything the fetch would bring in.
+ git rev-list --objects $theirs --not --all \
+ >/dev/null 2>/dev/null
+ then
+ echo "$ls_remote_result" | \
+ git fetch--tool pick-rref "$rref" "-"
+ else
+ flags=
+ case $verbose in
+ YesYes*)
+ flags="-v"
+ ;;
+ esac
+ git-fetch-pack --thin $exec $keep $shallow_depth \
+ $quiet $no_progress $flags "$remote" $rref ||
+ echo failed "$remote"
+ fi
+ fi
+ ) |
+ (
+ flags=
+ test -n "$verbose" && flags="$flags -v"
+ test -n "$force" && flags="$flags -f"
+ GIT_REFLOG_ACTION="$GIT_REFLOG_ACTION" \
+ git fetch--tool $flags native-store \
+ "$remote" "$remote_nick" "$refs"
+ )
+ ) || exit
+
+}
+
+fetch_per_ref () {
+ reflist="$1"
+ refs=
+ rref=
+
+ for ref in $reflist
+ do
+ refs="$refs$LF$ref"
+
+ # These are relative path from $GIT_DIR, typically starting at refs/
+ # but may be HEAD
+ if expr "z$ref" : 'z\.' >/dev/null
+ then
+ not_for_merge=t
+ ref=$(expr "z$ref" : 'z\.\(.*\)')
+ else
+ not_for_merge=
+ fi
+ if expr "z$ref" : 'z+' >/dev/null
+ then
+ single_force=t
+ ref=$(expr "z$ref" : 'z+\(.*\)')
+ else
+ single_force=
+ fi
+ remote_name=$(expr "z$ref" : 'z\([^:]*\):')
+ local_name=$(expr "z$ref" : 'z[^:]*:\(.*\)')
+
+ rref="$rref$LF$remote_name"
+
+ # There are transports that can fetch only one head at a time...
+ case "$remote" in
+ http://* | https://* | ftp://*)
+ test -n "$shallow_depth" &&
+ die "shallow clone with http not supported"
+ proto=`expr "$remote" : '\([^:]*\):'`
+ if [ -n "$GIT_SSL_NO_VERIFY" ]; then
+ curl_extra_args="-k"
+ fi
+ if [ -n "$GIT_CURL_FTP_NO_EPSV" -o \
+ "`git config --bool http.noEPSV`" = true ]; then
+ noepsv_opt="--disable-epsv"
+ fi
+
+ # Find $remote_name from ls-remote output.
+ head=$(echo "$ls_remote_result" | \
+ git fetch--tool -s pick-rref "$remote_name" "-")
+ expr "z$head" : "z$_x40\$" >/dev/null ||
+ die "No such ref $remote_name at $remote"
+ echo >&2 "Fetching $remote_name from $remote using $proto"
+ case "$quiet" in '') v=-v ;; *) v= ;; esac
+ git-http-fetch $v -a "$head" "$remote" || exit
+ ;;
+ rsync://*)
+ test -n "$shallow_depth" &&
+ die "shallow clone with rsync not supported"
+ TMP_HEAD="$GIT_DIR/TMP_HEAD"
+ rsync -L -q "$remote/$remote_name" "$TMP_HEAD" || exit 1
+ head=$(git rev-parse --verify TMP_HEAD)
+ rm -f "$TMP_HEAD"
+ case "$quiet" in '') v=-v ;; *) v= ;; esac
+ test "$rsync_slurped_objects" || {
+ rsync -a $v --ignore-existing --exclude info \
+ "$remote/objects/" "$GIT_OBJECT_DIRECTORY/" || exit
+
+ # Look at objects/info/alternates for rsync -- http will
+ # support it natively and git native ones will do it on
+ # the remote end. Not having that file is not a crime.
+ rsync -q "$remote/objects/info/alternates" \
+ "$GIT_DIR/TMP_ALT" 2>/dev/null ||
+ rm -f "$GIT_DIR/TMP_ALT"
+ if test -f "$GIT_DIR/TMP_ALT"
+ then
+ resolve_alternates "$remote" <"$GIT_DIR/TMP_ALT" |
+ while read alt
+ do
+ case "$alt" in 'bad alternate: '*) die "$alt";; esac
+ echo >&2 "Getting alternate: $alt"
+ rsync -av --ignore-existing --exclude info \
+ "$alt" "$GIT_OBJECT_DIRECTORY/" || exit
+ done
+ rm -f "$GIT_DIR/TMP_ALT"
+ fi
+ rsync_slurped_objects=t
+ }
+ ;;
+ esac
+
+ append_fetch_head "$head" "$remote" \
+ "$remote_name" "$remote_nick" "$local_name" "$not_for_merge" || exit
+
+ done
+
+}
+
+fetch_main () {
+ case "$remote" in
+ http://* | https://* | ftp://* | rsync://* )
+ fetch_per_ref "$@"
+ ;;
+ *)
+ fetch_all_at_once "$@"
+ ;;
+ esac
+}
+
+fetch_main "$reflist" || exit
+
+# automated tag following
+case "$no_tags$tags" in
+'')
+ case "$reflist" in
+ *:refs/*)
+ # effective only when we are following remote branch
+ # using local tracking branch.
+ taglist=$(IFS=' ' &&
+ echo "$ls_remote_result" |
+ git show-ref --exclude-existing=refs/tags/ |
+ while read sha1 name
+ do
+ git cat-file -t "$sha1" >/dev/null 2>&1 || continue
+ echo >&2 "Auto-following $name"
+ echo ".${name}:${name}"
+ done)
+ esac
+ case "$taglist" in
+ '') ;;
+ ?*)
+ # do not deepen a shallow tree when following tags
+ shallow_depth=
+ fetch_main "$taglist" || exit ;;
+ esac
+esac
+
+# If the original head was empty (i.e. no "master" yet), or
+# if we were told not to worry, we do not have to check.
+case "$orig_head" in
+'')
+ ;;
+?*)
+ curr_head=$(git rev-parse --verify HEAD 2>/dev/null)
+ if test "$curr_head" != "$orig_head"
+ then
+ git update-ref \
+ -m "$GIT_REFLOG_ACTION: Undoing incorrectly fetched HEAD." \
+ HEAD "$orig_head"
+ die "Cannot fetch into the current branch."
+ fi
+ ;;
+esac
diff --git a/contrib/examples/git-gc.sh b/contrib/examples/git-gc.sh
index 2ae235b081..1597e9f33f 100755
--- a/contrib/examples/git-gc.sh
+++ b/contrib/examples/git-gc.sh
@@ -9,7 +9,7 @@ SUBDIRECTORY_OK=Yes
. git-sh-setup
no_prune=:
-while case $# in 0) break ;; esac
+while test $# != 0
do
case "$1" in
--prune)
diff --git a/contrib/examples/git-ls-remote.sh b/contrib/examples/git-ls-remote.sh
new file mode 100755
index 0000000000..fec70bbf88
--- /dev/null
+++ b/contrib/examples/git-ls-remote.sh
@@ -0,0 +1,142 @@
+#!/bin/sh
+#
+
+usage () {
+ echo >&2 "usage: $0 [--heads] [--tags] [-u|--upload-pack <upload-pack>]"
+ echo >&2 " <repository> <refs>..."
+ exit 1;
+}
+
+die () {
+ echo >&2 "$*"
+ exit 1
+}
+
+exec=
+while test $# != 0
+do
+ case "$1" in
+ -h|--h|--he|--hea|--head|--heads)
+ heads=heads; shift ;;
+ -t|--t|--ta|--tag|--tags)
+ tags=tags; shift ;;
+ -u|--u|--up|--upl|--uploa|--upload|--upload-|--upload-p|--upload-pa|\
+ --upload-pac|--upload-pack)
+ shift
+ exec="--upload-pack=$1"
+ shift;;
+ -u=*|--u=*|--up=*|--upl=*|--uplo=*|--uploa=*|--upload=*|\
+ --upload-=*|--upload-p=*|--upload-pa=*|--upload-pac=*|--upload-pack=*)
+ exec=--upload-pack=$(expr "z$1" : 'z-[^=]*=\(.*\)')
+ shift;;
+ --)
+ shift; break ;;
+ -*)
+ usage ;;
+ *)
+ break ;;
+ esac
+done
+
+case "$#" in 0) usage ;; esac
+
+case ",$heads,$tags," in
+,,,) heads=heads tags=tags other=other ;;
+esac
+
+. git-parse-remote
+peek_repo="$(get_remote_url "$@")"
+shift
+
+tmp=.ls-remote-$$
+trap "rm -fr $tmp-*" 0 1 2 3 15
+tmpdir=$tmp-d
+
+case "$peek_repo" in
+http://* | https://* | ftp://* )
+ if [ -n "$GIT_SSL_NO_VERIFY" -o \
+ "`git config --bool http.sslVerify`" = false ]; then
+ curl_extra_args="-k"
+ fi
+ if [ -n "$GIT_CURL_FTP_NO_EPSV" -o \
+ "`git config --bool http.noEPSV`" = true ]; then
+ curl_extra_args="${curl_extra_args} --disable-epsv"
+ fi
+ curl -nsf $curl_extra_args --header "Pragma: no-cache" "$peek_repo/info/refs" ||
+ echo "failed slurping"
+ ;;
+
+rsync://* )
+ mkdir $tmpdir &&
+ rsync -rlq "$peek_repo/HEAD" $tmpdir &&
+ rsync -rq "$peek_repo/refs" $tmpdir || {
+ echo "failed slurping"
+ exit
+ }
+ head=$(cat "$tmpdir/HEAD") &&
+ case "$head" in
+ ref:' '*)
+ head=$(expr "z$head" : 'zref: \(.*\)') &&
+ head=$(cat "$tmpdir/$head") || exit
+ esac &&
+ echo "$head HEAD"
+ (cd $tmpdir && find refs -type f) |
+ while read path
+ do
+ tr -d '\012' <"$tmpdir/$path"
+ echo " $path"
+ done &&
+ rm -fr $tmpdir
+ ;;
+
+* )
+ if test -f "$peek_repo" ; then
+ git bundle list-heads "$peek_repo" ||
+ echo "failed slurping"
+ else
+ git-peek-remote $exec "$peek_repo" ||
+ echo "failed slurping"
+ fi
+ ;;
+esac |
+sort -t ' ' -k 2 |
+while read sha1 path
+do
+ case "$sha1" in
+ failed)
+ exit 1 ;;
+ esac
+ case "$path" in
+ refs/heads/*)
+ group=heads ;;
+ refs/tags/*)
+ group=tags ;;
+ *)
+ group=other ;;
+ esac
+ case ",$heads,$tags,$other," in
+ *,$group,*)
+ ;;
+ *)
+ continue;;
+ esac
+ case "$#" in
+ 0)
+ match=yes ;;
+ *)
+ match=no
+ for pat
+ do
+ case "/$path" in
+ */$pat )
+ match=yes
+ break ;;
+ esac
+ done
+ esac
+ case "$match" in
+ no)
+ continue ;;
+ esac
+ echo "$sha1 $path"
+done
diff --git a/contrib/examples/git-merge-ours.sh b/contrib/examples/git-merge-ours.sh
new file mode 100755
index 0000000000..29dba4ba3a
--- /dev/null
+++ b/contrib/examples/git-merge-ours.sh
@@ -0,0 +1,14 @@
+#!/bin/sh
+#
+# Copyright (c) 2005 Junio C Hamano
+#
+# Pretend we resolved the heads, but declare our tree trumps everybody else.
+#
+
+# We need to exit with 2 if the index does not match our HEAD tree,
+# because the current index is what we will be committing as the
+# merge result.
+
+git diff-index --quiet --cached HEAD -- || exit 2
+
+exit 0
diff --git a/contrib/examples/git-merge.sh b/contrib/examples/git-merge.sh
new file mode 100755
index 0000000000..e9588eec33
--- /dev/null
+++ b/contrib/examples/git-merge.sh
@@ -0,0 +1,554 @@
+#!/bin/sh
+#
+# Copyright (c) 2005 Junio C Hamano
+#
+
+OPTIONS_KEEPDASHDASH=
+OPTIONS_SPEC="\
+git merge [options] <remote>...
+git merge [options] <msg> HEAD <remote>
+--
+stat show a diffstat at the end of the merge
+n don't show a diffstat at the end of the merge
+summary (synonym to --stat)
+log add list of one-line log to merge commit message
+squash create a single commit instead of doing a merge
+commit perform a commit if the merge succeeds (default)
+ff allow fast forward (default)
+s,strategy= merge strategy to use
+m,message= message to be used for the merge commit (if any)
+"
+
+SUBDIRECTORY_OK=Yes
+. git-sh-setup
+require_work_tree
+cd_to_toplevel
+
+test -z "$(git ls-files -u)" ||
+ die "You are in the middle of a conflicted merge."
+
+LF='
+'
+
+all_strategies='recur recursive octopus resolve stupid ours subtree'
+default_twohead_strategies='recursive'
+default_octopus_strategies='octopus'
+no_fast_forward_strategies='subtree ours'
+no_trivial_strategies='recursive recur subtree ours'
+use_strategies=
+
+allow_fast_forward=t
+allow_trivial_merge=t
+squash= no_commit= log_arg=
+
+dropsave() {
+ rm -f -- "$GIT_DIR/MERGE_HEAD" "$GIT_DIR/MERGE_MSG" \
+ "$GIT_DIR/MERGE_STASH" || exit 1
+}
+
+savestate() {
+ # Stash away any local modifications.
+ git stash create >"$GIT_DIR/MERGE_STASH"
+}
+
+restorestate() {
+ if test -f "$GIT_DIR/MERGE_STASH"
+ then
+ git reset --hard $head >/dev/null
+ git stash apply $(cat "$GIT_DIR/MERGE_STASH")
+ git update-index --refresh >/dev/null
+ fi
+}
+
+finish_up_to_date () {
+ case "$squash" in
+ t)
+ echo "$1 (nothing to squash)" ;;
+ '')
+ echo "$1" ;;
+ esac
+ dropsave
+}
+
+squash_message () {
+ echo Squashed commit of the following:
+ echo
+ git log --no-merges --pretty=medium ^"$head" $remoteheads
+}
+
+finish () {
+ if test '' = "$2"
+ then
+ rlogm="$GIT_REFLOG_ACTION"
+ else
+ echo "$2"
+ rlogm="$GIT_REFLOG_ACTION: $2"
+ fi
+ case "$squash" in
+ t)
+ echo "Squash commit -- not updating HEAD"
+ squash_message >"$GIT_DIR/SQUASH_MSG"
+ ;;
+ '')
+ case "$merge_msg" in
+ '')
+ echo "No merge message -- not updating HEAD"
+ ;;
+ *)
+ git update-ref -m "$rlogm" HEAD "$1" "$head" || exit 1
+ git gc --auto
+ ;;
+ esac
+ ;;
+ esac
+ case "$1" in
+ '')
+ ;;
+ ?*)
+ if test "$show_diffstat" = t
+ then
+ # We want color (if set), but no pager
+ GIT_PAGER='' git diff --stat --summary -M "$head" "$1"
+ fi
+ ;;
+ esac
+
+ # Run a post-merge hook
+ if test -x "$GIT_DIR"/hooks/post-merge
+ then
+ case "$squash" in
+ t)
+ "$GIT_DIR"/hooks/post-merge 1
+ ;;
+ '')
+ "$GIT_DIR"/hooks/post-merge 0
+ ;;
+ esac
+ fi
+}
+
+merge_name () {
+ remote="$1"
+ rh=$(git rev-parse --verify "$remote^0" 2>/dev/null) || return
+ bh=$(git show-ref -s --verify "refs/heads/$remote" 2>/dev/null)
+ if test "$rh" = "$bh"
+ then
+ echo "$rh branch '$remote' of ."
+ elif truname=$(expr "$remote" : '\(.*\)~[1-9][0-9]*$') &&
+ git show-ref -q --verify "refs/heads/$truname" 2>/dev/null
+ then
+ echo "$rh branch '$truname' (early part) of ."
+ elif test "$remote" = "FETCH_HEAD" -a -r "$GIT_DIR/FETCH_HEAD"
+ then
+ sed -e 's/ not-for-merge / /' -e 1q \
+ "$GIT_DIR/FETCH_HEAD"
+ else
+ echo "$rh commit '$remote'"
+ fi
+}
+
+parse_config () {
+ while test $# != 0; do
+ case "$1" in
+ -n|--no-stat|--no-summary)
+ show_diffstat=false ;;
+ --stat|--summary)
+ show_diffstat=t ;;
+ --log|--no-log)
+ log_arg=$1 ;;
+ --squash)
+ test "$allow_fast_forward" = t ||
+ die "You cannot combine --squash with --no-ff."
+ squash=t no_commit=t ;;
+ --no-squash)
+ squash= no_commit= ;;
+ --commit)
+ no_commit= ;;
+ --no-commit)
+ no_commit=t ;;
+ --ff)
+ allow_fast_forward=t ;;
+ --no-ff)
+ test "$squash" != t ||
+ die "You cannot combine --squash with --no-ff."
+ allow_fast_forward=f ;;
+ -s|--strategy)
+ shift
+ case " $all_strategies " in
+ *" $1 "*)
+ use_strategies="$use_strategies$1 " ;;
+ *)
+ die "available strategies are: $all_strategies" ;;
+ esac
+ ;;
+ -m|--message)
+ shift
+ merge_msg="$1"
+ have_message=t
+ ;;
+ --)
+ shift
+ break ;;
+ *) usage ;;
+ esac
+ shift
+ done
+ args_left=$#
+}
+
+test $# != 0 || usage
+
+have_message=
+
+if branch=$(git-symbolic-ref -q HEAD)
+then
+ mergeopts=$(git config "branch.${branch#refs/heads/}.mergeoptions")
+ if test -n "$mergeopts"
+ then
+ parse_config $mergeopts --
+ fi
+fi
+
+parse_config "$@"
+while test $args_left -lt $#; do shift; done
+
+if test -z "$show_diffstat"; then
+ test "$(git config --bool merge.diffstat)" = false && show_diffstat=false
+ test "$(git config --bool merge.stat)" = false && show_diffstat=false
+ test -z "$show_diffstat" && show_diffstat=t
+fi
+
+# This could be traditional "merge <msg> HEAD <commit>..." and the
+# way we can tell it is to see if the second token is HEAD, but some
+# people might have misused the interface and used a committish that
+# is the same as HEAD there instead. Traditional format never would
+# have "-m" so it is an additional safety measure to check for it.
+
+if test -z "$have_message" &&
+ second_token=$(git rev-parse --verify "$2^0" 2>/dev/null) &&
+ head_commit=$(git rev-parse --verify "HEAD" 2>/dev/null) &&
+ test "$second_token" = "$head_commit"
+then
+ merge_msg="$1"
+ shift
+ head_arg="$1"
+ shift
+elif ! git rev-parse --verify HEAD >/dev/null 2>&1
+then
+ # If the merged head is a valid one there is no reason to
+ # forbid "git merge" into a branch yet to be born. We do
+ # the same for "git pull".
+ if test 1 -ne $#
+ then
+ echo >&2 "Can merge only exactly one commit into empty head"
+ exit 1
+ fi
+
+ rh=$(git rev-parse --verify "$1^0") ||
+ die "$1 - not something we can merge"
+
+ git update-ref -m "initial pull" HEAD "$rh" "" &&
+ git read-tree --reset -u HEAD
+ exit
+
+else
+ # We are invoked directly as the first-class UI.
+ head_arg=HEAD
+
+ # All the rest are the commits being merged; prepare
+ # the standard merge summary message to be appended to
+ # the given message. If remote is invalid we will die
+ # later in the common codepath so we discard the error
+ # in this loop.
+ merge_name=$(for remote
+ do
+ merge_name "$remote"
+ done | git fmt-merge-msg $log_arg
+ )
+ merge_msg="${merge_msg:+$merge_msg$LF$LF}$merge_name"
+fi
+head=$(git rev-parse --verify "$head_arg"^0) || usage
+
+# All the rest are remote heads
+test "$#" = 0 && usage ;# we need at least one remote head.
+set_reflog_action "merge $*"
+
+remoteheads=
+for remote
+do
+ remotehead=$(git rev-parse --verify "$remote"^0 2>/dev/null) ||
+ die "$remote - not something we can merge"
+ remoteheads="${remoteheads}$remotehead "
+ eval GITHEAD_$remotehead='"$remote"'
+ export GITHEAD_$remotehead
+done
+set x $remoteheads ; shift
+
+case "$use_strategies" in
+'')
+ case "$#" in
+ 1)
+ var="`git config --get pull.twohead`"
+ if test -n "$var"
+ then
+ use_strategies="$var"
+ else
+ use_strategies="$default_twohead_strategies"
+ fi ;;
+ *)
+ var="`git config --get pull.octopus`"
+ if test -n "$var"
+ then
+ use_strategies="$var"
+ else
+ use_strategies="$default_octopus_strategies"
+ fi ;;
+ esac
+ ;;
+esac
+
+for s in $use_strategies
+do
+ for ss in $no_fast_forward_strategies
+ do
+ case " $s " in
+ *" $ss "*)
+ allow_fast_forward=f
+ break
+ ;;
+ esac
+ done
+ for ss in $no_trivial_strategies
+ do
+ case " $s " in
+ *" $ss "*)
+ allow_trivial_merge=f
+ break
+ ;;
+ esac
+ done
+done
+
+case "$#" in
+1)
+ common=$(git merge-base --all $head "$@")
+ ;;
+*)
+ common=$(git show-branch --merge-base $head "$@")
+ ;;
+esac
+echo "$head" >"$GIT_DIR/ORIG_HEAD"
+
+case "$allow_fast_forward,$#,$common,$no_commit" in
+?,*,'',*)
+ # No common ancestors found. We need a real merge.
+ ;;
+?,1,"$1",*)
+ # If head can reach all the merge then we are up to date.
+ # but first the most common case of merging one remote.
+ finish_up_to_date "Already up-to-date."
+ exit 0
+ ;;
+t,1,"$head",*)
+ # Again the most common case of merging one remote.
+ echo "Updating $(git rev-parse --short $head)..$(git rev-parse --short $1)"
+ git update-index --refresh 2>/dev/null
+ msg="Fast forward"
+ if test -n "$have_message"
+ then
+ msg="$msg (no commit created; -m option ignored)"
+ fi
+ new_head=$(git rev-parse --verify "$1^0") &&
+ git read-tree -v -m -u --exclude-per-directory=.gitignore $head "$new_head" &&
+ finish "$new_head" "$msg" || exit
+ dropsave
+ exit 0
+ ;;
+?,1,?*"$LF"?*,*)
+ # We are not doing octopus and not fast forward. Need a
+ # real merge.
+ ;;
+?,1,*,)
+ # We are not doing octopus, not fast forward, and have only
+ # one common.
+ git update-index --refresh 2>/dev/null
+ case "$allow_trivial_merge" in
+ t)
+ # See if it is really trivial.
+ git var GIT_COMMITTER_IDENT >/dev/null || exit
+ echo "Trying really trivial in-index merge..."
+ if git read-tree --trivial -m -u -v $common $head "$1" &&
+ result_tree=$(git write-tree)
+ then
+ echo "Wonderful."
+ result_commit=$(
+ printf '%s\n' "$merge_msg" |
+ git commit-tree $result_tree -p HEAD -p "$1"
+ ) || exit
+ finish "$result_commit" "In-index merge"
+ dropsave
+ exit 0
+ fi
+ echo "Nope."
+ esac
+ ;;
+*)
+ # An octopus. If we can reach all the remote we are up to date.
+ up_to_date=t
+ for remote
+ do
+ common_one=$(git merge-base --all $head $remote)
+ if test "$common_one" != "$remote"
+ then
+ up_to_date=f
+ break
+ fi
+ done
+ if test "$up_to_date" = t
+ then
+ finish_up_to_date "Already up-to-date. Yeeah!"
+ exit 0
+ fi
+ ;;
+esac
+
+# We are going to make a new commit.
+git var GIT_COMMITTER_IDENT >/dev/null || exit
+
+# At this point, we need a real merge. No matter what strategy
+# we use, it would operate on the index, possibly affecting the
+# working tree, and when resolved cleanly, have the desired tree
+# in the index -- this means that the index must be in sync with
+# the $head commit. The strategies are responsible to ensure this.
+
+case "$use_strategies" in
+?*' '?*)
+ # Stash away the local changes so that we can try more than one.
+ savestate
+ single_strategy=no
+ ;;
+*)
+ rm -f "$GIT_DIR/MERGE_STASH"
+ single_strategy=yes
+ ;;
+esac
+
+result_tree= best_cnt=-1 best_strategy= wt_strategy=
+merge_was_ok=
+for strategy in $use_strategies
+do
+ test "$wt_strategy" = '' || {
+ echo "Rewinding the tree to pristine..."
+ restorestate
+ }
+ case "$single_strategy" in
+ no)
+ echo "Trying merge strategy $strategy..."
+ ;;
+ esac
+
+ # Remember which strategy left the state in the working tree
+ wt_strategy=$strategy
+
+ git-merge-$strategy $common -- "$head_arg" "$@"
+ exit=$?
+ if test "$no_commit" = t && test "$exit" = 0
+ then
+ merge_was_ok=t
+ exit=1 ;# pretend it left conflicts.
+ fi
+
+ test "$exit" = 0 || {
+
+ # The backend exits with 1 when conflicts are left to be resolved,
+ # with 2 when it does not handle the given merge at all.
+
+ if test "$exit" -eq 1
+ then
+ cnt=`{
+ git diff-files --name-only
+ git ls-files --unmerged
+ } | wc -l`
+ if test $best_cnt -le 0 -o $cnt -le $best_cnt
+ then
+ best_strategy=$strategy
+ best_cnt=$cnt
+ fi
+ fi
+ continue
+ }
+
+ # Automerge succeeded.
+ result_tree=$(git write-tree) && break
+done
+
+# If we have a resulting tree, that means the strategy module
+# auto resolved the merge cleanly.
+if test '' != "$result_tree"
+then
+ if test "$allow_fast_forward" = "t"
+ then
+ parents=$(git show-branch --independent "$head" "$@")
+ else
+ parents=$(git rev-parse "$head" "$@")
+ fi
+ parents=$(echo "$parents" | sed -e 's/^/-p /')
+ result_commit=$(printf '%s\n' "$merge_msg" | git commit-tree $result_tree $parents) || exit
+ finish "$result_commit" "Merge made by $wt_strategy."
+ dropsave
+ exit 0
+fi
+
+# Pick the result from the best strategy and have the user fix it up.
+case "$best_strategy" in
+'')
+ restorestate
+ case "$use_strategies" in
+ ?*' '?*)
+ echo >&2 "No merge strategy handled the merge."
+ ;;
+ *)
+ echo >&2 "Merge with strategy $use_strategies failed."
+ ;;
+ esac
+ exit 2
+ ;;
+"$wt_strategy")
+ # We already have its result in the working tree.
+ ;;
+*)
+ echo "Rewinding the tree to pristine..."
+ restorestate
+ echo "Using the $best_strategy to prepare resolving by hand."
+ git-merge-$best_strategy $common -- "$head_arg" "$@"
+ ;;
+esac
+
+if test "$squash" = t
+then
+ finish
+else
+ for remote
+ do
+ echo $remote
+ done >"$GIT_DIR/MERGE_HEAD"
+ printf '%s\n' "$merge_msg" >"$GIT_DIR/MERGE_MSG"
+fi
+
+if test "$merge_was_ok" = t
+then
+ echo >&2 \
+ "Automatic merge went well; stopped before committing as requested"
+ exit 0
+else
+ {
+ echo '
+Conflicts:
+'
+ git ls-files --unmerged |
+ sed -e 's/^[^ ]* / /' |
+ uniq
+ } >>"$GIT_DIR/MERGE_MSG"
+ git rerere
+ die "Automatic merge failed; fix conflicts and then commit the result."
+fi
diff --git a/contrib/examples/git-remote.perl b/contrib/examples/git-remote.perl
new file mode 100755
index 0000000000..b17952a785
--- /dev/null
+++ b/contrib/examples/git-remote.perl
@@ -0,0 +1,474 @@
+#!/usr/bin/perl -w
+
+use strict;
+use Git;
+my $git = Git->repository();
+
+sub add_remote_config {
+ my ($hash, $name, $what, $value) = @_;
+ if ($what eq 'url') {
+ # Having more than one is Ok -- it is used for push.
+ if (! exists $hash->{'URL'}) {
+ $hash->{$name}{'URL'} = $value;
+ }
+ }
+ elsif ($what eq 'fetch') {
+ $hash->{$name}{'FETCH'} ||= [];
+ push @{$hash->{$name}{'FETCH'}}, $value;
+ }
+ elsif ($what eq 'push') {
+ $hash->{$name}{'PUSH'} ||= [];
+ push @{$hash->{$name}{'PUSH'}}, $value;
+ }
+ if (!exists $hash->{$name}{'SOURCE'}) {
+ $hash->{$name}{'SOURCE'} = 'config';
+ }
+}
+
+sub add_remote_remotes {
+ my ($hash, $file, $name) = @_;
+
+ if (exists $hash->{$name}) {
+ $hash->{$name}{'WARNING'} = 'ignored due to config';
+ return;
+ }
+
+ my $fh;
+ if (!open($fh, '<', $file)) {
+ print STDERR "Warning: cannot open $file\n";
+ return;
+ }
+ my $it = { 'SOURCE' => 'remotes' };
+ $hash->{$name} = $it;
+ while (<$fh>) {
+ chomp;
+ if (/^URL:\s*(.*)$/) {
+ # Having more than one is Ok -- it is used for push.
+ if (! exists $it->{'URL'}) {
+ $it->{'URL'} = $1;
+ }
+ }
+ elsif (/^Push:\s*(.*)$/) {
+ $it->{'PUSH'} ||= [];
+ push @{$it->{'PUSH'}}, $1;
+ }
+ elsif (/^Pull:\s*(.*)$/) {
+ $it->{'FETCH'} ||= [];
+ push @{$it->{'FETCH'}}, $1;
+ }
+ elsif (/^\#/) {
+ ; # ignore
+ }
+ else {
+ print STDERR "Warning: funny line in $file: $_\n";
+ }
+ }
+ close($fh);
+}
+
+sub list_remote {
+ my ($git) = @_;
+ my %seen = ();
+ my @remotes = eval {
+ $git->command(qw(config --get-regexp), '^remote\.');
+ };
+ for (@remotes) {
+ if (/^remote\.(\S+?)\.([^.\s]+)\s+(.*)$/) {
+ add_remote_config(\%seen, $1, $2, $3);
+ }
+ }
+
+ my $dir = $git->repo_path() . "/remotes";
+ if (opendir(my $dh, $dir)) {
+ local $_;
+ while ($_ = readdir($dh)) {
+ chomp;
+ next if (! -f "$dir/$_" || ! -r _);
+ add_remote_remotes(\%seen, "$dir/$_", $_);
+ }
+ }
+
+ return \%seen;
+}
+
+sub add_branch_config {
+ my ($hash, $name, $what, $value) = @_;
+ if ($what eq 'remote') {
+ if (exists $hash->{$name}{'REMOTE'}) {
+ print STDERR "Warning: more than one branch.$name.remote\n";
+ }
+ $hash->{$name}{'REMOTE'} = $value;
+ }
+ elsif ($what eq 'merge') {
+ $hash->{$name}{'MERGE'} ||= [];
+ push @{$hash->{$name}{'MERGE'}}, $value;
+ }
+}
+
+sub list_branch {
+ my ($git) = @_;
+ my %seen = ();
+ my @branches = eval {
+ $git->command(qw(config --get-regexp), '^branch\.');
+ };
+ for (@branches) {
+ if (/^branch\.([^.]*)\.(\S*)\s+(.*)$/) {
+ add_branch_config(\%seen, $1, $2, $3);
+ }
+ }
+
+ return \%seen;
+}
+
+my $remote = list_remote($git);
+my $branch = list_branch($git);
+
+sub update_ls_remote {
+ my ($harder, $info) = @_;
+
+ return if (($harder == 0) ||
+ (($harder == 1) && exists $info->{'LS_REMOTE'}));
+
+ my @ref = map { s|refs/heads/||; $_; } keys %{$git->remote_refs($info->{'URL'}, [ 'heads' ])};
+ $info->{'LS_REMOTE'} = \@ref;
+}
+
+sub list_wildcard_mapping {
+ my ($forced, $ours, $ls) = @_;
+ my %refs;
+ for (@$ls) {
+ $refs{$_} = 01; # bit #0 to say "they have"
+ }
+ for ($git->command('for-each-ref', "refs/remotes/$ours")) {
+ chomp;
+ next unless (s|^[0-9a-f]{40}\s[a-z]+\srefs/remotes/$ours/||);
+ next if ($_ eq 'HEAD');
+ $refs{$_} ||= 0;
+ $refs{$_} |= 02; # bit #1 to say "we have"
+ }
+ my (@new, @stale, @tracked);
+ for (sort keys %refs) {
+ my $have = $refs{$_};
+ if ($have == 1) {
+ push @new, $_;
+ }
+ elsif ($have == 2) {
+ push @stale, $_;
+ }
+ elsif ($have == 3) {
+ push @tracked, $_;
+ }
+ }
+ return \@new, \@stale, \@tracked;
+}
+
+sub list_mapping {
+ my ($name, $info) = @_;
+ my $fetch = $info->{'FETCH'};
+ my $ls = $info->{'LS_REMOTE'};
+ my (@new, @stale, @tracked);
+
+ for (@$fetch) {
+ next unless (/(\+)?([^:]+):(.*)/);
+ my ($forced, $theirs, $ours) = ($1, $2, $3);
+ if ($theirs eq 'refs/heads/*' &&
+ $ours =~ /^refs\/remotes\/(.*)\/\*$/) {
+ # wildcard mapping
+ my ($w_new, $w_stale, $w_tracked)
+ = list_wildcard_mapping($forced, $1, $ls);
+ push @new, @$w_new;
+ push @stale, @$w_stale;
+ push @tracked, @$w_tracked;
+ }
+ elsif ($theirs =~ /\*/ || $ours =~ /\*/) {
+ print STDERR "Warning: unrecognized mapping in remotes.$name.fetch: $_\n";
+ }
+ elsif ($theirs =~ s|^refs/heads/||) {
+ if (!grep { $_ eq $theirs } @$ls) {
+ push @stale, $theirs;
+ }
+ elsif ($ours ne '') {
+ push @tracked, $theirs;
+ }
+ }
+ }
+ return \@new, \@stale, \@tracked;
+}
+
+sub show_mapping {
+ my ($name, $info) = @_;
+ my ($new, $stale, $tracked) = list_mapping($name, $info);
+ if (@$new) {
+ print " New remote branches (next fetch will store in remotes/$name)\n";
+ print " @$new\n";
+ }
+ if (@$stale) {
+ print " Stale tracking branches in remotes/$name (use 'git remote prune')\n";
+ print " @$stale\n";
+ }
+ if (@$tracked) {
+ print " Tracked remote branches\n";
+ print " @$tracked\n";
+ }
+}
+
+sub prune_remote {
+ my ($name, $ls_remote) = @_;
+ if (!exists $remote->{$name}) {
+ print STDERR "No such remote $name\n";
+ return 1;
+ }
+ my $info = $remote->{$name};
+ update_ls_remote($ls_remote, $info);
+
+ my ($new, $stale, $tracked) = list_mapping($name, $info);
+ my $prefix = "refs/remotes/$name";
+ foreach my $to_prune (@$stale) {
+ my @v = $git->command(qw(rev-parse --verify), "$prefix/$to_prune");
+ $git->command(qw(update-ref -d), "$prefix/$to_prune", $v[0]);
+ }
+ return 0;
+}
+
+sub show_remote {
+ my ($name, $ls_remote) = @_;
+ if (!exists $remote->{$name}) {
+ print STDERR "No such remote $name\n";
+ return 1;
+ }
+ my $info = $remote->{$name};
+ update_ls_remote($ls_remote, $info);
+
+ print "* remote $name\n";
+ print " URL: $info->{'URL'}\n";
+ for my $branchname (sort keys %$branch) {
+ next unless (defined $branch->{$branchname}{'REMOTE'} &&
+ $branch->{$branchname}{'REMOTE'} eq $name);
+ my @merged = map {
+ s|^refs/heads/||;
+ $_;
+ } split(' ',"@{$branch->{$branchname}{'MERGE'}}");
+ next unless (@merged);
+ print " Remote branch(es) merged with 'git pull' while on branch $branchname\n";
+ print " @merged\n";
+ }
+ if ($info->{'LS_REMOTE'}) {
+ show_mapping($name, $info);
+ }
+ if ($info->{'PUSH'}) {
+ my @pushed = map {
+ s|^refs/heads/||;
+ s|^\+refs/heads/|+|;
+ s|:refs/heads/|:|;
+ $_;
+ } @{$info->{'PUSH'}};
+ print " Local branch(es) pushed with 'git push'\n";
+ print " @pushed\n";
+ }
+ return 0;
+}
+
+sub add_remote {
+ my ($name, $url, $opts) = @_;
+ if (exists $remote->{$name}) {
+ print STDERR "remote $name already exists.\n";
+ exit(1);
+ }
+ $git->command('config', "remote.$name.url", $url);
+ my $track = $opts->{'track'} || ["*"];
+
+ for (@$track) {
+ $git->command('config', '--add', "remote.$name.fetch",
+ $opts->{'mirror'} ?
+ "+refs/$_:refs/$_" :
+ "+refs/heads/$_:refs/remotes/$name/$_");
+ }
+ if ($opts->{'fetch'}) {
+ $git->command('fetch', $name);
+ }
+ if (exists $opts->{'master'}) {
+ $git->command('symbolic-ref', "refs/remotes/$name/HEAD",
+ "refs/remotes/$name/$opts->{'master'}");
+ }
+}
+
+sub update_remote {
+ my ($name) = @_;
+ my @remotes;
+
+ my $conf = $git->config("remotes." . $name);
+ if (defined($conf)) {
+ @remotes = split(' ', $conf);
+ } elsif ($name eq 'default') {
+ @remotes = ();
+ for (sort keys %$remote) {
+ my $do_fetch = $git->config_bool("remote." . $_ .
+ ".skipDefaultUpdate");
+ unless ($do_fetch) {
+ push @remotes, $_;
+ }
+ }
+ } else {
+ print STDERR "Remote group $name does not exist.\n";
+ exit(1);
+ }
+ for (@remotes) {
+ print "Updating $_\n";
+ $git->command('fetch', "$_");
+ }
+}
+
+sub rm_remote {
+ my ($name) = @_;
+ if (!exists $remote->{$name}) {
+ print STDERR "No such remote $name\n";
+ return 1;
+ }
+
+ $git->command('config', '--remove-section', "remote.$name");
+
+ eval {
+ my @trackers = $git->command('config', '--get-regexp',
+ 'branch.*.remote', $name);
+ for (@trackers) {
+ /^branch\.(.*)?\.remote/;
+ $git->config('--unset', "branch.$1.remote");
+ $git->config('--unset', "branch.$1.merge");
+ }
+ };
+
+ my @refs = $git->command('for-each-ref',
+ '--format=%(refname) %(objectname)', "refs/remotes/$name");
+ for (@refs) {
+ my ($ref, $object) = split;
+ $git->command(qw(update-ref -d), $ref, $object);
+ }
+ return 0;
+}
+
+sub add_usage {
+ print STDERR "Usage: git remote add [-f] [-t track]* [-m master] <name> <url>\n";
+ exit(1);
+}
+
+my $VERBOSE = 0;
+@ARGV = grep {
+ if ($_ eq '-v' or $_ eq '--verbose') {
+ $VERBOSE=1;
+ 0
+ } else {
+ 1
+ }
+} @ARGV;
+
+if (!@ARGV) {
+ for (sort keys %$remote) {
+ print "$_";
+ print "\t$remote->{$_}->{URL}" if $VERBOSE;
+ print "\n";
+ }
+}
+elsif ($ARGV[0] eq 'show') {
+ my $ls_remote = 1;
+ my $i;
+ for ($i = 1; $i < @ARGV; $i++) {
+ if ($ARGV[$i] eq '-n') {
+ $ls_remote = 0;
+ }
+ else {
+ last;
+ }
+ }
+ if ($i >= @ARGV) {
+ print STDERR "Usage: git remote show <remote>\n";
+ exit(1);
+ }
+ my $status = 0;
+ for (; $i < @ARGV; $i++) {
+ $status |= show_remote($ARGV[$i], $ls_remote);
+ }
+ exit($status);
+}
+elsif ($ARGV[0] eq 'update') {
+ if (@ARGV <= 1) {
+ update_remote("default");
+ exit(1);
+ }
+ for (my $i = 1; $i < @ARGV; $i++) {
+ update_remote($ARGV[$i]);
+ }
+}
+elsif ($ARGV[0] eq 'prune') {
+ my $ls_remote = 1;
+ my $i;
+ for ($i = 1; $i < @ARGV; $i++) {
+ if ($ARGV[$i] eq '-n') {
+ $ls_remote = 0;
+ }
+ else {
+ last;
+ }
+ }
+ if ($i >= @ARGV) {
+ print STDERR "Usage: git remote prune <remote>\n";
+ exit(1);
+ }
+ my $status = 0;
+ for (; $i < @ARGV; $i++) {
+ $status |= prune_remote($ARGV[$i], $ls_remote);
+ }
+ exit($status);
+}
+elsif ($ARGV[0] eq 'add') {
+ my %opts = ();
+ while (1 < @ARGV && $ARGV[1] =~ /^-/) {
+ my $opt = $ARGV[1];
+ shift @ARGV;
+ if ($opt eq '-f' || $opt eq '--fetch') {
+ $opts{'fetch'} = 1;
+ next;
+ }
+ if ($opt eq '-t' || $opt eq '--track') {
+ if (@ARGV < 1) {
+ add_usage();
+ }
+ $opts{'track'} ||= [];
+ push @{$opts{'track'}}, $ARGV[1];
+ shift @ARGV;
+ next;
+ }
+ if ($opt eq '-m' || $opt eq '--master') {
+ if ((@ARGV < 1) || exists $opts{'master'}) {
+ add_usage();
+ }
+ $opts{'master'} = $ARGV[1];
+ shift @ARGV;
+ next;
+ }
+ if ($opt eq '--mirror') {
+ $opts{'mirror'} = 1;
+ next;
+ }
+ add_usage();
+ }
+ if (@ARGV != 3) {
+ add_usage();
+ }
+ add_remote($ARGV[1], $ARGV[2], \%opts);
+}
+elsif ($ARGV[0] eq 'rm') {
+ if (@ARGV <= 1) {
+ print STDERR "Usage: git remote rm <remote>\n";
+ exit(1);
+ }
+ exit(rm_remote($ARGV[1]));
+}
+else {
+ print STDERR "Usage: git remote\n";
+ print STDERR " git remote add <name> <url>\n";
+ print STDERR " git remote rm <name>\n";
+ print STDERR " git remote show <name>\n";
+ print STDERR " git remote prune <name>\n";
+ print STDERR " git remote update [group]\n";
+ exit(1);
+}
diff --git a/contrib/examples/git-rerere.perl b/contrib/examples/git-rerere.perl
new file mode 100755
index 0000000000..4f692091e7
--- /dev/null
+++ b/contrib/examples/git-rerere.perl
@@ -0,0 +1,284 @@
+#!/usr/bin/perl
+#
+# REuse REcorded REsolve. This tool records a conflicted automerge
+# result and its hand resolution, and helps to resolve future
+# automerge that results in the same conflict.
+#
+# To enable this feature, create a directory 'rr-cache' under your
+# .git/ directory.
+
+use Digest;
+use File::Path;
+use File::Copy;
+
+my $git_dir = $::ENV{GIT_DIR} || ".git";
+my $rr_dir = "$git_dir/rr-cache";
+my $merge_rr = "$git_dir/rr-cache/MERGE_RR";
+
+my %merge_rr = ();
+
+sub read_rr {
+ if (!-f $merge_rr) {
+ %merge_rr = ();
+ return;
+ }
+ my $in;
+ local $/ = "\0";
+ open $in, "<$merge_rr" or die "$!: $merge_rr";
+ while (<$in>) {
+ chomp;
+ my ($name, $path) = /^([0-9a-f]{40})\t(.*)$/s;
+ $merge_rr{$path} = $name;
+ }
+ close $in;
+}
+
+sub write_rr {
+ my $out;
+ open $out, ">$merge_rr" or die "$!: $merge_rr";
+ for my $path (sort keys %merge_rr) {
+ my $name = $merge_rr{$path};
+ print $out "$name\t$path\0";
+ }
+ close $out;
+}
+
+sub compute_conflict_name {
+ my ($path) = @_;
+ my @side = ();
+ my $in;
+ open $in, "<$path" or die "$!: $path";
+
+ my $sha1 = Digest->new("SHA-1");
+ my $hunk = 0;
+ while (<$in>) {
+ if (/^<<<<<<< .*/) {
+ $hunk++;
+ @side = ([], undef);
+ }
+ elsif (/^=======$/) {
+ $side[1] = [];
+ }
+ elsif (/^>>>>>>> .*/) {
+ my ($one, $two);
+ $one = join('', @{$side[0]});
+ $two = join('', @{$side[1]});
+ if ($two le $one) {
+ ($one, $two) = ($two, $one);
+ }
+ $sha1->add($one);
+ $sha1->add("\0");
+ $sha1->add($two);
+ $sha1->add("\0");
+ @side = ();
+ }
+ elsif (@side == 0) {
+ next;
+ }
+ elsif (defined $side[1]) {
+ push @{$side[1]}, $_;
+ }
+ else {
+ push @{$side[0]}, $_;
+ }
+ }
+ close $in;
+ return ($sha1->hexdigest, $hunk);
+}
+
+sub record_preimage {
+ my ($path, $name) = @_;
+ my @side = ();
+ my ($in, $out);
+ open $in, "<$path" or die "$!: $path";
+ open $out, ">$name" or die "$!: $name";
+
+ while (<$in>) {
+ if (/^<<<<<<< .*/) {
+ @side = ([], undef);
+ }
+ elsif (/^=======$/) {
+ $side[1] = [];
+ }
+ elsif (/^>>>>>>> .*/) {
+ my ($one, $two);
+ $one = join('', @{$side[0]});
+ $two = join('', @{$side[1]});
+ if ($two le $one) {
+ ($one, $two) = ($two, $one);
+ }
+ print $out "<<<<<<<\n";
+ print $out $one;
+ print $out "=======\n";
+ print $out $two;
+ print $out ">>>>>>>\n";
+ @side = ();
+ }
+ elsif (@side == 0) {
+ print $out $_;
+ }
+ elsif (defined $side[1]) {
+ push @{$side[1]}, $_;
+ }
+ else {
+ push @{$side[0]}, $_;
+ }
+ }
+ close $out;
+ close $in;
+}
+
+sub find_conflict {
+ my $in;
+ local $/ = "\0";
+ my $pid = open($in, '-|');
+ die "$!" unless defined $pid;
+ if (!$pid) {
+ exec(qw(git ls-files -z -u)) or die "$!: ls-files";
+ }
+ my %path = ();
+ my @path = ();
+ while (<$in>) {
+ chomp;
+ my ($mode, $sha1, $stage, $path) =
+ /^([0-7]+) ([0-9a-f]{40}) ([123])\t(.*)$/s;
+ $path{$path} |= (1 << $stage);
+ }
+ close $in;
+ while (my ($path, $status) = each %path) {
+ if ($status == 14) { push @path, $path; }
+ }
+ return @path;
+}
+
+sub merge {
+ my ($name, $path) = @_;
+ record_preimage($path, "$rr_dir/$name/thisimage");
+ unless (system('git', 'merge-file', map { "$rr_dir/$name/${_}image" }
+ qw(this pre post))) {
+ my $in;
+ open $in, "<$rr_dir/$name/thisimage" or
+ die "$!: $name/thisimage";
+ my $out;
+ open $out, ">$path" or die "$!: $path";
+ while (<$in>) { print $out $_; }
+ close $in;
+ close $out;
+ return 1;
+ }
+ return 0;
+}
+
+sub garbage_collect_rerere {
+ # We should allow specifying these from the command line and
+ # that is why the caller gives @ARGV to us, but I am lazy.
+
+ my $cutoff_noresolve = 15; # two weeks
+ my $cutoff_resolve = 60; # two months
+ my @to_remove;
+ while (<$rr_dir/*/preimage>) {
+ my ($dir) = /^(.*)\/preimage$/;
+ my $cutoff = ((-f "$dir/postimage")
+ ? $cutoff_resolve
+ : $cutoff_noresolve);
+ my $age = -M "$_";
+ if ($cutoff <= $age) {
+ push @to_remove, $dir;
+ }
+ }
+ if (@to_remove) {
+ rmtree(\@to_remove);
+ }
+}
+
+-d "$rr_dir" || exit(0);
+
+read_rr();
+
+if (@ARGV) {
+ my $arg = shift @ARGV;
+ if ($arg eq 'clear') {
+ for my $path (keys %merge_rr) {
+ my $name = $merge_rr{$path};
+ if (-d "$rr_dir/$name" &&
+ ! -f "$rr_dir/$name/postimage") {
+ rmtree(["$rr_dir/$name"]);
+ }
+ }
+ unlink $merge_rr;
+ }
+ elsif ($arg eq 'status') {
+ for my $path (keys %merge_rr) {
+ print $path, "\n";
+ }
+ }
+ elsif ($arg eq 'diff') {
+ for my $path (keys %merge_rr) {
+ my $name = $merge_rr{$path};
+ system('diff', ((@ARGV == 0) ? ('-u') : @ARGV),
+ '-L', "a/$path", '-L', "b/$path",
+ "$rr_dir/$name/preimage", $path);
+ }
+ }
+ elsif ($arg eq 'gc') {
+ garbage_collect_rerere(@ARGV);
+ }
+ else {
+ die "$0 unknown command: $arg\n";
+ }
+ exit 0;
+}
+
+my %conflict = map { $_ => 1 } find_conflict();
+
+# MERGE_RR records paths with conflicts immediately after merge
+# failed. Some of the conflicted paths might have been hand resolved
+# in the working tree since then, but the initial run would catch all
+# and register their preimages.
+
+for my $path (keys %conflict) {
+ # This path has conflict. If it is not recorded yet,
+ # record the pre-image.
+ if (!exists $merge_rr{$path}) {
+ my ($name, $hunk) = compute_conflict_name($path);
+ next unless ($hunk);
+ $merge_rr{$path} = $name;
+ if (! -d "$rr_dir/$name") {
+ mkpath("$rr_dir/$name", 0, 0777);
+ print STDERR "Recorded preimage for '$path'\n";
+ record_preimage($path, "$rr_dir/$name/preimage");
+ }
+ }
+}
+
+# Now some of the paths that had conflicts earlier might have been
+# hand resolved. Others may be similar to a conflict already that
+# was resolved before.
+
+for my $path (keys %merge_rr) {
+ my $name = $merge_rr{$path};
+
+ # We could resolve this automatically if we have images.
+ if (-f "$rr_dir/$name/preimage" &&
+ -f "$rr_dir/$name/postimage") {
+ if (merge($name, $path)) {
+ print STDERR "Resolved '$path' using previous resolution.\n";
+ # Then we do not have to worry about this path
+ # anymore.
+ delete $merge_rr{$path};
+ next;
+ }
+ }
+
+ # Let's see if we have resolved it.
+ (undef, my $hunk) = compute_conflict_name($path);
+ next if ($hunk);
+
+ print STDERR "Recorded resolution for '$path'.\n";
+ copy($path, "$rr_dir/$name/postimage");
+ # And we do not have to worry about this path anymore.
+ delete $merge_rr{$path};
+}
+
+# Write out the rest.
+write_rr();
diff --git a/contrib/examples/git-reset.sh b/contrib/examples/git-reset.sh
new file mode 100755
index 0000000000..bafeb52cd1
--- /dev/null
+++ b/contrib/examples/git-reset.sh
@@ -0,0 +1,106 @@
+#!/bin/sh
+#
+# Copyright (c) 2005, 2006 Linus Torvalds and Junio C Hamano
+#
+USAGE='[--mixed | --soft | --hard] [<commit-ish>] [ [--] <paths>...]'
+SUBDIRECTORY_OK=Yes
+. git-sh-setup
+set_reflog_action "reset $*"
+require_work_tree
+
+update= reset_type=--mixed
+unset rev
+
+while test $# != 0
+do
+ case "$1" in
+ --mixed | --soft | --hard)
+ reset_type="$1"
+ ;;
+ --)
+ break
+ ;;
+ -*)
+ usage
+ ;;
+ *)
+ rev=$(git rev-parse --verify "$1") || exit
+ shift
+ break
+ ;;
+ esac
+ shift
+done
+
+: ${rev=HEAD}
+rev=$(git rev-parse --verify $rev^0) || exit
+
+# Skip -- in "git reset HEAD -- foo" and "git reset -- foo".
+case "$1" in --) shift ;; esac
+
+# git reset --mixed tree [--] paths... can be used to
+# load chosen paths from the tree into the index without
+# affecting the working tree nor HEAD.
+if test $# != 0
+then
+ test "$reset_type" = "--mixed" ||
+ die "Cannot do partial $reset_type reset."
+
+ git diff-index --cached $rev -- "$@" |
+ sed -e 's/^:\([0-7][0-7]*\) [0-7][0-7]* \([0-9a-f][0-9a-f]*\) [0-9a-f][0-9a-f]* [A-Z] \(.*\)$/\1 \2 \3/' |
+ git update-index --add --remove --index-info || exit
+ git update-index --refresh
+ exit
+fi
+
+cd_to_toplevel
+
+if test "$reset_type" = "--hard"
+then
+ update=-u
+fi
+
+# Soft reset does not touch the index file nor the working tree
+# at all, but requires them in a good order. Other resets reset
+# the index file to the tree object we are switching to.
+if test "$reset_type" = "--soft"
+then
+ if test -f "$GIT_DIR/MERGE_HEAD" ||
+ test "" != "$(git ls-files --unmerged)"
+ then
+ die "Cannot do a soft reset in the middle of a merge."
+ fi
+else
+ git read-tree -v --reset $update "$rev" || exit
+fi
+
+# Any resets update HEAD to the head being switched to.
+if orig=$(git rev-parse --verify HEAD 2>/dev/null)
+then
+ echo "$orig" >"$GIT_DIR/ORIG_HEAD"
+else
+ rm -f "$GIT_DIR/ORIG_HEAD"
+fi
+git update-ref -m "$GIT_REFLOG_ACTION" HEAD "$rev"
+update_ref_status=$?
+
+case "$reset_type" in
+--hard )
+ test $update_ref_status = 0 && {
+ printf "HEAD is now at "
+ GIT_PAGER= git log --max-count=1 --pretty=oneline \
+ --abbrev-commit HEAD
+ }
+ ;;
+--soft )
+ ;; # Nothing else to do
+--mixed )
+ # Report what has not been updated.
+ git update-index --refresh
+ ;;
+esac
+
+rm -f "$GIT_DIR/MERGE_HEAD" "$GIT_DIR/rr-cache/MERGE_RR" \
+ "$GIT_DIR/SQUASH_MSG" "$GIT_DIR/MERGE_MSG"
+
+exit $update_ref_status
diff --git a/contrib/examples/git-revert.sh b/contrib/examples/git-revert.sh
new file mode 100755
index 0000000000..49f00321b2
--- /dev/null
+++ b/contrib/examples/git-revert.sh
@@ -0,0 +1,197 @@
+#!/bin/sh
+#
+# Copyright (c) 2005 Linus Torvalds
+# Copyright (c) 2005 Junio C Hamano
+#
+
+case "$0" in
+*-revert* )
+ test -t 0 && edit=-e
+ replay=
+ me=revert
+ USAGE='[--edit | --no-edit] [-n] <commit-ish>' ;;
+*-cherry-pick* )
+ replay=t
+ edit=
+ me=cherry-pick
+ USAGE='[--edit] [-n] [-r] [-x] <commit-ish>' ;;
+* )
+ echo >&2 "What are you talking about?"
+ exit 1 ;;
+esac
+
+SUBDIRECTORY_OK=Yes ;# we will cd up
+. git-sh-setup
+require_work_tree
+cd_to_toplevel
+
+no_commit=
+while case "$#" in 0) break ;; esac
+do
+ case "$1" in
+ -n|--n|--no|--no-|--no-c|--no-co|--no-com|--no-comm|\
+ --no-commi|--no-commit)
+ no_commit=t
+ ;;
+ -e|--e|--ed|--edi|--edit)
+ edit=-e
+ ;;
+ --n|--no|--no-|--no-e|--no-ed|--no-edi|--no-edit)
+ edit=
+ ;;
+ -r)
+ : no-op ;;
+ -x|--i-really-want-to-expose-my-private-commit-object-name)
+ replay=
+ ;;
+ -*)
+ usage
+ ;;
+ *)
+ break
+ ;;
+ esac
+ shift
+done
+
+set_reflog_action "$me"
+
+test "$me,$replay" = "revert,t" && usage
+
+case "$no_commit" in
+t)
+ # We do not intend to commit immediately. We just want to
+ # merge the differences in.
+ head=$(git-write-tree) ||
+ die "Your index file is unmerged."
+ ;;
+*)
+ head=$(git-rev-parse --verify HEAD) ||
+ die "You do not have a valid HEAD"
+ files=$(git-diff-index --cached --name-only $head) || exit
+ if [ "$files" ]; then
+ die "Dirty index: cannot $me (dirty: $files)"
+ fi
+ ;;
+esac
+
+rev=$(git-rev-parse --verify "$@") &&
+commit=$(git-rev-parse --verify "$rev^0") ||
+ die "Not a single commit $@"
+prev=$(git-rev-parse --verify "$commit^1" 2>/dev/null) ||
+ die "Cannot run $me a root commit"
+git-rev-parse --verify "$commit^2" >/dev/null 2>&1 &&
+ die "Cannot run $me a multi-parent commit."
+
+encoding=$(git config i18n.commitencoding || echo UTF-8)
+
+# "commit" is an existing commit. We would want to apply
+# the difference it introduces since its first parent "prev"
+# on top of the current HEAD if we are cherry-pick. Or the
+# reverse of it if we are revert.
+
+case "$me" in
+revert)
+ git show -s --pretty=oneline --encoding="$encoding" $commit |
+ sed -e '
+ s/^[^ ]* /Revert "/
+ s/$/"/
+ '
+ echo
+ echo "This reverts commit $commit."
+ test "$rev" = "$commit" ||
+ echo "(original 'git revert' arguments: $@)"
+ base=$commit next=$prev
+ ;;
+
+cherry-pick)
+ pick_author_script='
+ /^author /{
+ s/'\''/'\''\\'\'\''/g
+ h
+ s/^author \([^<]*\) <[^>]*> .*$/\1/
+ s/'\''/'\''\'\'\''/g
+ s/.*/GIT_AUTHOR_NAME='\''&'\''/p
+
+ g
+ s/^author [^<]* <\([^>]*\)> .*$/\1/
+ s/'\''/'\''\'\'\''/g
+ s/.*/GIT_AUTHOR_EMAIL='\''&'\''/p
+
+ g
+ s/^author [^<]* <[^>]*> \(.*\)$/\1/
+ s/'\''/'\''\'\'\''/g
+ s/.*/GIT_AUTHOR_DATE='\''&'\''/p
+
+ q
+ }'
+
+ logmsg=`git show -s --pretty=raw --encoding="$encoding" "$commit"`
+ set_author_env=`echo "$logmsg" |
+ LANG=C LC_ALL=C sed -ne "$pick_author_script"`
+ eval "$set_author_env"
+ export GIT_AUTHOR_NAME
+ export GIT_AUTHOR_EMAIL
+ export GIT_AUTHOR_DATE
+
+ echo "$logmsg" |
+ sed -e '1,/^$/d' -e 's/^ //'
+ case "$replay" in
+ '')
+ echo "(cherry picked from commit $commit)"
+ test "$rev" = "$commit" ||
+ echo "(original 'git cherry-pick' arguments: $@)"
+ ;;
+ esac
+ base=$prev next=$commit
+ ;;
+
+esac >.msg
+
+eval GITHEAD_$head=HEAD
+eval GITHEAD_$next='`git show -s \
+ --pretty=oneline --encoding="$encoding" "$commit" |
+ sed -e "s/^[^ ]* //"`'
+export GITHEAD_$head GITHEAD_$next
+
+# This three way merge is an interesting one. We are at
+# $head, and would want to apply the change between $commit
+# and $prev on top of us (when reverting), or the change between
+# $prev and $commit on top of us (when cherry-picking or replaying).
+
+git-merge-recursive $base -- $head $next &&
+result=$(git-write-tree 2>/dev/null) || {
+ mv -f .msg "$GIT_DIR/MERGE_MSG"
+ {
+ echo '
+Conflicts:
+'
+ git ls-files --unmerged |
+ sed -e 's/^[^ ]* / /' |
+ uniq
+ } >>"$GIT_DIR/MERGE_MSG"
+ echo >&2 "Automatic $me failed. After resolving the conflicts,"
+ echo >&2 "mark the corrected paths with 'git-add <paths>'"
+ echo >&2 "and commit the result."
+ case "$me" in
+ cherry-pick)
+ echo >&2 "You may choose to use the following when making"
+ echo >&2 "the commit:"
+ echo >&2 "$set_author_env"
+ esac
+ exit 1
+}
+echo >&2 "Finished one $me."
+
+# If we are cherry-pick, and if the merge did not result in
+# hand-editing, we will hit this commit and inherit the original
+# author date and name.
+# If we are revert, or if our cherry-pick results in a hand merge,
+# we had better say that the current user is responsible for that.
+
+case "$no_commit" in
+'')
+ git-commit -n -F .msg $edit
+ rm -f .msg
+ ;;
+esac
diff --git a/contrib/examples/git-svnimport.perl b/contrib/examples/git-svnimport.perl
new file mode 100755
index 0000000000..4576c4a862
--- /dev/null
+++ b/contrib/examples/git-svnimport.perl
@@ -0,0 +1,976 @@
+#!/usr/bin/perl -w
+
+# This tool is copyright (c) 2005, Matthias Urlichs.
+# It is released under the Gnu Public License, version 2.
+#
+# The basic idea is to pull and analyze SVN changes.
+#
+# Checking out the files is done by a single long-running SVN connection.
+#
+# The head revision is on branch "origin" by default.
+# You can change that with the '-o' option.
+
+use strict;
+use warnings;
+use Getopt::Std;
+use File::Copy;
+use File::Spec;
+use File::Temp qw(tempfile);
+use File::Path qw(mkpath);
+use File::Basename qw(basename dirname);
+use Time::Local;
+use IO::Pipe;
+use POSIX qw(strftime dup2);
+use IPC::Open2;
+use SVN::Core;
+use SVN::Ra;
+
+die "Need SVN:Core 1.2.1 or better" if $SVN::Core::VERSION lt "1.2.1";
+
+$SIG{'PIPE'}="IGNORE";
+$ENV{'TZ'}="UTC";
+
+our($opt_h,$opt_o,$opt_v,$opt_u,$opt_C,$opt_i,$opt_m,$opt_M,$opt_t,$opt_T,
+ $opt_b,$opt_r,$opt_I,$opt_A,$opt_s,$opt_l,$opt_d,$opt_D,$opt_S,$opt_F,
+ $opt_P,$opt_R);
+
+sub usage() {
+ print STDERR <<END;
+Usage: ${\basename $0} # fetch/update GIT from SVN
+ [-o branch-for-HEAD] [-h] [-v] [-l max_rev] [-R repack_each_revs]
+ [-C GIT_repository] [-t tagname] [-T trunkname] [-b branchname]
+ [-d|-D] [-i] [-u] [-r] [-I ignorefilename] [-s start_chg]
+ [-m] [-M regex] [-A author_file] [-S] [-F] [-P project_name] [SVN_URL]
+END
+ exit(1);
+}
+
+getopts("A:b:C:dDFhiI:l:mM:o:rs:t:T:SP:R:uv") or usage();
+usage if $opt_h;
+
+my $tag_name = $opt_t || "tags";
+my $trunk_name = defined $opt_T ? $opt_T : "trunk";
+my $branch_name = $opt_b || "branches";
+my $project_name = $opt_P || "";
+$project_name = "/" . $project_name if ($project_name);
+my $repack_after = $opt_R || 1000;
+my $root_pool = SVN::Pool->new_default;
+
+@ARGV == 1 or @ARGV == 2 or usage();
+
+$opt_o ||= "origin";
+$opt_s ||= 1;
+my $git_tree = $opt_C;
+$git_tree ||= ".";
+
+my $svn_url = $ARGV[0];
+my $svn_dir = $ARGV[1];
+
+our @mergerx = ();
+if ($opt_m) {
+ my $branch_esc = quotemeta ($branch_name);
+ my $trunk_esc = quotemeta ($trunk_name);
+ @mergerx =
+ (
+ qr!\b(?:merg(?:ed?|ing))\b.*?\b((?:(?<=$branch_esc/)[\w\.\-]+)|(?:$trunk_esc))\b!i,
+ qr!\b(?:from|of)\W+((?:(?<=$branch_esc/)[\w\.\-]+)|(?:$trunk_esc))\b!i,
+ qr!\b(?:from|of)\W+(?:the )?([\w\.\-]+)[-\s]branch\b!i
+ );
+}
+if ($opt_M) {
+ unshift (@mergerx, qr/$opt_M/);
+}
+
+# Absolutize filename now, since we will have chdir'ed by the time we
+# get around to opening it.
+$opt_A = File::Spec->rel2abs($opt_A) if $opt_A;
+
+our %users = ();
+our $users_file = undef;
+sub read_users($) {
+ $users_file = File::Spec->rel2abs(@_);
+ die "Cannot open $users_file\n" unless -f $users_file;
+ open(my $authors,$users_file);
+ while(<$authors>) {
+ chomp;
+ next unless /^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/;
+ (my $user,my $name,my $email) = ($1,$2,$3);
+ $users{$user} = [$name,$email];
+ }
+ close($authors);
+}
+
+select(STDERR); $|=1; select(STDOUT);
+
+
+package SVNconn;
+# Basic SVN connection.
+# We're only interested in connecting and downloading, so ...
+
+use File::Spec;
+use File::Temp qw(tempfile);
+use POSIX qw(strftime dup2);
+use Fcntl qw(SEEK_SET);
+
+sub new {
+ my($what,$repo) = @_;
+ $what=ref($what) if ref($what);
+
+ my $self = {};
+ $self->{'buffer'} = "";
+ bless($self,$what);
+
+ $repo =~ s#/+$##;
+ $self->{'fullrep'} = $repo;
+ $self->conn();
+
+ return $self;
+}
+
+sub conn {
+ my $self = shift;
+ my $repo = $self->{'fullrep'};
+ my $auth = SVN::Core::auth_open ([SVN::Client::get_simple_provider,
+ SVN::Client::get_ssl_server_trust_file_provider,
+ SVN::Client::get_username_provider]);
+ my $s = SVN::Ra->new(url => $repo, auth => $auth, pool => $root_pool);
+ die "SVN connection to $repo: $!\n" unless defined $s;
+ $self->{'svn'} = $s;
+ $self->{'repo'} = $repo;
+ $self->{'maxrev'} = $s->get_latest_revnum();
+}
+
+sub file {
+ my($self,$path,$rev) = @_;
+
+ my ($fh, $name) = tempfile('gitsvn.XXXXXX',
+ DIR => File::Spec->tmpdir(), UNLINK => 1);
+
+ print "... $rev $path ...\n" if $opt_v;
+ my (undef, $properties);
+ $path =~ s#^/*##;
+ my $subpool = SVN::Pool::new_default_sub;
+ eval { (undef, $properties)
+ = $self->{'svn'}->get_file($path,$rev,$fh); };
+ if($@) {
+ return undef if $@ =~ /Attempted to get checksum/;
+ die $@;
+ }
+ my $mode;
+ if (exists $properties->{'svn:executable'}) {
+ $mode = '100755';
+ } elsif (exists $properties->{'svn:special'}) {
+ my ($special_content, $filesize);
+ $filesize = tell $fh;
+ seek $fh, 0, SEEK_SET;
+ read $fh, $special_content, $filesize;
+ if ($special_content =~ s/^link //) {
+ $mode = '120000';
+ seek $fh, 0, SEEK_SET;
+ truncate $fh, 0;
+ print $fh $special_content;
+ } else {
+ die "unexpected svn:special file encountered";
+ }
+ } else {
+ $mode = '100644';
+ }
+ close ($fh);
+
+ return ($name, $mode);
+}
+
+sub ignore {
+ my($self,$path,$rev) = @_;
+
+ print "... $rev $path ...\n" if $opt_v;
+ $path =~ s#^/*##;
+ my $subpool = SVN::Pool::new_default_sub;
+ my (undef,undef,$properties)
+ = $self->{'svn'}->get_dir($path,$rev,undef);
+ if (exists $properties->{'svn:ignore'}) {
+ my ($fh, $name) = tempfile('gitsvn.XXXXXX',
+ DIR => File::Spec->tmpdir(),
+ UNLINK => 1);
+ print $fh $properties->{'svn:ignore'};
+ close($fh);
+ return $name;
+ } else {
+ return undef;
+ }
+}
+
+sub dir_list {
+ my($self,$path,$rev) = @_;
+ $path =~ s#^/*##;
+ my $subpool = SVN::Pool::new_default_sub;
+ my ($dirents,undef,$properties)
+ = $self->{'svn'}->get_dir($path,$rev,undef);
+ return $dirents;
+}
+
+package main;
+use URI;
+
+our $svn = $svn_url;
+$svn .= "/$svn_dir" if defined $svn_dir;
+my $svn2 = SVNconn->new($svn);
+$svn = SVNconn->new($svn);
+
+my $lwp_ua;
+if($opt_d or $opt_D) {
+ $svn_url = URI->new($svn_url)->canonical;
+ if($opt_D) {
+ $svn_dir =~ s#/*$#/#;
+ } else {
+ $svn_dir = "";
+ }
+ if ($svn_url->scheme eq "http") {
+ use LWP::UserAgent;
+ $lwp_ua = LWP::UserAgent->new(keep_alive => 1, requests_redirectable => []);
+ } else {
+ print STDERR "Warning: not HTTP; turning off direct file access\n";
+ $opt_d=0;
+ }
+}
+
+sub pdate($) {
+ my($d) = @_;
+ $d =~ m#(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)#
+ or die "Unparseable date: $d\n";
+ my $y=$1; $y-=1900 if $y>1900;
+ return timegm($6||0,$5,$4,$3,$2-1,$y);
+}
+
+sub getwd() {
+ my $pwd = `pwd`;
+ chomp $pwd;
+ return $pwd;
+}
+
+
+sub get_headref($$) {
+ my $name = shift;
+ my $git_dir = shift;
+ my $sha;
+
+ if (open(C,"$git_dir/refs/heads/$name")) {
+ chomp($sha = <C>);
+ close(C);
+ length($sha) == 40
+ or die "Cannot get head id for $name ($sha): $!\n";
+ }
+ return $sha;
+}
+
+
+-d $git_tree
+ or mkdir($git_tree,0777)
+ or die "Could not create $git_tree: $!";
+chdir($git_tree);
+
+my $orig_branch = "";
+my $forward_master = 0;
+my %branches;
+
+my $git_dir = $ENV{"GIT_DIR"} || ".git";
+$git_dir = getwd()."/".$git_dir unless $git_dir =~ m#^/#;
+$ENV{"GIT_DIR"} = $git_dir;
+my $orig_git_index;
+$orig_git_index = $ENV{GIT_INDEX_FILE} if exists $ENV{GIT_INDEX_FILE};
+my ($git_ih, $git_index) = tempfile('gitXXXXXX', SUFFIX => '.idx',
+ DIR => File::Spec->tmpdir());
+close ($git_ih);
+$ENV{GIT_INDEX_FILE} = $git_index;
+my $maxnum = 0;
+my $last_rev = "";
+my $last_branch;
+my $current_rev = $opt_s || 1;
+unless(-d $git_dir) {
+ system("git init");
+ die "Cannot init the GIT db at $git_tree: $?\n" if $?;
+ system("git read-tree");
+ die "Cannot init an empty tree: $?\n" if $?;
+
+ $last_branch = $opt_o;
+ $orig_branch = "";
+} else {
+ -f "$git_dir/refs/heads/$opt_o"
+ or die "Branch '$opt_o' does not exist.\n".
+ "Either use the correct '-o branch' option,\n".
+ "or import to a new repository.\n";
+
+ -f "$git_dir/svn2git"
+ or die "'$git_dir/svn2git' does not exist.\n".
+ "You need that file for incremental imports.\n";
+ open(F, "git symbolic-ref HEAD |") or
+ die "Cannot run git-symbolic-ref: $!\n";
+ chomp ($last_branch = <F>);
+ $last_branch = basename($last_branch);
+ close(F);
+ unless($last_branch) {
+ warn "Cannot read the last branch name: $! -- assuming 'master'\n";
+ $last_branch = "master";
+ }
+ $orig_branch = $last_branch;
+ $last_rev = get_headref($orig_branch, $git_dir);
+ if (-f "$git_dir/SVN2GIT_HEAD") {
+ die <<EOM;
+SVN2GIT_HEAD exists.
+Make sure your working directory corresponds to HEAD and remove SVN2GIT_HEAD.
+You may need to run
+
+ git-read-tree -m -u SVN2GIT_HEAD HEAD
+EOM
+ }
+ system('cp', "$git_dir/HEAD", "$git_dir/SVN2GIT_HEAD");
+
+ $forward_master =
+ $opt_o ne 'master' && -f "$git_dir/refs/heads/master" &&
+ system('cmp', '-s', "$git_dir/refs/heads/master",
+ "$git_dir/refs/heads/$opt_o") == 0;
+
+ # populate index
+ system('git', 'read-tree', $last_rev);
+ die "read-tree failed: $?\n" if $?;
+
+ # Get the last import timestamps
+ open my $B,"<", "$git_dir/svn2git";
+ while(<$B>) {
+ chomp;
+ my($num,$branch,$ref) = split;
+ $branches{$branch}{$num} = $ref;
+ $branches{$branch}{"LAST"} = $ref;
+ $current_rev = $num+1 if $current_rev <= $num;
+ }
+ close($B);
+}
+-d $git_dir
+ or die "Could not create git subdir ($git_dir).\n";
+
+my $default_authors = "$git_dir/svn-authors";
+if ($opt_A) {
+ read_users($opt_A);
+ copy($opt_A,$default_authors) or die "Copy failed: $!";
+} else {
+ read_users($default_authors) if -f $default_authors;
+}
+
+open BRANCHES,">>", "$git_dir/svn2git";
+
+sub node_kind($$) {
+ my ($svnpath, $revision) = @_;
+ $svnpath =~ s#^/*##;
+ my $subpool = SVN::Pool::new_default_sub;
+ my $kind = $svn->{'svn'}->check_path($svnpath,$revision);
+ return $kind;
+}
+
+sub get_file($$$) {
+ my($svnpath,$rev,$path) = @_;
+
+ # now get it
+ my ($name,$mode);
+ if($opt_d) {
+ my($req,$res);
+
+ # /svn/!svn/bc/2/django/trunk/django-docs/build.py
+ my $url=$svn_url->clone();
+ $url->path($url->path."/!svn/bc/$rev/$svn_dir$svnpath");
+ print "... $path...\n" if $opt_v;
+ $req = HTTP::Request->new(GET => $url);
+ $res = $lwp_ua->request($req);
+ if ($res->is_success) {
+ my $fh;
+ ($fh, $name) = tempfile('gitsvn.XXXXXX',
+ DIR => File::Spec->tmpdir(), UNLINK => 1);
+ print $fh $res->content;
+ close($fh) or die "Could not write $name: $!\n";
+ } else {
+ return undef if $res->code == 301; # directory?
+ die $res->status_line." at $url\n";
+ }
+ $mode = '0644'; # can't obtain mode via direct http request?
+ } else {
+ ($name,$mode) = $svn->file("$svnpath",$rev);
+ return undef unless defined $name;
+ }
+
+ my $pid = open(my $F, '-|');
+ die $! unless defined $pid;
+ if (!$pid) {
+ exec("git", "hash-object", "-w", $name)
+ or die "Cannot create object: $!\n";
+ }
+ my $sha = <$F>;
+ chomp $sha;
+ close $F;
+ unlink $name;
+ return [$mode, $sha, $path];
+}
+
+sub get_ignore($$$$$) {
+ my($new,$old,$rev,$path,$svnpath) = @_;
+
+ return unless $opt_I;
+ my $name = $svn->ignore("$svnpath",$rev);
+ if ($path eq '/') {
+ $path = $opt_I;
+ } else {
+ $path = File::Spec->catfile($path,$opt_I);
+ }
+ if (defined $name) {
+ my $pid = open(my $F, '-|');
+ die $! unless defined $pid;
+ if (!$pid) {
+ exec("git", "hash-object", "-w", $name)
+ or die "Cannot create object: $!\n";
+ }
+ my $sha = <$F>;
+ chomp $sha;
+ close $F;
+ unlink $name;
+ push(@$new,['0644',$sha,$path]);
+ } elsif (defined $old) {
+ push(@$old,$path);
+ }
+}
+
+sub project_path($$)
+{
+ my ($path, $project) = @_;
+
+ $path = "/".$path unless ($path =~ m#^\/#) ;
+ return $1 if ($path =~ m#^$project\/(.*)$#);
+
+ $path =~ s#\.#\\\.#g;
+ $path =~ s#\+#\\\+#g;
+ return "/" if ($project =~ m#^$path.*$#);
+
+ return undef;
+}
+
+sub split_path($$) {
+ my($rev,$path) = @_;
+ my $branch;
+
+ if($path =~ s#^/\Q$tag_name\E/([^/]+)/?##) {
+ $branch = "/$1";
+ } elsif($path =~ s#^/\Q$trunk_name\E/?##) {
+ $branch = "/";
+ } elsif($path =~ s#^/\Q$branch_name\E/([^/]+)/?##) {
+ $branch = $1;
+ } else {
+ my %no_error = (
+ "/" => 1,
+ "/$tag_name" => 1,
+ "/$branch_name" => 1
+ );
+ print STDERR "$rev: Unrecognized path: $path\n" unless (defined $no_error{$path});
+ return ()
+ }
+ if ($path eq "") {
+ $path = "/";
+ } elsif ($project_name) {
+ $path = project_path($path, $project_name);
+ }
+ return ($branch,$path);
+}
+
+sub branch_rev($$) {
+
+ my ($srcbranch,$uptorev) = @_;
+
+ my $bbranches = $branches{$srcbranch};
+ my @revs = reverse sort { ($a eq 'LAST' ? 0 : $a) <=> ($b eq 'LAST' ? 0 : $b) } keys %$bbranches;
+ my $therev;
+ foreach my $arev(@revs) {
+ next if ($arev eq 'LAST');
+ if ($arev <= $uptorev) {
+ $therev = $arev;
+ last;
+ }
+ }
+ return $therev;
+}
+
+sub expand_svndir($$$);
+
+sub expand_svndir($$$)
+{
+ my ($svnpath, $rev, $path) = @_;
+ my @list;
+ get_ignore(\@list, undef, $rev, $path, $svnpath);
+ my $dirents = $svn->dir_list($svnpath, $rev);
+ foreach my $p(keys %$dirents) {
+ my $kind = node_kind($svnpath.'/'.$p, $rev);
+ if ($kind eq $SVN::Node::file) {
+ my $f = get_file($svnpath.'/'.$p, $rev, $path.'/'.$p);
+ push(@list, $f) if $f;
+ } elsif ($kind eq $SVN::Node::dir) {
+ push(@list,
+ expand_svndir($svnpath.'/'.$p, $rev, $path.'/'.$p));
+ }
+ }
+ return @list;
+}
+
+sub copy_path($$$$$$$$) {
+ # Somebody copied a whole subdirectory.
+ # We need to find the index entries from the old version which the
+ # SVN log entry points to, and add them to the new place.
+
+ my($newrev,$newbranch,$path,$oldpath,$rev,$node_kind,$new,$parents) = @_;
+
+ my($srcbranch,$srcpath) = split_path($rev,$oldpath);
+ unless(defined $srcbranch && defined $srcpath) {
+ print "Path not found when copying from $oldpath @ $rev.\n".
+ "Will try to copy from original SVN location...\n"
+ if $opt_v;
+ push (@$new, expand_svndir($oldpath, $rev, $path));
+ return;
+ }
+ my $therev = branch_rev($srcbranch, $rev);
+ my $gitrev = $branches{$srcbranch}{$therev};
+ unless($gitrev) {
+ print STDERR "$newrev:$newbranch: could not find $oldpath \@ $rev\n";
+ return;
+ }
+ if ($srcbranch ne $newbranch) {
+ push(@$parents, $branches{$srcbranch}{'LAST'});
+ }
+ print "$newrev:$newbranch:$path: copying from $srcbranch:$srcpath @ $rev\n" if $opt_v;
+ if ($node_kind eq $SVN::Node::dir) {
+ $srcpath =~ s#/*$#/#;
+ }
+
+ my $pid = open my $f,'-|';
+ die $! unless defined $pid;
+ if (!$pid) {
+ exec("git","ls-tree","-r","-z",$gitrev,$srcpath)
+ or die $!;
+ }
+ local $/ = "\0";
+ while(<$f>) {
+ chomp;
+ my($m,$p) = split(/\t/,$_,2);
+ my($mode,$type,$sha1) = split(/ /,$m);
+ next if $type ne "blob";
+ if ($node_kind eq $SVN::Node::dir) {
+ $p = $path . substr($p,length($srcpath)-1);
+ } else {
+ $p = $path;
+ }
+ push(@$new,[$mode,$sha1,$p]);
+ }
+ close($f) or
+ print STDERR "$newrev:$newbranch: could not list files in $oldpath \@ $rev\n";
+}
+
+sub commit {
+ my($branch, $changed_paths, $revision, $author, $date, $message) = @_;
+ my($committer_name,$committer_email,$dest);
+ my($author_name,$author_email);
+ my(@old,@new,@parents);
+
+ if (not defined $author or $author eq "") {
+ $committer_name = $committer_email = "unknown";
+ } elsif (defined $users_file) {
+ die "User $author is not listed in $users_file\n"
+ unless exists $users{$author};
+ ($committer_name,$committer_email) = @{$users{$author}};
+ } elsif ($author =~ /^(.*?)\s+<(.*)>$/) {
+ ($committer_name, $committer_email) = ($1, $2);
+ } else {
+ $author =~ s/^<(.*)>$/$1/;
+ $committer_name = $committer_email = $author;
+ }
+
+ if ($opt_F && $message =~ /From:\s+(.*?)\s+<(.*)>\s*\n/) {
+ ($author_name, $author_email) = ($1, $2);
+ print "Author from From: $1 <$2>\n" if ($opt_v);;
+ } elsif ($opt_S && $message =~ /Signed-off-by:\s+(.*?)\s+<(.*)>\s*\n/) {
+ ($author_name, $author_email) = ($1, $2);
+ print "Author from Signed-off-by: $1 <$2>\n" if ($opt_v);;
+ } else {
+ $author_name = $committer_name;
+ $author_email = $committer_email;
+ }
+
+ $date = pdate($date);
+
+ my $tag;
+ my $parent;
+ if($branch eq "/") { # trunk
+ $parent = $opt_o;
+ } elsif($branch =~ m#^/(.+)#) { # tag
+ $tag = 1;
+ $parent = $1;
+ } else { # "normal" branch
+ # nothing to do
+ $parent = $branch;
+ }
+ $dest = $parent;
+
+ my $prev = $changed_paths->{"/"};
+ if($prev and $prev->[0] eq "A") {
+ delete $changed_paths->{"/"};
+ my $oldpath = $prev->[1];
+ my $rev;
+ if(defined $oldpath) {
+ my $p;
+ ($parent,$p) = split_path($revision,$oldpath);
+ if(defined $parent) {
+ if($parent eq "/") {
+ $parent = $opt_o;
+ } else {
+ $parent =~ s#^/##; # if it's a tag
+ }
+ }
+ } else {
+ $parent = undef;
+ }
+ }
+
+ my $rev;
+ if($revision > $opt_s and defined $parent) {
+ open(H,'-|',"git","rev-parse","--verify",$parent);
+ $rev = <H>;
+ close(H) or do {
+ print STDERR "$revision: cannot find commit '$parent'!\n";
+ return;
+ };
+ chop $rev;
+ if(length($rev) != 40) {
+ print STDERR "$revision: cannot find commit '$parent'!\n";
+ return;
+ }
+ $rev = $branches{($parent eq $opt_o) ? "/" : $parent}{"LAST"};
+ if($revision != $opt_s and not $rev) {
+ print STDERR "$revision: do not know ancestor for '$parent'!\n";
+ return;
+ }
+ } else {
+ $rev = undef;
+ }
+
+# if($prev and $prev->[0] eq "A") {
+# if(not $tag) {
+# unless(open(H,"> $git_dir/refs/heads/$branch")) {
+# print STDERR "$revision: Could not create branch $branch: $!\n";
+# $state=11;
+# next;
+# }
+# print H "$rev\n"
+# or die "Could not write branch $branch: $!";
+# close(H)
+# or die "Could not write branch $branch: $!";
+# }
+# }
+ if(not defined $rev) {
+ unlink($git_index);
+ } elsif ($rev ne $last_rev) {
+ print "Switching from $last_rev to $rev ($branch)\n" if $opt_v;
+ system("git", "read-tree", $rev);
+ die "read-tree failed for $rev: $?\n" if $?;
+ $last_rev = $rev;
+ }
+
+ push (@parents, $rev) if defined $rev;
+
+ my $cid;
+ if($tag and not %$changed_paths) {
+ $cid = $rev;
+ } else {
+ my @paths = sort keys %$changed_paths;
+ foreach my $path(@paths) {
+ my $action = $changed_paths->{$path};
+
+ if ($action->[0] eq "R") {
+ # refer to a file/tree in an earlier commit
+ push(@old,$path); # remove any old stuff
+ }
+ if(($action->[0] eq "A") || ($action->[0] eq "R")) {
+ my $node_kind = node_kind($action->[3], $revision);
+ if ($node_kind eq $SVN::Node::file) {
+ my $f = get_file($action->[3],
+ $revision, $path);
+ if ($f) {
+ push(@new,$f) if $f;
+ } else {
+ my $opath = $action->[3];
+ print STDERR "$revision: $branch: could not fetch '$opath'\n";
+ }
+ } elsif ($node_kind eq $SVN::Node::dir) {
+ if($action->[1]) {
+ copy_path($revision, $branch,
+ $path, $action->[1],
+ $action->[2], $node_kind,
+ \@new, \@parents);
+ } else {
+ get_ignore(\@new, \@old, $revision,
+ $path, $action->[3]);
+ }
+ }
+ } elsif ($action->[0] eq "D") {
+ push(@old,$path);
+ } elsif ($action->[0] eq "M") {
+ my $node_kind = node_kind($action->[3], $revision);
+ if ($node_kind eq $SVN::Node::file) {
+ my $f = get_file($action->[3],
+ $revision, $path);
+ push(@new,$f) if $f;
+ } elsif ($node_kind eq $SVN::Node::dir) {
+ get_ignore(\@new, \@old, $revision,
+ $path, $action->[3]);
+ }
+ } else {
+ die "$revision: unknown action '".$action->[0]."' for $path\n";
+ }
+ }
+
+ while(@old) {
+ my @o1;
+ if(@old > 55) {
+ @o1 = splice(@old,0,50);
+ } else {
+ @o1 = @old;
+ @old = ();
+ }
+ my $pid = open my $F, "-|";
+ die "$!" unless defined $pid;
+ if (!$pid) {
+ exec("git", "ls-files", "-z", @o1) or die $!;
+ }
+ @o1 = ();
+ local $/ = "\0";
+ while(<$F>) {
+ chomp;
+ push(@o1,$_);
+ }
+ close($F);
+
+ while(@o1) {
+ my @o2;
+ if(@o1 > 55) {
+ @o2 = splice(@o1,0,50);
+ } else {
+ @o2 = @o1;
+ @o1 = ();
+ }
+ system("git","update-index","--force-remove","--",@o2);
+ die "Cannot remove files: $?\n" if $?;
+ }
+ }
+ while(@new) {
+ my @n2;
+ if(@new > 12) {
+ @n2 = splice(@new,0,10);
+ } else {
+ @n2 = @new;
+ @new = ();
+ }
+ system("git","update-index","--add",
+ (map { ('--cacheinfo', @$_) } @n2));
+ die "Cannot add files: $?\n" if $?;
+ }
+
+ my $pid = open(C,"-|");
+ die "Cannot fork: $!" unless defined $pid;
+ unless($pid) {
+ exec("git","write-tree");
+ die "Cannot exec git-write-tree: $!\n";
+ }
+ chomp(my $tree = <C>);
+ length($tree) == 40
+ or die "Cannot get tree id ($tree): $!\n";
+ close(C)
+ or die "Error running git-write-tree: $?\n";
+ print "Tree ID $tree\n" if $opt_v;
+
+ my $pr = IO::Pipe->new() or die "Cannot open pipe: $!\n";
+ my $pw = IO::Pipe->new() or die "Cannot open pipe: $!\n";
+ $pid = fork();
+ die "Fork: $!\n" unless defined $pid;
+ unless($pid) {
+ $pr->writer();
+ $pw->reader();
+ open(OUT,">&STDOUT");
+ dup2($pw->fileno(),0);
+ dup2($pr->fileno(),1);
+ $pr->close();
+ $pw->close();
+
+ my @par = ();
+
+ # loose detection of merges
+ # based on the commit msg
+ foreach my $rx (@mergerx) {
+ if ($message =~ $rx) {
+ my $mparent = $1;
+ if ($mparent eq 'HEAD') { $mparent = $opt_o };
+ if ( -e "$git_dir/refs/heads/$mparent") {
+ $mparent = get_headref($mparent, $git_dir);
+ push (@parents, $mparent);
+ print OUT "Merge parent branch: $mparent\n" if $opt_v;
+ }
+ }
+ }
+ my %seen_parents = ();
+ my @unique_parents = grep { ! $seen_parents{$_} ++ } @parents;
+ foreach my $bparent (@unique_parents) {
+ push @par, '-p', $bparent;
+ print OUT "Merge parent branch: $bparent\n" if $opt_v;
+ }
+
+ exec("env",
+ "GIT_AUTHOR_NAME=$author_name",
+ "GIT_AUTHOR_EMAIL=$author_email",
+ "GIT_AUTHOR_DATE=".strftime("+0000 %Y-%m-%d %H:%M:%S",gmtime($date)),
+ "GIT_COMMITTER_NAME=$committer_name",
+ "GIT_COMMITTER_EMAIL=$committer_email",
+ "GIT_COMMITTER_DATE=".strftime("+0000 %Y-%m-%d %H:%M:%S",gmtime($date)),
+ "git", "commit-tree", $tree,@par);
+ die "Cannot exec git-commit-tree: $!\n";
+ }
+ $pw->writer();
+ $pr->reader();
+
+ $message =~ s/[\s\n]+\z//;
+ $message = "r$revision: $message" if $opt_r;
+
+ print $pw "$message\n"
+ or die "Error writing to git-commit-tree: $!\n";
+ $pw->close();
+
+ print "Committed change $revision:$branch ".strftime("%Y-%m-%d %H:%M:%S",gmtime($date)).")\n" if $opt_v;
+ chomp($cid = <$pr>);
+ length($cid) == 40
+ or die "Cannot get commit id ($cid): $!\n";
+ print "Commit ID $cid\n" if $opt_v;
+ $pr->close();
+
+ waitpid($pid,0);
+ die "Error running git-commit-tree: $?\n" if $?;
+ }
+
+ if (not defined $cid) {
+ $cid = $branches{"/"}{"LAST"};
+ }
+
+ if(not defined $dest) {
+ print "... no known parent\n" if $opt_v;
+ } elsif(not $tag) {
+ print "Writing to refs/heads/$dest\n" if $opt_v;
+ open(C,">$git_dir/refs/heads/$dest") and
+ print C ("$cid\n") and
+ close(C)
+ or die "Cannot write branch $dest for update: $!\n";
+ }
+
+ if ($tag) {
+ $last_rev = "-" if %$changed_paths;
+ # the tag was 'complex', i.e. did not refer to a "real" revision
+
+ $dest =~ tr/_/\./ if $opt_u;
+
+ system('git', 'tag', '-f', $dest, $cid) == 0
+ or die "Cannot create tag $dest: $!\n";
+
+ print "Created tag '$dest' on '$branch'\n" if $opt_v;
+ }
+ $branches{$branch}{"LAST"} = $cid;
+ $branches{$branch}{$revision} = $cid;
+ $last_rev = $cid;
+ print BRANCHES "$revision $branch $cid\n";
+ print "DONE: $revision $dest $cid\n" if $opt_v;
+}
+
+sub commit_all {
+ # Recursive use of the SVN connection does not work
+ local $svn = $svn2;
+
+ my ($changed_paths, $revision, $author, $date, $message) = @_;
+ my %p;
+ while(my($path,$action) = each %$changed_paths) {
+ $p{$path} = [ $action->action,$action->copyfrom_path, $action->copyfrom_rev, $path ];
+ }
+ $changed_paths = \%p;
+
+ my %done;
+ my @col;
+ my $pref;
+ my $branch;
+
+ while(my($path,$action) = each %$changed_paths) {
+ ($branch,$path) = split_path($revision,$path);
+ next if not defined $branch;
+ next if not defined $path;
+ $done{$branch}{$path} = $action;
+ }
+ while(($branch,$changed_paths) = each %done) {
+ commit($branch, $changed_paths, $revision, $author, $date, $message);
+ }
+}
+
+$opt_l = $svn->{'maxrev'} if not defined $opt_l or $opt_l > $svn->{'maxrev'};
+
+if ($opt_l < $current_rev) {
+ print "Up to date: no new revisions to fetch!\n" if $opt_v;
+ unlink("$git_dir/SVN2GIT_HEAD");
+ exit;
+}
+
+print "Processing from $current_rev to $opt_l ...\n" if $opt_v;
+
+my $from_rev;
+my $to_rev = $current_rev - 1;
+
+my $subpool = SVN::Pool::new_default_sub;
+while ($to_rev < $opt_l) {
+ $subpool->clear;
+ $from_rev = $to_rev + 1;
+ $to_rev = $from_rev + $repack_after;
+ $to_rev = $opt_l if $opt_l < $to_rev;
+ print "Fetching from $from_rev to $to_rev ...\n" if $opt_v;
+ $svn->{'svn'}->get_log("",$from_rev,$to_rev,0,1,1,\&commit_all);
+ my $pid = fork();
+ die "Fork: $!\n" unless defined $pid;
+ unless($pid) {
+ exec("git", "repack", "-d")
+ or die "Cannot repack: $!\n";
+ }
+ waitpid($pid, 0);
+}
+
+
+unlink($git_index);
+
+if (defined $orig_git_index) {
+ $ENV{GIT_INDEX_FILE} = $orig_git_index;
+} else {
+ delete $ENV{GIT_INDEX_FILE};
+}
+
+# Now switch back to the branch we were in before all of this happened
+if($orig_branch) {
+ print "DONE\n" if $opt_v and (not defined $opt_l or $opt_l > 0);
+ system("cp","$git_dir/refs/heads/$opt_o","$git_dir/refs/heads/master")
+ if $forward_master;
+ unless ($opt_i) {
+ system('git', 'read-tree', '-m', '-u', 'SVN2GIT_HEAD', 'HEAD');
+ die "read-tree failed: $?\n" if $?;
+ }
+} else {
+ $orig_branch = "master";
+ print "DONE; creating $orig_branch branch\n" if $opt_v and (not defined $opt_l or $opt_l > 0);
+ system("cp","$git_dir/refs/heads/$opt_o","$git_dir/refs/heads/master")
+ unless -f "$git_dir/refs/heads/master";
+ system('git', 'update-ref', 'HEAD', "$orig_branch");
+ unless ($opt_i) {
+ system('git checkout');
+ die "checkout failed: $?\n" if $?;
+ }
+}
+unlink("$git_dir/SVN2GIT_HEAD");
+close(BRANCHES);
diff --git a/contrib/examples/git-svnimport.txt b/contrib/examples/git-svnimport.txt
new file mode 100644
index 0000000000..3bb871e42f
--- /dev/null
+++ b/contrib/examples/git-svnimport.txt
@@ -0,0 +1,179 @@
+git-svnimport(1)
+================
+v0.1, July 2005
+
+NAME
+----
+git-svnimport - Import a SVN repository into git
+
+
+SYNOPSIS
+--------
+[verse]
+'git-svnimport' [ -o <branch-for-HEAD> ] [ -h ] [ -v ] [ -d | -D ]
+ [ -C <GIT_repository> ] [ -i ] [ -u ] [-l limit_rev]
+ [ -b branch_subdir ] [ -T trunk_subdir ] [ -t tag_subdir ]
+ [ -s start_chg ] [ -m ] [ -r ] [ -M regex ]
+ [ -I <ignorefile_name> ] [ -A <author_file> ]
+ [ -R <repack_each_revs>] [ -P <path_from_trunk> ]
+ <SVN_repository_URL> [ <path> ]
+
+
+DESCRIPTION
+-----------
+Imports a SVN repository into git. It will either create a new
+repository, or incrementally import into an existing one.
+
+SVN access is done by the SVN::Perl module.
+
+git-svnimport assumes that SVN repositories are organized into one
+"trunk" directory where the main development happens, "branches/FOO"
+directories for branches, and "/tags/FOO" directories for tags.
+Other subdirectories are ignored.
+
+git-svnimport creates a file ".git/svn2git", which is required for
+incremental SVN imports.
+
+OPTIONS
+-------
+-C <target-dir>::
+ The GIT repository to import to. If the directory doesn't
+ exist, it will be created. Default is the current directory.
+
+-s <start_rev>::
+ Start importing at this SVN change number. The default is 1.
++
+When importing incrementally, you might need to edit the .git/svn2git file.
+
+-i::
+ Import-only: don't perform a checkout after importing. This option
+ ensures the working directory and index remain untouched and will
+ not create them if they do not exist.
+
+-T <trunk_subdir>::
+ Name the SVN trunk. Default "trunk".
+
+-t <tag_subdir>::
+ Name the SVN subdirectory for tags. Default "tags".
+
+-b <branch_subdir>::
+ Name the SVN subdirectory for branches. Default "branches".
+
+-o <branch-for-HEAD>::
+ The 'trunk' branch from SVN is imported to the 'origin' branch within
+ the git repository. Use this option if you want to import into a
+ different branch.
+
+-r::
+ Prepend 'rX: ' to commit messages, where X is the imported
+ subversion revision.
+
+-u::
+ Replace underscores in tag names with periods.
+
+-I <ignorefile_name>::
+ Import the svn:ignore directory property to files with this
+ name in each directory. (The Subversion and GIT ignore
+ syntaxes are similar enough that using the Subversion patterns
+ directly with "-I .gitignore" will almost always just work.)
+
+-A <author_file>::
+ Read a file with lines on the form
++
+------
+ username = User's Full Name <email@addr.es>
+
+------
++
+and use "User's Full Name <email@addr.es>" as the GIT
+author and committer for Subversion commits made by
+"username". If encountering a commit made by a user not in the
+list, abort.
++
+For convenience, this data is saved to $GIT_DIR/svn-authors
+each time the -A option is provided, and read from that same
+file each time git-svnimport is run with an existing GIT
+repository without -A.
+
+-m::
+ Attempt to detect merges based on the commit message. This option
+ will enable default regexes that try to capture the name source
+ branch name from the commit message.
+
+-M <regex>::
+ Attempt to detect merges based on the commit message with a custom
+ regex. It can be used with -m to also see the default regexes.
+ You must escape forward slashes.
+
+-l <max_rev>::
+ Specify a maximum revision number to pull.
++
+Formerly, this option controlled how many revisions to pull,
+due to SVN memory leaks. (These have been worked around.)
+
+-R <repack_each_revs>::
+ Specify how often git repository should be repacked.
++
+The default value is 1000. git-svnimport will do imports in chunks of 1000
+revisions, after each chunk the git repository will be repacked. To disable
+this behavior specify some large value here which is greater than the number of
+revisions to import.
+
+-P <path_from_trunk>::
+ Partial import of the SVN tree.
++
+By default, the whole tree on the SVN trunk (/trunk) is imported.
+'-P my/proj' will import starting only from '/trunk/my/proj'.
+This option is useful when you want to import one project from a
+svn repo which hosts multiple projects under the same trunk.
+
+-v::
+ Verbosity: let 'svnimport' report what it is doing.
+
+-d::
+ Use direct HTTP requests if possible. The "<path>" argument is used
+ only for retrieving the SVN logs; the path to the contents is
+ included in the SVN log.
+
+-D::
+ Use direct HTTP requests if possible. The "<path>" argument is used
+ for retrieving the logs, as well as for the contents.
++
+There's no safe way to automatically find out which of these options to
+use, so you need to try both. Usually, the one that's wrong will die
+with a 40x error pretty quickly.
+
+<SVN_repository_URL>::
+ The URL of the SVN module you want to import. For local
+ repositories, use "file:///absolute/path".
++
+If you're using the "-d" or "-D" option, this is the URL of the SVN
+repository itself; it usually ends in "/svn".
+
+<path>::
+ The path to the module you want to check out.
+
+-h::
+ Print a short usage message and exit.
+
+OUTPUT
+------
+If '-v' is specified, the script reports what it is doing.
+
+Otherwise, success is indicated the Unix way, i.e. by simply exiting with
+a zero exit status.
+
+Author
+------
+Written by Matthias Urlichs <smurf@smurf.noris.de>, with help from
+various participants of the git-list <git@vger.kernel.org>.
+
+Based on a cvs2git script by the same author.
+
+Documentation
+--------------
+Documentation by Matthias Urlichs <smurf@smurf.noris.de>.
+
+GIT
+---
+Part of the gitlink:git[7] suite
diff --git a/contrib/examples/git-tag.sh b/contrib/examples/git-tag.sh
index 5ee3f50a3c..2c15bc955b 100755
--- a/contrib/examples/git-tag.sh
+++ b/contrib/examples/git-tag.sh
@@ -14,7 +14,7 @@ username=
list=
verify=
LINES=0
-while case "$#" in 0) break ;; esac
+while test $# != 0
do
case "$1" in
-a)
@@ -164,10 +164,10 @@ git check-ref-format "tags/$name" ||
object=$(git rev-parse --verify --default HEAD "$@") || exit 1
type=$(git cat-file -t $object) || exit 1
-tagger=$(git-var GIT_COMMITTER_IDENT) || exit 1
+tagger=$(git var GIT_COMMITTER_IDENT) || exit 1
test -n "$username" ||
- username=$(git repo-config user.signingkey) ||
+ username=$(git config user.signingkey) ||
username=$(expr "z$tagger" : 'z\(.*>\)')
trap 'rm -f "$GIT_DIR"/TAG_TMP* "$GIT_DIR"/TAG_FINALMSG "$GIT_DIR"/TAG_EDITMSG' 0
diff --git a/contrib/examples/git-verify-tag.sh b/contrib/examples/git-verify-tag.sh
index 37b0023b27..0902a5c21a 100755
--- a/contrib/examples/git-verify-tag.sh
+++ b/contrib/examples/git-verify-tag.sh
@@ -5,7 +5,7 @@ SUBDIRECTORY_OK='Yes'
. git-sh-setup
verbose=
-while case $# in 0) break;; esac
+while test $# != 0
do
case "$1" in
-v|--v|--ve|--ver|--verb|--verbo|--verbos|--verbose)
diff --git a/contrib/fast-import/git-import.perl b/contrib/fast-import/git-import.perl
new file mode 100755
index 0000000000..f9fef6db28
--- /dev/null
+++ b/contrib/fast-import/git-import.perl
@@ -0,0 +1,64 @@
+#!/usr/bin/perl
+#
+# Performs an initial import of a directory. This is the equivalent
+# of doing 'git init; git add .; git commit'. It's a little slower,
+# but is meant to be a simple fast-import example.
+
+use strict;
+use File::Find;
+
+my $USAGE = 'Usage: git-import branch import-message';
+my $branch = shift or die "$USAGE\n";
+my $message = shift or die "$USAGE\n";
+
+chomp(my $username = `git config user.name`);
+chomp(my $email = `git config user.email`);
+die 'You need to set user name and email'
+ unless $username && $email;
+
+system('git init');
+open(my $fi, '|-', qw(git fast-import --date-format=now))
+ or die "unable to spawn fast-import: $!";
+
+print $fi <<EOF;
+commit refs/heads/$branch
+committer $username <$email> now
+data <<MSGEOF
+$message
+MSGEOF
+
+EOF
+
+find(
+ sub {
+ if($File::Find::name eq './.git') {
+ $File::Find::prune = 1;
+ return;
+ }
+ return unless -f $_;
+
+ my $fn = $File::Find::name;
+ $fn =~ s#^.\/##;
+
+ open(my $in, '<', $_)
+ or die "unable to open $fn: $!";
+ my @st = stat($in)
+ or die "unable to stat $fn: $!";
+ my $len = $st[7];
+
+ print $fi "M 644 inline $fn\n";
+ print $fi "data $len\n";
+ while($len > 0) {
+ my $r = read($in, my $buf, $len < 4096 ? $len : 4096);
+ defined($r) or die "read error from $fn: $!";
+ $r > 0 or die "premature EOF from $fn: $!";
+ print $fi $buf;
+ $len -= $r;
+ }
+ print $fi "\n";
+
+ }, '.'
+);
+
+close($fi);
+exit $?;
diff --git a/contrib/fast-import/git-import.sh b/contrib/fast-import/git-import.sh
new file mode 100755
index 0000000000..0ca7718d05
--- /dev/null
+++ b/contrib/fast-import/git-import.sh
@@ -0,0 +1,38 @@
+#!/bin/sh
+#
+# Performs an initial import of a directory. This is the equivalent
+# of doing 'git init; git add .; git commit'. It's a lot slower,
+# but is meant to be a simple fast-import example.
+
+if [ -z "$1" -o -z "$2" ]; then
+ echo "Usage: git-import branch import-message"
+ exit 1
+fi
+
+USERNAME="$(git config user.name)"
+EMAIL="$(git config user.email)"
+
+if [ -z "$USERNAME" -o -z "$EMAIL" ]; then
+ echo "You need to set user name and email"
+ exit 1
+fi
+
+git init
+
+(
+ cat <<EOF
+commit refs/heads/$1
+committer $USERNAME <$EMAIL> now
+data <<MSGEOF
+$2
+MSGEOF
+
+EOF
+ find * -type f|while read i;do
+ echo "M 100644 inline $i"
+ echo data $(stat -c '%s' "$i")
+ cat "$i"
+ echo
+ done
+ echo
+) | git fast-import --date-format=now
diff --git a/contrib/fast-import/git-p4 b/contrib/fast-import/git-p4
index adaaae6633..342529db30 100755
--- a/contrib/fast-import/git-p4
+++ b/contrib/fast-import/git-p4
@@ -16,6 +16,46 @@ from sets import Set;
verbose = False
+
+def p4_build_cmd(cmd):
+ """Build a suitable p4 command line.
+
+ This consolidates building and returning a p4 command line into one
+ location. It means that hooking into the environment, or other configuration
+ can be done more easily.
+ """
+ real_cmd = "%s " % "p4"
+
+ user = gitConfig("git-p4.user")
+ if len(user) > 0:
+ real_cmd += "-u %s " % user
+
+ password = gitConfig("git-p4.password")
+ if len(password) > 0:
+ real_cmd += "-P %s " % password
+
+ port = gitConfig("git-p4.port")
+ if len(port) > 0:
+ real_cmd += "-p %s " % port
+
+ host = gitConfig("git-p4.host")
+ if len(host) > 0:
+ real_cmd += "-h %s " % host
+
+ client = gitConfig("git-p4.client")
+ if len(client) > 0:
+ real_cmd += "-c %s " % client
+
+ real_cmd += "%s" % (cmd)
+ if verbose:
+ print real_cmd
+ return real_cmd
+
+def chdir(dir):
+ if os.name == 'nt':
+ os.environ['PWD']=dir
+ os.chdir(dir)
+
def die(msg):
if verbose:
raise Exception(msg)
@@ -34,6 +74,10 @@ def write_pipe(c, str):
return val
+def p4_write_pipe(c, str):
+ real_cmd = p4_build_cmd(c)
+ return write_pipe(real_cmd, str)
+
def read_pipe(c, ignore_error=False):
if verbose:
sys.stderr.write('Reading pipe: %s\n' % c)
@@ -45,6 +89,9 @@ def read_pipe(c, ignore_error=False):
return val
+def p4_read_pipe(c, ignore_error=False):
+ real_cmd = p4_build_cmd(c)
+ return read_pipe(real_cmd, ignore_error)
def read_pipe_lines(c):
if verbose:
@@ -57,14 +104,105 @@ def read_pipe_lines(c):
return val
+def p4_read_pipe_lines(c):
+ """Specifically invoke p4 on the command supplied. """
+ real_cmd = p4_build_cmd(c)
+ return read_pipe_lines(real_cmd)
+
def system(cmd):
if verbose:
sys.stderr.write("executing %s\n" % cmd)
if os.system(cmd) != 0:
die("command failed: %s" % cmd)
+def p4_system(cmd):
+ """Specifically invoke p4 as the system command. """
+ real_cmd = p4_build_cmd(cmd)
+ return system(real_cmd)
+
+def isP4Exec(kind):
+ """Determine if a Perforce 'kind' should have execute permission
+
+ 'p4 help filetypes' gives a list of the types. If it starts with 'x',
+ or x follows one of a few letters. Otherwise, if there is an 'x' after
+ a plus sign, it is also executable"""
+ return (re.search(r"(^[cku]?x)|\+.*x", kind) != None)
+
+def setP4ExecBit(file, mode):
+ # Reopens an already open file and changes the execute bit to match
+ # the execute bit setting in the passed in mode.
+
+ p4Type = "+x"
+
+ if not isModeExec(mode):
+ p4Type = getP4OpenedType(file)
+ p4Type = re.sub('^([cku]?)x(.*)', '\\1\\2', p4Type)
+ p4Type = re.sub('(.*?\+.*?)x(.*?)', '\\1\\2', p4Type)
+ if p4Type[-1] == "+":
+ p4Type = p4Type[0:-1]
+
+ p4_system("reopen -t %s %s" % (p4Type, file))
+
+def getP4OpenedType(file):
+ # Returns the perforce file type for the given file.
+
+ result = p4_read_pipe("opened %s" % file)
+ match = re.match(".*\((.+)\)\r?$", result)
+ if match:
+ return match.group(1)
+ else:
+ die("Could not determine file type for %s (result: '%s')" % (file, result))
+
+def diffTreePattern():
+ # This is a simple generator for the diff tree regex pattern. This could be
+ # a class variable if this and parseDiffTreeEntry were a part of a class.
+ pattern = re.compile(':(\d+) (\d+) (\w+) (\w+) ([A-Z])(\d+)?\t(.*?)((\t(.*))|$)')
+ while True:
+ yield pattern
+
+def parseDiffTreeEntry(entry):
+ """Parses a single diff tree entry into its component elements.
+
+ See git-diff-tree(1) manpage for details about the format of the diff
+ output. This method returns a dictionary with the following elements:
+
+ src_mode - The mode of the source file
+ dst_mode - The mode of the destination file
+ src_sha1 - The sha1 for the source file
+ dst_sha1 - The sha1 fr the destination file
+ status - The one letter status of the diff (i.e. 'A', 'M', 'D', etc)
+ status_score - The score for the status (applicable for 'C' and 'R'
+ statuses). This is None if there is no score.
+ src - The path for the source file.
+ dst - The path for the destination file. This is only present for
+ copy or renames. If it is not present, this is None.
+
+ If the pattern is not matched, None is returned."""
+
+ match = diffTreePattern().next().match(entry)
+ if match:
+ return {
+ 'src_mode': match.group(1),
+ 'dst_mode': match.group(2),
+ 'src_sha1': match.group(3),
+ 'dst_sha1': match.group(4),
+ 'status': match.group(5),
+ 'status_score': match.group(6),
+ 'src': match.group(7),
+ 'dst': match.group(10)
+ }
+ return None
+
+def isModeExec(mode):
+ # Returns True if the given git mode represents an executable file,
+ # otherwise False.
+ return mode[-3:] == "755"
+
+def isModeExecChanged(src_mode, dst_mode):
+ return isModeExec(src_mode) != isModeExec(dst_mode)
+
def p4CmdList(cmd, stdin=None, stdin_mode='w+b'):
- cmd = "p4 -G %s" % cmd
+ cmd = p4_build_cmd("-G %s" % (cmd))
if verbose:
sys.stderr.write("Opening pipe: %s\n" % cmd)
@@ -107,7 +245,22 @@ def p4Cmd(cmd):
def p4Where(depotPath):
if not depotPath.endswith("/"):
depotPath += "/"
- output = p4Cmd("where %s..." % depotPath)
+ depotPath = depotPath + "..."
+ outputList = p4CmdList("where %s" % depotPath)
+ output = None
+ for entry in outputList:
+ if "depotFile" in entry:
+ if entry["depotFile"] == depotPath:
+ output = entry
+ break
+ elif "data" in entry:
+ data = entry.get("data")
+ space = data.find(" ")
+ if data[:space] == depotPath:
+ output = entry
+ break
+ if output == None:
+ return ""
if output["code"] == "error":
return ""
clientPath = ""
@@ -178,8 +331,11 @@ def gitBranchExists(branch):
stderr=subprocess.PIPE, stdout=subprocess.PIPE);
return proc.wait() == 0;
+_gitConfig = {}
def gitConfig(key):
- return read_pipe("git config %s" % key, ignore_error=True).strip()
+ if not _gitConfig.has_key(key):
+ _gitConfig[key] = read_pipe("git config %s" % key, ignore_error=True).strip()
+ return _gitConfig[key]
def p4BranchesInGit(branchesAreInRemotes = True):
branches = {}
@@ -283,16 +439,17 @@ def originP4BranchesExist():
def p4ChangesForPaths(depotPaths, changeRange):
assert depotPaths
- output = read_pipe_lines("p4 changes " + ' '.join (["%s...%s" % (p, changeRange)
+ output = p4_read_pipe_lines("changes " + ' '.join (["%s...%s" % (p, changeRange)
for p in depotPaths]))
- changes = []
+ changes = {}
for line in output:
- changeNum = line.split(" ")[1]
- changes.append(int(changeNum))
+ changeNum = int(line.split(" ")[1])
+ changes[changeNum] = True
- changes.sort()
- return changes
+ changelist = changes.keys()
+ changelist.sort()
+ return changelist
class Command:
def __init__(self):
@@ -383,73 +540,47 @@ class P4Submit(Command):
def __init__(self):
Command.__init__(self)
self.options = [
- optparse.make_option("--continue", action="store_false", dest="firstTime"),
optparse.make_option("--verbose", dest="verbose", action="store_true"),
optparse.make_option("--origin", dest="origin"),
- optparse.make_option("--reset", action="store_true", dest="reset"),
- optparse.make_option("--log-substitutions", dest="substFile"),
- optparse.make_option("--dry-run", action="store_true"),
- optparse.make_option("--direct", dest="directSubmit", action="store_true"),
- optparse.make_option("--trust-me-like-a-fool", dest="trustMeLikeAFool", action="store_true"),
+ optparse.make_option("-M", dest="detectRename", action="store_true"),
]
self.description = "Submit changes from git to the perforce depot."
self.usage += " [name of git branch to submit into perforce depot]"
- self.firstTime = True
- self.reset = False
self.interactive = True
- self.dryRun = False
- self.substFile = ""
- self.firstTime = True
self.origin = ""
- self.directSubmit = False
- self.trustMeLikeAFool = False
+ self.detectRename = False
self.verbose = False
self.isWindows = (platform.system() == "Windows")
- self.logSubstitutions = {}
- self.logSubstitutions["<enter description here>"] = "%log%"
- self.logSubstitutions["\tDetails:"] = "\tDetails: %log%"
-
def check(self):
if len(p4CmdList("opened ...")) > 0:
die("You have files opened with perforce! Close them before starting the sync.")
- def start(self):
- if len(self.config) > 0 and not self.reset:
- die("Cannot start sync. Previous sync config found at %s\n"
- "If you want to start submitting again from scratch "
- "maybe you want to call git-p4 submit --reset" % self.configFile)
-
- commits = []
- if self.directSubmit:
- commits.append("0")
- else:
- for line in read_pipe_lines("git rev-list --no-merges %s..%s" % (self.origin, self.master)):
- commits.append(line.strip())
- commits.reverse()
-
- self.config["commits"] = commits
-
+ # replaces everything between 'Description:' and the next P4 submit template field with the
+ # commit message
def prepareLogMessage(self, template, message):
result = ""
+ inDescriptionSection = False
+
for line in template.split("\n"):
if line.startswith("#"):
result += line + "\n"
continue
- substituted = False
- for key in self.logSubstitutions.keys():
- if line.find(key) != -1:
- value = self.logSubstitutions[key]
- value = value.replace("%log%", message)
- if value != "@remove@":
- result += line.replace(key, value) + "\n"
- substituted = True
- break
+ if inDescriptionSection:
+ if line.startswith("Files:"):
+ inDescriptionSection = False
+ else:
+ continue
+ else:
+ if line.startswith("Description:"):
+ inDescriptionSection = True
+ line += "\n"
+ for messageLine in message.split("\n"):
+ line += "\t" + messageLine + "\n"
- if not substituted:
- result += line + "\n"
+ result += line + "\n"
return result
@@ -457,7 +588,9 @@ class P4Submit(Command):
# remove lines in the Files section that show changes to files outside the depot path we're committing into
template = ""
inFilesSection = False
- for line in read_pipe_lines("p4 change -o"):
+ for line in p4_read_pipe_lines("change -o"):
+ if line.endswith("\r\n"):
+ line = line[:-2] + "\n"
if inFilesSection:
if line.startswith("\t"):
# path starts and ends with a tab
@@ -478,36 +611,44 @@ class P4Submit(Command):
return template
def applyCommit(self, id):
- if self.directSubmit:
- print "Applying local change in working directory/index"
- diff = self.diffStatus
- else:
- print "Applying %s" % (read_pipe("git log --max-count=1 --pretty=oneline %s" % id))
- diff = read_pipe_lines("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id))
+ print "Applying %s" % (read_pipe("git log --max-count=1 --pretty=oneline %s" % id))
+ diffOpts = ("", "-M")[self.detectRename]
+ diff = read_pipe_lines("git diff-tree -r %s \"%s^\" \"%s\"" % (diffOpts, id, id))
filesToAdd = set()
filesToDelete = set()
editedFiles = set()
+ filesToChangeExecBit = {}
for line in diff:
- modifier = line[0]
- path = line[1:].strip()
+ diff = parseDiffTreeEntry(line)
+ modifier = diff['status']
+ path = diff['src']
if modifier == "M":
- system("p4 edit \"%s\"" % path)
+ p4_system("edit \"%s\"" % path)
+ if isModeExecChanged(diff['src_mode'], diff['dst_mode']):
+ filesToChangeExecBit[path] = diff['dst_mode']
editedFiles.add(path)
elif modifier == "A":
filesToAdd.add(path)
+ filesToChangeExecBit[path] = diff['dst_mode']
if path in filesToDelete:
filesToDelete.remove(path)
elif modifier == "D":
filesToDelete.add(path)
if path in filesToAdd:
filesToAdd.remove(path)
+ elif modifier == "R":
+ src, dest = diff['src'], diff['dst']
+ p4_system("integrate -Dt \"%s\" \"%s\"" % (src, dest))
+ p4_system("edit \"%s\"" % (dest))
+ if isModeExecChanged(diff['src_mode'], diff['dst_mode']):
+ filesToChangeExecBit[dest] = diff['dst_mode']
+ os.unlink(dest)
+ editedFiles.add(dest)
+ filesToDelete.add(src)
else:
die("unknown modifier %s for %s" % (modifier, path))
- if self.directSubmit:
- diffcmd = "cat \"%s\"" % self.diffFile
- else:
- diffcmd = "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
+ diffcmd = "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
patchcmd = diffcmd + " | git apply "
tryPatchCmd = patchcmd + "--check -"
applyPatchCmd = patchcmd + "--check --apply -"
@@ -521,6 +662,10 @@ class P4Submit(Command):
"and with .rej files / [w]rite the patch to a file (patch.txt) ")
if response == "s":
print "Skipping! Good luck with the next patches..."
+ for f in editedFiles:
+ p4_system("revert \"%s\"" % f);
+ for f in filesToAdd:
+ system("rm %s" %f)
return
elif response == "a":
os.system(applyPatchCmd)
@@ -541,90 +686,79 @@ class P4Submit(Command):
system(applyPatchCmd)
for f in filesToAdd:
- system("p4 add \"%s\"" % f)
+ p4_system("add \"%s\"" % f)
for f in filesToDelete:
- system("p4 revert \"%s\"" % f)
- system("p4 delete \"%s\"" % f)
+ p4_system("revert \"%s\"" % f)
+ p4_system("delete \"%s\"" % f)
- logMessage = ""
- if not self.directSubmit:
- logMessage = extractLogMessageFromGitCommit(id)
- logMessage = logMessage.replace("\n", "\n\t")
- if self.isWindows:
- logMessage = logMessage.replace("\n", "\r\n")
- logMessage = logMessage.strip()
+ # Set/clear executable bits
+ for f in filesToChangeExecBit.keys():
+ mode = filesToChangeExecBit[f]
+ setP4ExecBit(f, mode)
+
+ logMessage = extractLogMessageFromGitCommit(id)
+ logMessage = logMessage.strip()
template = self.prepareSubmitTemplate()
if self.interactive:
submitTemplate = self.prepareLogMessage(template, logMessage)
- diff = read_pipe("p4 diff -du ...")
+ if os.environ.has_key("P4DIFF"):
+ del(os.environ["P4DIFF"])
+ diff = p4_read_pipe("diff -du ...")
+ newdiff = ""
for newFile in filesToAdd:
- diff += "==== new file ====\n"
- diff += "--- /dev/null\n"
- diff += "+++ %s\n" % newFile
+ newdiff += "==== new file ====\n"
+ newdiff += "--- /dev/null\n"
+ newdiff += "+++ %s\n" % newFile
f = open(newFile, "r")
for line in f.readlines():
- diff += "+" + line
+ newdiff += "+" + line
f.close()
- separatorLine = "######## everything below this line is just the diff #######"
+ separatorLine = "######## everything below this line is just the diff #######\n"
+
+ [handle, fileName] = tempfile.mkstemp()
+ tmpFile = os.fdopen(handle, "w+")
+ if self.isWindows:
+ submitTemplate = submitTemplate.replace("\n", "\r\n")
+ separatorLine = separatorLine.replace("\n", "\r\n")
+ newdiff = newdiff.replace("\n", "\r\n")
+ tmpFile.write(submitTemplate + separatorLine + diff + newdiff)
+ tmpFile.close()
+ mtime = os.stat(fileName).st_mtime
+ defaultEditor = "vi"
if platform.system() == "Windows":
- separatorLine += "\r"
- separatorLine += "\n"
-
- response = "e"
- if self.trustMeLikeAFool:
- response = "y"
-
- firstIteration = True
- while response == "e":
- if not firstIteration:
- response = raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
- firstIteration = False
- if response == "e":
- [handle, fileName] = tempfile.mkstemp()
- tmpFile = os.fdopen(handle, "w+")
- tmpFile.write(submitTemplate + separatorLine + diff)
- tmpFile.close()
- defaultEditor = "vi"
- if platform.system() == "Windows":
- defaultEditor = "notepad"
- editor = os.environ.get("EDITOR", defaultEditor);
- system(editor + " " + fileName)
- tmpFile = open(fileName, "rb")
- message = tmpFile.read()
- tmpFile.close()
- os.remove(fileName)
- submitTemplate = message[:message.index(separatorLine)]
- if self.isWindows:
- submitTemplate = submitTemplate.replace("\r\n", "\n")
-
- if response == "y" or response == "yes":
- if self.dryRun:
- print submitTemplate
- raw_input("Press return to continue...")
- else:
- if self.directSubmit:
- print "Submitting to git first"
- os.chdir(self.oldWorkingDirectory)
- write_pipe("git commit -a -F -", submitTemplate)
- os.chdir(self.clientPath)
-
- write_pipe("p4 submit -i", submitTemplate)
- elif response == "s":
+ defaultEditor = "notepad"
+ if os.environ.has_key("P4EDITOR"):
+ editor = os.environ.get("P4EDITOR")
+ else:
+ editor = os.environ.get("EDITOR", defaultEditor);
+ system(editor + " " + fileName)
+
+ response = "y"
+ if os.stat(fileName).st_mtime <= mtime:
+ response = "x"
+ while response != "y" and response != "n":
+ response = raw_input("Submit template unchanged. Submit anyway? [y]es, [n]o (skip this patch) ")
+
+ if response == "y":
+ tmpFile = open(fileName, "rb")
+ message = tmpFile.read()
+ tmpFile.close()
+ submitTemplate = message[:message.index(separatorLine)]
+ if self.isWindows:
+ submitTemplate = submitTemplate.replace("\r\n", "\n")
+ p4_write_pipe("submit -i", submitTemplate)
+ else:
for f in editedFiles:
- system("p4 revert \"%s\"" % f);
+ p4_system("revert \"%s\"" % f);
for f in filesToAdd:
- system("p4 revert \"%s\"" % f);
+ p4_system("revert \"%s\"" % f);
system("rm %s" %f)
- for f in filesToDelete:
- system("p4 delete \"%s\"" % f);
- return
- else:
- print "Not submitting!"
- self.interactive = False
+
+ os.remove(fileName)
else:
fileName = "submit.txt"
file = open(fileName, "w+")
@@ -644,6 +778,10 @@ class P4Submit(Command):
else:
return False
+ allowSubmit = gitConfig("git-p4.allowSubmit")
+ if len(allowSubmit) > 0 and not self.master in allowSubmit.split(","):
+ die("%s is not in git-p4.allowSubmit" % self.master)
+
[upstream, settings] = findUpstreamBranchPoint()
self.depotPath = settings['depot-paths'][0]
if len(self.origin) == 0:
@@ -665,67 +803,33 @@ class P4Submit(Command):
print "Perforce checkout for depot path %s located at %s" % (self.depotPath, self.clientPath)
self.oldWorkingDirectory = os.getcwd()
- if self.directSubmit:
- self.diffStatus = read_pipe_lines("git diff -r --name-status HEAD")
- if len(self.diffStatus) == 0:
- print "No changes in working directory to submit."
- return True
- patch = read_pipe("git diff -p --binary --diff-filter=ACMRTUXB HEAD")
- self.diffFile = self.gitdir + "/p4-git-diff"
- f = open(self.diffFile, "wb")
- f.write(patch)
- f.close();
-
- os.chdir(self.clientPath)
+ chdir(self.clientPath)
print "Syncronizing p4 checkout..."
- system("p4 sync ...")
-
- if self.reset:
- self.firstTime = True
-
- if len(self.substFile) > 0:
- for line in open(self.substFile, "r").readlines():
- tokens = line.strip().split("=")
- self.logSubstitutions[tokens[0]] = tokens[1]
+ p4_system("sync ...")
self.check()
- self.configFile = self.gitdir + "/p4-git-sync.cfg"
- self.config = shelve.open(self.configFile, writeback=True)
-
- if self.firstTime:
- self.start()
- commits = self.config.get("commits", [])
+ commits = []
+ for line in read_pipe_lines("git rev-list --no-merges %s..%s" % (self.origin, self.master)):
+ commits.append(line.strip())
+ commits.reverse()
while len(commits) > 0:
- self.firstTime = False
commit = commits[0]
commits = commits[1:]
- self.config["commits"] = commits
self.applyCommit(commit)
if not self.interactive:
break
- self.config.close()
-
- if self.directSubmit:
- os.remove(self.diffFile)
-
if len(commits) == 0:
- if self.firstTime:
- print "No changes found to apply between %s and current HEAD" % self.origin
- else:
- print "All changes applied!"
- os.chdir(self.oldWorkingDirectory)
+ print "All changes applied!"
+ chdir(self.oldWorkingDirectory)
- sync = P4Sync()
- sync.run([])
+ sync = P4Sync()
+ sync.run([])
- response = raw_input("Do you want to rebase current HEAD from Perforce now using git-p4 rebase? [y]es/[n]o ")
- if response == "y" or response == "yes":
- rebase = P4Rebase()
- rebase.rebase()
- os.remove(self.configFile)
+ rebase = P4Rebase()
+ rebase.rebase()
return True
@@ -743,7 +847,9 @@ class P4Sync(Command):
help="Import into refs/heads/ , not refs/remotes"),
optparse.make_option("--max-changes", dest="maxChanges"),
optparse.make_option("--keep-path", dest="keepRepoPath", action='store_true',
- help="Keep entire BRANCH/DIR/SUBDIR prefix during import")
+ help="Keep entire BRANCH/DIR/SUBDIR prefix during import"),
+ optparse.make_option("--use-client-spec", dest="useClientSpec", action='store_true',
+ help="Only sync files that are included in the Perforce Client Spec")
]
self.description = """Imports from Perforce into a git repository.\n
example:
@@ -769,18 +875,27 @@ class P4Sync(Command):
self.keepRepoPath = False
self.depotPaths = None
self.p4BranchesInGit = []
+ self.cloneExclude = []
+ self.useClientSpec = False
+ self.clientSpecDirs = []
if gitConfig("git-p4.syncFromOrigin") == "false":
self.syncWithOrigin = False
def extractFilesFromCommit(self, commit):
+ self.cloneExclude = [re.sub(r"\.\.\.$", "", path)
+ for path in self.cloneExclude]
files = []
fnum = 0
while commit.has_key("depotFile%s" % fnum):
path = commit["depotFile%s" % fnum]
- found = [p for p in self.depotPaths
- if path.startswith (p)]
+ if [p for p in self.cloneExclude
+ if path.startswith (p)]:
+ found = False
+ else:
+ found = [p for p in self.depotPaths
+ if path.startswith (p)]
if not found:
fnum = fnum + 1
continue
@@ -837,19 +952,32 @@ class P4Sync(Command):
## Should move this out, doesn't use SELF.
def readP4Files(self, files):
- files = [f for f in files
- if f['action'] != 'delete']
+ filesForCommit = []
+ filesToRead = []
- if not files:
- return
+ for f in files:
+ includeFile = True
+ for val in self.clientSpecDirs:
+ if f['path'].startswith(val[0]):
+ if val[1] <= 0:
+ includeFile = False
+ break
+
+ if includeFile:
+ filesForCommit.append(f)
+ if f['action'] not in ('delete', 'purge'):
+ filesToRead.append(f)
- filedata = p4CmdList('-x - print',
- stdin='\n'.join(['%s#%s' % (f['path'], f['rev'])
- for f in files]),
- stdin_mode='w+')
- if "p4ExitCode" in filedata[0]:
- die("Problems executing p4. Error: [%d]."
- % (filedata[0]['p4ExitCode']));
+ filedata = []
+ if len(filesToRead) > 0:
+ filedata = p4CmdList('-x - print',
+ stdin='\n'.join(['%s#%s' % (f['path'], f['rev'])
+ for f in filesToRead]),
+ stdin_mode='w+')
+
+ if "p4ExitCode" in filedata[0]:
+ die("Problems executing p4. Error: [%d]."
+ % (filedata[0]['p4ExitCode']));
j = 0;
contents = {}
@@ -857,21 +985,28 @@ class P4Sync(Command):
stat = filedata[j]
j += 1
text = ''
- while j < len(filedata) and filedata[j]['code'] in ('text',
- 'binary'):
+ while j < len(filedata) and filedata[j]['code'] in ('text', 'unicode', 'binary'):
text += filedata[j]['data']
+ del filedata[j]['data']
j += 1
-
if not stat.has_key('depotFile'):
sys.stderr.write("p4 print fails with: %s\n" % repr(stat))
continue
+ if stat['type'] in ('text+ko', 'unicode+ko', 'binary+ko'):
+ text = re.sub(r'(?i)\$(Id|Header):[^$]*\$',r'$\1$', text)
+ elif stat['type'] in ('text+k', 'ktext', 'kxtext', 'unicode+k', 'binary+k'):
+ text = re.sub(r'\$(Id|Header|Author|Date|DateTime|Change|File|Revision):[^$\n]*\$',r'$\1$', text)
+
contents[stat['depotFile']] = text
- for f in files:
- assert not f.has_key('data')
- f['data'] = contents[f['path']]
+ for f in filesForCommit:
+ path = f['path']
+ if contents.has_key(path):
+ f['data'] = contents[path]
+
+ return filesForCommit
def commit(self, details, files, branch, branchPrefixes, parent = ""):
epoch = details["time"]
@@ -888,11 +1023,7 @@ class P4Sync(Command):
new_files.append (f)
else:
sys.stderr.write("Ignoring file outside of prefix: %s\n" % path)
- files = new_files
- self.readP4Files(files)
-
-
-
+ files = self.readP4Files(new_files)
self.gitStream.write("commit %s\n" % branch)
# gitStream.write("mark :%s\n" % details["change"])
@@ -926,13 +1057,13 @@ class P4Sync(Command):
continue
relPath = self.stripRepoPath(file['path'], branchPrefixes)
- if file["action"] == "delete":
+ if file["action"] in ("delete", "purge"):
self.gitStream.write("D %s\n" % relPath)
else:
data = file['data']
mode = "644"
- if file["type"].startswith("x"):
+ if isP4Exec(file["type"]):
mode = "755"
elif file["type"] == "symlink":
mode = "120000"
@@ -965,7 +1096,7 @@ class P4Sync(Command):
cleanedFiles = {}
for info in files:
- if info["action"] == "delete":
+ if info["action"] in ("delete", "purge"):
continue
cleanedFiles[info["depotFile"]] = info["rev"]
@@ -1011,7 +1142,7 @@ class P4Sync(Command):
s = ''
for (key, val) in self.users.items():
- s += "%s\t%s\n" % (key, val)
+ s += "%s\t%s\n" % (key.expandtabs(1), val.expandtabs(1))
open(self.getUserCacheFilename(), "wb").write(s)
self.userMapFromPerforceServer = True
@@ -1034,7 +1165,7 @@ class P4Sync(Command):
l = p4CmdList("labels %s..." % ' '.join (self.depotPaths))
if len(l) > 0 and not self.silent:
- print "Finding files belonging to labels in %s" % `self.depotPath`
+ print "Finding files belonging to labels in %s" % `self.depotPaths`
for output in l:
label = output["label"]
@@ -1100,6 +1231,15 @@ class P4Sync(Command):
for branch in lostAndFoundBranches:
self.knownBranches[branch] = branch
+ def getBranchMappingFromGitBranches(self):
+ branches = p4BranchesInGit(self.importIntoRemotes)
+ for branch in branches.keys():
+ if branch == "master":
+ branch = "main"
+ else:
+ branch = branch[len(self.projectName):]
+ self.knownBranches[branch] = branch
+
def listExistingP4GitBranches(self):
# branches holds mapping from name to commit
branches = p4BranchesInGit(self.importIntoRemotes)
@@ -1279,7 +1419,7 @@ class P4Sync(Command):
if change > newestRevision:
newestRevision = change
- if info["action"] == "delete":
+ if info["action"] in ("delete", "purge"):
# don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
#fileCnt = fileCnt + 1
continue
@@ -1298,6 +1438,26 @@ class P4Sync(Command):
print self.gitError.read()
+ def getClientSpec(self):
+ specList = p4CmdList( "client -o" )
+ temp = {}
+ for entry in specList:
+ for k,v in entry.iteritems():
+ if k.startswith("View"):
+ if v.startswith('"'):
+ start = 1
+ else:
+ start = 0
+ index = v.find("...")
+ v = v[start:index]
+ if v.startswith("-"):
+ v = v[1:]
+ temp[v] = -len(v)
+ else:
+ temp[v] = len(v)
+ self.clientSpecDirs = temp.items()
+ self.clientSpecDirs.sort( lambda x, y: abs( y[1] ) - abs( x[1] ) )
+
def run(self, args):
self.depotPaths = []
self.changeRange = ""
@@ -1330,6 +1490,9 @@ class P4Sync(Command):
if not gitBranchExists(self.refPrefix + "HEAD") and self.importIntoRemotes and gitBranchExists(self.branch):
system("git symbolic-ref %sHEAD %s" % (self.refPrefix, self.branch))
+ if self.useClientSpec or gitConfig("git-p4.useclientspec") == "true":
+ self.getClientSpec()
+
# TODO: should always look at previous commits,
# merge with previous imports, if possible.
if args == []:
@@ -1434,8 +1597,10 @@ class P4Sync(Command):
## FIXME - what's a P4 projectName ?
self.projectName = self.guessProjectName()
- if not self.hasOrigin:
- self.getBranchMapping();
+ if self.hasOrigin:
+ self.getBranchMappingFromGitBranches()
+ else:
+ self.getBranchMapping()
if self.verbose:
print "p4-git branches: %s" % self.p4BranchesInGit
print "initial parents: %s" % self.initialParents
@@ -1522,6 +1687,11 @@ class P4Rebase(Command):
return self.rebase()
def rebase(self):
+ if os.system("git update-index --refresh") != 0:
+ die("Some files in your working directory are modified and different than what is in your index. You can use git update-index <filename> to bring the index up-to-date or stash away all your changes with git stash.");
+ if len(read_pipe("git diff-index HEAD --")) > 0:
+ die("You have uncommited changes. Please commit them before rebasing or stash them away with git stash.");
+
[upstream, settings] = findUpstreamBranchPoint()
if len(upstream) == 0:
die("Cannot find upstream branchpoint for rebase")
@@ -1540,19 +1710,29 @@ class P4Clone(P4Sync):
P4Sync.__init__(self)
self.description = "Creates a new git repository and imports from Perforce into it"
self.usage = "usage: %prog [options] //depot/path[@revRange]"
- self.options.append(
+ self.options += [
optparse.make_option("--destination", dest="cloneDestination",
action='store', default=None,
- help="where to leave result of the clone"))
+ help="where to leave result of the clone"),
+ optparse.make_option("-/", dest="cloneExclude",
+ action="append", type="string",
+ help="exclude depot path")
+ ]
self.cloneDestination = None
self.needsGit = False
+ # This is required for the "append" cloneExclude action
+ def ensure_value(self, attr, value):
+ if not hasattr(self, attr) or getattr(self, attr) is None:
+ setattr(self, attr, value)
+ return getattr(self, attr)
+
def defaultDestination(self, args):
## TODO: use common prefix of args?
depotPath = args[0]
depotDir = re.sub("(@[^@]*)$", "", depotPath)
depotDir = re.sub("(#[^#]*)$", "", depotDir)
- depotDir = re.sub(r"\.\.\.$,", "", depotDir)
+ depotDir = re.sub(r"\.\.\.$", "", depotDir)
depotDir = re.sub(r"/$", "", depotDir)
return os.path.split(depotDir)[1]
@@ -1570,6 +1750,7 @@ class P4Clone(P4Sync):
self.cloneDestination = depotPaths[-1]
depotPaths = depotPaths[:-1]
+ self.cloneExclude = ["/"+p for p in self.cloneExclude]
for p in depotPaths:
if not p.startswith("//"):
return False
@@ -1580,14 +1761,18 @@ class P4Clone(P4Sync):
print "Importing from %s into %s" % (', '.join(depotPaths), self.cloneDestination)
if not os.path.exists(self.cloneDestination):
os.makedirs(self.cloneDestination)
- os.chdir(self.cloneDestination)
+ chdir(self.cloneDestination)
system("git init")
self.gitdir = os.getcwd() + "/.git"
if not P4Sync.run(self, depotPaths):
return False
if self.branch != "master":
- if gitBranchExists("refs/remotes/p4/master"):
- system("git branch master refs/remotes/p4/master")
+ if self.importIntoRemotes:
+ masterbranch = "refs/remotes/p4/master"
+ else:
+ masterbranch = "refs/heads/p4/master"
+ if gitBranchExists(masterbranch):
+ system("git branch master %s" % masterbranch)
system("git checkout -f")
else:
print "Could not detect main branch. No checkout/master branch created."
@@ -1643,6 +1828,7 @@ def printUsage(commands):
commands = {
"debug" : P4Debug,
"submit" : P4Submit,
+ "commit" : P4Submit,
"sync" : P4Sync,
"rebase" : P4Rebase,
"clone" : P4Clone,
@@ -1691,7 +1877,7 @@ def main():
if os.path.exists(cmd.gitdir):
cdup = read_pipe("git rev-parse --show-cdup").strip()
if len(cdup) > 0:
- os.chdir(cdup);
+ chdir(cdup);
if not isValidGitDir(cmd.gitdir):
if isValidGitDir(cmd.gitdir + "/.git"):
diff --git a/contrib/fast-import/git-p4.txt b/contrib/fast-import/git-p4.txt
index b16a8384bc..49b335921a 100644
--- a/contrib/fast-import/git-p4.txt
+++ b/contrib/fast-import/git-p4.txt
@@ -3,14 +3,16 @@ git-p4 - Perforce <-> Git converter using git-fast-import
Usage
=====
-git-p4 supports two main modes: Importing from Perforce to a Git repository is
-done using "git-p4 sync" or "git-p4 rebase". Submitting changes from Git back
-to Perforce is done using "git-p4 submit".
+git-p4 can be used in two different ways:
+
+1) To import changes from Perforce to a Git repository, using "git-p4 sync".
+
+2) To submit changes from Git back to Perforce, using "git-p4 submit".
Importing
=========
-You can simply start with
+Simply start with
git-p4 clone //depot/path/project
@@ -18,11 +20,18 @@ or
git-p4 clone //depot/path/project myproject
-This will create an empty git repository in a subdirectory called "project" (or
-"myproject" with the second command), import the head revision from the
-specified perforce path into a git "p4" branch (remotes/p4 actually), create a
-master branch off it and check it out. If you want the entire history (not just
-the head revision) then you can simply append a "@all" to the depot path:
+This will:
+
+1) Create an empty git repository in a subdirectory called "project" (or
+"myproject" with the second command)
+
+2) Import the head revision from the given Perforce path into a git branch
+called "p4" (remotes/p4 actually)
+
+3) Create a master branch based on it and check it out.
+
+If you want the entire history (not just the head revision) then you can simply
+append a "@all" to the depot path:
git-p4 clone //depot/project/main@all myproject
@@ -37,43 +46,40 @@ If you want more control you can also use the git-p4 sync command directly:
This will import the current head revision of the specified depot path into a
"remotes/p4/master" branch of your git repository. You can use the
---branch=mybranch option to use a different branch.
+--branch=mybranch option to import into a different branch.
-If you want to import the entire history of a given depot path just use
+If you want to import the entire history of a given depot path simply use:
git-p4 sync //path/in/depot@all
+
+Note:
+
To achieve optimal compression you may want to run 'git repack -a -d -f' after
a big import. This may take a while.
-Support for Perforce integrations is still work in progress. Don't bother
-trying it unless you want to hack on it :)
-
Incremental Imports
===================
-After an initial import you can easily synchronize your git repository with
-newer changes from the Perforce depot by just calling
+After an initial import you can continue to synchronize your git repository
+with newer changes from the Perforce depot by just calling
git-p4 sync
in your git repository. By default the "remotes/p4/master" branch is updated.
-It is recommended to run 'git repack -a -d -f' from time to time when using
-incremental imports to optimally combine the individual git packs that each
-incremental import creates through the use of git-fast-import.
-
+Advanced Setup
+==============
-A useful setup may be that you have a periodically updated git repository
-somewhere that contains a complete import of a Perforce project. That git
-repository can be used to clone the working repository from and one would
-import from Perforce directly after cloning using git-p4. If the connection to
-the Perforce server is slow and the working repository hasn't been synced for a
-while it may be desirable to fetch changes from the origin git repository using
-the efficient git protocol. git-p4 supports this setup by calling "git fetch origin"
-by default if there is an origin branch. You can disable this using
+Suppose you have a periodically updated git repository somewhere, containing a
+complete import of a Perforce project. This repository can be cloned and used
+with git-p4. When updating the cloned repository with the "sync" command,
+git-p4 will try to fetch changes from the original repository first. The git
+protocol used with this is usually faster than importing from Perforce
+directly.
- git config git-p4.syncFromOrigin false
+This behaviour can be disabled by setting the "git-p4.syncFromOrigin" git
+configuration variable to "false".
Updating
========
@@ -91,7 +97,7 @@ Submitting
==========
git-p4 has support for submitting changes from a git repository back to the
-Perforce depot. This requires a Perforce checkout separate to your git
+Perforce depot. This requires a Perforce checkout separate from your git
repository. To submit all changes that are in the current git branch but not in
the "p4" branch (or "origin" if "p4" doesn't exist) simply call
@@ -109,17 +115,6 @@ continue importing the remaining changes with
git-p4 submit --continue
-After submitting you should sync your perforce import branch ("p4" or "origin")
-from Perforce using git-p4's sync command.
-
-If you have changes in your working directory that you haven't committed into
-git yet but that you want to commit to Perforce directly ("quick fixes") then
-you do not have to go through the intermediate step of creating a git commit
-first but you can just call
-
- git-p4 submit --direct
-
-
Example
=======
@@ -140,6 +135,62 @@ Example
git-p4 rebase
+Configuration parameters
+========================
+
+git-p4.user ($P4USER)
+
+Allows you to specify the username to use to connect to the Perforce repository.
+
+ git config [--global] git-p4.user public
+
+git-p4.password ($P4PASS)
+
+Allows you to specify the password to use to connect to the Perforce repository.
+Warning this password will be visible on the command-line invocation of the p4 binary.
+
+ git config [--global] git-p4.password public1234
+
+git-p4.port ($P4PORT)
+
+Specify the port to be used to contact the Perforce server. As this will be passed
+directly to the p4 binary, it may be in the format host:port as well.
+
+ git config [--global] git-p4.port codes.zimbra.com:2666
+
+git-p4.host ($P4HOST)
+
+Specify the host to contact for a Perforce repository.
+
+ git config [--global] git-p4.host perforce.example.com
+
+git-p4.client ($P4CLIENT)
+
+Specify the client name to use
+
+ git config [--global] git-p4.client public-view
+
+git-p4.allowSubmit
+
+ git config [--global] git-p4.allowSubmit false
+
+git-p4.syncFromOrigin
+
+A useful setup may be that you have a periodically updated git repository
+somewhere that contains a complete import of a Perforce project. That git
+repository can be used to clone the working repository from and one would
+import from Perforce directly after cloning using git-p4. If the connection to
+the Perforce server is slow and the working repository hasn't been synced for a
+while it may be desirable to fetch changes from the origin git repository using
+the efficient git protocol. git-p4 supports this setup by calling "git fetch origin"
+by default if there is an origin branch. You can disable this using:
+
+ git config [--global] git-p4.syncFromOrigin false
+
+git-p4.useclientspec
+
+ git config [--global] git-p4.useclientspec false
+
Implementation Details...
=========================
diff --git a/contrib/fast-import/import-tars.perl b/contrib/fast-import/import-tars.perl
index 23aeb257b9..6309d146e7 100755
--- a/contrib/fast-import/import-tars.perl
+++ b/contrib/fast-import/import-tars.perl
@@ -14,13 +14,18 @@ die "usage: import-tars *.tar.{gz,bz2,Z}\n" unless @ARGV;
my $branch_name = 'import-tars';
my $branch_ref = "refs/heads/$branch_name";
-my $committer_name = 'T Ar Creator';
-my $committer_email = 'tar@example.com';
+my $author_name = $ENV{'GIT_AUTHOR_NAME'} || 'T Ar Creator';
+my $author_email = $ENV{'GIT_AUTHOR_EMAIL'} || 'tar@example.com';
+my $committer_name = $ENV{'GIT_COMMITTER_NAME'} || `git config --get user.name`;
+my $committer_email = $ENV{'GIT_COMMITTER_EMAIL'} || `git config --get user.email`;
+
+chomp($committer_name, $committer_email);
open(FI, '|-', 'git', 'fast-import', '--quiet')
or die "Unable to start git fast-import: $!\n";
foreach my $tar_file (@ARGV)
{
+ my $commit_time = time;
$tar_file =~ m,([^/]+)$,;
my $tar_name = $1;
@@ -39,7 +44,7 @@ foreach my $tar_file (@ARGV)
die "Unrecognized compression format: $tar_file\n";
}
- my $commit_time = 0;
+ my $author_time = 0;
my $next_mark = 1;
my $have_top_dir = 1;
my ($top_dir, %files);
@@ -92,7 +97,7 @@ foreach my $tar_file (@ARGV)
}
$files{$path} = [$next_mark++, $mode];
- $commit_time = $mtime if $mtime > $commit_time;
+ $author_time = $mtime if $mtime > $author_time;
$path =~ m,^([^/]+)/,;
$top_dir = $1 unless $top_dir;
$have_top_dir = 0 if $top_dir ne $1;
@@ -100,6 +105,7 @@ foreach my $tar_file (@ARGV)
print FI <<EOF;
commit $branch_ref
+author $author_name <$author_email> $author_time +0000
committer $committer_name <$committer_email> $commit_time +0000
data <<END_OF_COMMIT_MESSAGE
Imported from $tar_file.
@@ -119,7 +125,7 @@ EOF
print FI <<EOF;
tag $tar_name
from $branch_ref
-tagger $committer_name <$committer_email> $commit_time +0000
+tagger $author_name <$author_email> $author_time +0000
data <<END_OF_TAG_MESSAGE
Package $tar_name
END_OF_TAG_MESSAGE
diff --git a/contrib/fast-import/import-zips.py b/contrib/fast-import/import-zips.py
new file mode 100755
index 0000000000..7051a83a59
--- /dev/null
+++ b/contrib/fast-import/import-zips.py
@@ -0,0 +1,73 @@
+#!/usr/bin/python
+
+## zip archive frontend for git-fast-import
+##
+## For example:
+##
+## mkdir project; cd project; git init
+## python import-zips.py *.zip
+## git log --stat import-zips
+
+from os import popen, path
+from sys import argv, exit
+from time import mktime
+from zipfile import ZipFile
+
+if len(argv) < 2:
+ print 'Usage:', argv[0], '<zipfile>...'
+ exit(1)
+
+branch_ref = 'refs/heads/import-zips'
+committer_name = 'Z Ip Creator'
+committer_email = 'zip@example.com'
+
+fast_import = popen('git fast-import --quiet', 'w')
+def printlines(list):
+ for str in list:
+ fast_import.write(str + "\n")
+
+for zipfile in argv[1:]:
+ commit_time = 0
+ next_mark = 1
+ common_prefix = None
+ mark = dict()
+
+ zip = ZipFile(zipfile, 'r')
+ for name in zip.namelist():
+ if name.endswith('/'):
+ continue
+ info = zip.getinfo(name)
+
+ if commit_time < info.date_time:
+ commit_time = info.date_time
+ if common_prefix == None:
+ common_prefix = name[:name.rfind('/') + 1]
+ else:
+ while not name.startswith(common_prefix):
+ last_slash = common_prefix[:-1].rfind('/') + 1
+ common_prefix = common_prefix[:last_slash]
+
+ mark[name] = ':' + str(next_mark)
+ next_mark += 1
+
+ printlines(('blob', 'mark ' + mark[name], \
+ 'data ' + str(info.file_size)))
+ fast_import.write(zip.read(name) + "\n")
+
+ committer = committer_name + ' <' + committer_email + '> %d +0000' % \
+ mktime(commit_time + (0, 0, 0))
+
+ printlines(('commit ' + branch_ref, 'committer ' + committer, \
+ 'data <<EOM', 'Imported from ' + zipfile + '.', 'EOM', \
+ '', 'deleteall'))
+
+ for name in mark.keys():
+ fast_import.write('M 100644 ' + mark[name] + ' ' +
+ name[len(common_prefix):] + "\n")
+
+ printlines(('', 'tag ' + path.basename(zipfile), \
+ 'from ' + branch_ref, 'tagger ' + committer, \
+ 'data <<EOM', 'Package ' + zipfile, 'EOM', ''))
+
+if fast_import.close():
+ exit(1)
diff --git a/contrib/git-resurrect.sh b/contrib/git-resurrect.sh
new file mode 100755
index 0000000000..c364dda696
--- /dev/null
+++ b/contrib/git-resurrect.sh
@@ -0,0 +1,180 @@
+#!/bin/sh
+
+USAGE="[-a] [-r] [-m] [-t] [-n] [-b <newname>] <name>"
+LONG_USAGE="git-resurrect attempts to find traces of a branch tip
+called <name>, and tries to resurrect it. Currently, the reflog is
+searched for checkout messages, and with -r also merge messages. With
+-m and -t, the history of all refs is scanned for Merge <name> into
+other/Merge <other> into <name> (respectively) commit subjects, which
+is rather slow but allows you to resurrect other people's topic
+branches."
+
+OPTIONS_SPEC="\
+git resurrect $USAGE
+--
+b,branch= save branch as <newname> instead of <name>
+a,all same as -l -r -m -t
+k,keep-going full rev-list scan (instead of first match)
+l,reflog scan reflog for checkouts (enabled by default)
+r,reflog-merges scan for merges recorded in reflog
+m,merges scan for merges into other branches (slow)
+t,merge-targets scan for merges of other branches into <name>
+n,dry-run don't recreate the branch"
+
+. git-sh-setup
+
+search_reflog () {
+ sed -ne 's~^\([^ ]*\) .*\tcheckout: moving from '"$1"' .*~\1~p' \
+ < "$GIT_DIR"/logs/HEAD
+}
+
+search_reflog_merges () {
+ git rev-parse $(
+ sed -ne 's~^[^ ]* \([^ ]*\) .*\tmerge '"$1"':.*~\1^2~p' \
+ < "$GIT_DIR"/logs/HEAD
+ )
+}
+
+_x40="[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]"
+_x40="$_x40$_x40$_x40$_x40$_x40$_x40$_x40$_x40"
+
+search_merges () {
+ git rev-list --all --grep="Merge branch '$1'" \
+ --pretty=tformat:"%P %s" |
+ sed -ne "/^$_x40 \($_x40\) Merge .*/ {s//\1/p;$early_exit}"
+}
+
+search_merge_targets () {
+ git rev-list --all --grep="Merge branch '[^']*' into $branch\$" \
+ --pretty=tformat:"%H %s" --all |
+ sed -ne "/^\($_x40\) Merge .*/ {s//\1/p;$early_exit} "
+}
+
+dry_run=
+early_exit=q
+scan_reflog=t
+scan_reflog_merges=
+scan_merges=
+scan_merge_targets=
+new_name=
+
+while test "$#" != 0; do
+ case "$1" in
+ -b|--branch)
+ shift
+ new_name="$1"
+ ;;
+ -n|--dry-run)
+ dry_run=t
+ ;;
+ --no-dry-run)
+ dry_run=
+ ;;
+ -k|--keep-going)
+ early_exit=
+ ;;
+ --no-keep-going)
+ early_exit=q
+ ;;
+ -m|--merges)
+ scan_merges=t
+ ;;
+ --no-merges)
+ scan_merges=
+ ;;
+ -l|--reflog)
+ scan_reflog=t
+ ;;
+ --no-reflog)
+ scan_reflog=
+ ;;
+ -r|--reflog_merges)
+ scan_reflog_merges=t
+ ;;
+ --no-reflog_merges)
+ scan_reflog_merges=
+ ;;
+ -t|--merge-targets)
+ scan_merge_targets=t
+ ;;
+ --no-merge-targets)
+ scan_merge_targets=
+ ;;
+ -a|--all)
+ scan_reflog=t
+ scan_reflog_merges=t
+ scan_merges=t
+ scan_merge_targets=t
+ ;;
+ --)
+ shift
+ break
+ ;;
+ *)
+ usage
+ ;;
+ esac
+ shift
+done
+
+test "$#" = 1 || usage
+
+all_strategies="$scan_reflog$scan_reflog_merges$scan_merges$scan_merge_targets"
+if test -z "$all_strategies"; then
+ die "must enable at least one of -lrmt"
+fi
+
+branch="$1"
+test -z "$new_name" && new_name="$branch"
+
+if test ! -z "$scan_reflog"; then
+ if test -r "$GIT_DIR"/logs/HEAD; then
+ candidates="$(search_reflog $branch)"
+ else
+ die 'reflog scanning requested, but' \
+ '$GIT_DIR/logs/HEAD not readable'
+ fi
+fi
+if test ! -z "$scan_reflog_merges"; then
+ if test -r "$GIT_DIR"/logs/HEAD; then
+ candidates="$candidates $(search_reflog_merges $branch)"
+ else
+ die 'reflog scanning requested, but' \
+ '$GIT_DIR/logs/HEAD not readable'
+ fi
+fi
+if test ! -z "$scan_merges"; then
+ candidates="$candidates $(search_merges $branch)"
+fi
+if test ! -z "$scan_merge_targets"; then
+ candidates="$candidates $(search_merge_targets $branch)"
+fi
+
+candidates="$(git rev-parse $candidates | sort -u)"
+
+if test -z "$candidates"; then
+ hint=
+ test "z$all_strategies" != "ztttt" \
+ && hint=" (maybe try again with -a)"
+ die "no candidates for $branch found$hint"
+fi
+
+echo "** Candidates for $branch **"
+for cmt in $candidates; do
+ git --no-pager log --pretty=tformat:"%ct:%h [%cr] %s" --abbrev-commit -1 $cmt
+done \
+| sort -n | cut -d: -f2-
+
+newest="$(git rev-list -1 $candidates)"
+if test ! -z "$dry_run"; then
+ printf "** Most recent: "
+ git --no-pager log -1 --pretty=tformat:"%h %s" $newest
+elif ! git rev-parse --verify --quiet $new_name >/dev/null; then
+ printf "** Restoring $new_name to "
+ git --no-pager log -1 --pretty=tformat:"%h %s" $newest
+ git branch $new_name $newest
+else
+ printf "Most recent: "
+ git --no-pager log -1 --pretty=tformat:"%h %s" $newest
+ echo "** $new_name already exists, doing nothing"
+fi
diff --git a/contrib/gitview/gitview b/contrib/gitview/gitview
index 5931766620..4c99dfb903 100755
--- a/contrib/gitview/gitview
+++ b/contrib/gitview/gitview
@@ -27,12 +27,17 @@ import math
import string
import fcntl
+have_gtksourceview2 = False
+have_gtksourceview = False
try:
- import gtksourceview
- have_gtksourceview = True
+ import gtksourceview2
+ have_gtksourceview2 = True
except ImportError:
- have_gtksourceview = False
- print "Running without gtksourceview module"
+ try:
+ import gtksourceview
+ have_gtksourceview = True
+ except ImportError:
+ print "Running without gtksourceview2 or gtksourceview module"
re_ident = re.compile('(author|committer) (?P<ident>.*) (?P<epoch>\d+) (?P<tz>[+-]\d{4})')
@@ -58,6 +63,26 @@ def show_date(epoch, tz):
return time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(secs))
+def get_source_buffer_and_view():
+ if have_gtksourceview2:
+ buffer = gtksourceview2.Buffer()
+ slm = gtksourceview2.LanguageManager()
+ gsl = slm.get_language("diff")
+ buffer.set_highlight_syntax(True)
+ buffer.set_language(gsl)
+ view = gtksourceview2.View(buffer)
+ elif have_gtksourceview:
+ buffer = gtksourceview.SourceBuffer()
+ slm = gtksourceview.SourceLanguagesManager()
+ gsl = slm.get_language_from_mime_type("text/x-patch")
+ buffer.set_highlight(True)
+ buffer.set_language(gsl)
+ view = gtksourceview.SourceView(buffer)
+ else:
+ buffer = gtk.TextBuffer()
+ view = gtk.TextView(buffer)
+ return (buffer, view)
+
class CellRendererGraph(gtk.GenericCellRenderer):
"""Cell renderer for directed graph.
@@ -582,17 +607,7 @@ class DiffWindow(object):
hpan.pack1(scrollwin, True, True)
scrollwin.show()
- if have_gtksourceview:
- self.buffer = gtksourceview.SourceBuffer()
- slm = gtksourceview.SourceLanguagesManager()
- gsl = slm.get_language_from_mime_type("text/x-patch")
- self.buffer.set_highlight(True)
- self.buffer.set_language(gsl)
- sourceview = gtksourceview.SourceView(self.buffer)
- else:
- self.buffer = gtk.TextBuffer()
- sourceview = gtk.TextView(self.buffer)
-
+ (self.buffer, sourceview) = get_source_buffer_and_view()
sourceview.set_editable(False)
sourceview.modify_font(pango.FontDescription("Monospace"))
@@ -956,16 +971,7 @@ class GitView(object):
vbox.pack_start(scrollwin, expand=True, fill=True)
scrollwin.show()
- if have_gtksourceview:
- self.message_buffer = gtksourceview.SourceBuffer()
- slm = gtksourceview.SourceLanguagesManager()
- gsl = slm.get_language_from_mime_type("text/x-patch")
- self.message_buffer.set_highlight(True)
- self.message_buffer.set_language(gsl)
- sourceview = gtksourceview.SourceView(self.message_buffer)
- else:
- self.message_buffer = gtk.TextBuffer()
- sourceview = gtk.TextView(self.message_buffer)
+ (self.message_buffer, sourceview) = get_source_buffer_and_view()
sourceview.set_editable(False)
sourceview.modify_font(pango.FontDescription("Monospace"))
diff --git a/contrib/hg-to-git/hg-to-git.py b/contrib/hg-to-git/hg-to-git.py
index 37337ff01f..7b03204ed1 100755
--- a/contrib/hg-to-git/hg-to-git.py
+++ b/contrib/hg-to-git/hg-to-git.py
@@ -1,6 +1,6 @@
#! /usr/bin/python
-""" hg-to-svn.py - A Mercurial to GIT converter
+""" hg-to-git.py - A Mercurial to GIT converter
Copyright (C)2007 Stelian Pop <stelian@popies.net>
@@ -27,8 +27,12 @@ import re
hgvers = {}
# List of children for each hg revision
hgchildren = {}
+# List of parents for each hg revision
+hgparents = {}
# Current branch for each hg revision
hgbranch = {}
+# Number of new changesets converted from hg
+hgnewcsets = 0
#------------------------------------------------------------------------------
@@ -40,6 +44,9 @@ def usage():
options:
-s, --gitstate=FILE: name of the state to be saved/read
for incrementals
+ -n, --nrepack=INT: number of changesets that will trigger
+ a repack (default=0, -1 to deactivate)
+ -v, --verbose: be verbose
required:
hgprj: name of the HG project to import (directory)
@@ -68,16 +75,21 @@ def getgitenv(user, date):
#------------------------------------------------------------------------------
state = ''
+opt_nrepack = 0
+verbose = False
try:
- opts, args = getopt.getopt(sys.argv[1:], 's:t:', ['gitstate=', 'tempdir='])
+ opts, args = getopt.getopt(sys.argv[1:], 's:t:n:v', ['gitstate=', 'tempdir=', 'nrepack=', 'verbose'])
for o, a in opts:
if o in ('-s', '--gitstate'):
state = a
state = os.path.abspath(state)
-
+ if o in ('-n', '--nrepack'):
+ opt_nrepack = int(a)
+ if o in ('-v', '--verbose'):
+ verbose = True
if len(args) != 1:
- raise('params')
+ raise Exception('params')
except:
usage()
sys.exit(1)
@@ -87,23 +99,31 @@ os.chdir(hgprj)
if state:
if os.path.exists(state):
- print 'State does exist, reading'
+ if verbose:
+ print 'State does exist, reading'
f = open(state, 'r')
hgvers = pickle.load(f)
else:
print 'State does not exist, first run'
-tip = os.popen('hg tip | head -1 | cut -f 2 -d :').read().strip()
-print 'tip is', tip
+sock = os.popen('hg tip --template "{rev}"')
+tip = sock.read()
+if sock.close():
+ sys.exit(1)
+if verbose:
+ print 'tip is', tip
# Calculate the branches
-print 'analysing the branches...'
+if verbose:
+ print 'analysing the branches...'
hgchildren["0"] = ()
+hgparents["0"] = (None, None)
hgbranch["0"] = "master"
for cset in range(1, int(tip) + 1):
hgchildren[str(cset)] = ()
- prnts = os.popen('hg log -r %d | grep ^parent: | cut -f 2 -d :' % cset).readlines()
- if len(prnts) > 0:
+ prnts = os.popen('hg log -r %d --template "{parents}"' % cset).read().strip().split(' ')
+ prnts = map(lambda x: x[:x.find(':')], prnts)
+ if prnts[0] != '':
parent = prnts[0].strip()
else:
parent = str(cset - 1)
@@ -114,6 +134,8 @@ for cset in range(1, int(tip) + 1):
else:
mparent = None
+ hgparents[str(cset)] = (parent, mparent)
+
if mparent:
# For merge changesets, take either one, preferably the 'master' branch
if hgbranch[mparent] == 'master':
@@ -130,7 +152,7 @@ for cset in range(1, int(tip) + 1):
if not hgvers.has_key("0"):
print 'creating repository'
- os.system('git-init-db')
+ os.system('git init')
# loop through every hg changeset
for cset in range(int(tip) + 1):
@@ -138,36 +160,30 @@ for cset in range(int(tip) + 1):
# incremental, already seen
if hgvers.has_key(str(cset)):
continue
+ hgnewcsets += 1
# get info
- prnts = os.popen('hg log -r %d | grep ^parent: | cut -f 2 -d :' % cset).readlines()
- if len(prnts) > 0:
- parent = prnts[0].strip()
- else:
- parent = str(cset - 1)
- if len(prnts) > 1:
- mparent = prnts[1].strip()
- else:
- mparent = None
-
+ log_data = os.popen('hg log -r %d --template "{tags}\n{date|date}\n{author}\n"' % cset).readlines()
+ tag = log_data[0].strip()
+ date = log_data[1].strip()
+ user = log_data[2].strip()
+ parent = hgparents[str(cset)][0]
+ mparent = hgparents[str(cset)][1]
+
+ #get comment
(fdcomment, filecomment) = tempfile.mkstemp()
- csetcomment = os.popen('hg log -r %d -v | grep -v ^changeset: | grep -v ^parent: | grep -v ^user: | grep -v ^date | grep -v ^files: | grep -v ^description: | grep -v ^tag:' % cset).read().strip()
+ csetcomment = os.popen('hg log -r %d --template "{desc}"' % cset).read().strip()
os.write(fdcomment, csetcomment)
os.close(fdcomment)
- date = os.popen('hg log -r %d | grep ^date: | cut -f 2- -d :' % cset).read().strip()
-
- tag = os.popen('hg log -r %d | grep ^tag: | cut -f 2- -d :' % cset).read().strip()
-
- user = os.popen('hg log -r %d | grep ^user: | cut -f 2- -d :' % cset).read().strip()
-
print '-----------------------------------------'
print 'cset:', cset
print 'branch:', hgbranch[str(cset)]
print 'user:', user
print 'date:', date
print 'comment:', csetcomment
- print 'parent:', parent
+ if parent:
+ print 'parent:', parent
if mparent:
print 'mparent:', mparent
if tag:
@@ -178,10 +194,10 @@ for cset in range(int(tip) + 1):
if cset != 0:
if hgbranch[str(cset)] == "branch-" + str(cset):
print 'creating new branch', hgbranch[str(cset)]
- os.system('git-checkout -b %s %s' % (hgbranch[str(cset)], hgvers[parent]))
+ os.system('git checkout -b %s %s' % (hgbranch[str(cset)], hgvers[parent]))
else:
print 'checking out branch', hgbranch[str(cset)]
- os.system('git-checkout %s' % hgbranch[str(cset)])
+ os.system('git checkout %s' % hgbranch[str(cset)])
# merge
if mparent:
@@ -190,7 +206,7 @@ for cset in range(int(tip) + 1):
else:
otherbranch = hgbranch[parent]
print 'merging', otherbranch, 'into', hgbranch[str(cset)]
- os.system(getgitenv(user, date) + 'git-merge --no-commit -s ours "" %s %s' % (hgbranch[str(cset)], otherbranch))
+ os.system(getgitenv(user, date) + 'git merge --no-commit -s ours "" %s %s' % (hgbranch[str(cset)], otherbranch))
# remove everything except .git and .hg directories
os.system('find . \( -path "./.hg" -o -path "./.git" \) -prune -o ! -name "." -print | xargs rm -rf')
@@ -199,34 +215,35 @@ for cset in range(int(tip) + 1):
os.system('hg update -C %d' % cset)
# add new files
- os.system('git-ls-files -x .hg --others | git-update-index --add --stdin')
+ os.system('git ls-files -x .hg --others | git update-index --add --stdin')
# delete removed files
- os.system('git-ls-files -x .hg --deleted | git-update-index --remove --stdin')
+ os.system('git ls-files -x .hg --deleted | git update-index --remove --stdin')
# commit
- os.system(getgitenv(user, date) + 'git-commit -a -F %s' % filecomment)
+ os.system(getgitenv(user, date) + 'git commit --allow-empty -a -F %s' % filecomment)
os.unlink(filecomment)
# tag
if tag and tag != 'tip':
- os.system(getgitenv(user, date) + 'git-tag %s' % tag)
+ os.system(getgitenv(user, date) + 'git tag %s' % tag)
# delete branch if not used anymore...
if mparent and len(hgchildren[str(cset)]):
print "Deleting unused branch:", otherbranch
- os.system('git-branch -d %s' % otherbranch)
+ os.system('git branch -d %s' % otherbranch)
# retrieve and record the version
- vvv = os.popen('git-show | head -1').read()
- vvv = vvv[vvv.index(' ') + 1 : ].strip()
+ vvv = os.popen('git show --quiet --pretty=format:%H').read()
print 'record', cset, '->', vvv
hgvers[str(cset)] = vvv
-os.system('git-repack -a -d')
+if hgnewcsets >= opt_nrepack and opt_nrepack != -1:
+ os.system('git repack -a -d')
# write the state for incrementals
if state:
- print 'Writing state'
+ if verbose:
+ print 'Writing state'
f = open(state, 'w')
pickle.dump(hgvers, f)
diff --git a/contrib/hooks/post-receive-email b/contrib/hooks/post-receive-email
index c589a39a0c..60cbab65d3 100644
--- a/contrib/hooks/post-receive-email
+++ b/contrib/hooks/post-receive-email
@@ -2,24 +2,26 @@
#
# Copyright (c) 2007 Andy Parkins
#
-# An example hook script to mail out commit update information. This hook sends emails
-# listing new revisions to the repository introduced by the change being reported. The
-# rule is that (for branch updates) each commit will appear on one email and one email
-# only.
+# An example hook script to mail out commit update information. This hook
+# sends emails listing new revisions to the repository introduced by the
+# change being reported. The rule is that (for branch updates) each commit
+# will appear on one email and one email only.
#
-# This hook is stored in the contrib/hooks directory. Your distribution will have put
-# this somewhere standard. You should make this script executable then link to it in
-# the repository you would like to use it in. For example, on debian the hook is stored
-# in /usr/share/doc/git-core/contrib/hooks/post-receive-email:
+# This hook is stored in the contrib/hooks directory. Your distribution
+# will have put this somewhere standard. You should make this script
+# executable then link to it in the repository you would like to use it in.
+# For example, on debian the hook is stored in
+# /usr/share/doc/git-core/contrib/hooks/post-receive-email:
#
# chmod a+x post-receive-email
# cd /path/to/your/repository.git
# ln -sf /usr/share/doc/git-core/contrib/hooks/post-receive-email hooks/post-receive
#
-# This hook script assumes it is enabled on the central repository of a project, with
-# all users pushing only to it and not between each other. It will still work if you
-# don't operate in that style, but it would become possible for the email to be from
-# someone other than the person doing the push.
+# This hook script assumes it is enabled on the central repository of a
+# project, with all users pushing only to it and not between each other. It
+# will still work if you don't operate in that style, but it would become
+# possible for the email to be from someone other than the person doing the
+# push.
#
# Config
# ------
@@ -28,15 +30,23 @@
# emails for every ref update.
# hooks.announcelist
# This is the list that all pushes of annotated tags will go to. Leave it
-# blank to default to the mailinglist field. The announce emails lists the
-# short log summary of the changes since the last annotated tag.
-# hook.envelopesender
-# If set then the -f option is passed to sendmail to allow the envelope sender
-# address to be set
+# blank to default to the mailinglist field. The announce emails lists
+# the short log summary of the changes since the last annotated tag.
+# hooks.envelopesender
+# If set then the -f option is passed to sendmail to allow the envelope
+# sender address to be set
+# hooks.emailprefix
+# All emails have their subjects prefixed with this prefix, or "[SCM]"
+# if emailprefix is unset, to aid filtering
+# hooks.showrev
+# The shell command used to format each revision in the email, with
+# "%s" replaced with the commit id. Defaults to "git rev-list -1
+# --pretty %s", displaying the commit id, author, date and log
+# message. To list full patches separated by a blank line, you
+# could set this to "git show -C %s; echo".
#
# Notes
# -----
-# All emails have their subjects prefixed with "[SCM]" to aid filtering.
# All emails include the headers "X-Git-Refname", "X-Git-Oldrev",
# "X-Git-Newrev", and "X-Git-Reftype" to enable fine tuned filtering and
# give information for debugging.
@@ -49,8 +59,8 @@
# this is and calls the appropriate body-generation routine after outputting
# the common header
#
-# Note this function doesn't actually generate any email output, that is taken
-# care of by the functions it calls:
+# Note this function doesn't actually generate any email output, that is
+# taken care of by the functions it calls:
# - generate_email_header
# - generate_create_XXXX_email
# - generate_update_XXXX_email
@@ -138,16 +148,20 @@ generate_email()
# Check if we've got anyone to send to
if [ -z "$recipients" ]; then
- echo >&2 "*** hooks.recipients is not set so no email will be sent"
+ case "$refname_type" in
+ "annotated tag")
+ config_name="hooks.announcelist"
+ ;;
+ *)
+ config_name="hooks.mailinglist"
+ ;;
+ esac
+ echo >&2 "*** $config_name is not set so no email will be sent"
echo >&2 "*** for $refname update $oldrev->$newrev"
exit 0
fi
# Email parameters
- # The committer will be obtained from the latest existing rev; so
- # for a deletion it will be the oldrev, for the others, then newrev
- committer=$(git show --pretty=full -s $rev | sed -ne "s/^Commit: //p" |
- sed -ne 's/\(.*\) </"\1" </p')
# The email subject will contain the best description of the ref
# that we can build from the parameters
describe=$(git describe $rev 2>/dev/null)
@@ -177,9 +191,8 @@ generate_email_header()
# --- Email (all stdout will be the email)
# Generate header
cat <<-EOF
- From: $committer
To: $recipients
- Subject: ${EMAILPREFIX}$projectdesc $refname_type, $short_refname, ${change_type}d. $describe
+ Subject: ${emailprefix}$projectdesc $refname_type, $short_refname, ${change_type}d. $describe
X-Git-Refname: $refname
X-Git-Reftype: $refname_type
X-Git-Oldrev: $oldrev
@@ -195,11 +208,12 @@ generate_email_header()
generate_email_footer()
{
+ SPACE=" "
cat <<-EOF
hooks/post-receive
- --
+ --${SPACE}
$projectdesc
EOF
}
@@ -216,12 +230,7 @@ generate_create_branch_email()
echo ""
echo $LOGBEGIN
- # This shows all log entries that are not already covered by
- # another ref - i.e. commits that are now accessible from this
- # ref that were previously not accessible (see generate_update_branch_email
- # for the explanation of this command)
- git rev-parse --not --branches | grep -v $(git rev-parse $refname) |
- git rev-list --pretty --stdin $newrev
+ show_new_revisions
echo $LOGEND
}
@@ -240,35 +249,37 @@ generate_update_branch_email()
# In this case we want to issue an email containing only revisions
# 3, 4, and N. Given (almost) by
#
- # git-rev-list N ^O --not --all
+ # git rev-list N ^O --not --all
#
# The reason for the "almost", is that the "--not --all" will take
# precedence over the "N", and effectively will translate to
#
- # git-rev-list N ^O ^X ^N
+ # git rev-list N ^O ^X ^N
#
- # So, we need to build up the list more carefully. git-rev-parse will
- # generate a list of revs that may be fed into git-rev-list. We can get
- # it to make the "--not --all" part and then filter out the "^N" with:
+ # So, we need to build up the list more carefully. git rev-parse
+ # will generate a list of revs that may be fed into git rev-list.
+ # We can get it to make the "--not --all" part and then filter out
+ # the "^N" with:
#
- # git-rev-parse --not --all | grep -v N
+ # git rev-parse --not --all | grep -v N
#
- # Then, using the --stdin switch to git-rev-list we have effectively
+ # Then, using the --stdin switch to git rev-list we have effectively
# manufactured
#
- # git-rev-list N ^O ^X
+ # git rev-list N ^O ^X
#
# This leaves a problem when someone else updates the repository
- # while this script is running. Their new value of the ref we're working
- # on would be included in the "--not --all" output; and as our $newrev
- # would be an ancestor of that commit, it would exclude all of our
- # commits. What we really want is to exclude the current value of
- # $refname from the --not list, rather than N itself. So:
+ # while this script is running. Their new value of the ref we're
+ # working on would be included in the "--not --all" output; and as
+ # our $newrev would be an ancestor of that commit, it would exclude
+ # all of our commits. What we really want is to exclude the current
+ # value of $refname from the --not list, rather than N itself. So:
#
- # git-rev-parse --not --all | grep -v $(git-rev-parse $refname)
+ # git rev-parse --not --all | grep -v $(git rev-parse $refname)
#
- # Get's us to something pretty safe (apart from the small time between
- # refname being read, and git-rev-parse running - for that, I give up)
+ # Get's us to something pretty safe (apart from the small time
+ # between refname being read, and git rev-parse running - for that,
+ # I give up)
#
#
# Next problem, consider this:
@@ -276,18 +287,18 @@ generate_update_branch_email()
# \
# * --- X --- * --- N ($newrev)
#
- # That is to say, there is no guarantee that oldrev is a strict subset of
- # newrev (it would have required a --force, but that's allowed). So, we
- # can't simply say rev-list $oldrev..$newrev. Instead we find the common
- # base of the two revs and list from there.
+ # That is to say, there is no guarantee that oldrev is a strict
+ # subset of newrev (it would have required a --force, but that's
+ # allowed). So, we can't simply say rev-list $oldrev..$newrev.
+ # Instead we find the common base of the two revs and list from
+ # there.
#
- # As above, we need to take into account the presence of X; if another
- # branch is already in the repository and points at some of the revisions
- # that we are about to output - we don't want them. The solution is as
- # before: git-rev-parse output filtered.
+ # As above, we need to take into account the presence of X; if
+ # another branch is already in the repository and points at some of
+ # the revisions that we are about to output - we don't want them.
+ # The solution is as before: git rev-parse output filtered.
#
- # Finally, tags:
- # 1 --- 2 --- O --- T --- 3 --- 4 --- N
+ # Finally, tags: 1 --- 2 --- O --- T --- 3 --- 4 --- N
#
# Tags pushed into the repository generate nice shortlog emails that
# summarise the commits between them and the previous tag. However,
@@ -295,13 +306,14 @@ generate_update_branch_email()
# for a branch update. Therefore we still want to output revisions
# that have been output on a tag email.
#
- # Luckily, git-rev-parse includes just the tool. Instead of using "--all"
- # we use "--branches"; this has the added benefit that "remotes/" will
- # be ignored as well.
-
- # List all of the revisions that were removed by this update, in a fast forward
- # update, this list will be empty, because rev-list O ^N is empty. For a non
- # fast forward, O ^N is the list of removed revisions
+ # Luckily, git rev-parse includes just the tool. Instead of using
+ # "--all" we use "--branches"; this has the added benefit that
+ # "remotes/" will be ignored as well.
+
+ # List all of the revisions that were removed by this update, in a
+ # fast forward update, this list will be empty, because rev-list O
+ # ^N is empty. For a non fast forward, O ^N is the list of removed
+ # revisions
fast_forward=""
rev=""
for rev in $(git rev-list $newrev..$oldrev)
@@ -314,32 +326,33 @@ generate_update_branch_email()
fi
# List all the revisions from baserev to newrev in a kind of
- # "table-of-contents"; note this list can include revisions that have
- # already had notification emails and is present to show the full detail
- # of the change from rolling back the old revision to the base revision and
- # then forward to the new revision
+ # "table-of-contents"; note this list can include revisions that
+ # have already had notification emails and is present to show the
+ # full detail of the change from rolling back the old revision to
+ # the base revision and then forward to the new revision
for rev in $(git rev-list $oldrev..$newrev)
do
revtype=$(git cat-file -t "$rev")
echo " via $rev ($revtype)"
done
- if [ -z "$fastforward" ]; then
+ if [ "$fast_forward" ]; then
echo " from $oldrev ($oldrev_type)"
else
- # 1. Existing revisions were removed. In this case newrev is a
- # subset of oldrev - this is the reverse of a fast-forward,
- # a rewind
- # 2. New revisions were added on top of an old revision, this is
- # a rewind and addition.
+ # 1. Existing revisions were removed. In this case newrev
+ # is a subset of oldrev - this is the reverse of a
+ # fast-forward, a rewind
+ # 2. New revisions were added on top of an old revision,
+ # this is a rewind and addition.
- # (1) certainly happened, (2) possibly. When (2) hasn't happened,
- # we set a flag to indicate that no log printout is required.
+ # (1) certainly happened, (2) possibly. When (2) hasn't
+ # happened, we set a flag to indicate that no log printout
+ # is required.
echo ""
- # Find the common ancestor of the old and new revisions and compare
- # it with newrev
+ # Find the common ancestor of the old and new revisions and
+ # compare it with newrev
baserev=$(git merge-base $oldrev $newrev)
rewind_only=""
if [ "$baserev" = "$newrev" ]; then
@@ -377,24 +390,24 @@ generate_update_branch_email()
echo ""
echo $LOGBEGIN
- git rev-parse --not --branches | grep -v $(git rev-parse $refname) |
- git rev-list --pretty --stdin $oldrev..$newrev
+ show_new_revisions
- # XXX: Need a way of detecting whether git rev-list actually outputted
- # anything, so that we can issue a "no new revisions added by this
- # update" message
+ # XXX: Need a way of detecting whether git rev-list actually
+ # outputted anything, so that we can issue a "no new
+ # revisions added by this update" message
echo $LOGEND
else
echo "No new revisions were added by this update."
fi
- # The diffstat is shown from the old revision to the new revision. This
- # is to show the truth of what happened in this change. There's no point
- # showing the stat from the base to the new revision because the base
- # is effectively a random revision at this point - the user will be
- # interested in what this revision changed - including the undoing of
- # previous revisions in the case of non-fast forward updates.
+ # The diffstat is shown from the old revision to the new revision.
+ # This is to show the truth of what happened in this change.
+ # There's no point showing the stat from the base to the new
+ # revision because the base is effectively a random revision at this
+ # point - the user will be interested in what this revision changed
+ # - including the undoing of previous revisions in the case of
+ # non-fast forward updates.
echo ""
echo "Summary of changes:"
git diff-tree --stat --summary --find-copies-harder $oldrev..$newrev
@@ -441,7 +454,8 @@ generate_update_atag_email()
#
generate_atag_email()
{
- # Use git-for-each-ref to pull out the individual fields from the tag
+ # Use git for-each-ref to pull out the individual fields from the
+ # tag
eval $(git for-each-ref --shell --format='
tagobject=%(*objectname)
tagtype=%(*objecttype)
@@ -452,8 +466,10 @@ generate_atag_email()
echo " tagging $tagobject ($tagtype)"
case "$tagtype" in
commit)
+
# If the tagged object is a commit, then we assume this is a
- # release, and so we calculate which tag this tag is replacing
+ # release, and so we calculate which tag this tag is
+ # replacing
prevtag=$(git describe --abbrev=0 $newrev^ 2>/dev/null)
if [ -n "$prevtag" ]; then
@@ -470,25 +486,27 @@ generate_atag_email()
echo ""
echo $LOGBEGIN
- # Show the content of the tag message; this might contain a change log
- # or release notes so is worth displaying.
+ # Show the content of the tag message; this might contain a change
+ # log or release notes so is worth displaying.
git cat-file tag $newrev | sed -e '1,/^$/d'
echo ""
case "$tagtype" in
commit)
- # Only commit tags make sense to have rev-list operations performed
- # on them
+ # Only commit tags make sense to have rev-list operations
+ # performed on them
if [ -n "$prevtag" ]; then
# Show changes since the previous release
git rev-list --pretty=short "$prevtag..$newrev" | git shortlog
else
- # No previous tag, show all the changes since time began
+ # No previous tag, show all the changes since time
+ # began
git rev-list --pretty=short $newrev | git shortlog
fi
;;
*)
- # XXX: Is there anything useful we can do for non-commit objects?
+ # XXX: Is there anything useful we can do for non-commit
+ # objects?
;;
esac
@@ -537,24 +555,25 @@ generate_update_general_email()
#
generate_general_email()
{
- # Unannotated tags are more about marking a point than releasing a version;
- # therefore we don't do the shortlog summary that we do for annotated tags
- # above - we simply show that the point has been marked, and print the log
- # message for the marked point for reference purposes
+ # Unannotated tags are more about marking a point than releasing a
+ # version; therefore we don't do the shortlog summary that we do for
+ # annotated tags above - we simply show that the point has been
+ # marked, and print the log message for the marked point for
+ # reference purposes
#
- # Note this section also catches any other reference type (although there
- # aren't any) and deals with them in the same way.
+ # Note this section also catches any other reference type (although
+ # there aren't any) and deals with them in the same way.
echo ""
if [ "$newrev_type" = "commit" ]; then
echo $LOGBEGIN
- git show --no-color --root -s $newrev
+ git show --no-color --root -s --pretty=medium $newrev
echo $LOGEND
else
- # What can we do here? The tag marks an object that is not a commit,
- # so there is no log for us to display. It's probably not wise to
- # output git-cat-file as it could be a binary blob. We'll just say how
- # big it is
+ # What can we do here? The tag marks an object that is not
+ # a commit, so there is no log for us to display. It's
+ # probably not wise to output git cat-file as it could be a
+ # binary blob. We'll just say how big it is
echo "$newrev is a $newrev_type, and is $(git cat-file -s $newrev) bytes long."
fi
}
@@ -571,10 +590,59 @@ generate_delete_general_email()
echo $LOGEND
}
+
+# --------------- Miscellaneous utilities
+
+#
+# Show new revisions as the user would like to see them in the email.
+#
+show_new_revisions()
+{
+ # This shows all log entries that are not already covered by
+ # another ref - i.e. commits that are now accessible from this
+ # ref that were previously not accessible
+ # (see generate_update_branch_email for the explanation of this
+ # command)
+
+ # Revision range passed to rev-list differs for new vs. updated
+ # branches.
+ if [ "$change_type" = create ]
+ then
+ # Show all revisions exclusive to this (new) branch.
+ revspec=$newrev
+ else
+ # Branch update; show revisions not part of $oldrev.
+ revspec=$oldrev..$newrev
+ fi
+
+ other_branches=$(git for-each-ref --format='%(refname)' refs/heads/ |
+ grep -F -v $refname)
+ git rev-parse --not $other_branches |
+ if [ -z "$custom_showrev" ]
+ then
+ git rev-list --pretty --stdin $revspec
+ else
+ git rev-list --stdin $revspec |
+ while read onerev
+ do
+ eval $(printf "$custom_showrev" $onerev)
+ done
+ fi
+}
+
+
+send_mail()
+{
+ if [ -n "$envelopesender" ]; then
+ /usr/sbin/sendmail -t -f "$envelopesender"
+ else
+ /usr/sbin/sendmail -t
+ fi
+}
+
# ---------------------------- main()
# --- Constants
-EMAILPREFIX="[SCM] "
LOGBEGIN="- Log -----------------------------------------------------------------"
LOGEND="-----------------------------------------------------------------------"
@@ -588,32 +656,30 @@ if [ -z "$GIT_DIR" ]; then
fi
projectdesc=$(sed -ne '1p' "$GIT_DIR/description")
-# Check if the description is unchanged from it's default, and shorten it to a
-# more manageable length if it is
+# Check if the description is unchanged from it's default, and shorten it to
+# a more manageable length if it is
if expr "$projectdesc" : "Unnamed repository.*$" >/dev/null
then
projectdesc="UNNAMED PROJECT"
fi
-recipients=$(git repo-config hooks.mailinglist)
-announcerecipients=$(git repo-config hooks.announcelist)
-envelopesender=$(git-repo-config hooks.envelopesender)
+recipients=$(git config hooks.mailinglist)
+announcerecipients=$(git config hooks.announcelist)
+envelopesender=$(git config hooks.envelopesender)
+emailprefix=$(git config hooks.emailprefix || echo '[SCM] ')
+custom_showrev=$(git config hooks.showrev)
# --- Main loop
-# Allow dual mode: run from the command line just like the update hook, or if
-# no arguments are given then run as a hook script
+# Allow dual mode: run from the command line just like the update hook, or
+# if no arguments are given then run as a hook script
if [ -n "$1" -a -n "$2" -a -n "$3" ]; then
# Output to the terminal in command line mode - if someone wanted to
- # resend an email; they could redirect the output to sendmail themselves
+ # resend an email; they could redirect the output to sendmail
+ # themselves
PAGER= generate_email $2 $3 $1
else
- if [ -n "$envelopesender" ]; then
- envelopesender="-f '$envelopesender'"
- fi
-
while read oldrev newrev refname
do
- generate_email $oldrev $newrev $refname |
- /usr/sbin/sendmail -t $envelopesender
+ generate_email $oldrev $newrev $refname | send_mail
done
fi
diff --git a/contrib/hooks/pre-auto-gc-battery b/contrib/hooks/pre-auto-gc-battery
new file mode 100644
index 0000000000..1f914c94aa
--- /dev/null
+++ b/contrib/hooks/pre-auto-gc-battery
@@ -0,0 +1,43 @@
+#!/bin/sh
+#
+# An example hook script to verify if you are on battery, in case you
+# are running Linux or OS X. Called by git-gc --auto with no arguments.
+# The hook should exit with non-zero status after issuing an appropriate
+# message if it wants to stop the auto repacking.
+#
+# This hook is stored in the contrib/hooks directory. Your distribution
+# may have put this somewhere else. If you want to use this hook, you
+# should make this script executable then link to it in the repository
+# you would like to use it in.
+#
+# For example, if the hook is stored in
+# /usr/share/git-core/contrib/hooks/pre-auto-gc-battery:
+#
+# chmod a+x pre-auto-gc-battery
+# cd /path/to/your/repository.git
+# ln -sf /usr/share/git-core/contrib/hooks/pre-auto-gc-battery \
+# hooks/pre-auto-gc
+
+if test -x /sbin/on_ac_power && /sbin/on_ac_power
+then
+ exit 0
+elif test "$(cat /sys/class/power_supply/AC/online 2>/dev/null)" = 1
+then
+ exit 0
+elif grep -q 'on-line' /proc/acpi/ac_adapter/AC/state 2>/dev/null
+then
+ exit 0
+elif grep -q '0x01$' /proc/apm 2>/dev/null
+then
+ exit 0
+elif grep -q "AC Power \+: 1" /proc/pmu/info 2>/dev/null
+then
+ exit 0
+elif test -x /usr/bin/pmset && /usr/bin/pmset -g batt |
+ grep -q "Currently drawing from 'AC Power'"
+then
+ exit 0
+fi
+
+echo "Auto packing deferred; not on AC"
+exit 1
diff --git a/contrib/hooks/setgitperms.perl b/contrib/hooks/setgitperms.perl
new file mode 100644
index 0000000000..a577ad095f
--- /dev/null
+++ b/contrib/hooks/setgitperms.perl
@@ -0,0 +1,214 @@
+#!/usr/bin/perl
+#
+# Copyright (c) 2006 Josh England
+#
+# This script can be used to save/restore full permissions and ownership data
+# within a git working tree.
+#
+# To save permissions/ownership data, place this script in your .git/hooks
+# directory and enable a `pre-commit` hook with the following lines:
+# #!/bin/sh
+# SUBDIRECTORY_OK=1 . git-sh-setup
+# $GIT_DIR/hooks/setgitperms.perl -r
+#
+# To restore permissions/ownership data, place this script in your .git/hooks
+# directory and enable a `post-merge` and `post-checkout` hook with the
+# following lines:
+# #!/bin/sh
+# SUBDIRECTORY_OK=1 . git-sh-setup
+# $GIT_DIR/hooks/setgitperms.perl -w
+#
+use strict;
+use Getopt::Long;
+use File::Find;
+use File::Basename;
+
+my $usage =
+"Usage: setgitperms.perl [OPTION]... <--read|--write>
+This program uses a file `.gitmeta` to store/restore permissions and uid/gid
+info for all files/dirs tracked by git in the repository.
+
+---------------------------------Read Mode-------------------------------------
+-r, --read Reads perms/etc from working dir into a .gitmeta file
+-s, --stdout Output to stdout instead of .gitmeta
+-d, --diff Show unified diff of perms file (XOR with --stdout)
+
+---------------------------------Write Mode------------------------------------
+-w, --write Modify perms/etc in working dir to match the .gitmeta file
+-v, --verbose Be verbose
+
+\n";
+
+my ($stdout, $showdiff, $verbose, $read_mode, $write_mode);
+
+if ((@ARGV < 0) || !GetOptions(
+ "stdout", \$stdout,
+ "diff", \$showdiff,
+ "read", \$read_mode,
+ "write", \$write_mode,
+ "verbose", \$verbose,
+ )) { die $usage; }
+die $usage unless ($read_mode xor $write_mode);
+
+my $topdir = `git rev-parse --show-cdup` or die "\n"; chomp $topdir;
+my $gitdir = $topdir . '.git';
+my $gitmeta = $topdir . '.gitmeta';
+
+if ($write_mode) {
+ # Update the working dir permissions/ownership based on data from .gitmeta
+ open (IN, "<$gitmeta") or die "Could not open $gitmeta for reading: $!\n";
+ while (defined ($_ = <IN>)) {
+ chomp;
+ if (/^(.*) mode=(\S+)\s+uid=(\d+)\s+gid=(\d+)/) {
+ # Compare recorded perms to actual perms in the working dir
+ my ($path, $mode, $uid, $gid) = ($1, $2, $3, $4);
+ my $fullpath = $topdir . $path;
+ my (undef,undef,$wmode,undef,$wuid,$wgid) = lstat($fullpath);
+ $wmode = sprintf "%04o", $wmode & 07777;
+ if ($mode ne $wmode) {
+ $verbose && print "Updating permissions on $path: old=$wmode, new=$mode\n";
+ chmod oct($mode), $fullpath;
+ }
+ if ($uid != $wuid || $gid != $wgid) {
+ if ($verbose) {
+ # Print out user/group names instead of uid/gid
+ my $pwname = getpwuid($uid);
+ my $grpname = getgrgid($gid);
+ my $wpwname = getpwuid($wuid);
+ my $wgrpname = getgrgid($wgid);
+ $pwname = $uid if !defined $pwname;
+ $grpname = $gid if !defined $grpname;
+ $wpwname = $wuid if !defined $wpwname;
+ $wgrpname = $wgid if !defined $wgrpname;
+
+ print "Updating uid/gid on $path: old=$wpwname/$wgrpname, new=$pwname/$grpname\n";
+ }
+ chown $uid, $gid, $fullpath;
+ }
+ }
+ else {
+ warn "Invalid input format in $gitmeta:\n\t$_\n";
+ }
+ }
+ close IN;
+}
+elsif ($read_mode) {
+ # Handle merge conflicts in the .gitperms file
+ if (-e "$gitdir/MERGE_MSG") {
+ if (`grep ====== $gitmeta`) {
+ # Conflict not resolved -- abort the commit
+ print "PERMISSIONS/OWNERSHIP CONFLICT\n";
+ print " Resolve the conflict in the $gitmeta file and then run\n";
+ print " `.git/hooks/setgitperms.perl --write` to reconcile.\n";
+ exit 1;
+ }
+ elsif (`grep $gitmeta $gitdir/MERGE_MSG`) {
+ # A conflict in .gitmeta has been manually resolved. Verify that
+ # the working dir perms matches the current .gitmeta perms for
+ # each file/dir that conflicted.
+ # This is here because a `setgitperms.perl --write` was not
+ # performed due to a merge conflict, so permissions/ownership
+ # may not be consistent with the manually merged .gitmeta file.
+ my @conflict_diff = `git show \$(cat $gitdir/MERGE_HEAD)`;
+ my @conflict_files;
+ my $metadiff = 0;
+
+ # Build a list of files that conflicted from the .gitmeta diff
+ foreach my $line (@conflict_diff) {
+ if ($line =~ m|^diff --git a/$gitmeta b/$gitmeta|) {
+ $metadiff = 1;
+ }
+ elsif ($line =~ /^diff --git/) {
+ $metadiff = 0;
+ }
+ elsif ($metadiff && $line =~ /^\+(.*) mode=/) {
+ push @conflict_files, $1;
+ }
+ }
+
+ # Verify that each conflict file now has permissions consistent
+ # with the .gitmeta file
+ foreach my $file (@conflict_files) {
+ my $absfile = $topdir . $file;
+ my $gm_entry = `grep "^$file mode=" $gitmeta`;
+ if ($gm_entry =~ /mode=(\d+) uid=(\d+) gid=(\d+)/) {
+ my ($gm_mode, $gm_uid, $gm_gid) = ($1, $2, $3);
+ my (undef,undef,$mode,undef,$uid,$gid) = lstat("$absfile");
+ $mode = sprintf("%04o", $mode & 07777);
+ if (($gm_mode ne $mode) || ($gm_uid != $uid)
+ || ($gm_gid != $gid)) {
+ print "PERMISSIONS/OWNERSHIP CONFLICT\n";
+ print " Mismatch found for file: $file\n";
+ print " Run `.git/hooks/setgitperms.perl --write` to reconcile.\n";
+ exit 1;
+ }
+ }
+ else {
+ print "Warning! Permissions/ownership no longer being tracked for file: $file\n";
+ }
+ }
+ }
+ }
+
+ # No merge conflicts -- write out perms/ownership data to .gitmeta file
+ unless ($stdout) {
+ open (OUT, ">$gitmeta.tmp") or die "Could not open $gitmeta.tmp for writing: $!\n";
+ }
+
+ my @files = `git ls-files`;
+ my %dirs;
+
+ foreach my $path (@files) {
+ chomp $path;
+ # We have to manually add stats for parent directories
+ my $parent = dirname($path);
+ while (!exists $dirs{$parent}) {
+ $dirs{$parent} = 1;
+ next if $parent eq '.';
+ printstats($parent);
+ $parent = dirname($parent);
+ }
+ # Now the git-tracked file
+ printstats($path);
+ }
+
+ # diff the temporary metadata file to see if anything has changed
+ # If no metadata has changed, don't overwrite the real file
+ # This is just so `git commit -a` doesn't try to commit a bogus update
+ unless ($stdout) {
+ if (! -e $gitmeta) {
+ rename "$gitmeta.tmp", $gitmeta;
+ }
+ else {
+ my $diff = `diff -U 0 $gitmeta $gitmeta.tmp`;
+ if ($diff ne '') {
+ rename "$gitmeta.tmp", $gitmeta;
+ }
+ else {
+ unlink "$gitmeta.tmp";
+ }
+ if ($showdiff) {
+ print $diff;
+ }
+ }
+ close OUT;
+ }
+ # Make sure the .gitmeta file is tracked
+ system("git add $gitmeta");
+}
+
+
+sub printstats {
+ my $path = $_[0];
+ $path =~ s/@/\@/g;
+ my (undef,undef,$mode,undef,$uid,$gid) = lstat($path);
+ $path =~ s/%/\%/g;
+ if ($stdout) {
+ print $path;
+ printf " mode=%04o uid=$uid gid=$gid\n", $mode & 07777;
+ }
+ else {
+ print OUT $path;
+ printf OUT " mode=%04o uid=$uid gid=$gid\n", $mode & 07777;
+ }
+}
diff --git a/contrib/hooks/update-paranoid b/contrib/hooks/update-paranoid
index 068fa37083..d18b317b2f 100644
--- a/contrib/hooks/update-paranoid
+++ b/contrib/hooks/update-paranoid
@@ -136,6 +136,7 @@ sub parse_config ($$$$) {
local $ENV{GIT_DIR} = shift;
my $br = shift;
my $fn = shift;
+ return unless git_value('rev-list','--max-count=1',$br,'--',$fn);
info "Loading $br:$fn";
open(I,'-|','git','cat-file','blob',"$br:$fn");
my $section = '';
@@ -225,14 +226,12 @@ sub load_diff ($) {
local $/ = "\0";
my %this_diff;
if ($base =~ /^0{40}$/) {
- open(T,'-|','git','ls-tree',
- '-r','--name-only','-z',
- $new) or return undef;
- while (<T>) {
- chop;
- $this_diff{$_} = 'A';
- }
- close T or return undef;
+ # Don't load the diff at all; we are making the
+ # branch and have no base to compare to in this
+ # case. A file level ACL makes no sense in this
+ # context. Having an empty diff will allow the
+ # branch creation.
+ #
} else {
open(T,'-|','git','diff-tree',
'-r','--name-status','-z',
@@ -260,6 +259,7 @@ deny "Refusing funny ref $ref" unless $ref =~ s,^refs/,,;
deny "Bad old value $old" unless $old =~ /^[a-z0-9]{40}$/;
deny "Bad new value $new" unless $new =~ /^[a-z0-9]{40}$/;
deny "Cannot determine who you are." unless $this_user;
+grant "No change requested." if $old eq $new;
$repository_name = File::Spec->rel2abs($git_dir);
$repository_name =~ m,/([^/]+)(?:\.git|/\.git)$,;
diff --git a/contrib/remotes2config.sh b/contrib/remotes2config.sh
index 5838b3ab05..1cda19f66a 100644..100755
--- a/contrib/remotes2config.sh
+++ b/contrib/remotes2config.sh
@@ -11,11 +11,11 @@ if [ -d "$GIT_DIR"/remotes ]; then
{
cd "$GIT_DIR"/remotes
ls | while read f; do
- name=$(printf "$f" | tr -c "A-Za-z0-9" ".")
+ name=$(printf "$f" | tr -c "A-Za-z0-9-" ".")
sed -n \
- -e "s/^URL: \(.*\)$/remote.$name.url \1 ./p" \
- -e "s/^Pull: \(.*\)$/remote.$name.fetch \1 ^$ /p" \
- -e "s/^Push: \(.*\)$/remote.$name.push \1 ^$ /p" \
+ -e "s/^URL:[ ]*\(.*\)$/remote.$name.url \1 ./p" \
+ -e "s/^Pull:[ ]*\(.*\)$/remote.$name.fetch \1 ^$ /p" \
+ -e "s/^Push:[ ]*\(.*\)$/remote.$name.push \1 ^$ /p" \
< "$f"
done
echo done
diff --git a/contrib/rerere-train.sh b/contrib/rerere-train.sh
new file mode 100755
index 0000000000..2cfe1b936b
--- /dev/null
+++ b/contrib/rerere-train.sh
@@ -0,0 +1,52 @@
+#!/bin/sh
+# Copyright (c) 2008, Nanako Shiraishi
+# Prime rerere database from existing merge commits
+
+me=rerere-train
+USAGE="$me rev-list-args"
+
+SUBDIRECTORY_OK=Yes
+OPTIONS_SPEC=
+. git-sh-setup
+require_work_tree
+cd_to_toplevel
+
+# Remember original branch
+branch=$(git symbolic-ref -q HEAD) ||
+original_HEAD=$(git rev-parse --verify HEAD) || {
+ echo >&2 "Not on any branch and no commit yet?"
+ exit 1
+}
+
+mkdir -p "$GIT_DIR/rr-cache" || exit
+
+git rev-list --parents "$@" |
+while read commit parent1 other_parents
+do
+ if test -z "$other_parents"
+ then
+ # Skip non-merges
+ continue
+ fi
+ git checkout -q "$parent1^0"
+ if git merge $other_parents >/dev/null 2>&1
+ then
+ # Cleanly merges
+ continue
+ fi
+ if test -s "$GIT_DIR/MERGE_RR"
+ then
+ git show -s --pretty=format:"Learning from %h %s" "$commit"
+ git rerere
+ git checkout -q $commit -- .
+ git rerere
+ fi
+ git reset -q --hard
+done
+
+if test -z "$branch"
+then
+ git checkout "$original_HEAD"
+else
+ git checkout "${branch#refs/heads/}"
+fi
diff --git a/contrib/stats/packinfo.pl b/contrib/stats/packinfo.pl
index aab501ea08..be188c0f11 100755
--- a/contrib/stats/packinfo.pl
+++ b/contrib/stats/packinfo.pl
@@ -1,9 +1,9 @@
#!/usr/bin/perl
#
# This tool will print vaguely pretty information about a pack. It
-# expects the output of "git-verify-pack -v" as input on stdin.
+# expects the output of "git verify-pack -v" as input on stdin.
#
-# $ git-verify-pack -v | packinfo.pl
+# $ git verify-pack -v | packinfo.pl
#
# This prints some full-pack statistics; currently "all sizes", "all
# path sizes", "tree sizes", "tree path sizes", and "depths".
@@ -20,7 +20,7 @@
#
# When run as:
#
-# $ git-verify-pack -v | packinfo.pl -tree
+# $ git verify-pack -v | packinfo.pl -tree
#
# the trees of objects are output along with the stats. This looks
# like:
@@ -43,7 +43,7 @@
#
# When run as:
#
-# $ git-verify-pack -v | packinfo.pl -tree -filenames
+# $ git verify-pack -v | packinfo.pl -tree -filenames
#
# it adds filenames to the tree. Getting this information is slow:
#
@@ -58,7 +58,7 @@
#
# When run as:
#
-# $ git-verify-pack -v | packinfo.pl -dump
+# $ git verify-pack -v | packinfo.pl -dump
#
# it prints out "sha1 size pathsize depth" for each sha1 in lexical
# order.
@@ -93,7 +93,7 @@ my %depths;
my @depths;
while (<STDIN>) {
- my ($sha1, $type, $size, $offset, $depth, $parent) = split(/\s+/, $_);
+ my ($sha1, $type, $size, $space, $offset, $depth, $parent) = split(/\s+/, $_);
next unless ($sha1 =~ /^[0-9a-f]{40}$/);
$depths{$sha1} = $depth || 0;
push(@depths, $depth || 0);
@@ -106,7 +106,7 @@ while (<STDIN>) {
}
if ($filenames && ($tree || $dump)) {
- open(NAMES, "git-name-rev --all|");
+ open(NAMES, "git name-rev --all|");
while (<NAMES>) {
if (/^(\S+)\s+(.*)$/) {
my ($sha1, $name) = ($1, $2);
@@ -117,7 +117,7 @@ if ($filenames && ($tree || $dump)) {
for my $commit (@commits) {
my $name = $names{$commit};
- open(TREE, "git-ls-tree -t -r $commit|");
+ open(TREE, "git ls-tree -t -r $commit|");
print STDERR "Plumbing tree $name\n";
while (<TREE>) {
if (/^(\S+)\s+(\S+)\s+(\S+)\s+(.*)$/) {
diff --git a/contrib/thunderbird-patch-inline/README b/contrib/thunderbird-patch-inline/README
new file mode 100644
index 0000000000..000147bbe4
--- /dev/null
+++ b/contrib/thunderbird-patch-inline/README
@@ -0,0 +1,20 @@
+appp.sh is a script that is supposed to be used together with ExternalEditor
+for Mozilla Thunderbird. It will let you include patches inline in e-mails
+in an easy way.
+
+Usage:
+- Generate the patch with git format-patch.
+- Start writing a new e-mail in Thunderbird.
+- Press the external editor button (or Ctrl-E) to run appp.sh
+- Select the previously generated patch file.
+- Finish editing the e-mail.
+
+Any text that is entered into the message editor before appp.sh is called
+will be moved to the section between the --- and the diffstat.
+
+All S-O-B:s and Cc:s in the patch will be added to the CC list.
+
+To set it up, just install External Editor and tell it to use appp.sh as the
+editor.
+
+Zenity is a required dependency.
diff --git a/contrib/thunderbird-patch-inline/appp.sh b/contrib/thunderbird-patch-inline/appp.sh
new file mode 100755
index 0000000000..cc518f3c89
--- /dev/null
+++ b/contrib/thunderbird-patch-inline/appp.sh
@@ -0,0 +1,55 @@
+#!/bin/bash
+# Copyright 2008 Lukas Sandström <luksan@gmail.com>
+#
+# AppendPatch - A script to be used together with ExternalEditor
+# for Mozilla Thunderbird to properly include pathes inline i e-mails.
+
+# ExternalEditor can be downloaded at http://globs.org/articles.php?lng=en&pg=2
+
+CONFFILE=~/.appprc
+
+SEP="-=-=-=-=-=-=-=-=-=# Don't remove this line #=-=-=-=-=-=-=-=-=-"
+if [ -e "$CONFFILE" ] ; then
+ LAST_DIR=`grep -m 1 "^LAST_DIR=" "${CONFFILE}"|sed -e 's/^LAST_DIR=//'`
+ cd "${LAST_DIR}"
+else
+ cd > /dev/null
+fi
+
+PATCH=$(zenity --file-selection)
+
+if [ "$?" != "0" ] ; then
+ #zenity --error --text "No patchfile given."
+ exit 1
+fi
+
+cd - > /dev/null
+
+SUBJECT=`sed -n -e '/^Subject: /p' "${PATCH}"`
+HEADERS=`sed -e '/^'"${SEP}"'$/,$d' $1`
+BODY=`sed -e "1,/${SEP}/d" $1`
+CMT_MSG=`sed -e '1,/^$/d' -e '/^---$/,$d' "${PATCH}"`
+DIFF=`sed -e '1,/^---$/d' "${PATCH}"`
+
+CCS=`echo -e "$CMT_MSG\n$HEADERS" | sed -n -e 's/^Cc: \(.*\)$/\1,/gp' \
+ -e 's/^Signed-off-by: \(.*\)/\1,/gp'`
+
+echo "$SUBJECT" > $1
+echo "Cc: $CCS" >> $1
+echo "$HEADERS" | sed -e '/^Subject: /d' -e '/^Cc: /d' >> $1
+echo "$SEP" >> $1
+
+echo "$CMT_MSG" >> $1
+echo "---" >> $1
+if [ "x${BODY}x" != "xx" ] ; then
+ echo >> $1
+ echo "$BODY" >> $1
+ echo >> $1
+fi
+echo "$DIFF" >> $1
+
+LAST_DIR=`dirname "${PATCH}"`
+
+grep -v "^LAST_DIR=" "${CONFFILE}" > "${CONFFILE}_"
+echo "LAST_DIR=${LAST_DIR}" >> "${CONFFILE}_"
+mv "${CONFFILE}_" "${CONFFILE}"
diff --git a/contrib/vim/README b/contrib/vim/README
index 9e7881fea9..fca1e17251 100644
--- a/contrib/vim/README
+++ b/contrib/vim/README
@@ -1,8 +1,32 @@
-To syntax highlight git's commit messages, you need to:
- 1. Copy syntax/gitcommit.vim to vim's syntax directory:
- $ mkdir -p $HOME/.vim/syntax
- $ cp syntax/gitcommit.vim $HOME/.vim/syntax
- 2. Auto-detect the editing of git commit files:
- $ cat >>$HOME/.vimrc <<'EOF'
- autocmd BufNewFile,BufRead COMMIT_EDITMSG set filetype=gitcommit
- EOF
+Syntax highlighting for git commit messages, config files, etc. is
+included with the vim distribution as of vim 7.2, and should work
+automatically.
+
+If you have an older version of vim, you can get the latest syntax
+files from the vim project:
+
+ http://ftp.vim.org/pub/vim/runtime/syntax/git.vim
+ http://ftp.vim.org/pub/vim/runtime/syntax/gitcommit.vim
+ http://ftp.vim.org/pub/vim/runtime/syntax/gitconfig.vim
+ http://ftp.vim.org/pub/vim/runtime/syntax/gitrebase.vim
+ http://ftp.vim.org/pub/vim/runtime/syntax/gitsendemail.vim
+
+These files are also available via FTP at the same location.
+
+To install:
+
+ 1. Copy these files to vim's syntax directory $HOME/.vim/syntax
+ 2. To auto-detect the editing of various git-related filetypes:
+ $ cat >>$HOME/.vim/filetype.vim <<'EOF'
+ autocmd BufNewFile,BufRead *.git/COMMIT_EDITMSG setf gitcommit
+ autocmd BufNewFile,BufRead *.git/config,.gitconfig setf gitconfig
+ autocmd BufNewFile,BufRead git-rebase-todo setf gitrebase
+ autocmd BufNewFile,BufRead .msg.[0-9]*
+ \ if getline(1) =~ '^From.*# This line is ignored.$' |
+ \ setf gitsendemail |
+ \ endif
+ autocmd BufNewFile,BufRead *.git/**
+ \ if getline(1) =~ '^\x\{40\}\>\|^ref: ' |
+ \ setf git |
+ \ endif
+ EOF
diff --git a/contrib/vim/syntax/gitcommit.vim b/contrib/vim/syntax/gitcommit.vim
deleted file mode 100644
index 332121b40e..0000000000
--- a/contrib/vim/syntax/gitcommit.vim
+++ /dev/null
@@ -1,18 +0,0 @@
-syn region gitLine start=/^#/ end=/$/
-syn region gitCommit start=/^# Changes to be committed:$/ end=/^#$/ contains=gitHead,gitCommitFile
-syn region gitHead contained start=/^# (.*)/ end=/^#$/
-syn region gitChanged start=/^# Changed but not updated:/ end=/^#$/ contains=gitHead,gitChangedFile
-syn region gitUntracked start=/^# Untracked files:/ end=/^#$/ contains=gitHead,gitUntrackedFile
-
-syn match gitCommitFile contained /^#\t.*/hs=s+2
-syn match gitChangedFile contained /^#\t.*/hs=s+2
-syn match gitUntrackedFile contained /^#\t.*/hs=s+2
-
-hi def link gitLine Comment
-hi def link gitCommit Comment
-hi def link gitChanged Comment
-hi def link gitHead Comment
-hi def link gitUntracked Comment
-hi def link gitCommitFile Type
-hi def link gitChangedFile Constant
-hi def link gitUntrackedFile Constant
diff --git a/contrib/workdir/git-new-workdir b/contrib/workdir/git-new-workdir
index 2838546d16..993cacf324 100755
--- a/contrib/workdir/git-new-workdir
+++ b/contrib/workdir/git-new-workdir
@@ -22,7 +22,7 @@ branch=$3
# want to make sure that what is pointed to has a .git directory ...
git_dir=$(cd "$orig_git" 2>/dev/null &&
git rev-parse --git-dir 2>/dev/null) ||
- die "\"$orig_git\" is not a git repository!"
+ die "Not a git repository: \"$orig_git\""
case "$git_dir" in
.git)
@@ -63,7 +63,7 @@ mkdir -p "$new_workdir/.git" || die "unable to create \"$new_workdir\"!"
# create the links to the original repo. explictly exclude index, HEAD and
# logs/HEAD from the list since they are purely related to the current working
# directory, and should not be shared.
-for x in config refs logs/refs objects info hooks packed-refs remotes rr-cache
+for x in config refs logs/refs objects info hooks packed-refs remotes rr-cache svn
do
case $x in
*/*)