summaryrefslogtreecommitdiff
path: root/contrib
diff options
context:
space:
mode:
Diffstat (limited to 'contrib')
-rw-r--r--contrib/coccinelle/array.cocci16
-rw-r--r--contrib/coccinelle/free.cocci6
-rw-r--r--contrib/coccinelle/qsort.cocci37
-rw-r--r--contrib/coccinelle/strbuf.cocci6
-rw-r--r--contrib/coccinelle/swap.cocci28
-rw-r--r--contrib/coccinelle/xstrdup_or_null.cocci6
-rw-r--r--contrib/completion/git-completion.bash706
-rw-r--r--contrib/completion/git-completion.zsh9
-rw-r--r--contrib/completion/git-prompt.sh3
-rw-r--r--contrib/convert-objects/convert-objects.c329
-rw-r--r--contrib/convert-objects/git-convert-objects.txt29
-rw-r--r--contrib/credential/libsecret/Makefile25
-rw-r--r--contrib/credential/libsecret/git-credential-libsecret.c370
-rwxr-xr-xcontrib/examples/git-difftool.perl481
-rwxr-xr-xcontrib/git-resurrect.sh4
-rwxr-xr-xcontrib/gitview/gitview1305
-rw-r--r--contrib/gitview/gitview.txt57
-rwxr-xr-xcontrib/long-running-filter/example.pl132
-rwxr-xr-xcontrib/remote-helpers/git-remote-bzr16
-rwxr-xr-xcontrib/remote-helpers/git-remote-hg16
-rw-r--r--contrib/update-unicode/.gitignore3
-rw-r--r--contrib/update-unicode/README20
-rwxr-xr-xcontrib/update-unicode/update_unicode.sh33
23 files changed, 1718 insertions, 1919 deletions
diff --git a/contrib/coccinelle/array.cocci b/contrib/coccinelle/array.cocci
index 2d7f25d..4ba98b7 100644
--- a/contrib/coccinelle/array.cocci
+++ b/contrib/coccinelle/array.cocci
@@ -24,3 +24,19 @@ expression n;
@@
- memcpy(dst, src, n * sizeof(T));
+ COPY_ARRAY(dst, src, n);
+
+@@
+type T;
+T *ptr;
+expression n;
+@@
+- ptr = xmalloc(n * sizeof(*ptr));
++ ALLOC_ARRAY(ptr, n);
+
+@@
+type T;
+T *ptr;
+expression n;
+@@
+- ptr = xmalloc(n * sizeof(T));
++ ALLOC_ARRAY(ptr, n);
diff --git a/contrib/coccinelle/free.cocci b/contrib/coccinelle/free.cocci
index e282131..c03ba73 100644
--- a/contrib/coccinelle/free.cocci
+++ b/contrib/coccinelle/free.cocci
@@ -3,3 +3,9 @@ expression E;
@@
- if (E)
free(E);
+
+@@
+expression E;
+@@
+- if (!E)
+ free(E);
diff --git a/contrib/coccinelle/qsort.cocci b/contrib/coccinelle/qsort.cocci
new file mode 100644
index 0000000..22b93a9
--- /dev/null
+++ b/contrib/coccinelle/qsort.cocci
@@ -0,0 +1,37 @@
+@@
+expression base, nmemb, compar;
+@@
+- qsort(base, nmemb, sizeof(*base), compar);
++ QSORT(base, nmemb, compar);
+
+@@
+expression base, nmemb, compar;
+@@
+- qsort(base, nmemb, sizeof(base[0]), compar);
++ QSORT(base, nmemb, compar);
+
+@@
+type T;
+T *base;
+expression nmemb, compar;
+@@
+- qsort(base, nmemb, sizeof(T), compar);
++ QSORT(base, nmemb, compar);
+
+@@
+expression base, nmemb, compar;
+@@
+- if (nmemb)
+ QSORT(base, nmemb, compar);
+
+@@
+expression base, nmemb, compar;
+@@
+- if (nmemb > 0)
+ QSORT(base, nmemb, compar);
+
+@@
+expression base, nmemb, compar;
+@@
+- if (nmemb > 1)
+ QSORT(base, nmemb, compar);
diff --git a/contrib/coccinelle/strbuf.cocci b/contrib/coccinelle/strbuf.cocci
index 63995f2..1d580e4 100644
--- a/contrib/coccinelle/strbuf.cocci
+++ b/contrib/coccinelle/strbuf.cocci
@@ -38,3 +38,9 @@ expression E1, E2, E3;
@@
- strbuf_addstr(E1, find_unique_abbrev(E2, E3));
+ strbuf_add_unique_abbrev(E1, E2, E3);
+
+@@
+expression E1, E2;
+@@
+- strbuf_addstr(E1, real_path(E2));
++ strbuf_add_real_path(E1, E2);
diff --git a/contrib/coccinelle/swap.cocci b/contrib/coccinelle/swap.cocci
new file mode 100644
index 0000000..a0934d1
--- /dev/null
+++ b/contrib/coccinelle/swap.cocci
@@ -0,0 +1,28 @@
+@ swap_with_declaration @
+type T;
+identifier tmp;
+T a, b;
+@@
+- T tmp = a;
++ T tmp;
++ tmp = a;
+ a = b;
+ b = tmp;
+
+@ swap @
+type T;
+T tmp, a, b;
+@@
+- tmp = a;
+- a = b;
+- b = tmp;
++ SWAP(a, b);
+
+@ extends swap @
+identifier unused;
+@@
+ {
+ ...
+- T unused;
+ ... when != unused
+ }
diff --git a/contrib/coccinelle/xstrdup_or_null.cocci b/contrib/coccinelle/xstrdup_or_null.cocci
index 3fceef1..8e05d1c 100644
--- a/contrib/coccinelle/xstrdup_or_null.cocci
+++ b/contrib/coccinelle/xstrdup_or_null.cocci
@@ -5,3 +5,9 @@ expression V;
- if (E)
- V = xstrdup(E);
+ V = xstrdup_or_null(E);
+
+@@
+expression E;
+@@
+- xstrdup(absolute_path(E))
++ absolute_pathdup(E)
diff --git a/contrib/completion/git-completion.bash b/contrib/completion/git-completion.bash
index 21016bf..1150164 100644
--- a/contrib/completion/git-completion.bash
+++ b/contrib/completion/git-completion.bash
@@ -34,21 +34,41 @@ case "$COMP_WORDBREAKS" in
*) COMP_WORDBREAKS="$COMP_WORDBREAKS:"
esac
+# Discovers the path to the git repository taking any '--git-dir=<path>' and
+# '-C <path>' options into account and stores it in the $__git_repo_path
+# variable.
+__git_find_repo_path ()
+{
+ if [ -n "$__git_repo_path" ]; then
+ # we already know where it is
+ return
+ fi
+
+ if [ -n "${__git_C_args-}" ]; then
+ __git_repo_path="$(git "${__git_C_args[@]}" \
+ ${__git_dir:+--git-dir="$__git_dir"} \
+ rev-parse --absolute-git-dir 2>/dev/null)"
+ elif [ -n "${__git_dir-}" ]; then
+ test -d "$__git_dir" &&
+ __git_repo_path="$__git_dir"
+ elif [ -n "${GIT_DIR-}" ]; then
+ test -d "${GIT_DIR-}" &&
+ __git_repo_path="$GIT_DIR"
+ elif [ -d .git ]; then
+ __git_repo_path=.git
+ else
+ __git_repo_path="$(git rev-parse --git-dir 2>/dev/null)"
+ fi
+}
+
+# Deprecated: use __git_find_repo_path() and $__git_repo_path instead
# __gitdir accepts 0 or 1 arguments (i.e., location)
# returns location of .git repo
__gitdir ()
{
if [ -z "${1-}" ]; then
- if [ -n "${__git_dir-}" ]; then
- echo "$__git_dir"
- elif [ -n "${GIT_DIR-}" ]; then
- test -d "${GIT_DIR-}" || return 1
- echo "$GIT_DIR"
- elif [ -d .git ]; then
- echo .git
- else
- git rev-parse --git-dir 2>/dev/null
- fi
+ __git_find_repo_path || return 1
+ echo "$__git_repo_path"
elif [ -d "$1/.git" ]; then
echo "$1/.git"
else
@@ -56,6 +76,14 @@ __gitdir ()
fi
}
+# Runs git with all the options given as argument, respecting any
+# '--git-dir=<path>' and '-C <path>' options present on the command line
+__git ()
+{
+ git ${__git_C_args:+"${__git_C_args[@]}"} \
+ ${__git_dir:+--git-dir="$__git_dir"} "$@" 2>/dev/null
+}
+
# The following function is based on code from:
#
# bash_completion - programmable completion functions for bash 3.2+
@@ -185,6 +213,20 @@ _get_comp_words_by_ref ()
}
fi
+# Fills the COMPREPLY array with prefiltered words without any additional
+# processing.
+# Callers must take care of providing only words that match the current word
+# to be completed and adding any prefix and/or suffix (trailing space!), if
+# necessary.
+# 1: List of newline-separated matching completion words, complete with
+# prefix and suffix.
+__gitcomp_direct ()
+{
+ local IFS=$'\n'
+
+ COMPREPLY=($1)
+}
+
__gitcompappend ()
{
local x i=${#COMPREPLY[@]}
@@ -283,11 +325,11 @@ __gitcomp_file ()
__git_ls_files_helper ()
{
if [ "$2" == "--committable" ]; then
- git -C "$1" diff-index --name-only --relative HEAD
+ __git -C "$1" diff-index --name-only --relative HEAD
else
# NOTE: $2 is not quoted in order to support multiple options
- git -C "$1" ls-files --exclude-standard $2
- fi 2>/dev/null
+ __git -C "$1" ls-files --exclude-standard $2
+ fi
}
@@ -299,100 +341,195 @@ __git_ls_files_helper ()
# slash.
__git_index_files ()
{
- local dir="$(__gitdir)" root="${2-.}" file
+ local root="${2-.}" file
- if [ -d "$dir" ]; then
- __git_ls_files_helper "$root" "$1" |
- while read -r file; do
- case "$file" in
- ?*/*) echo "${file%%/*}" ;;
- *) echo "$file" ;;
- esac
- done | sort | uniq
- fi
+ __git_ls_files_helper "$root" "$1" |
+ while read -r file; do
+ case "$file" in
+ ?*/*) echo "${file%%/*}" ;;
+ *) echo "$file" ;;
+ esac
+ done | sort | uniq
}
+# Lists branches from the local repository.
+# 1: A prefix to be added to each listed branch (optional).
+# 2: List only branches matching this word (optional; list all branches if
+# unset or empty).
+# 3: A suffix to be appended to each listed branch (optional).
__git_heads ()
{
- local dir="$(__gitdir)"
- if [ -d "$dir" ]; then
- git --git-dir="$dir" for-each-ref --format='%(refname:short)' \
- refs/heads
- return
- fi
+ local pfx="${1-}" cur_="${2-}" sfx="${3-}"
+
+ __git for-each-ref --format="${pfx//\%/%%}%(refname:strip=2)$sfx" \
+ "refs/heads/$cur_*" "refs/heads/$cur_*/**"
}
+# Lists tags from the local repository.
+# Accepts the same positional parameters as __git_heads() above.
__git_tags ()
{
- local dir="$(__gitdir)"
- if [ -d "$dir" ]; then
- git --git-dir="$dir" for-each-ref --format='%(refname:short)' \
- refs/tags
- return
- fi
+ local pfx="${1-}" cur_="${2-}" sfx="${3-}"
+
+ __git for-each-ref --format="${pfx//\%/%%}%(refname:strip=2)$sfx" \
+ "refs/tags/$cur_*" "refs/tags/$cur_*/**"
}
-# __git_refs accepts 0, 1 (to pass to __gitdir), or 2 arguments
-# presence of 2nd argument means use the guess heuristic employed
-# by checkout for tracking branches
+# Lists refs from the local (by default) or from a remote repository.
+# It accepts 0, 1 or 2 arguments:
+# 1: The remote to list refs from (optional; ignored, if set but empty).
+# Can be the name of a configured remote, a path, or a URL.
+# 2: In addition to local refs, list unique branches from refs/remotes/ for
+# 'git checkout's tracking DWIMery (optional; ignored, if set but empty).
+# 3: A prefix to be added to each listed ref (optional).
+# 4: List only refs matching this word (optional; list all refs if unset or
+# empty).
+# 5: A suffix to be appended to each listed ref (optional; ignored, if set
+# but empty).
+#
+# Use __git_complete_refs() instead.
__git_refs ()
{
- local i hash dir="$(__gitdir "${1-}")" track="${2-}"
- local format refs pfx
- if [ -d "$dir" ]; then
- case "$cur" in
+ local i hash dir track="${2-}"
+ local list_refs_from=path remote="${1-}"
+ local format refs
+ local pfx="${3-}" cur_="${4-$cur}" sfx="${5-}"
+ local match="${4-}"
+ local fer_pfx="${pfx//\%/%%}" # "escape" for-each-ref format specifiers
+
+ __git_find_repo_path
+ dir="$__git_repo_path"
+
+ if [ -z "$remote" ]; then
+ if [ -z "$dir" ]; then
+ return
+ fi
+ else
+ if __git_is_configured_remote "$remote"; then
+ # configured remote takes precedence over a
+ # local directory with the same name
+ list_refs_from=remote
+ elif [ -d "$remote/.git" ]; then
+ dir="$remote/.git"
+ elif [ -d "$remote" ]; then
+ dir="$remote"
+ else
+ list_refs_from=url
+ fi
+ fi
+
+ if [ "$list_refs_from" = path ]; then
+ if [[ "$cur_" == ^* ]]; then
+ pfx="$pfx^"
+ fer_pfx="$fer_pfx^"
+ cur_=${cur_#^}
+ match=${match#^}
+ fi
+ case "$cur_" in
refs|refs/*)
format="refname"
- refs="${cur%/*}"
+ refs=("$match*" "$match*/**")
track=""
;;
*)
- [[ "$cur" == ^* ]] && pfx="^"
for i in HEAD FETCH_HEAD ORIG_HEAD MERGE_HEAD; do
- if [ -e "$dir/$i" ]; then echo $pfx$i; fi
+ case "$i" in
+ $match*)
+ if [ -e "$dir/$i" ]; then
+ echo "$pfx$i$sfx"
+ fi
+ ;;
+ esac
done
- format="refname:short"
- refs="refs/tags refs/heads refs/remotes"
+ format="refname:strip=2"
+ refs=("refs/tags/$match*" "refs/tags/$match*/**"
+ "refs/heads/$match*" "refs/heads/$match*/**"
+ "refs/remotes/$match*" "refs/remotes/$match*/**")
;;
esac
- git --git-dir="$dir" for-each-ref --format="$pfx%($format)" \
- $refs
+ __git_dir="$dir" __git for-each-ref --format="$fer_pfx%($format)$sfx" \
+ "${refs[@]}"
if [ -n "$track" ]; then
# employ the heuristic used by git checkout
# Try to find a remote branch that matches the completion word
# but only output if the branch name is unique
- local ref entry
- git --git-dir="$dir" for-each-ref --shell --format="ref=%(refname:short)" \
- "refs/remotes/" | \
- while read -r entry; do
- eval "$entry"
- ref="${ref#*/}"
- if [[ "$ref" == "$cur"* ]]; then
- echo "$ref"
- fi
- done | sort | uniq -u
+ __git for-each-ref --format="$fer_pfx%(refname:strip=3)$sfx" \
+ --sort="refname:strip=3" \
+ "refs/remotes/*/$match*" "refs/remotes/*/$match*/**" | \
+ uniq -u
fi
return
fi
- case "$cur" in
+ case "$cur_" in
refs|refs/*)
- git ls-remote "$dir" "$cur*" 2>/dev/null | \
+ __git ls-remote "$remote" "$match*" | \
while read -r hash i; do
case "$i" in
*^{}) ;;
- *) echo "$i" ;;
+ *) echo "$pfx$i$sfx" ;;
esac
done
;;
*)
- echo "HEAD"
- git for-each-ref --format="%(refname:short)" -- \
- "refs/remotes/$dir/" 2>/dev/null | sed -e "s#^$dir/##"
+ if [ "$list_refs_from" = remote ]; then
+ case "HEAD" in
+ $match*) echo "${pfx}HEAD$sfx" ;;
+ esac
+ __git for-each-ref --format="$fer_pfx%(refname:strip=3)$sfx" \
+ "refs/remotes/$remote/$match*" \
+ "refs/remotes/$remote/$match*/**"
+ else
+ local query_symref
+ case "HEAD" in
+ $match*) query_symref="HEAD" ;;
+ esac
+ __git ls-remote "$remote" $query_symref \
+ "refs/tags/$match*" "refs/heads/$match*" \
+ "refs/remotes/$match*" |
+ while read -r hash i; do
+ case "$i" in
+ *^{}) ;;
+ refs/*) echo "$pfx${i#refs/*/}$sfx" ;;
+ *) echo "$pfx$i$sfx" ;; # symbolic refs
+ esac
+ done
+ fi
;;
esac
}
+# Completes refs, short and long, local and remote, symbolic and pseudo.
+#
+# Usage: __git_complete_refs [<option>]...
+# --remote=<remote>: The remote to list refs from, can be the name of a
+# configured remote, a path, or a URL.
+# --track: List unique remote branches for 'git checkout's tracking DWIMery.
+# --pfx=<prefix>: A prefix to be added to each ref.
+# --cur=<word>: The current ref to be completed. Defaults to the current
+# word to be completed.
+# --sfx=<suffix>: A suffix to be appended to each ref instead of the default
+# space.
+__git_complete_refs ()
+{
+ local remote track pfx cur_="$cur" sfx=" "
+
+ while test $# != 0; do
+ case "$1" in
+ --remote=*) remote="${1##--remote=}" ;;
+ --track) track="yes" ;;
+ --pfx=*) pfx="${1##--pfx=}" ;;
+ --cur=*) cur_="${1##--cur=}" ;;
+ --sfx=*) sfx="${1##--sfx=}" ;;
+ *) return 1 ;;
+ esac
+ shift
+ done
+
+ __gitcomp_direct "$(__git_refs "$remote" "$track" "$pfx" "$cur_" "$sfx")"
+}
+
# __git_refs2 requires 1 argument (to pass to __git_refs)
+# Deprecated: use __git_complete_fetch_refspecs() instead.
__git_refs2 ()
{
local i
@@ -401,11 +538,29 @@ __git_refs2 ()
done
}
+# Completes refspecs for fetching from a remote repository.
+# 1: The remote repository.
+# 2: A prefix to be added to each listed refspec (optional).
+# 3: The ref to be completed as a refspec instead of the current word to be
+# completed (optional)
+# 4: A suffix to be appended to each listed refspec instead of the default
+# space (optional).
+__git_complete_fetch_refspecs ()
+{
+ local i remote="$1" pfx="${2-}" cur_="${3-$cur}" sfx="${4- }"
+
+ __gitcomp_direct "$(
+ for i in $(__git_refs "$remote" "" "" "$cur_") ; do
+ echo "$pfx$i:$i$sfx"
+ done
+ )"
+}
+
# __git_refs_remotes requires 1 argument (to pass to ls-remote)
__git_refs_remotes ()
{
local i hash
- git ls-remote "$1" 'refs/heads/*' 2>/dev/null | \
+ __git ls-remote "$1" 'refs/heads/*' | \
while read -r hash i; do
echo "$i:refs/remotes/$1/${i#refs/heads/}"
done
@@ -413,9 +568,21 @@ __git_refs_remotes ()
__git_remotes ()
{
- local d="$(__gitdir)"
- test -d "$d/remotes" && ls -1 "$d/remotes"
- git --git-dir="$d" remote
+ __git_find_repo_path
+ test -d "$__git_repo_path/remotes" && ls -1 "$__git_repo_path/remotes"
+ __git remote
+}
+
+# Returns true if $1 matches the name of a configured remote, false otherwise.
+__git_is_configured_remote ()
+{
+ local remote
+ for remote in $(__git_remotes); do
+ if [ "$remote" = "$1" ]; then
+ return 0
+ fi
+ done
+ return 1
}
__git_list_merge_strategies ()
@@ -469,7 +636,7 @@ __git_complete_revlist_file ()
*) pfx="$ref:$pfx" ;;
esac
- __gitcomp_nl "$(git --git-dir="$(__gitdir)" ls-tree "$ls" 2>/dev/null \
+ __gitcomp_nl "$(__git ls-tree "$ls" \
| sed '/^100... blob /{
s,^.* ,,
s,$, ,
@@ -488,15 +655,15 @@ __git_complete_revlist_file ()
*...*)
pfx="${cur_%...*}..."
cur_="${cur_#*...}"
- __gitcomp_nl "$(__git_refs)" "$pfx" "$cur_"
+ __git_complete_refs --pfx="$pfx" --cur="$cur_"
;;
*..*)
pfx="${cur_%..*}.."
cur_="${cur_#*..}"
- __gitcomp_nl "$(__git_refs)" "$pfx" "$cur_"
+ __git_complete_refs --pfx="$pfx" --cur="$cur_"
;;
*)
- __gitcomp_nl "$(__git_refs)"
+ __git_complete_refs
;;
esac
}
@@ -581,23 +748,23 @@ __git_complete_remote_or_refspec ()
case "$cmd" in
fetch)
if [ $lhs = 1 ]; then
- __gitcomp_nl "$(__git_refs2 "$remote")" "$pfx" "$cur_"
+ __git_complete_fetch_refspecs "$remote" "$pfx" "$cur_"
else
- __gitcomp_nl "$(__git_refs)" "$pfx" "$cur_"
+ __git_complete_refs --pfx="$pfx" --cur="$cur_"
fi
;;
pull|remote)
if [ $lhs = 1 ]; then
- __gitcomp_nl "$(__git_refs "$remote")" "$pfx" "$cur_"
+ __git_complete_refs --remote="$remote" --pfx="$pfx" --cur="$cur_"
else
- __gitcomp_nl "$(__git_refs)" "$pfx" "$cur_"
+ __git_complete_refs --pfx="$pfx" --cur="$cur_"
fi
;;
push)
if [ $lhs = 1 ]; then
- __gitcomp_nl "$(__git_refs)" "$pfx" "$cur_"
+ __git_complete_refs --pfx="$pfx" --cur="$cur_"
else
- __gitcomp_nl "$(__git_refs "$remote")" "$pfx" "$cur_"
+ __git_complete_refs --remote="$remote" --pfx="$pfx" --cur="$cur_"
fi
;;
esac
@@ -747,7 +914,7 @@ __git_compute_porcelain_commands ()
__git_get_config_variables ()
{
local section="$1" i IFS=$'\n'
- for i in $(git --git-dir="$(__gitdir)" config --name-only --get-regexp "^$section\..*" 2>/dev/null); do
+ for i in $(__git config --name-only --get-regexp "^$section\..*"); do
echo "${i#$section.}"
done
}
@@ -765,8 +932,7 @@ __git_aliases ()
# __git_aliased_command requires 1 argument
__git_aliased_command ()
{
- local word cmdline=$(git --git-dir="$(__gitdir)" \
- config --get "alias.$1")
+ local word cmdline=$(__git config --get "alias.$1")
for word in $cmdline; do
case "$word" in
\!gitk|gitk)
@@ -842,7 +1008,7 @@ __git_get_option_value ()
done
if [ -n "$config_key" ] && [ -z "$result" ]; then
- result="$(git --git-dir="$(__gitdir)" config "$config_key")"
+ result="$(__git config "$config_key")"
fi
echo "$result"
@@ -901,8 +1067,8 @@ __git_whitespacelist="nowarn warn error error-all fix"
_git_am ()
{
- local dir="$(__gitdir)"
- if [ -d "$dir"/rebase-apply ]; then
+ __git_find_repo_path
+ if [ -d "$__git_repo_path"/rebase-apply ]; then
__gitcomp "--skip --continue --resolved --abort"
return
fi
@@ -936,6 +1102,7 @@ _git_apply ()
--apply --no-add --exclude=
--ignore-whitespace --ignore-space-change
--whitespace= --inaccurate-eof --verbose
+ --recount --directory=
"
return
esac
@@ -947,13 +1114,17 @@ _git_add ()
--*)
__gitcomp "
--interactive --refresh --patch --update --dry-run
- --ignore-errors --intent-to-add
+ --ignore-errors --intent-to-add --force --edit --chmod=
"
return
esac
- # XXX should we check for --update and --all options ?
- __git_complete_index_file "--others --modified --directory --no-empty-directory"
+ local complete_opt="--others --modified --directory --no-empty-directory"
+ if test -n "$(__git_find_on_cmdline "-u --update")"
+ then
+ complete_opt="--modified"
+ fi
+ __git_complete_index_file "$complete_opt"
}
_git_archive ()
@@ -970,7 +1141,7 @@ _git_archive ()
--*)
__gitcomp "
--format= --list --verbose
- --prefix= --remote= --exec=
+ --prefix= --remote= --exec= --output
"
return
;;
@@ -985,7 +1156,8 @@ _git_bisect ()
local subcommands="start bad good skip reset visualize replay log run"
local subcommand="$(__git_find_on_cmdline "$subcommands")"
if [ -z "$subcommand" ]; then
- if [ -f "$(__gitdir)"/BISECT_START ]; then
+ __git_find_repo_path
+ if [ -f "$__git_repo_path"/BISECT_START ]; then
__gitcomp "$subcommands"
else
__gitcomp "replay start"
@@ -995,7 +1167,7 @@ _git_bisect ()
case "$subcommand" in
bad|good|reset|skip|start)
- __gitcomp_nl "$(__git_refs)"
+ __git_complete_refs
;;
*)
;;
@@ -1017,21 +1189,22 @@ _git_branch ()
case "$cur" in
--set-upstream-to=*)
- __gitcomp_nl "$(__git_refs)" "" "${cur##--set-upstream-to=}"
+ __git_complete_refs --cur="${cur##--set-upstream-to=}"
;;
--*)
__gitcomp "
--color --no-color --verbose --abbrev= --no-abbrev
- --track --no-track --contains --merged --no-merged
+ --track --no-track --contains --no-contains --merged --no-merged
--set-upstream-to= --edit-description --list
--unset-upstream --delete --move --remotes
+ --column --no-column --sort= --points-at
"
;;
*)
if [ $only_local_ref = "y" -a $has_r = "n" ]; then
- __gitcomp_nl "$(__git_heads)"
+ __gitcomp_direct "$(__git_heads "" "$cur" " ")"
else
- __gitcomp_nl "$(__git_refs)"
+ __git_complete_refs
fi
;;
esac
@@ -1074,24 +1247,24 @@ _git_checkout ()
*)
# check if --track, --no-track, or --no-guess was specified
# if so, disable DWIM mode
- local flags="--track --no-track --no-guess" track=1
+ local flags="--track --no-track --no-guess" track_opt="--track"
if [ -n "$(__git_find_on_cmdline "$flags")" ]; then
- track=''
+ track_opt=''
fi
- __gitcomp_nl "$(__git_refs '' $track)"
+ __git_complete_refs $track_opt
;;
esac
}
_git_cherry ()
{
- __gitcomp_nl "$(__git_refs)"
+ __git_complete_refs
}
_git_cherry_pick ()
{
- local dir="$(__gitdir)"
- if [ -f "$dir"/CHERRY_PICK_HEAD ]; then
+ __git_find_repo_path
+ if [ -f "$__git_repo_path"/CHERRY_PICK_HEAD ]; then
__gitcomp "--continue --quit --abort"
return
fi
@@ -1100,7 +1273,7 @@ _git_cherry_pick ()
__gitcomp "--edit --no-commit --signoff --strategy= --mainline"
;;
*)
- __gitcomp_nl "$(__git_refs)"
+ __git_complete_refs
;;
esac
}
@@ -1138,6 +1311,8 @@ _git_clone ()
--single-branch
--branch
--recurse-submodules
+ --no-single-branch
+ --shallow-submodules
"
return
;;
@@ -1150,7 +1325,7 @@ _git_commit ()
{
case "$prev" in
-c|-C)
- __gitcomp_nl "$(__git_refs)" "" "${cur}"
+ __git_complete_refs
return
;;
esac
@@ -1163,7 +1338,7 @@ _git_commit ()
;;
--reuse-message=*|--reedit-message=*|\
--fixup=*|--squash=*)
- __gitcomp_nl "$(__git_refs)" "" "${cur#*=}"
+ __git_complete_refs --cur="${cur#*=}"
return
;;
--untracked-files=*)
@@ -1179,11 +1354,12 @@ _git_commit ()
--reset-author --file= --message= --template=
--cleanup= --untracked-files --untracked-files=
--verbose --quiet --fixup= --squash=
+ --patch --short --date --allow-empty
"
return
esac
- if git rev-parse --verify --quiet HEAD >/dev/null; then
+ if __git rev-parse --verify --quiet HEAD >/dev/null; then
__git_complete_index_file "--committable"
else
# This is the first commit
@@ -1197,16 +1373,17 @@ _git_describe ()
--*)
__gitcomp "
--all --tags --contains --abbrev= --candidates=
- --exact-match --debug --long --match --always
+ --exact-match --debug --long --match --always --first-parent
+ --exclude
"
return
esac
- __gitcomp_nl "$(__git_refs)"
+ __git_complete_refs
}
__git_diff_algorithms="myers minimal patience histogram"
-__git_diff_submodule_formats="log short"
+__git_diff_submodule_formats="diff log short"
__git_diff_common_options="--stat --numstat --shortstat --summary
--patch-with-stat --name-only --name-status --color
@@ -1280,6 +1457,7 @@ __git_fetch_recurse_submodules="yes on-demand no"
__git_fetch_options="
--quiet --verbose --append --upload-pack --force --keep --depth=
--tags --no-tags --all --prune --dry-run --recurse-submodules=
+ --unshallow --update-shallow
"
_git_fetch ()
@@ -1329,7 +1507,7 @@ _git_fsck ()
--*)
__gitcomp "
--tags --root --unreachable --cache --no-reflogs --full
- --strict --verbose --lost-found
+ --strict --verbose --lost-found --name-objects
"
return
;;
@@ -1351,8 +1529,43 @@ _git_gitk ()
_gitk
}
-__git_match_ctag() {
- awk "/^${1//\//\\/}/ { print \$1 }" "$2"
+# Lists matching symbol names from a tag (as in ctags) file.
+# 1: List symbol names matching this word.
+# 2: The tag file to list symbol names from.
+# 3: A prefix to be added to each listed symbol name (optional).
+# 4: A suffix to be appended to each listed symbol name (optional).
+__git_match_ctag () {
+ awk -v pfx="${3-}" -v sfx="${4-}" "
+ /^${1//\//\\/}/ { print pfx \$1 sfx }
+ " "$2"
+}
+
+# Complete symbol names from a tag file.
+# Usage: __git_complete_symbol [<option>]...
+# --tags=<file>: The tag file to list symbol names from instead of the
+# default "tags".
+# --pfx=<prefix>: A prefix to be added to each symbol name.
+# --cur=<word>: The current symbol name to be completed. Defaults to
+# the current word to be completed.
+# --sfx=<suffix>: A suffix to be appended to each symbol name instead
+# of the default space.
+__git_complete_symbol () {
+ local tags=tags pfx="" cur_="${cur-}" sfx=" "
+
+ while test $# != 0; do
+ case "$1" in
+ --tags=*) tags="${1##--tags=}" ;;
+ --pfx=*) pfx="${1##--pfx=}" ;;
+ --cur=*) cur_="${1##--cur=}" ;;
+ --sfx=*) sfx="${1##--sfx=}" ;;
+ *) return 1 ;;
+ esac
+ shift
+ done
+
+ if test -r "$tags"; then
+ __gitcomp_direct "$(__git_match_ctag "$cur_" "$tags" "$pfx" "$sfx")"
+ fi
}
_git_grep ()
@@ -1373,6 +1586,8 @@ _git_grep ()
--max-depth
--count
--and --or --not --all-match
+ --break --heading --show-function --function-context
+ --untracked --no-index
"
return
;;
@@ -1380,14 +1595,11 @@ _git_grep ()
case "$cword,$prev" in
2,*|*,-*)
- if test -r tags; then
- __gitcomp_nl "$(__git_match_ctag "$cur" tags)"
- return
- fi
+ __git_complete_symbol && return
;;
esac
- __gitcomp_nl "$(__git_refs)"
+ __git_complete_refs
}
_git_help ()
@@ -1445,6 +1657,12 @@ _git_ls_files ()
_git_ls_remote ()
{
+ case "$cur" in
+ --*)
+ __gitcomp "--heads --tags --refs --get-url --symref"
+ return
+ ;;
+ esac
__gitcomp_nl "$(__git_remotes)"
}
@@ -1482,12 +1700,25 @@ __git_log_date_formats="relative iso8601 rfc2822 short local default raw"
_git_log ()
{
__git_has_doubledash && return
+ __git_find_repo_path
- local g="$(git rev-parse --git-dir 2>/dev/null)"
local merge=""
- if [ -f "$g/MERGE_HEAD" ]; then
+ if [ -f "$__git_repo_path/MERGE_HEAD" ]; then
merge="--merge"
fi
+ case "$prev,$cur" in
+ -L,:*:*)
+ return # fall back to Bash filename completion
+ ;;
+ -L,:*)
+ __git_complete_symbol --cur="${cur#:}" --sfx=":"
+ return
+ ;;
+ -G,*|-S,*)
+ __git_complete_symbol
+ return
+ ;;
+ esac
case "$cur" in
--pretty=*|--format=*)
__gitcomp "$__git_log_pretty_formats $(__git_pretty_aliases)
@@ -1533,6 +1764,21 @@ _git_log ()
"
return
;;
+ -L:*:*)
+ return # fall back to Bash filename completion
+ ;;
+ -L:*)
+ __git_complete_symbol --cur="${cur#-L:}" --sfx=":"
+ return
+ ;;
+ -G*)
+ __git_complete_symbol --pfx="-G" --cur="${cur#-G}"
+ return
+ ;;
+ -S*)
+ __git_complete_symbol --pfx="-S" --cur="${cur#-S}"
+ return
+ ;;
esac
__git_complete_revlist
}
@@ -1552,10 +1798,10 @@ _git_merge ()
case "$cur" in
--*)
__gitcomp "$__git_merge_options
- --rerere-autoupdate --no-rerere-autoupdate --abort"
+ --rerere-autoupdate --no-rerere-autoupdate --abort --continue"
return
esac
- __gitcomp_nl "$(__git_refs)"
+ __git_complete_refs
}
_git_mergetool ()
@@ -1566,7 +1812,7 @@ _git_mergetool ()
return
;;
--*)
- __gitcomp "--tool="
+ __gitcomp "--tool= --prompt --no-prompt"
return
;;
esac
@@ -1580,7 +1826,7 @@ _git_merge_base ()
return
;;
esac
- __gitcomp_nl "$(__git_refs)"
+ __git_complete_refs
}
_git_mv ()
@@ -1618,7 +1864,7 @@ _git_notes ()
,*)
case "$prev" in
--ref)
- __gitcomp_nl "$(__git_refs)"
+ __git_complete_refs
;;
*)
__gitcomp "$subcommands --ref"
@@ -1627,7 +1873,7 @@ _git_notes ()
;;
add,--reuse-message=*|append,--reuse-message=*|\
add,--reedit-message=*|append,--reedit-message=*)
- __gitcomp_nl "$(__git_refs)" "" "${cur#*=}"
+ __git_complete_refs --cur="${cur#*=}"
;;
add,--*|append,--*)
__gitcomp '--file= --message= --reedit-message=
@@ -1646,7 +1892,7 @@ _git_notes ()
-m|-F)
;;
*)
- __gitcomp_nl "$(__git_refs)"
+ __git_complete_refs
;;
esac
;;
@@ -1674,7 +1920,7 @@ _git_pull ()
__git_complete_remote_or_refspec
}
-__git_push_recurse_submodules="check on-demand"
+__git_push_recurse_submodules="check on-demand only"
__git_complete_force_with_lease ()
{
@@ -1684,10 +1930,10 @@ __git_complete_force_with_lease ()
--*=)
;;
*:*)
- __gitcomp_nl "$(__git_refs)" "" "${cur_#*:}"
+ __git_complete_refs --cur="${cur_#*:}"
;;
*)
- __gitcomp_nl "$(__git_refs)" "" "$cur_"
+ __git_complete_refs --cur="$cur_"
;;
esac
}
@@ -1732,12 +1978,13 @@ _git_push ()
_git_rebase ()
{
- local dir="$(__gitdir)"
- if [ -f "$dir"/rebase-merge/interactive ]; then
- __gitcomp "--continue --skip --abort --edit-todo"
+ __git_find_repo_path
+ if [ -f "$__git_repo_path"/rebase-merge/interactive ]; then
+ __gitcomp "--continue --skip --abort --quit --edit-todo"
return
- elif [ -d "$dir"/rebase-apply ] || [ -d "$dir"/rebase-merge ]; then
- __gitcomp "--continue --skip --abort"
+ elif [ -d "$__git_repo_path"/rebase-apply ] || \
+ [ -d "$__git_repo_path"/rebase-merge ]; then
+ __gitcomp "--continue --skip --abort --quit"
return
fi
__git_complete_strategy && return
@@ -1762,7 +2009,7 @@ _git_rebase ()
return
esac
- __gitcomp_nl "$(__git_refs)"
+ __git_complete_refs
}
_git_reflog ()
@@ -1773,7 +2020,7 @@ _git_reflog ()
if [ -z "$subcommand" ]; then
__gitcomp "$subcommands"
else
- __gitcomp_nl "$(__git_refs)"
+ __git_complete_refs
fi
}
@@ -1784,9 +2031,7 @@ _git_send_email ()
{
case "$prev" in
--to|--cc|--bcc|--from)
- __gitcomp "
- $(git --git-dir="$(__gitdir)" send-email --dump-aliases 2>/dev/null)
- "
+ __gitcomp "$(__git send-email --dump-aliases)"
return
;;
esac
@@ -1816,9 +2061,7 @@ _git_send_email ()
return
;;
--to=*|--cc=*|--bcc=*|--from=*)
- __gitcomp "
- $(git --git-dir="$(__gitdir)" send-email --dump-aliases 2>/dev/null)
- " "" "${cur#--*=}"
+ __gitcomp "$(__git send-email --dump-aliases)" "" "${cur#--*=}"
return
;;
--*)
@@ -1912,7 +2155,7 @@ __git_config_get_set_variables ()
c=$((--c))
done
- git --git-dir="$(__gitdir)" config $config_file --name-only --list 2>/dev/null
+ __git config $config_file --name-only --list
}
_git_config ()
@@ -1923,7 +2166,7 @@ _git_config ()
return
;;
branch.*.merge)
- __gitcomp_nl "$(__git_refs)"
+ __git_complete_refs
return
;;
branch.*.rebase)
@@ -1947,9 +2190,8 @@ _git_config ()
remote.*.push)
local remote="${prev#remote.}"
remote="${remote%.push}"
- __gitcomp_nl "$(git --git-dir="$(__gitdir)" \
- for-each-ref --format='%(refname):%(refname)' \
- refs/heads)"
+ __gitcomp_nl "$(__git for-each-ref \
+ --format='%(refname):%(refname)' refs/heads)"
return
;;
pull.twohead|pull.octopus)
@@ -2028,7 +2270,7 @@ _git_config ()
;;
branch.*)
local pfx="${cur%.*}." cur_="${cur#*.}"
- __gitcomp_nl "$(__git_heads)" "$pfx" "$cur_" "."
+ __gitcomp_direct "$(__git_heads "$pfx" "$cur_" ".")"
__gitcomp_nl_append $'autosetupmerge\nautosetuprebase\n' "$pfx" "$cur_"
return
;;
@@ -2374,31 +2616,79 @@ _git_config ()
_git_remote ()
{
- local subcommands="add rename remove set-head set-branches set-url show prune update"
+ local subcommands="
+ add rename remove set-head set-branches
+ get-url set-url show prune update
+ "
local subcommand="$(__git_find_on_cmdline "$subcommands")"
if [ -z "$subcommand" ]; then
- __gitcomp "$subcommands"
+ case "$cur" in
+ --*)
+ __gitcomp "--verbose"
+ ;;
+ *)
+ __gitcomp "$subcommands"
+ ;;
+ esac
return
fi
- case "$subcommand" in
- rename|remove|set-url|show|prune)
- __gitcomp_nl "$(__git_remotes)"
+ case "$subcommand,$cur" in
+ add,--*)
+ __gitcomp "--track --master --fetch --tags --no-tags --mirror="
+ ;;
+ add,*)
+ ;;
+ set-head,--*)
+ __gitcomp "--auto --delete"
+ ;;
+ set-branches,--*)
+ __gitcomp "--add"
;;
- set-head|set-branches)
+ set-head,*|set-branches,*)
__git_complete_remote_or_refspec
;;
- update)
+ update,--*)
+ __gitcomp "--prune"
+ ;;
+ update,*)
__gitcomp "$(__git_get_config_variables "remotes")"
;;
+ set-url,--*)
+ __gitcomp "--push --add --delete"
+ ;;
+ get-url,--*)
+ __gitcomp "--push --all"
+ ;;
+ prune,--*)
+ __gitcomp "--dry-run"
+ ;;
*)
+ __gitcomp_nl "$(__git_remotes)"
;;
esac
}
_git_replace ()
{
- __gitcomp_nl "$(__git_refs)"
+ case "$cur" in
+ --*)
+ __gitcomp "--edit --graft --format= --list --delete"
+ return
+ ;;
+ esac
+ __git_complete_refs
+}
+
+_git_rerere ()
+{
+ local subcommands="clear forget diff remaining status gc"
+ local subcommand="$(__git_find_on_cmdline "$subcommands")"
+ if test -z "$subcommand"
+ then
+ __gitcomp "$subcommands"
+ return
+ fi
}
_git_reset ()
@@ -2407,27 +2697,30 @@ _git_reset ()
case "$cur" in
--*)
- __gitcomp "--merge --mixed --hard --soft --patch"
+ __gitcomp "--merge --mixed --hard --soft --patch --keep"
return
;;
esac
- __gitcomp_nl "$(__git_refs)"
+ __git_complete_refs
}
_git_revert ()
{
- local dir="$(__gitdir)"
- if [ -f "$dir"/REVERT_HEAD ]; then
+ __git_find_repo_path
+ if [ -f "$__git_repo_path"/REVERT_HEAD ]; then
__gitcomp "--continue --quit --abort"
return
fi
case "$cur" in
--*)
- __gitcomp "--edit --mainline --no-edit --no-commit --signoff"
+ __gitcomp "
+ --edit --mainline --no-edit --no-commit --signoff
+ --strategy= --strategy-option=
+ "
return
;;
esac
- __gitcomp_nl "$(__git_refs)"
+ __git_complete_refs
}
_git_rm ()
@@ -2451,7 +2744,7 @@ _git_shortlog ()
__gitcomp "
$__git_log_common_options
$__git_log_shortlog_options
- --numbered --summary
+ --numbered --summary --email
"
return
;;
@@ -2535,14 +2828,14 @@ _git_stash ()
;;
branch,*)
if [ $cword -eq 3 ]; then
- __gitcomp_nl "$(__git_refs)";
+ __git_complete_refs
else
- __gitcomp_nl "$(git --git-dir="$(__gitdir)" stash list \
+ __gitcomp_nl "$(__git stash list \
| sed -n -e 's/:.*//p')"
fi
;;
show,*|apply,*|drop,*|pop,*)
- __gitcomp_nl "$(git --git-dir="$(__gitdir)" stash list \
+ __gitcomp_nl "$(__git stash list \
| sed -n -e 's/:.*//p')"
;;
*)
@@ -2556,10 +2849,11 @@ _git_submodule ()
__git_has_doubledash && return
local subcommands="add status init deinit update summary foreach sync"
- if [ -z "$(__git_find_on_cmdline "$subcommands")" ]; then
+ local subcommand="$(__git_find_on_cmdline "$subcommands")"
+ if [ -z "$subcommand" ]; then
case "$cur" in
--*)
- __gitcomp "--quiet --cached"
+ __gitcomp "--quiet"
;;
*)
__gitcomp "$subcommands"
@@ -2567,6 +2861,33 @@ _git_submodule ()
esac
return
fi
+
+ case "$subcommand,$cur" in
+ add,--*)
+ __gitcomp "--branch --force --name --reference --depth"
+ ;;
+ status,--*)
+ __gitcomp "--cached --recursive"
+ ;;
+ deinit,--*)
+ __gitcomp "--force --all"
+ ;;
+ update,--*)
+ __gitcomp "
+ --init --remote --no-fetch
+ --recommend-shallow --no-recommend-shallow
+ --force --rebase --merge --reference --depth --recursive --jobs
+ "
+ ;;
+ summary,--*)
+ __gitcomp "--cached --files --summary-limit"
+ ;;
+ foreach,--*|sync,--*)
+ __gitcomp "--recursive"
+ ;;
+ *)
+ ;;
+ esac
}
_git_svn ()
@@ -2587,14 +2908,14 @@ _git_svn ()
--no-metadata --use-svm-props --use-svnsync-props
--log-window-size= --no-checkout --quiet
--repack-flags --use-log-author --localtime
+ --add-author-from
--ignore-paths= --include-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
+ --rewrite-root= --prefix= $remote_opts
"
local cmt_opts="
--edit --rmdir --find-copies-harder --copy-similarity=
@@ -2674,7 +2995,7 @@ _git_tag ()
i="${words[c]}"
case "$i" in
-d|-v)
- __gitcomp_nl "$(__git_tags)"
+ __gitcomp_direct "$(__git_tags "" "$cur" " ")"
return
;;
-f)
@@ -2689,11 +3010,11 @@ _git_tag ()
;;
-*|tag)
if [ $f = 1 ]; then
- __gitcomp_nl "$(__git_tags)"
+ __gitcomp_direct "$(__git_tags "" "$cur" " ")"
fi
;;
*)
- __gitcomp_nl "$(__git_refs)"
+ __git_complete_refs
;;
esac
@@ -2701,8 +3022,8 @@ _git_tag ()
--*)
__gitcomp "
--list --delete --verify --annotate --message --file
- --sign --cleanup --local-user --force --column --sort
- --contains --points-at
+ --sign --cleanup --local-user --force --column --sort=
+ --contains --no-contains --points-at --merged --no-merged --create-reflog
"
;;
esac
@@ -2741,7 +3062,8 @@ _git_worktree ()
__git_main ()
{
- local i c=1 command __git_dir
+ local i c=1 command __git_dir __git_repo_path
+ local __git_C_args C_args_count=0
while [ $c -lt $cword ]; do
i="${words[c]}"
@@ -2751,6 +3073,10 @@ __git_main ()
--bare) __git_dir="." ;;
--help) command="help"; break ;;
-c|--work-tree|--namespace) ((c++)) ;;
+ -C) __git_C_args[C_args_count++]=-C
+ ((c++))
+ __git_C_args[C_args_count++]="${words[c]}"
+ ;;
-*) ;;
*) command="$i"; break ;;
esac
@@ -2758,6 +3084,17 @@ __git_main ()
done
if [ -z "$command" ]; then
+ case "$prev" in
+ --git-dir|-C|--work-tree)
+ # these need a path argument, let's fall back to
+ # Bash filename completion
+ return
+ ;;
+ -c|--namespace)
+ # we don't support completing these options' arguments
+ return
+ ;;
+ esac
case "$cur" in
--*) __gitcomp "
--paginate
@@ -2783,13 +3120,13 @@ __git_main ()
fi
local completion_func="_git_${command//-/_}"
- declare -f $completion_func >/dev/null && $completion_func && return
+ declare -f $completion_func >/dev/null 2>/dev/null && $completion_func && return
local expansion=$(__git_aliased_command "$command")
if [ -n "$expansion" ]; then
words[1]=$expansion
completion_func="_git_${expansion//-/_}"
- declare -f $completion_func >/dev/null && $completion_func
+ declare -f $completion_func >/dev/null 2>/dev/null && $completion_func
fi
}
@@ -2797,9 +3134,11 @@ __gitk_main ()
{
__git_has_doubledash && return
- local g="$(__gitdir)"
+ local __git_repo_path
+ __git_find_repo_path
+
local merge=""
- if [ -f "$g/MERGE_HEAD" ]; then
+ if [ -f "$__git_repo_path/MERGE_HEAD" ]; then
merge="--merge"
fi
case "$cur" in
@@ -2846,6 +3185,15 @@ if [[ -n ${ZSH_VERSION-} ]]; then
esac
}
+ __gitcomp_direct ()
+ {
+ emulate -L zsh
+
+ local IFS=$'\n'
+ compset -P '*[=:]'
+ compadd -Q -- ${=1} && _ret=0
+ }
+
__gitcomp_nl ()
{
emulate -L zsh
diff --git a/contrib/completion/git-completion.zsh b/contrib/completion/git-completion.zsh
index e255413..c3521fb 100644
--- a/contrib/completion/git-completion.zsh
+++ b/contrib/completion/git-completion.zsh
@@ -67,6 +67,15 @@ __gitcomp ()
esac
}
+__gitcomp_direct ()
+{
+ emulate -L zsh
+
+ local IFS=$'\n'
+ compset -P '*[=:]'
+ compadd -Q -- ${=1} && _ret=0
+}
+
__gitcomp_nl ()
{
emulate -L zsh
diff --git a/contrib/completion/git-prompt.sh b/contrib/completion/git-prompt.sh
index 97eacd7..c6cbef3 100644
--- a/contrib/completion/git-prompt.sh
+++ b/contrib/completion/git-prompt.sh
@@ -82,6 +82,7 @@
# contains relative to newer annotated tag (v1.6.3.2~35)
# branch relative to newer tag or branch (master~4)
# describe relative to older annotated tag (v1.6.3.1-13-gdd42c2f)
+# tag relative to any older tag (v1.6.3.1-13-gdd42c2f)
# default exactly matching tag
#
# If you would like a colored hint about the current dirty state, set
@@ -443,6 +444,8 @@ __git_ps1 ()
git describe --contains HEAD ;;
(branch)
git describe --contains --all HEAD ;;
+ (tag)
+ git describe --tags HEAD ;;
(describe)
git describe HEAD ;;
(* | default)
diff --git a/contrib/convert-objects/convert-objects.c b/contrib/convert-objects/convert-objects.c
deleted file mode 100644
index f3b57bf..0000000
--- a/contrib/convert-objects/convert-objects.c
+++ /dev/null
@@ -1,329 +0,0 @@
-#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
deleted file mode 100644
index f871880..0000000
--- a/contrib/convert-objects/git-convert-objects.txt
+++ /dev/null
@@ -1,29 +0,0 @@
-git-convert-objects(1)
-======================
-
-NAME
-----
-git-convert-objects - Converts old-style git repository
-
-
-SYNOPSIS
---------
-[verse]
-'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 linkgit:git[7] suite
diff --git a/contrib/credential/libsecret/Makefile b/contrib/credential/libsecret/Makefile
new file mode 100644
index 0000000..3e67552
--- /dev/null
+++ b/contrib/credential/libsecret/Makefile
@@ -0,0 +1,25 @@
+MAIN:=git-credential-libsecret
+all:: $(MAIN)
+
+CC = gcc
+RM = rm -f
+CFLAGS = -g -O2 -Wall
+PKG_CONFIG = pkg-config
+
+-include ../../../config.mak.autogen
+-include ../../../config.mak
+
+INCS:=$(shell $(PKG_CONFIG) --cflags libsecret-1 glib-2.0)
+LIBS:=$(shell $(PKG_CONFIG) --libs libsecret-1 glib-2.0)
+
+SRCS:=$(MAIN).c
+OBJS:=$(SRCS:.c=.o)
+
+%.o: %.c
+ $(CC) $(CFLAGS) $(CPPFLAGS) $(INCS) -o $@ -c $<
+
+$(MAIN): $(OBJS)
+ $(CC) -o $@ $(LDFLAGS) $^ $(LIBS)
+
+clean:
+ @$(RM) $(MAIN) $(OBJS)
diff --git a/contrib/credential/libsecret/git-credential-libsecret.c b/contrib/credential/libsecret/git-credential-libsecret.c
new file mode 100644
index 0000000..4c56979
--- /dev/null
+++ b/contrib/credential/libsecret/git-credential-libsecret.c
@@ -0,0 +1,370 @@
+/*
+ * Copyright (C) 2011 John Szakmeister <john@szakmeister.net>
+ * 2012 Philipp A. Hartmann <pah@qo.cx>
+ * 2016 Mantas MikulÄ—nas <grawity@gmail.com>
+ *
+ * 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
+ */
+
+/*
+ * Credits:
+ * - GNOME Keyring API handling originally written by John Szakmeister
+ * - ported to credential helper API by Philipp A. Hartmann
+ */
+
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <glib.h>
+#include <libsecret/secret.h>
+
+/*
+ * This credential struct and API is simplified from git's credential.{h,c}
+ */
+struct credential {
+ char *protocol;
+ char *host;
+ unsigned short port;
+ char *path;
+ char *username;
+ char *password;
+};
+
+#define CREDENTIAL_INIT { NULL, NULL, 0, NULL, NULL, NULL }
+
+typedef int (*credential_op_cb)(struct credential *);
+
+struct credential_operation {
+ char *name;
+ credential_op_cb op;
+};
+
+#define CREDENTIAL_OP_END { NULL, NULL }
+
+/* ----------------- Secret Service functions ----------------- */
+
+static char *make_label(struct credential *c)
+{
+ if (c->port)
+ return g_strdup_printf("Git: %s://%s:%hu/%s",
+ c->protocol, c->host, c->port, c->path ? c->path : "");
+ else
+ return g_strdup_printf("Git: %s://%s/%s",
+ c->protocol, c->host, c->path ? c->path : "");
+}
+
+static GHashTable *make_attr_list(struct credential *c)
+{
+ GHashTable *al = g_hash_table_new_full(g_str_hash, g_str_equal, NULL, g_free);
+
+ if (c->username)
+ g_hash_table_insert(al, "user", g_strdup(c->username));
+ if (c->protocol)
+ g_hash_table_insert(al, "protocol", g_strdup(c->protocol));
+ if (c->host)
+ g_hash_table_insert(al, "server", g_strdup(c->host));
+ if (c->port)
+ g_hash_table_insert(al, "port", g_strdup_printf("%hu", c->port));
+ if (c->path)
+ g_hash_table_insert(al, "object", g_strdup(c->path));
+
+ return al;
+}
+
+static int keyring_get(struct credential *c)
+{
+ SecretService *service = NULL;
+ GHashTable *attributes = NULL;
+ GError *error = NULL;
+ GList *items = NULL;
+
+ if (!c->protocol || !(c->host || c->path))
+ return EXIT_FAILURE;
+
+ service = secret_service_get_sync(0, NULL, &error);
+ if (error != NULL) {
+ g_critical("could not connect to Secret Service: %s", error->message);
+ g_error_free(error);
+ return EXIT_FAILURE;
+ }
+
+ attributes = make_attr_list(c);
+ items = secret_service_search_sync(service,
+ SECRET_SCHEMA_COMPAT_NETWORK,
+ attributes,
+ SECRET_SEARCH_LOAD_SECRETS,
+ NULL,
+ &error);
+ g_hash_table_unref(attributes);
+ if (error != NULL) {
+ g_critical("lookup failed: %s", error->message);
+ g_error_free(error);
+ return EXIT_FAILURE;
+ }
+
+ if (items != NULL) {
+ SecretItem *item;
+ SecretValue *secret;
+ const char *s;
+
+ item = items->data;
+ secret = secret_item_get_secret(item);
+ attributes = secret_item_get_attributes(item);
+
+ s = g_hash_table_lookup(attributes, "user");
+ if (s) {
+ g_free(c->username);
+ c->username = g_strdup(s);
+ }
+
+ s = secret_value_get_text(secret);
+ if (s) {
+ g_free(c->password);
+ c->password = g_strdup(s);
+ }
+
+ g_hash_table_unref(attributes);
+ secret_value_unref(secret);
+ g_list_free_full(items, g_object_unref);
+ }
+
+ return EXIT_SUCCESS;
+}
+
+
+static int keyring_store(struct credential *c)
+{
+ char *label = NULL;
+ GHashTable *attributes = NULL;
+ GError *error = NULL;
+
+ /*
+ * Sanity check that what we are storing is actually sensible.
+ * In particular, we can't make a URL without a protocol field.
+ * Without either a host or pathname (depending on the scheme),
+ * we have no primary key. And without a username and password,
+ * we are not actually storing a credential.
+ */
+ if (!c->protocol || !(c->host || c->path) ||
+ !c->username || !c->password)
+ return EXIT_FAILURE;
+
+ label = make_label(c);
+ attributes = make_attr_list(c);
+ secret_password_storev_sync(SECRET_SCHEMA_COMPAT_NETWORK,
+ attributes,
+ NULL,
+ label,
+ c->password,
+ NULL,
+ &error);
+ g_free(label);
+ g_hash_table_unref(attributes);
+
+ if (error != NULL) {
+ g_critical("store failed: %s", error->message);
+ g_error_free(error);
+ return EXIT_FAILURE;
+ }
+
+ return EXIT_SUCCESS;
+}
+
+static int keyring_erase(struct credential *c)
+{
+ GHashTable *attributes = NULL;
+ GError *error = NULL;
+
+ /*
+ * Sanity check that we actually have something to match
+ * against. The input we get is a restrictive pattern,
+ * so technically a blank credential means "erase everything".
+ * But it is too easy to accidentally send this, since it is equivalent
+ * to empty input. So explicitly disallow it, and require that the
+ * pattern have some actual content to match.
+ */
+ if (!c->protocol && !c->host && !c->path && !c->username)
+ return EXIT_FAILURE;
+
+ attributes = make_attr_list(c);
+ secret_password_clearv_sync(SECRET_SCHEMA_COMPAT_NETWORK,
+ attributes,
+ NULL,
+ &error);
+ g_hash_table_unref(attributes);
+
+ if (error != NULL) {
+ g_critical("erase failed: %s", error->message);
+ g_error_free(error);
+ return EXIT_FAILURE;
+ }
+
+ return EXIT_SUCCESS;
+}
+
+/*
+ * Table with helper operation callbacks, used by generic
+ * credential helper main function.
+ */
+static struct credential_operation const credential_helper_ops[] = {
+ { "get", keyring_get },
+ { "store", keyring_store },
+ { "erase", keyring_erase },
+ CREDENTIAL_OP_END
+};
+
+/* ------------------ credential functions ------------------ */
+
+static void credential_init(struct credential *c)
+{
+ memset(c, 0, sizeof(*c));
+}
+
+static void credential_clear(struct credential *c)
+{
+ g_free(c->protocol);
+ g_free(c->host);
+ g_free(c->path);
+ g_free(c->username);
+ g_free(c->password);
+
+ credential_init(c);
+}
+
+static int credential_read(struct credential *c)
+{
+ char *buf;
+ size_t line_len;
+ char *key;
+ char *value;
+
+ key = buf = g_malloc(1024);
+
+ while (fgets(buf, 1024, stdin)) {
+ line_len = strlen(buf);
+
+ if (line_len && buf[line_len-1] == '\n')
+ buf[--line_len] = '\0';
+
+ if (!line_len)
+ break;
+
+ value = strchr(buf, '=');
+ if (!value) {
+ g_warning("invalid credential line: %s", key);
+ g_free(buf);
+ return -1;
+ }
+ *value++ = '\0';
+
+ if (!strcmp(key, "protocol")) {
+ g_free(c->protocol);
+ c->protocol = g_strdup(value);
+ } else if (!strcmp(key, "host")) {
+ g_free(c->host);
+ c->host = g_strdup(value);
+ value = strrchr(c->host, ':');
+ if (value) {
+ *value++ = '\0';
+ c->port = atoi(value);
+ }
+ } else if (!strcmp(key, "path")) {
+ g_free(c->path);
+ c->path = g_strdup(value);
+ } else if (!strcmp(key, "username")) {
+ g_free(c->username);
+ c->username = g_strdup(value);
+ } else if (!strcmp(key, "password")) {
+ g_free(c->password);
+ c->password = g_strdup(value);
+ while (*value)
+ *value++ = '\0';
+ }
+ /*
+ * Ignore other lines; we don't know what they mean, but
+ * this future-proofs us when later versions of git do
+ * learn new lines, and the helpers are updated to match.
+ */
+ }
+
+ g_free(buf);
+
+ return 0;
+}
+
+static void credential_write_item(FILE *fp, const char *key, const char *value)
+{
+ if (!value)
+ return;
+ fprintf(fp, "%s=%s\n", key, value);
+}
+
+static void credential_write(const struct credential *c)
+{
+ /* only write username/password, if set */
+ credential_write_item(stdout, "username", c->username);
+ credential_write_item(stdout, "password", c->password);
+}
+
+static void usage(const char *name)
+{
+ struct credential_operation const *try_op = credential_helper_ops;
+ const char *basename = strrchr(name, '/');
+
+ basename = (basename) ? basename + 1 : name;
+ fprintf(stderr, "usage: %s <", basename);
+ while (try_op->name) {
+ fprintf(stderr, "%s", (try_op++)->name);
+ if (try_op->name)
+ fprintf(stderr, "%s", "|");
+ }
+ fprintf(stderr, "%s", ">\n");
+}
+
+int main(int argc, char *argv[])
+{
+ int ret = EXIT_SUCCESS;
+
+ struct credential_operation const *try_op = credential_helper_ops;
+ struct credential cred = CREDENTIAL_INIT;
+
+ if (!argv[1]) {
+ usage(argv[0]);
+ exit(EXIT_FAILURE);
+ }
+
+ g_set_application_name("Git Credential Helper");
+
+ /* lookup operation callback */
+ while (try_op->name && strcmp(argv[1], try_op->name))
+ try_op++;
+
+ /* unsupported operation given -- ignore silently */
+ if (!try_op->name || !try_op->op)
+ goto out;
+
+ ret = credential_read(&cred);
+ if (ret)
+ goto out;
+
+ /* perform credential operation */
+ ret = (*try_op->op)(&cred);
+
+ credential_write(&cred);
+
+out:
+ credential_clear(&cred);
+ return ret;
+}
diff --git a/contrib/examples/git-difftool.perl b/contrib/examples/git-difftool.perl
new file mode 100755
index 0000000..df59bdf
--- /dev/null
+++ b/contrib/examples/git-difftool.perl
@@ -0,0 +1,481 @@
+#!/usr/bin/perl
+# Copyright (c) 2009, 2010 David Aguilar
+# Copyright (c) 2012 Tim Henigan
+#
+# This is a wrapper around the GIT_EXTERNAL_DIFF-compatible
+# git-difftool--helper script.
+#
+# This script exports GIT_EXTERNAL_DIFF and GIT_PAGER for use by git.
+# The GIT_DIFF* variables are exported for use by git-difftool--helper.
+#
+# Any arguments that are unknown to this script are forwarded to 'git diff'.
+
+use 5.008;
+use strict;
+use warnings;
+use Error qw(:try);
+use File::Basename qw(dirname);
+use File::Copy;
+use File::Find;
+use File::stat;
+use File::Path qw(mkpath rmtree);
+use File::Temp qw(tempdir);
+use Getopt::Long qw(:config pass_through);
+use Git;
+use Git::I18N;
+
+sub usage
+{
+ my $exitcode = shift;
+ print << 'USAGE';
+usage: git difftool [-t|--tool=<tool>] [--tool-help]
+ [-x|--extcmd=<cmd>]
+ [-g|--gui] [--no-gui]
+ [--prompt] [-y|--no-prompt]
+ [-d|--dir-diff]
+ ['git diff' options]
+USAGE
+ exit($exitcode);
+}
+
+sub print_tool_help
+{
+ # See the comment at the bottom of file_diff() for the reason behind
+ # using system() followed by exit() instead of exec().
+ my $rc = system(qw(git mergetool --tool-help=diff));
+ exit($rc | ($rc >> 8));
+}
+
+sub exit_cleanup
+{
+ my ($tmpdir, $status) = @_;
+ my $errno = $!;
+ rmtree($tmpdir);
+ if ($status and $errno) {
+ my ($package, $file, $line) = caller();
+ warn "$file line $line: $errno\n";
+ }
+ exit($status | ($status >> 8));
+}
+
+sub use_wt_file
+{
+ my ($file, $sha1) = @_;
+ my $null_sha1 = '0' x 40;
+
+ if (-l $file || ! -e _) {
+ return (0, $null_sha1);
+ }
+
+ my $wt_sha1 = Git::command_oneline('hash-object', $file);
+ my $use = ($sha1 eq $null_sha1) || ($sha1 eq $wt_sha1);
+ return ($use, $wt_sha1);
+}
+
+sub changed_files
+{
+ my ($repo_path, $index, $worktree) = @_;
+ $ENV{GIT_INDEX_FILE} = $index;
+
+ my @gitargs = ('--git-dir', $repo_path, '--work-tree', $worktree);
+ my @refreshargs = (
+ @gitargs, 'update-index',
+ '--really-refresh', '-q', '--unmerged');
+ try {
+ Git::command_oneline(@refreshargs);
+ } catch Git::Error::Command with {};
+
+ my @diffargs = (@gitargs, 'diff-files', '--name-only', '-z');
+ my $line = Git::command_oneline(@diffargs);
+ my @files;
+ if (defined $line) {
+ @files = split('\0', $line);
+ } else {
+ @files = ();
+ }
+
+ delete($ENV{GIT_INDEX_FILE});
+
+ return map { $_ => 1 } @files;
+}
+
+sub setup_dir_diff
+{
+ my ($worktree, $symlinks) = @_;
+ my @gitargs = ('diff', '--raw', '--no-abbrev', '-z', @ARGV);
+ my $diffrtn = Git::command_oneline(@gitargs);
+ exit(0) unless defined($diffrtn);
+
+ # Go to the root of the worktree now that we've captured the list of
+ # changed files. The paths returned by diff --raw are relative to the
+ # top-level of the repository, but we defer changing directories so
+ # that @ARGV can perform pathspec limiting in the current directory.
+ chdir($worktree);
+
+ # Build index info for left and right sides of the diff
+ my $submodule_mode = '160000';
+ my $symlink_mode = '120000';
+ my $null_mode = '0' x 6;
+ my $null_sha1 = '0' x 40;
+ my $lindex = '';
+ my $rindex = '';
+ my $wtindex = '';
+ my %submodule;
+ my %symlink;
+ my @files = ();
+ my %working_tree_dups = ();
+ my @rawdiff = split('\0', $diffrtn);
+
+ my $i = 0;
+ while ($i < $#rawdiff) {
+ if ($rawdiff[$i] =~ /^::/) {
+ warn __ <<'EOF';
+Combined diff formats ('-c' and '--cc') are not supported in
+directory diff mode ('-d' and '--dir-diff').
+EOF
+ exit(1);
+ }
+
+ my ($lmode, $rmode, $lsha1, $rsha1, $status) =
+ split(' ', substr($rawdiff[$i], 1));
+ my $src_path = $rawdiff[$i + 1];
+ my $dst_path;
+
+ if ($status =~ /^[CR]/) {
+ $dst_path = $rawdiff[$i + 2];
+ $i += 3;
+ } else {
+ $dst_path = $src_path;
+ $i += 2;
+ }
+
+ if ($lmode eq $submodule_mode or $rmode eq $submodule_mode) {
+ $submodule{$src_path}{left} = $lsha1;
+ if ($lsha1 ne $rsha1) {
+ $submodule{$dst_path}{right} = $rsha1;
+ } else {
+ $submodule{$dst_path}{right} = "$rsha1-dirty";
+ }
+ next;
+ }
+
+ if ($lmode eq $symlink_mode) {
+ $symlink{$src_path}{left} =
+ Git::command_oneline('show', $lsha1);
+ }
+
+ if ($rmode eq $symlink_mode) {
+ $symlink{$dst_path}{right} =
+ Git::command_oneline('show', $rsha1);
+ }
+
+ if ($lmode ne $null_mode and $status !~ /^C/) {
+ $lindex .= "$lmode $lsha1\t$src_path\0";
+ }
+
+ if ($rmode ne $null_mode) {
+ # Avoid duplicate entries
+ if ($working_tree_dups{$dst_path}++) {
+ next;
+ }
+ my ($use, $wt_sha1) =
+ use_wt_file($dst_path, $rsha1);
+ if ($use) {
+ push @files, $dst_path;
+ $wtindex .= "$rmode $wt_sha1\t$dst_path\0";
+ } else {
+ $rindex .= "$rmode $rsha1\t$dst_path\0";
+ }
+ }
+ }
+
+ # Go to the root of the worktree so that the left index files
+ # are properly setup -- the index is toplevel-relative.
+ chdir($worktree);
+
+ # Setup temp directories
+ my $tmpdir = tempdir('git-difftool.XXXXX', CLEANUP => 0, TMPDIR => 1);
+ my $ldir = "$tmpdir/left";
+ my $rdir = "$tmpdir/right";
+ mkpath($ldir) or exit_cleanup($tmpdir, 1);
+ mkpath($rdir) or exit_cleanup($tmpdir, 1);
+
+ # Populate the left and right directories based on each index file
+ my ($inpipe, $ctx);
+ $ENV{GIT_INDEX_FILE} = "$tmpdir/lindex";
+ ($inpipe, $ctx) =
+ Git::command_input_pipe('update-index', '-z', '--index-info');
+ print($inpipe $lindex);
+ Git::command_close_pipe($inpipe, $ctx);
+
+ my $rc = system('git', 'checkout-index', '--all', "--prefix=$ldir/");
+ exit_cleanup($tmpdir, $rc) if $rc != 0;
+
+ $ENV{GIT_INDEX_FILE} = "$tmpdir/rindex";
+ ($inpipe, $ctx) =
+ Git::command_input_pipe('update-index', '-z', '--index-info');
+ print($inpipe $rindex);
+ Git::command_close_pipe($inpipe, $ctx);
+
+ $rc = system('git', 'checkout-index', '--all', "--prefix=$rdir/");
+ exit_cleanup($tmpdir, $rc) if $rc != 0;
+
+ $ENV{GIT_INDEX_FILE} = "$tmpdir/wtindex";
+ ($inpipe, $ctx) =
+ Git::command_input_pipe('update-index', '--info-only', '-z', '--index-info');
+ print($inpipe $wtindex);
+ Git::command_close_pipe($inpipe, $ctx);
+
+ # If $GIT_DIR was explicitly set just for the update/checkout
+ # commands, then it should be unset before continuing.
+ delete($ENV{GIT_INDEX_FILE});
+
+ # Changes in the working tree need special treatment since they are
+ # not part of the index.
+ for my $file (@files) {
+ my $dir = dirname($file);
+ unless (-d "$rdir/$dir") {
+ mkpath("$rdir/$dir") or
+ exit_cleanup($tmpdir, 1);
+ }
+ if ($symlinks) {
+ symlink("$worktree/$file", "$rdir/$file") or
+ exit_cleanup($tmpdir, 1);
+ } else {
+ copy($file, "$rdir/$file") or
+ exit_cleanup($tmpdir, 1);
+
+ my $mode = stat($file)->mode;
+ chmod($mode, "$rdir/$file") or
+ exit_cleanup($tmpdir, 1);
+ }
+ }
+
+ # Changes to submodules require special treatment. This loop writes a
+ # temporary file to both the left and right directories to show the
+ # change in the recorded SHA1 for the submodule.
+ for my $path (keys %submodule) {
+ my $ok = 0;
+ if (defined($submodule{$path}{left})) {
+ $ok = write_to_file("$ldir/$path",
+ "Subproject commit $submodule{$path}{left}");
+ }
+ if (defined($submodule{$path}{right})) {
+ $ok = write_to_file("$rdir/$path",
+ "Subproject commit $submodule{$path}{right}");
+ }
+ exit_cleanup($tmpdir, 1) if not $ok;
+ }
+
+ # Symbolic links require special treatment. The standard "git diff"
+ # shows only the link itself, not the contents of the link target.
+ # This loop replicates that behavior.
+ for my $path (keys %symlink) {
+ my $ok = 0;
+ if (defined($symlink{$path}{left})) {
+ $ok = write_to_file("$ldir/$path",
+ $symlink{$path}{left});
+ }
+ if (defined($symlink{$path}{right})) {
+ $ok = write_to_file("$rdir/$path",
+ $symlink{$path}{right});
+ }
+ exit_cleanup($tmpdir, 1) if not $ok;
+ }
+
+ return ($ldir, $rdir, $tmpdir, @files);
+}
+
+sub write_to_file
+{
+ my $path = shift;
+ my $value = shift;
+
+ # Make sure the path to the file exists
+ my $dir = dirname($path);
+ unless (-d "$dir") {
+ mkpath("$dir") or return 0;
+ }
+
+ # If the file already exists in that location, delete it. This
+ # is required in the case of symbolic links.
+ unlink($path);
+
+ open(my $fh, '>', $path) or return 0;
+ print($fh $value);
+ close($fh);
+
+ return 1;
+}
+
+sub main
+{
+ # parse command-line options. all unrecognized options and arguments
+ # are passed through to the 'git diff' command.
+ my %opts = (
+ difftool_cmd => undef,
+ dirdiff => undef,
+ extcmd => undef,
+ gui => undef,
+ help => undef,
+ prompt => undef,
+ symlinks => $^O ne 'cygwin' &&
+ $^O ne 'MSWin32' && $^O ne 'msys',
+ tool_help => undef,
+ trust_exit_code => undef,
+ );
+ GetOptions('g|gui!' => \$opts{gui},
+ 'd|dir-diff' => \$opts{dirdiff},
+ 'h' => \$opts{help},
+ 'prompt!' => \$opts{prompt},
+ 'y' => sub { $opts{prompt} = 0; },
+ 'symlinks' => \$opts{symlinks},
+ 'no-symlinks' => sub { $opts{symlinks} = 0; },
+ 't|tool:s' => \$opts{difftool_cmd},
+ 'tool-help' => \$opts{tool_help},
+ 'trust-exit-code' => \$opts{trust_exit_code},
+ 'no-trust-exit-code' => sub { $opts{trust_exit_code} = 0; },
+ 'x|extcmd:s' => \$opts{extcmd});
+
+ if (defined($opts{help})) {
+ usage(0);
+ }
+ if (defined($opts{tool_help})) {
+ print_tool_help();
+ }
+ if (defined($opts{difftool_cmd})) {
+ if (length($opts{difftool_cmd}) > 0) {
+ $ENV{GIT_DIFF_TOOL} = $opts{difftool_cmd};
+ } else {
+ print __("No <tool> given for --tool=<tool>\n");
+ usage(1);
+ }
+ }
+ if (defined($opts{extcmd})) {
+ if (length($opts{extcmd}) > 0) {
+ $ENV{GIT_DIFFTOOL_EXTCMD} = $opts{extcmd};
+ } else {
+ print __("No <cmd> given for --extcmd=<cmd>\n");
+ usage(1);
+ }
+ }
+ if ($opts{gui}) {
+ my $guitool = Git::config('diff.guitool');
+ if (defined($guitool) && length($guitool) > 0) {
+ $ENV{GIT_DIFF_TOOL} = $guitool;
+ }
+ }
+
+ if (!defined $opts{trust_exit_code}) {
+ $opts{trust_exit_code} = Git::config_bool('difftool.trustExitCode');
+ }
+ if ($opts{trust_exit_code}) {
+ $ENV{GIT_DIFFTOOL_TRUST_EXIT_CODE} = 'true';
+ } else {
+ $ENV{GIT_DIFFTOOL_TRUST_EXIT_CODE} = 'false';
+ }
+
+ # In directory diff mode, 'git-difftool--helper' is called once
+ # to compare the a/b directories. In file diff mode, 'git diff'
+ # will invoke a separate instance of 'git-difftool--helper' for
+ # each file that changed.
+ if (defined($opts{dirdiff})) {
+ dir_diff($opts{extcmd}, $opts{symlinks});
+ } else {
+ file_diff($opts{prompt});
+ }
+}
+
+sub dir_diff
+{
+ my ($extcmd, $symlinks) = @_;
+ my $rc;
+ my $error = 0;
+ my $repo = Git->repository();
+ my $repo_path = $repo->repo_path();
+ my $worktree = $repo->wc_path();
+ $worktree =~ s|/$||; # Avoid double slashes in symlink targets
+ my ($a, $b, $tmpdir, @files) = setup_dir_diff($worktree, $symlinks);
+
+ if (defined($extcmd)) {
+ $rc = system($extcmd, $a, $b);
+ } else {
+ $ENV{GIT_DIFFTOOL_DIRDIFF} = 'true';
+ $rc = system('git', 'difftool--helper', $a, $b);
+ }
+ # If the diff including working copy files and those
+ # files were modified during the diff, then the changes
+ # should be copied back to the working tree.
+ # Do not copy back files when symlinks are used and the
+ # external tool did not replace the original link with a file.
+ #
+ # These hashes are loaded lazily since they aren't needed
+ # in the common case of --symlinks and the difftool updating
+ # files through the symlink.
+ my %wt_modified;
+ my %tmp_modified;
+ my $indices_loaded = 0;
+
+ for my $file (@files) {
+ next if $symlinks && -l "$b/$file";
+ next if ! -f "$b/$file";
+
+ if (!$indices_loaded) {
+ %wt_modified = changed_files(
+ $repo_path, "$tmpdir/wtindex", $worktree);
+ %tmp_modified = changed_files(
+ $repo_path, "$tmpdir/wtindex", $b);
+ $indices_loaded = 1;
+ }
+
+ if (exists $wt_modified{$file} and exists $tmp_modified{$file}) {
+ warn sprintf(__(
+ "warning: Both files modified:\n" .
+ "'%s/%s' and '%s/%s'.\n" .
+ "warning: Working tree file has been left.\n" .
+ "warning:\n"), $worktree, $file, $b, $file);
+ $error = 1;
+ } elsif (exists $tmp_modified{$file}) {
+ my $mode = stat("$b/$file")->mode;
+ copy("$b/$file", $file) or
+ exit_cleanup($tmpdir, 1);
+
+ chmod($mode, $file) or
+ exit_cleanup($tmpdir, 1);
+ }
+ }
+ if ($error) {
+ warn sprintf(__(
+ "warning: Temporary files exist in '%s'.\n" .
+ "warning: You may want to cleanup or recover these.\n"), $tmpdir);
+ exit(1);
+ } else {
+ exit_cleanup($tmpdir, $rc);
+ }
+}
+
+sub file_diff
+{
+ my ($prompt) = @_;
+
+ if (defined($prompt)) {
+ if ($prompt) {
+ $ENV{GIT_DIFFTOOL_PROMPT} = 'true';
+ } else {
+ $ENV{GIT_DIFFTOOL_NO_PROMPT} = 'true';
+ }
+ }
+
+ $ENV{GIT_PAGER} = '';
+ $ENV{GIT_EXTERNAL_DIFF} = 'git-difftool--helper';
+
+ # ActiveState Perl for Win32 does not implement POSIX semantics of
+ # exec* system call. It just spawns the given executable and finishes
+ # the starting program, exiting with code 0.
+ # system will at least catch the errors returned by git diff,
+ # allowing the caller of git difftool better handling of failures.
+ my $rc = system('git', 'diff', @ARGV);
+ exit($rc | ($rc >> 8));
+}
+
+main();
diff --git a/contrib/git-resurrect.sh b/contrib/git-resurrect.sh
index d7e97bb..8c171dd 100755
--- a/contrib/git-resurrect.sh
+++ b/contrib/git-resurrect.sh
@@ -26,13 +26,13 @@ n,dry-run don't recreate the branch"
. git-sh-setup
search_reflog () {
- sed -ne 's~^\([^ ]*\) .*\tcheckout: moving from '"$1"' .*~\1~p' \
+ sed -ne 's~^\([^ ]*\) .* checkout: moving from '"$1"' .*~\1~p' \
< "$GIT_DIR"/logs/HEAD
}
search_reflog_merges () {
git rev-parse $(
- sed -ne 's~^[^ ]* \([^ ]*\) .*\tmerge '"$1"':.*~\1^2~p' \
+ sed -ne 's~^[^ ]* \([^ ]*\) .* merge '"$1"':.*~\1^2~p' \
< "$GIT_DIR"/logs/HEAD
)
}
diff --git a/contrib/gitview/gitview b/contrib/gitview/gitview
deleted file mode 100755
index 4e23c65..0000000
--- a/contrib/gitview/gitview
+++ /dev/null
@@ -1,1305 +0,0 @@
-#! /usr/bin/env python
-
-# 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.
-
-""" gitview
-GUI browser for git repository
-This program is based on bzrk by Scott James Remnant <scott@ubuntu.com>
-"""
-__copyright__ = "Copyright (C) 2006 Hewlett-Packard Development Company, L.P."
-__copyright__ = "Copyright (C) 2007 Aneesh Kumar K.V <aneesh.kumar@gmail.com"
-__author__ = "Aneesh Kumar K.V <aneesh.kumar@gmail.com>"
-
-
-import sys
-import os
-import gtk
-import pygtk
-import pango
-import re
-import time
-import gobject
-import cairo
-import math
-import string
-import fcntl
-
-have_gtksourceview2 = False
-have_gtksourceview = False
-try:
- import gtksourceview2
- have_gtksourceview2 = True
-except ImportError:
- 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})')
-
-def list_to_string(args, skip):
- count = len(args)
- i = skip
- str_arg=" "
- while (i < count ):
- str_arg = str_arg + args[i]
- str_arg = str_arg + " "
- i = i+1
-
- return str_arg
-
-def show_date(epoch, tz):
- secs = float(epoch)
- tzsecs = float(tz[1:3]) * 3600
- tzsecs += float(tz[3:5]) * 60
- if (tz[0] == "+"):
- secs += tzsecs
- else:
- secs -= tzsecs
-
- 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.
-
- This module contains the implementation of a custom GtkCellRenderer that
- draws part of the directed graph based on the lines suggested by the code
- in graph.py.
-
- Because we're shiny, we use Cairo to do this, and because we're naughty
- we cheat and draw over the bits of the TreeViewColumn that are supposed to
- just be for the background.
-
- Properties:
- node (column, colour, [ names ]) tuple to draw revision node,
- in_lines (start, end, colour) tuple list to draw inward lines,
- out_lines (start, end, colour) tuple list to draw outward lines.
- """
-
- __gproperties__ = {
- "node": ( gobject.TYPE_PYOBJECT, "node",
- "revision node instruction",
- gobject.PARAM_WRITABLE
- ),
- "in-lines": ( gobject.TYPE_PYOBJECT, "in-lines",
- "instructions to draw lines into the cell",
- gobject.PARAM_WRITABLE
- ),
- "out-lines": ( gobject.TYPE_PYOBJECT, "out-lines",
- "instructions to draw lines out of the cell",
- gobject.PARAM_WRITABLE
- ),
- }
-
- def do_set_property(self, property, value):
- """Set properties from GObject properties."""
- if property.name == "node":
- self.node = value
- elif property.name == "in-lines":
- self.in_lines = value
- elif property.name == "out-lines":
- self.out_lines = value
- else:
- raise AttributeError, "no such property: '%s'" % property.name
-
- def box_size(self, widget):
- """Calculate box size based on widget's font.
-
- Cache this as it's probably expensive to get. It ensures that we
- draw the graph at least as large as the text.
- """
- try:
- return self._box_size
- except AttributeError:
- pango_ctx = widget.get_pango_context()
- font_desc = widget.get_style().font_desc
- metrics = pango_ctx.get_metrics(font_desc)
-
- ascent = pango.PIXELS(metrics.get_ascent())
- descent = pango.PIXELS(metrics.get_descent())
-
- self._box_size = ascent + descent + 6
- return self._box_size
-
- def set_colour(self, ctx, colour, bg, fg):
- """Set the context source colour.
-
- Picks a distinct colour based on an internal wheel; the bg
- parameter provides the value that should be assigned to the 'zero'
- colours and the fg parameter provides the multiplier that should be
- applied to the foreground colours.
- """
- colours = [
- ( 1.0, 0.0, 0.0 ),
- ( 1.0, 1.0, 0.0 ),
- ( 0.0, 1.0, 0.0 ),
- ( 0.0, 1.0, 1.0 ),
- ( 0.0, 0.0, 1.0 ),
- ( 1.0, 0.0, 1.0 ),
- ]
-
- colour %= len(colours)
- red = (colours[colour][0] * fg) or bg
- green = (colours[colour][1] * fg) or bg
- blue = (colours[colour][2] * fg) or bg
-
- ctx.set_source_rgb(red, green, blue)
-
- def on_get_size(self, widget, cell_area):
- """Return the size we need for this cell.
-
- Each cell is drawn individually and is only as wide as it needs
- to be, we let the TreeViewColumn take care of making them all
- line up.
- """
- box_size = self.box_size(widget)
-
- cols = self.node[0]
- for start, end, colour in self.in_lines + self.out_lines:
- cols = int(max(cols, start, end))
-
- (column, colour, names) = self.node
- names_len = 0
- if (len(names) != 0):
- for item in names:
- names_len += len(item)
-
- width = box_size * (cols + 1 ) + names_len
- height = box_size
-
- # FIXME I have no idea how to use cell_area properly
- return (0, 0, width, height)
-
- def on_render(self, window, widget, bg_area, cell_area, exp_area, flags):
- """Render an individual cell.
-
- Draws the cell contents using cairo, taking care to clip what we
- do to within the background area so we don't draw over other cells.
- Note that we're a bit naughty there and should really be drawing
- in the cell_area (or even the exposed area), but we explicitly don't
- want any gutter.
-
- We try and be a little clever, if the line we need to draw is going
- to cross other columns we actually draw it as in the .---' style
- instead of a pure diagonal ... this reduces confusion by an
- incredible amount.
- """
- ctx = window.cairo_create()
- ctx.rectangle(bg_area.x, bg_area.y, bg_area.width, bg_area.height)
- ctx.clip()
-
- box_size = self.box_size(widget)
-
- ctx.set_line_width(box_size / 8)
- ctx.set_line_cap(cairo.LINE_CAP_SQUARE)
-
- # Draw lines into the cell
- for start, end, colour in self.in_lines:
- ctx.move_to(cell_area.x + box_size * start + box_size / 2,
- bg_area.y - bg_area.height / 2)
-
- if start - end > 1:
- ctx.line_to(cell_area.x + box_size * start, bg_area.y)
- ctx.line_to(cell_area.x + box_size * end + box_size, bg_area.y)
- elif start - end < -1:
- ctx.line_to(cell_area.x + box_size * start + box_size,
- bg_area.y)
- ctx.line_to(cell_area.x + box_size * end, bg_area.y)
-
- ctx.line_to(cell_area.x + box_size * end + box_size / 2,
- bg_area.y + bg_area.height / 2)
-
- self.set_colour(ctx, colour, 0.0, 0.65)
- ctx.stroke()
-
- # Draw lines out of the cell
- for start, end, colour in self.out_lines:
- ctx.move_to(cell_area.x + box_size * start + box_size / 2,
- bg_area.y + bg_area.height / 2)
-
- if start - end > 1:
- ctx.line_to(cell_area.x + box_size * start,
- bg_area.y + bg_area.height)
- ctx.line_to(cell_area.x + box_size * end + box_size,
- bg_area.y + bg_area.height)
- elif start - end < -1:
- ctx.line_to(cell_area.x + box_size * start + box_size,
- bg_area.y + bg_area.height)
- ctx.line_to(cell_area.x + box_size * end,
- bg_area.y + bg_area.height)
-
- ctx.line_to(cell_area.x + box_size * end + box_size / 2,
- bg_area.y + bg_area.height / 2 + bg_area.height)
-
- self.set_colour(ctx, colour, 0.0, 0.65)
- ctx.stroke()
-
- # Draw the revision node in the right column
- (column, colour, names) = self.node
- ctx.arc(cell_area.x + box_size * column + box_size / 2,
- cell_area.y + cell_area.height / 2,
- box_size / 4, 0, 2 * math.pi)
-
-
- self.set_colour(ctx, colour, 0.0, 0.5)
- ctx.stroke_preserve()
-
- self.set_colour(ctx, colour, 0.5, 1.0)
- ctx.fill_preserve()
-
- if (len(names) != 0):
- name = " "
- for item in names:
- name = name + item + " "
-
- ctx.set_font_size(13)
- if (flags & 1):
- self.set_colour(ctx, colour, 0.5, 1.0)
- else:
- self.set_colour(ctx, colour, 0.0, 0.5)
- ctx.show_text(name)
-
-class Commit(object):
- """ This represent a commit object obtained after parsing the git-rev-list
- output """
-
- __slots__ = ['children_sha1', 'message', 'author', 'date', 'committer',
- 'commit_date', 'commit_sha1', 'parent_sha1']
-
- children_sha1 = {}
-
- def __init__(self, commit_lines):
- self.message = ""
- self.author = ""
- self.date = ""
- self.committer = ""
- self.commit_date = ""
- self.commit_sha1 = ""
- self.parent_sha1 = [ ]
- self.parse_commit(commit_lines)
-
-
- def parse_commit(self, commit_lines):
-
- # First line is the sha1 lines
- line = string.strip(commit_lines[0])
- sha1 = re.split(" ", line)
- self.commit_sha1 = sha1[0]
- self.parent_sha1 = sha1[1:]
-
- #build the child list
- for parent_id in self.parent_sha1:
- try:
- Commit.children_sha1[parent_id].append(self.commit_sha1)
- except KeyError:
- Commit.children_sha1[parent_id] = [self.commit_sha1]
-
- # IF we don't have parent
- if (len(self.parent_sha1) == 0):
- self.parent_sha1 = [0]
-
- for line in commit_lines[1:]:
- m = re.match("^ ", line)
- if (m != None):
- # First line of the commit message used for short log
- if self.message == "":
- self.message = string.strip(line)
- continue
-
- m = re.match("tree", line)
- if (m != None):
- continue
-
- m = re.match("parent", line)
- if (m != None):
- continue
-
- m = re_ident.match(line)
- if (m != None):
- date = show_date(m.group('epoch'), m.group('tz'))
- if m.group(1) == "author":
- self.author = m.group('ident')
- self.date = date
- elif m.group(1) == "committer":
- self.committer = m.group('ident')
- self.commit_date = date
-
- continue
-
- def get_message(self, with_diff=0):
- if (with_diff == 1):
- message = self.diff_tree()
- else:
- fp = os.popen("git cat-file commit " + self.commit_sha1)
- message = fp.read()
- fp.close()
-
- return message
-
- def diff_tree(self):
- fp = os.popen("git diff-tree --pretty --cc -v -p --always " + self.commit_sha1)
- diff = fp.read()
- fp.close()
- return diff
-
-class AnnotateWindow(object):
- """Annotate window.
- This object represents and manages a single window containing the
- annotate information of the file
- """
-
- def __init__(self):
- self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
- self.window.set_border_width(0)
- self.window.set_title("Git repository browser annotation window")
- self.prev_read = ""
-
- # Use two thirds of the screen by default
- screen = self.window.get_screen()
- monitor = screen.get_monitor_geometry(0)
- width = int(monitor.width * 0.66)
- height = int(monitor.height * 0.66)
- self.window.set_default_size(width, height)
-
- def add_file_data(self, filename, commit_sha1, line_num):
- fp = os.popen("git cat-file blob " + commit_sha1 +":"+filename)
- i = 1;
- for line in fp.readlines():
- line = string.rstrip(line)
- self.model.append(None, ["HEAD", filename, line, i])
- i = i+1
- fp.close()
-
- # now set the cursor position
- self.treeview.set_cursor(line_num-1)
- self.treeview.grab_focus()
-
- def _treeview_cursor_cb(self, *args):
- """Callback for when the treeview cursor changes."""
- (path, col) = self.treeview.get_cursor()
- commit_sha1 = self.model[path][0]
- commit_msg = ""
- fp = os.popen("git cat-file commit " + commit_sha1)
- for line in fp.readlines():
- commit_msg = commit_msg + line
- fp.close()
-
- self.commit_buffer.set_text(commit_msg)
-
- def _treeview_row_activated(self, *args):
- """Callback for when the treeview row gets selected."""
- (path, col) = self.treeview.get_cursor()
- commit_sha1 = self.model[path][0]
- filename = self.model[path][1]
- line_num = self.model[path][3]
-
- window = AnnotateWindow();
- fp = os.popen("git rev-parse "+ commit_sha1 + "~1")
- commit_sha1 = string.strip(fp.readline())
- fp.close()
- window.annotate(filename, commit_sha1, line_num)
-
- def data_ready(self, source, condition):
- while (1):
- try :
- # A simple readline doesn't work
- # a readline bug ??
- buffer = source.read(100)
-
- except:
- # resource temporary not available
- return True
-
- if (len(buffer) == 0):
- gobject.source_remove(self.io_watch_tag)
- source.close()
- return False
-
- if (self.prev_read != ""):
- buffer = self.prev_read + buffer
- self.prev_read = ""
-
- if (buffer[len(buffer) -1] != '\n'):
- try:
- newline_index = buffer.rindex("\n")
- except ValueError:
- newline_index = 0
-
- self.prev_read = buffer[newline_index:(len(buffer))]
- buffer = buffer[0:newline_index]
-
- for buff in buffer.split("\n"):
- annotate_line = re.compile('^([0-9a-f]{40}) (.+) (.+) (.+)$')
- m = annotate_line.match(buff)
- if not m:
- annotate_line = re.compile('^(filename) (.+)$')
- m = annotate_line.match(buff)
- if not m:
- continue
- filename = m.group(2)
- else:
- self.commit_sha1 = m.group(1)
- self.source_line = int(m.group(2))
- self.result_line = int(m.group(3))
- self.count = int(m.group(4))
- #set the details only when we have the file name
- continue
-
- while (self.count > 0):
- # set at result_line + count-1 the sha1 as commit_sha1
- self.count = self.count - 1
- iter = self.model.iter_nth_child(None, self.result_line + self.count-1)
- self.model.set(iter, 0, self.commit_sha1, 1, filename, 3, self.source_line)
-
-
- def annotate(self, filename, commit_sha1, line_num):
- # verify the commit_sha1 specified has this filename
-
- fp = os.popen("git ls-tree "+ commit_sha1 + " -- " + filename)
- line = string.strip(fp.readline())
- if line == '':
- # pop up the message the file is not there as a part of the commit
- fp.close()
- dialog = gtk.MessageDialog(parent=None, flags=0,
- type=gtk.MESSAGE_WARNING, buttons=gtk.BUTTONS_CLOSE,
- message_format=None)
- dialog.set_markup("The file %s is not present in the parent commit %s" % (filename, commit_sha1))
- dialog.run()
- dialog.destroy()
- return
-
- fp.close()
-
- vpan = gtk.VPaned();
- self.window.add(vpan);
- vpan.show()
-
- scrollwin = gtk.ScrolledWindow()
- scrollwin.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
- scrollwin.set_shadow_type(gtk.SHADOW_IN)
- vpan.pack1(scrollwin, True, True);
- scrollwin.show()
-
- self.model = gtk.TreeStore(str, str, str, int)
- self.treeview = gtk.TreeView(self.model)
- self.treeview.set_rules_hint(True)
- self.treeview.set_search_column(0)
- self.treeview.connect("cursor-changed", self._treeview_cursor_cb)
- self.treeview.connect("row-activated", self._treeview_row_activated)
- scrollwin.add(self.treeview)
- self.treeview.show()
-
- cell = gtk.CellRendererText()
- cell.set_property("width-chars", 10)
- cell.set_property("ellipsize", pango.ELLIPSIZE_END)
- column = gtk.TreeViewColumn("Commit")
- column.set_resizable(True)
- column.pack_start(cell, expand=True)
- column.add_attribute(cell, "text", 0)
- self.treeview.append_column(column)
-
- cell = gtk.CellRendererText()
- cell.set_property("width-chars", 20)
- cell.set_property("ellipsize", pango.ELLIPSIZE_END)
- column = gtk.TreeViewColumn("File Name")
- column.set_resizable(True)
- column.pack_start(cell, expand=True)
- column.add_attribute(cell, "text", 1)
- self.treeview.append_column(column)
-
- cell = gtk.CellRendererText()
- cell.set_property("width-chars", 20)
- cell.set_property("ellipsize", pango.ELLIPSIZE_END)
- column = gtk.TreeViewColumn("Data")
- column.set_resizable(True)
- column.pack_start(cell, expand=True)
- column.add_attribute(cell, "text", 2)
- self.treeview.append_column(column)
-
- # The commit message window
- scrollwin = gtk.ScrolledWindow()
- scrollwin.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
- scrollwin.set_shadow_type(gtk.SHADOW_IN)
- vpan.pack2(scrollwin, True, True);
- scrollwin.show()
-
- commit_text = gtk.TextView()
- self.commit_buffer = gtk.TextBuffer()
- commit_text.set_buffer(self.commit_buffer)
- scrollwin.add(commit_text)
- commit_text.show()
-
- self.window.show()
-
- self.add_file_data(filename, commit_sha1, line_num)
-
- fp = os.popen("git blame --incremental -C -C -- " + filename + " " + commit_sha1)
- flags = fcntl.fcntl(fp.fileno(), fcntl.F_GETFL)
- fcntl.fcntl(fp.fileno(), fcntl.F_SETFL, flags | os.O_NONBLOCK)
- self.io_watch_tag = gobject.io_add_watch(fp, gobject.IO_IN, self.data_ready)
-
-
-class DiffWindow(object):
- """Diff window.
- This object represents and manages a single window containing the
- differences between two revisions on a branch.
- """
-
- def __init__(self):
- self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
- self.window.set_border_width(0)
- self.window.set_title("Git repository browser diff window")
-
- # Use two thirds of the screen by default
- screen = self.window.get_screen()
- monitor = screen.get_monitor_geometry(0)
- width = int(monitor.width * 0.66)
- height = int(monitor.height * 0.66)
- self.window.set_default_size(width, height)
-
-
- self.construct()
-
- def construct(self):
- """Construct the window contents."""
- vbox = gtk.VBox()
- self.window.add(vbox)
- vbox.show()
-
- menu_bar = gtk.MenuBar()
- save_menu = gtk.ImageMenuItem(gtk.STOCK_SAVE)
- save_menu.connect("activate", self.save_menu_response, "save")
- save_menu.show()
- menu_bar.append(save_menu)
- vbox.pack_start(menu_bar, expand=False, fill=True)
- menu_bar.show()
-
- hpan = gtk.HPaned()
-
- scrollwin = gtk.ScrolledWindow()
- scrollwin.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
- scrollwin.set_shadow_type(gtk.SHADOW_IN)
- hpan.pack1(scrollwin, True, True)
- scrollwin.show()
-
- (self.buffer, sourceview) = get_source_buffer_and_view()
-
- sourceview.set_editable(False)
- sourceview.modify_font(pango.FontDescription("Monospace"))
- scrollwin.add(sourceview)
- sourceview.show()
-
- # The file hierarchy: a scrollable treeview
- scrollwin = gtk.ScrolledWindow()
- scrollwin.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
- scrollwin.set_shadow_type(gtk.SHADOW_IN)
- scrollwin.set_size_request(20, -1)
- hpan.pack2(scrollwin, True, True)
- scrollwin.show()
-
- self.model = gtk.TreeStore(str, str, str)
- self.treeview = gtk.TreeView(self.model)
- self.treeview.set_search_column(1)
- self.treeview.connect("cursor-changed", self._treeview_clicked)
- scrollwin.add(self.treeview)
- self.treeview.show()
-
- cell = gtk.CellRendererText()
- cell.set_property("width-chars", 20)
- column = gtk.TreeViewColumn("Select to annotate")
- column.pack_start(cell, expand=True)
- column.add_attribute(cell, "text", 0)
- self.treeview.append_column(column)
-
- vbox.pack_start(hpan, expand=True, fill=True)
- hpan.show()
-
- def _treeview_clicked(self, *args):
- """Callback for when the treeview cursor changes."""
- (path, col) = self.treeview.get_cursor()
- specific_file = self.model[path][1]
- commit_sha1 = self.model[path][2]
- if specific_file == None :
- return
- elif specific_file == "" :
- specific_file = None
-
- window = AnnotateWindow();
- window.annotate(specific_file, commit_sha1, 1)
-
-
- def commit_files(self, commit_sha1, parent_sha1):
- self.model.clear()
- add = self.model.append(None, [ "Added", None, None])
- dele = self.model.append(None, [ "Deleted", None, None])
- mod = self.model.append(None, [ "Modified", None, None])
- diff_tree = re.compile('^(:.{6}) (.{6}) (.{40}) (.{40}) (A|D|M)\s(.+)$')
- fp = os.popen("git diff-tree -r --no-commit-id " + parent_sha1 + " " + commit_sha1)
- while 1:
- line = string.strip(fp.readline())
- if line == '':
- break
- m = diff_tree.match(line)
- if not m:
- continue
-
- attr = m.group(5)
- filename = m.group(6)
- if attr == "A":
- self.model.append(add, [filename, filename, commit_sha1])
- elif attr == "D":
- self.model.append(dele, [filename, filename, commit_sha1])
- elif attr == "M":
- self.model.append(mod, [filename, filename, commit_sha1])
- fp.close()
-
- self.treeview.expand_all()
-
- def set_diff(self, commit_sha1, parent_sha1, encoding):
- """Set the differences showed by this window.
- Compares the two trees and populates the window with the
- differences.
- """
- # Diff with the first commit or the last commit shows nothing
- if (commit_sha1 == 0 or parent_sha1 == 0 ):
- return
-
- fp = os.popen("git diff-tree -p " + parent_sha1 + " " + commit_sha1)
- self.buffer.set_text(unicode(fp.read(), encoding).encode('utf-8'))
- fp.close()
- self.commit_files(commit_sha1, parent_sha1)
- self.window.show()
-
- def save_menu_response(self, widget, string):
- dialog = gtk.FileChooserDialog("Save..", None, gtk.FILE_CHOOSER_ACTION_SAVE,
- (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
- gtk.STOCK_SAVE, gtk.RESPONSE_OK))
- dialog.set_default_response(gtk.RESPONSE_OK)
- response = dialog.run()
- if response == gtk.RESPONSE_OK:
- patch_buffer = self.buffer.get_text(self.buffer.get_start_iter(),
- self.buffer.get_end_iter())
- fp = open(dialog.get_filename(), "w")
- fp.write(patch_buffer)
- fp.close()
- dialog.destroy()
-
-class GitView(object):
- """ This is the main class
- """
- version = "0.9"
-
- def __init__(self, with_diff=0):
- self.with_diff = with_diff
- self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
- self.window.set_border_width(0)
- self.window.set_title("Git repository browser")
-
- self.get_encoding()
- self.get_bt_sha1()
-
- # Use three-quarters of the screen by default
- screen = self.window.get_screen()
- monitor = screen.get_monitor_geometry(0)
- width = int(monitor.width * 0.75)
- height = int(monitor.height * 0.75)
- self.window.set_default_size(width, height)
-
- # FIXME AndyFitz!
- icon = self.window.render_icon(gtk.STOCK_INDEX, gtk.ICON_SIZE_BUTTON)
- self.window.set_icon(icon)
-
- self.accel_group = gtk.AccelGroup()
- self.window.add_accel_group(self.accel_group)
- self.accel_group.connect_group(0xffc2, 0, gtk.ACCEL_LOCKED, self.refresh);
- self.accel_group.connect_group(0xffc1, 0, gtk.ACCEL_LOCKED, self.maximize);
- self.accel_group.connect_group(0xffc8, 0, gtk.ACCEL_LOCKED, self.fullscreen);
- self.accel_group.connect_group(0xffc9, 0, gtk.ACCEL_LOCKED, self.unfullscreen);
-
- self.window.add(self.construct())
-
- def refresh(self, widget, event=None, *arguments, **keywords):
- self.get_encoding()
- self.get_bt_sha1()
- Commit.children_sha1 = {}
- self.set_branch(sys.argv[without_diff:])
- self.window.show()
- return True
-
- def maximize(self, widget, event=None, *arguments, **keywords):
- self.window.maximize()
- return True
-
- def fullscreen(self, widget, event=None, *arguments, **keywords):
- self.window.fullscreen()
- return True
-
- def unfullscreen(self, widget, event=None, *arguments, **keywords):
- self.window.unfullscreen()
- return True
-
- def get_bt_sha1(self):
- """ Update the bt_sha1 dictionary with the
- respective sha1 details """
-
- self.bt_sha1 = { }
- ls_remote = re.compile('^(.{40})\trefs/([^^]+)(?:\\^(..))?$');
- fp = os.popen('git ls-remote "${GIT_DIR-.git}"')
- while 1:
- line = string.strip(fp.readline())
- if line == '':
- break
- m = ls_remote.match(line)
- if not m:
- continue
- (sha1, name) = (m.group(1), m.group(2))
- if not self.bt_sha1.has_key(sha1):
- self.bt_sha1[sha1] = []
- self.bt_sha1[sha1].append(name)
- fp.close()
-
- def get_encoding(self):
- fp = os.popen("git config --get i18n.commitencoding")
- self.encoding=string.strip(fp.readline())
- fp.close()
- if (self.encoding == ""):
- self.encoding = "utf-8"
-
-
- def construct(self):
- """Construct the window contents."""
- vbox = gtk.VBox()
- paned = gtk.VPaned()
- paned.pack1(self.construct_top(), resize=False, shrink=True)
- paned.pack2(self.construct_bottom(), resize=False, shrink=True)
- menu_bar = gtk.MenuBar()
- menu_bar.set_pack_direction(gtk.PACK_DIRECTION_RTL)
- help_menu = gtk.MenuItem("Help")
- menu = gtk.Menu()
- about_menu = gtk.MenuItem("About")
- menu.append(about_menu)
- about_menu.connect("activate", self.about_menu_response, "about")
- about_menu.show()
- help_menu.set_submenu(menu)
- help_menu.show()
- menu_bar.append(help_menu)
- menu_bar.show()
- vbox.pack_start(menu_bar, expand=False, fill=True)
- vbox.pack_start(paned, expand=True, fill=True)
- paned.show()
- vbox.show()
- return vbox
-
-
- def construct_top(self):
- """Construct the top-half of the window."""
- vbox = gtk.VBox(spacing=6)
- vbox.set_border_width(12)
- vbox.show()
-
-
- scrollwin = gtk.ScrolledWindow()
- scrollwin.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
- scrollwin.set_shadow_type(gtk.SHADOW_IN)
- vbox.pack_start(scrollwin, expand=True, fill=True)
- scrollwin.show()
-
- self.treeview = gtk.TreeView()
- self.treeview.set_rules_hint(True)
- self.treeview.set_search_column(4)
- self.treeview.connect("cursor-changed", self._treeview_cursor_cb)
- scrollwin.add(self.treeview)
- self.treeview.show()
-
- cell = CellRendererGraph()
- column = gtk.TreeViewColumn()
- column.set_resizable(True)
- column.pack_start(cell, expand=True)
- column.add_attribute(cell, "node", 1)
- column.add_attribute(cell, "in-lines", 2)
- column.add_attribute(cell, "out-lines", 3)
- self.treeview.append_column(column)
-
- cell = gtk.CellRendererText()
- cell.set_property("width-chars", 65)
- cell.set_property("ellipsize", pango.ELLIPSIZE_END)
- column = gtk.TreeViewColumn("Message")
- column.set_resizable(True)
- column.pack_start(cell, expand=True)
- column.add_attribute(cell, "text", 4)
- self.treeview.append_column(column)
-
- cell = gtk.CellRendererText()
- cell.set_property("width-chars", 40)
- cell.set_property("ellipsize", pango.ELLIPSIZE_END)
- column = gtk.TreeViewColumn("Author")
- column.set_resizable(True)
- column.pack_start(cell, expand=True)
- column.add_attribute(cell, "text", 5)
- self.treeview.append_column(column)
-
- cell = gtk.CellRendererText()
- cell.set_property("ellipsize", pango.ELLIPSIZE_END)
- column = gtk.TreeViewColumn("Date")
- column.set_resizable(True)
- column.pack_start(cell, expand=True)
- column.add_attribute(cell, "text", 6)
- self.treeview.append_column(column)
-
- return vbox
-
- def about_menu_response(self, widget, string):
- dialog = gtk.AboutDialog()
- dialog.set_name("Gitview")
- dialog.set_version(GitView.version)
- dialog.set_authors(["Aneesh Kumar K.V <aneesh.kumar@gmail.com>"])
- dialog.set_website("http://www.kernel.org/pub/software/scm/git/")
- dialog.set_copyright("Use and distribute under the terms of the GNU General Public License")
- dialog.set_wrap_license(True)
- dialog.run()
- dialog.destroy()
-
-
- def construct_bottom(self):
- """Construct the bottom half of the window."""
- vbox = gtk.VBox(False, spacing=6)
- vbox.set_border_width(12)
- (width, height) = self.window.get_size()
- vbox.set_size_request(width, int(height / 2.5))
- vbox.show()
-
- self.table = gtk.Table(rows=4, columns=4)
- self.table.set_row_spacings(6)
- self.table.set_col_spacings(6)
- vbox.pack_start(self.table, expand=False, fill=True)
- self.table.show()
-
- align = gtk.Alignment(0.0, 0.5)
- label = gtk.Label()
- label.set_markup("<b>Revision:</b>")
- align.add(label)
- self.table.attach(align, 0, 1, 0, 1, gtk.FILL, gtk.FILL)
- label.show()
- align.show()
-
- align = gtk.Alignment(0.0, 0.5)
- self.revid_label = gtk.Label()
- self.revid_label.set_selectable(True)
- align.add(self.revid_label)
- self.table.attach(align, 1, 2, 0, 1, gtk.EXPAND | gtk.FILL, gtk.FILL)
- self.revid_label.show()
- align.show()
-
- align = gtk.Alignment(0.0, 0.5)
- label = gtk.Label()
- label.set_markup("<b>Committer:</b>")
- align.add(label)
- self.table.attach(align, 0, 1, 1, 2, gtk.FILL, gtk.FILL)
- label.show()
- align.show()
-
- align = gtk.Alignment(0.0, 0.5)
- self.committer_label = gtk.Label()
- self.committer_label.set_selectable(True)
- align.add(self.committer_label)
- self.table.attach(align, 1, 2, 1, 2, gtk.EXPAND | gtk.FILL, gtk.FILL)
- self.committer_label.show()
- align.show()
-
- align = gtk.Alignment(0.0, 0.5)
- label = gtk.Label()
- label.set_markup("<b>Timestamp:</b>")
- align.add(label)
- self.table.attach(align, 0, 1, 2, 3, gtk.FILL, gtk.FILL)
- label.show()
- align.show()
-
- align = gtk.Alignment(0.0, 0.5)
- self.timestamp_label = gtk.Label()
- self.timestamp_label.set_selectable(True)
- align.add(self.timestamp_label)
- self.table.attach(align, 1, 2, 2, 3, gtk.EXPAND | gtk.FILL, gtk.FILL)
- self.timestamp_label.show()
- align.show()
-
- align = gtk.Alignment(0.0, 0.5)
- label = gtk.Label()
- label.set_markup("<b>Parents:</b>")
- align.add(label)
- self.table.attach(align, 0, 1, 3, 4, gtk.FILL, gtk.FILL)
- label.show()
- align.show()
- self.parents_widgets = []
-
- align = gtk.Alignment(0.0, 0.5)
- label = gtk.Label()
- label.set_markup("<b>Children:</b>")
- align.add(label)
- self.table.attach(align, 2, 3, 3, 4, gtk.FILL, gtk.FILL)
- label.show()
- align.show()
- self.children_widgets = []
-
- scrollwin = gtk.ScrolledWindow()
- scrollwin.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
- scrollwin.set_shadow_type(gtk.SHADOW_IN)
- vbox.pack_start(scrollwin, expand=True, fill=True)
- scrollwin.show()
-
- (self.message_buffer, sourceview) = get_source_buffer_and_view()
-
- sourceview.set_editable(False)
- sourceview.modify_font(pango.FontDescription("Monospace"))
- scrollwin.add(sourceview)
- sourceview.show()
-
- return vbox
-
- def _treeview_cursor_cb(self, *args):
- """Callback for when the treeview cursor changes."""
- (path, col) = self.treeview.get_cursor()
- commit = self.model[path][0]
-
- if commit.committer is not None:
- committer = commit.committer
- timestamp = commit.commit_date
- message = commit.get_message(self.with_diff)
- revid_label = commit.commit_sha1
- else:
- committer = ""
- timestamp = ""
- message = ""
- revid_label = ""
-
- self.revid_label.set_text(revid_label)
- self.committer_label.set_text(committer)
- self.timestamp_label.set_text(timestamp)
- self.message_buffer.set_text(unicode(message, self.encoding).encode('utf-8'))
-
- for widget in self.parents_widgets:
- self.table.remove(widget)
-
- self.parents_widgets = []
- self.table.resize(4 + len(commit.parent_sha1) - 1, 4)
- for idx, parent_id in enumerate(commit.parent_sha1):
- self.table.set_row_spacing(idx + 3, 0)
-
- align = gtk.Alignment(0.0, 0.0)
- self.parents_widgets.append(align)
- self.table.attach(align, 1, 2, idx + 3, idx + 4,
- gtk.EXPAND | gtk.FILL, gtk.FILL)
- align.show()
-
- hbox = gtk.HBox(False, 0)
- align.add(hbox)
- hbox.show()
-
- label = gtk.Label(parent_id)
- label.set_selectable(True)
- hbox.pack_start(label, expand=False, fill=True)
- label.show()
-
- image = gtk.Image()
- image.set_from_stock(gtk.STOCK_JUMP_TO, gtk.ICON_SIZE_MENU)
- image.show()
-
- button = gtk.Button()
- button.add(image)
- button.set_relief(gtk.RELIEF_NONE)
- button.connect("clicked", self._go_clicked_cb, parent_id)
- hbox.pack_start(button, expand=False, fill=True)
- button.show()
-
- image = gtk.Image()
- image.set_from_stock(gtk.STOCK_FIND, gtk.ICON_SIZE_MENU)
- image.show()
-
- button = gtk.Button()
- button.add(image)
- button.set_relief(gtk.RELIEF_NONE)
- button.set_sensitive(True)
- button.connect("clicked", self._show_clicked_cb,
- commit.commit_sha1, parent_id, self.encoding)
- hbox.pack_start(button, expand=False, fill=True)
- button.show()
-
- # Populate with child details
- for widget in self.children_widgets:
- self.table.remove(widget)
-
- self.children_widgets = []
- try:
- child_sha1 = Commit.children_sha1[commit.commit_sha1]
- except KeyError:
- # We don't have child
- child_sha1 = [ 0 ]
-
- if ( len(child_sha1) > len(commit.parent_sha1)):
- self.table.resize(4 + len(child_sha1) - 1, 4)
-
- for idx, child_id in enumerate(child_sha1):
- self.table.set_row_spacing(idx + 3, 0)
-
- align = gtk.Alignment(0.0, 0.0)
- self.children_widgets.append(align)
- self.table.attach(align, 3, 4, idx + 3, idx + 4,
- gtk.EXPAND | gtk.FILL, gtk.FILL)
- align.show()
-
- hbox = gtk.HBox(False, 0)
- align.add(hbox)
- hbox.show()
-
- label = gtk.Label(child_id)
- label.set_selectable(True)
- hbox.pack_start(label, expand=False, fill=True)
- label.show()
-
- image = gtk.Image()
- image.set_from_stock(gtk.STOCK_JUMP_TO, gtk.ICON_SIZE_MENU)
- image.show()
-
- button = gtk.Button()
- button.add(image)
- button.set_relief(gtk.RELIEF_NONE)
- button.connect("clicked", self._go_clicked_cb, child_id)
- hbox.pack_start(button, expand=False, fill=True)
- button.show()
-
- image = gtk.Image()
- image.set_from_stock(gtk.STOCK_FIND, gtk.ICON_SIZE_MENU)
- image.show()
-
- button = gtk.Button()
- button.add(image)
- button.set_relief(gtk.RELIEF_NONE)
- button.set_sensitive(True)
- button.connect("clicked", self._show_clicked_cb,
- child_id, commit.commit_sha1, self.encoding)
- hbox.pack_start(button, expand=False, fill=True)
- button.show()
-
- def _destroy_cb(self, widget):
- """Callback for when a window we manage is destroyed."""
- self.quit()
-
-
- def quit(self):
- """Stop the GTK+ main loop."""
- gtk.main_quit()
-
- def run(self, args):
- self.set_branch(args)
- self.window.connect("destroy", self._destroy_cb)
- self.window.show()
- gtk.main()
-
- def set_branch(self, args):
- """Fill in different windows with info from the reposiroty"""
- fp = os.popen("git rev-parse --sq --default HEAD " + list_to_string(args, 1))
- git_rev_list_cmd = fp.read()
- fp.close()
- fp = os.popen("git rev-list --header --topo-order --parents " + git_rev_list_cmd)
- self.update_window(fp)
-
- def update_window(self, fp):
- commit_lines = []
-
- self.model = gtk.ListStore(gobject.TYPE_PYOBJECT, gobject.TYPE_PYOBJECT,
- gobject.TYPE_PYOBJECT, gobject.TYPE_PYOBJECT, str, str, str)
-
- # used for cursor positioning
- self.index = {}
-
- self.colours = {}
- self.nodepos = {}
- self.incomplete_line = {}
- self.commits = []
-
- index = 0
- last_colour = 0
- last_nodepos = -1
- out_line = []
- input_line = fp.readline()
- while (input_line != ""):
- # The commit header ends with '\0'
- # This NULL is immediately followed by the sha1 of the
- # next commit
- if (input_line[0] != '\0'):
- commit_lines.append(input_line)
- input_line = fp.readline()
- continue;
-
- commit = Commit(commit_lines)
- if (commit != None ):
- self.commits.append(commit)
-
- # Skip the '\0
- commit_lines = []
- commit_lines.append(input_line[1:])
- input_line = fp.readline()
-
- fp.close()
-
- for commit in self.commits:
- (out_line, last_colour, last_nodepos) = self.draw_graph(commit,
- index, out_line,
- last_colour,
- last_nodepos)
- self.index[commit.commit_sha1] = index
- index += 1
-
- self.treeview.set_model(self.model)
- self.treeview.show()
-
- def draw_graph(self, commit, index, out_line, last_colour, last_nodepos):
- in_line=[]
-
- # | -> outline
- # X
- # |\ <- inline
-
- # Reset nodepostion
- if (last_nodepos > 5):
- last_nodepos = -1
-
- # Add the incomplete lines of the last cell in this
- try:
- colour = self.colours[commit.commit_sha1]
- except KeyError:
- self.colours[commit.commit_sha1] = last_colour+1
- last_colour = self.colours[commit.commit_sha1]
- colour = self.colours[commit.commit_sha1]
-
- try:
- node_pos = self.nodepos[commit.commit_sha1]
- except KeyError:
- self.nodepos[commit.commit_sha1] = last_nodepos+1
- last_nodepos = self.nodepos[commit.commit_sha1]
- node_pos = self.nodepos[commit.commit_sha1]
-
- #The first parent always continue on the same line
- try:
- # check we already have the value
- tmp_node_pos = self.nodepos[commit.parent_sha1[0]]
- except KeyError:
- self.colours[commit.parent_sha1[0]] = colour
- self.nodepos[commit.parent_sha1[0]] = node_pos
-
- for sha1 in self.incomplete_line.keys():
- if (sha1 != commit.commit_sha1):
- self.draw_incomplete_line(sha1, node_pos,
- out_line, in_line, index)
- else:
- del self.incomplete_line[sha1]
-
-
- for parent_id in commit.parent_sha1:
- try:
- tmp_node_pos = self.nodepos[parent_id]
- except KeyError:
- self.colours[parent_id] = last_colour+1
- last_colour = self.colours[parent_id]
- self.nodepos[parent_id] = last_nodepos+1
- last_nodepos = self.nodepos[parent_id]
-
- in_line.append((node_pos, self.nodepos[parent_id],
- self.colours[parent_id]))
- self.add_incomplete_line(parent_id)
-
- try:
- branch_tag = self.bt_sha1[commit.commit_sha1]
- except KeyError:
- branch_tag = [ ]
-
-
- node = (node_pos, colour, branch_tag)
-
- self.model.append([commit, node, out_line, in_line,
- commit.message, commit.author, commit.date])
-
- return (in_line, last_colour, last_nodepos)
-
- def add_incomplete_line(self, sha1):
- try:
- self.incomplete_line[sha1].append(self.nodepos[sha1])
- except KeyError:
- self.incomplete_line[sha1] = [self.nodepos[sha1]]
-
- def draw_incomplete_line(self, sha1, node_pos, out_line, in_line, index):
- for idx, pos in enumerate(self.incomplete_line[sha1]):
- if(pos == node_pos):
- #remove the straight line and add a slash
- if ((pos, pos, self.colours[sha1]) in out_line):
- out_line.remove((pos, pos, self.colours[sha1]))
- out_line.append((pos, pos+0.5, self.colours[sha1]))
- self.incomplete_line[sha1][idx] = pos = pos+0.5
- try:
- next_commit = self.commits[index+1]
- if (next_commit.commit_sha1 == sha1 and pos != int(pos)):
- # join the line back to the node point
- # This need to be done only if we modified it
- in_line.append((pos, pos-0.5, self.colours[sha1]))
- continue;
- except IndexError:
- pass
- in_line.append((pos, pos, self.colours[sha1]))
-
-
- def _go_clicked_cb(self, widget, revid):
- """Callback for when the go button for a parent is clicked."""
- try:
- self.treeview.set_cursor(self.index[revid])
- except KeyError:
- dialog = gtk.MessageDialog(parent=None, flags=0,
- type=gtk.MESSAGE_WARNING, buttons=gtk.BUTTONS_CLOSE,
- message_format=None)
- dialog.set_markup("Revision <b>%s</b> not present in the list" % revid)
- # revid == 0 is the parent of the first commit
- if (revid != 0 ):
- dialog.format_secondary_text("Try running gitview without any options")
- dialog.run()
- dialog.destroy()
-
- self.treeview.grab_focus()
-
- def _show_clicked_cb(self, widget, commit_sha1, parent_sha1, encoding):
- """Callback for when the show button for a parent is clicked."""
- window = DiffWindow()
- window.set_diff(commit_sha1, parent_sha1, encoding)
- self.treeview.grab_focus()
-
-without_diff = 0
-if __name__ == "__main__":
-
- if (len(sys.argv) > 1 ):
- if (sys.argv[1] == "--without-diff"):
- without_diff = 1
-
- view = GitView( without_diff != 1)
- view.run(sys.argv[without_diff:])
diff --git a/contrib/gitview/gitview.txt b/contrib/gitview/gitview.txt
deleted file mode 100644
index 7b5f900..0000000
--- a/contrib/gitview/gitview.txt
+++ /dev/null
@@ -1,57 +0,0 @@
-gitview(1)
-==========
-
-NAME
-----
-gitview - A GTK based repository browser for git
-
-SYNOPSIS
---------
-[verse]
-'gitview' [options] [args]
-
-DESCRIPTION
----------
-
-Dependencies:
-
-* Python 2.4
-* PyGTK 2.8 or later
-* PyCairo 1.0 or later
-
-OPTIONS
--------
---without-diff::
-
- If the user doesn't want to list the commit diffs in the main window.
- This may speed up the repository browsing.
-
-<args>::
-
- All the valid option for linkgit:git-rev-list[1].
-
-Key Bindings
-------------
-F4::
- To maximize the window
-
-F5::
- To reread references.
-
-F11::
- Full screen
-
-F12::
- Leave full screen
-
-EXAMPLES
---------
-
-gitview v2.6.12.. include/scsi drivers/scsi::
-
- Show as the changes since version v2.6.12 that changed any file in the
- include/scsi or drivers/scsi subdirectories
-
-gitview --since=2.weeks.ago::
-
- Show the changes during the last two weeks
diff --git a/contrib/long-running-filter/example.pl b/contrib/long-running-filter/example.pl
new file mode 100755
index 0000000..a677569
--- /dev/null
+++ b/contrib/long-running-filter/example.pl
@@ -0,0 +1,132 @@
+#!/usr/bin/perl
+#
+# Example implementation for the Git filter protocol version 2
+# See Documentation/gitattributes.txt, section "Filter Protocol"
+#
+# Please note, this pass-thru filter is a minimal skeleton. No proper
+# error handling was implemented.
+#
+
+use strict;
+use warnings;
+
+my $MAX_PACKET_CONTENT_SIZE = 65516;
+
+sub packet_bin_read {
+ my $buffer;
+ my $bytes_read = read STDIN, $buffer, 4;
+ if ( $bytes_read == 0 ) {
+
+ # EOF - Git stopped talking to us!
+ exit();
+ }
+ elsif ( $bytes_read != 4 ) {
+ die "invalid packet: '$buffer'";
+ }
+ my $pkt_size = hex($buffer);
+ if ( $pkt_size == 0 ) {
+ return ( 1, "" );
+ }
+ elsif ( $pkt_size > 4 ) {
+ my $content_size = $pkt_size - 4;
+ $bytes_read = read STDIN, $buffer, $content_size;
+ if ( $bytes_read != $content_size ) {
+ die "invalid packet ($content_size bytes expected; $bytes_read bytes read)";
+ }
+ return ( 0, $buffer );
+ }
+ else {
+ die "invalid packet size: $pkt_size";
+ }
+}
+
+sub packet_txt_read {
+ my ( $res, $buf ) = packet_bin_read();
+ unless ( $buf =~ s/\n$// ) {
+ die "A non-binary line MUST be terminated by an LF.";
+ }
+ return ( $res, $buf );
+}
+
+sub packet_bin_write {
+ my $buf = shift;
+ print STDOUT sprintf( "%04x", length($buf) + 4 );
+ print STDOUT $buf;
+ STDOUT->flush();
+}
+
+sub packet_txt_write {
+ packet_bin_write( $_[0] . "\n" );
+}
+
+sub packet_flush {
+ print STDOUT sprintf( "%04x", 0 );
+ STDOUT->flush();
+}
+
+( packet_txt_read() eq ( 0, "git-filter-client" ) ) || die "bad initialize";
+( packet_txt_read() eq ( 0, "version=2" ) ) || die "bad version";
+( packet_bin_read() eq ( 1, "" ) ) || die "bad version end";
+
+packet_txt_write("git-filter-server");
+packet_txt_write("version=2");
+packet_flush();
+
+( packet_txt_read() eq ( 0, "capability=clean" ) ) || die "bad capability";
+( packet_txt_read() eq ( 0, "capability=smudge" ) ) || die "bad capability";
+( packet_bin_read() eq ( 1, "" ) ) || die "bad capability end";
+
+packet_txt_write("capability=clean");
+packet_txt_write("capability=smudge");
+packet_flush();
+
+while (1) {
+ my ($command) = packet_txt_read() =~ /^command=(.+)$/;
+ my ($pathname) = packet_txt_read() =~ /^pathname=(.+)$/;
+
+ if ( $pathname eq "" ) {
+ die "bad pathname '$pathname'";
+ }
+
+ packet_bin_read();
+
+ my $input = "";
+ {
+ binmode(STDIN);
+ my $buffer;
+ my $done = 0;
+ while ( !$done ) {
+ ( $done, $buffer ) = packet_bin_read();
+ $input .= $buffer;
+ }
+ }
+
+ my $output;
+ if ( $command eq "clean" ) {
+ ### Perform clean here ###
+ $output = $input;
+ }
+ elsif ( $command eq "smudge" ) {
+ ### Perform smudge here ###
+ $output = $input;
+ }
+ else {
+ die "bad command '$command'";
+ }
+
+ packet_txt_write("status=success");
+ packet_flush();
+ while ( length($output) > 0 ) {
+ my $packet = substr( $output, 0, $MAX_PACKET_CONTENT_SIZE );
+ packet_bin_write($packet);
+ if ( length($output) > $MAX_PACKET_CONTENT_SIZE ) {
+ $output = substr( $output, $MAX_PACKET_CONTENT_SIZE );
+ }
+ else {
+ $output = "";
+ }
+ }
+ packet_flush(); # flush content!
+ packet_flush(); # empty list, keep "status=success" unchanged!
+
+}
diff --git a/contrib/remote-helpers/git-remote-bzr b/contrib/remote-helpers/git-remote-bzr
index 712a137..1c3d87f 100755
--- a/contrib/remote-helpers/git-remote-bzr
+++ b/contrib/remote-helpers/git-remote-bzr
@@ -1,13 +1,11 @@
-#!/usr/bin/env python
+#!/bin/sh
-import sys
-
-sys.stderr.write('WARNING: git-remote-bzr is now maintained independently.\n')
-sys.stderr.write('WARNING: For more information visit https://github.com/felipec/git-remote-bzr\n')
-
-sys.stderr.write('''WARNING:
+cat >&2 <<'EOT'
+WARNING: git-remote-bzr is now maintained independently.
+WARNING: For more information visit https://github.com/felipec/git-remote-bzr
+WARNING:
WARNING: You can pick a directory on your $PATH and download it, e.g.:
-WARNING: $ wget -O $HOME/bin/git-remote-bzr \\
+WARNING: $ wget -O $HOME/bin/git-remote-bzr \
WARNING: https://raw.github.com/felipec/git-remote-bzr/master/git-remote-bzr
WARNING: $ chmod +x $HOME/bin/git-remote-bzr
-''')
+EOT
diff --git a/contrib/remote-helpers/git-remote-hg b/contrib/remote-helpers/git-remote-hg
index 4255ad6..8e91883 100755
--- a/contrib/remote-helpers/git-remote-hg
+++ b/contrib/remote-helpers/git-remote-hg
@@ -1,13 +1,11 @@
-#!/usr/bin/env python
+#!/bin/sh
-import sys
-
-sys.stderr.write('WARNING: git-remote-hg is now maintained independently.\n')
-sys.stderr.write('WARNING: For more information visit https://github.com/felipec/git-remote-hg\n')
-
-sys.stderr.write('''WARNING:
+cat >&2 <<'EOT'
+WARNING: git-remote-hg is now maintained independently.
+WARNING: For more information visit https://github.com/felipec/git-remote-hg
+WARNING:
WARNING: You can pick a directory on your $PATH and download it, e.g.:
-WARNING: $ wget -O $HOME/bin/git-remote-hg \\
+WARNING: $ wget -O $HOME/bin/git-remote-hg \
WARNING: https://raw.github.com/felipec/git-remote-hg/master/git-remote-hg
WARNING: $ chmod +x $HOME/bin/git-remote-hg
-''')
+EOT
diff --git a/contrib/update-unicode/.gitignore b/contrib/update-unicode/.gitignore
new file mode 100644
index 0000000..b0ebc6a
--- /dev/null
+++ b/contrib/update-unicode/.gitignore
@@ -0,0 +1,3 @@
+uniset/
+UnicodeData.txt
+EastAsianWidth.txt
diff --git a/contrib/update-unicode/README b/contrib/update-unicode/README
new file mode 100644
index 0000000..b9e2fc8
--- /dev/null
+++ b/contrib/update-unicode/README
@@ -0,0 +1,20 @@
+TL;DR: Run update_unicode.sh after the publication of a new Unicode
+standard and commit the resulting unicode_widths.h file.
+
+The long version
+================
+
+The Git source code ships the file unicode_widths.h which contains
+tables of zero and double width Unicode code points, respectively.
+These tables are generated using update_unicode.sh in this directory.
+update_unicode.sh itself uses a third-party tool, uniset, to query two
+Unicode data files for the interesting code points.
+
+On first run, update_unicode.sh clones uniset from Github and builds it.
+This requires a current-ish version of autoconf (2.69 works per December
+2016).
+
+On each run, update_unicode.sh checks whether more recent Unicode data
+files are available from the Unicode consortium, and rebuilds the header
+unicode_widths.h with the new data. The new header can then be
+committed.
diff --git a/contrib/update-unicode/update_unicode.sh b/contrib/update-unicode/update_unicode.sh
new file mode 100755
index 0000000..e05db92
--- /dev/null
+++ b/contrib/update-unicode/update_unicode.sh
@@ -0,0 +1,33 @@
+#!/bin/sh
+#See http://www.unicode.org/reports/tr44/
+#
+#Me Enclosing_Mark an enclosing combining mark
+#Mn Nonspacing_Mark a nonspacing combining mark (zero advance width)
+#Cf Format a format control character
+#
+cd "$(dirname "$0")"
+UNICODEWIDTH_H=$(git rev-parse --show-toplevel)/unicode_width.h
+
+wget -N http://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt \
+ http://www.unicode.org/Public/UCD/latest/ucd/EastAsianWidth.txt &&
+if ! test -d uniset; then
+ git clone https://github.com/depp/uniset.git &&
+ ( cd uniset && git checkout 4b186196dd )
+fi &&
+(
+ cd uniset &&
+ if ! test -x uniset; then
+ autoreconf -i &&
+ ./configure --enable-warnings=-Werror CFLAGS='-O0 -ggdb'
+ fi &&
+ make
+) &&
+UNICODE_DIR=. && export UNICODE_DIR &&
+cat >$UNICODEWIDTH_H <<-EOF
+static const struct interval zero_width[] = {
+ $(uniset/uniset --32 cat:Me,Mn,Cf + U+1160..U+11FF - U+00AD)
+};
+static const struct interval double_width[] = {
+ $(uniset/uniset --32 eaw:F,W)
+};
+EOF