3 # git-submodule.sh: add, init, update or list git submodules
5 # Copyright (c) 2007 Lars Hjemli
7 dashless=$(basename "$0" | sed -e 's/-/ /')
8 USAGE="[--quiet] add [-b <branch>] [-f|--force] [--name <name>] [--reference <repository>] [--] <repository> [<path>]
9 or: $dashless [--quiet] status [--cached] [--recursive] [--] [<path>...]
10 or: $dashless [--quiet] init [--] [<path>...]
11 or: $dashless [--quiet] update [--init] [-N|--no-fetch] [-f|--force] [--rebase] [--reference <repository>] [--merge] [--recursive] [--] [<path>...]
12 or: $dashless [--quiet] summary [--cached|--files] [--summary-limit <n>] [commit] [--] [<path>...]
13 or: $dashless [--quiet] foreach [--recursive] <command>
14 or: $dashless [--quiet] sync [--recursive] [--] [<path>...]"
34 # The function takes at most 2 arguments. The first argument is the
35 # URL that navigates to the submodule origin repo. When relative, this URL
36 # is relative to the superproject origin URL repo. The second up_path
37 # argument, if specified, is the relative path that navigates
38 # from the submodule working tree to the superproject working tree.
40 # The output of the function is the origin URL of the submodule.
42 # The output will either be an absolute URL or filesystem path (if the
43 # superproject origin URL is an absolute URL or filesystem path,
44 # respectively) or a relative file system path (if the superproject
45 # origin URL is a relative file system path).
47 # When the output is a relative file system path, the path is either
48 # relative to the submodule working tree, if up_path is specified, or to
49 # the superproject working tree otherwise.
50 resolve_relative_url ()
52 remote=$(get_default_remote)
53 remoteurl=$(git config "remote.$remote.url") ||
54 remoteurl=$(pwd) # the repository is its own authoritative upstream
56 remoteurl=${remoteurl%/}
69 remoteurl="./$remoteurl"
80 remoteurl="${remoteurl%/*}"
83 remoteurl="${remoteurl%:*}"
87 if test -z "$is_relative" || test "." = "$remoteurl"
89 die "$(eval_gettext "cannot strip one component off url '\$remoteurl'")"
103 remoteurl="$remoteurl$sep${url%/}"
104 echo "${is_relative:+${up_path}}${remoteurl#./}"
108 # Get submodule info for registered submodules
109 # $@ = path to limit submodule list
114 git ls-files --error-unmatch --stage -- "$@" ||
115 echo "unmatched pathspec exists"
119 my ($null_sha1) = ("0" x 40);
123 if (/^unmatched pathspec/) {
128 my ($mode, $sha1, $stage, $path) =
129 /^([0-7]+) ([0-9a-f]{40}) ([0-3])\t(.*)$/;
130 next unless $mode eq "160000";
132 if (!$unmerged{$path}++) {
133 push @out, "$mode $null_sha1 U\t$path\n";
140 print "#unmatched\n";
149 if test "$1" = "#unmatched"
156 # Map submodule path to submodule name
162 # Do we have "submodule.<something>.path = $1" defined in .gitmodules file?
164 re=$(printf '%s\n' "$1" | sed -e 's/[].[^$\\*]/\\&/g')
165 name=$( git config -f .gitmodules --get-regexp '^submodule\..*\.path$' |
166 sed -n -e 's|^submodule\.\(.*\)\.path '"$re"'$|\1|p' )
168 die "$(eval_gettext "No submodule mapping found in .gitmodules for path '\$sm_path'")"
175 # Prior to calling, cmd_update checks that a possibly existing
176 # path is not a git repository.
177 # Likewise, cmd_add checks that path does not exist at all,
178 # since it is the location of a new submodule.
187 if test -n "$GIT_QUIET"
194 base_name=$(dirname "$name")
196 gitdir=$(git rev-parse --git-dir)
197 gitdir_base="$gitdir/modules/$base_name"
198 gitdir="$gitdir/modules/$name"
203 rm -f "$gitdir/index"
205 mkdir -p "$gitdir_base"
208 git clone $quiet -n ${reference:+"$reference"} \
209 --separate-git-dir "$gitdir" "$url" "$sm_path"
211 die "$(eval_gettext "Clone of '\$url' into submodule path '\$sm_path' failed")"
214 # We already are at the root of the work tree but cd_to_toplevel will
215 # resolve any symlinks that might be present in $PWD
216 a=$(cd_to_toplevel && cd "$gitdir" && pwd)/
217 b=$(cd_to_toplevel && cd "$sm_path" && pwd)/
218 # normalize Windows-style absolute paths to POSIX-style absolute paths
219 case $a in [a-zA-Z]:/*) a=/${a%%:*}${a#*:} ;; esac
220 case $b in [a-zA-Z]:/*) b=/${b%%:*}${b#*:} ;; esac
221 # Remove all common leading directories after a sanity check
222 if test "${a#$b}" != "$a" || test "${b#$a}" != "$b"; then
223 die "$(eval_gettext "Gitdir '\$a' is part of the submodule path '\$b' or vice versa")"
225 while test "${a%%/*}" = "${b%%/*}"
230 # Now chop off the trailing '/'s that were added in the beginning
234 # Turn each leading "*/" component into "../"
235 rel=$(echo $b | sed -e 's|[^/][^/]*|..|g')
236 echo "gitdir: $rel/$a" >"$sm_path/.git"
238 rel=$(echo $a | sed -e 's|[^/][^/]*|..|g')
239 (clear_local_git_env; cd "$sm_path" && GIT_WORK_TREE=. git config core.worktree "$rel/$b")
243 # Add a new submodule to the working tree, .gitmodules and the index
247 # optional branch is stored in global branch variable
251 # parse $args after "submodule ... add".
256 case "$2" in '') usage ;; esac
267 case "$2" in '') usage ;; esac
268 reference="--reference=$2"
275 case "$2" in '') usage ;; esac
296 if test -z "$sm_path"; then
297 sm_path=$(echo "$repo" |
298 sed -e 's|/$||' -e 's|:*/*\.git$||' -e 's|.*[/:]||g')
301 if test -z "$repo" -o -z "$sm_path"; then
305 # assure repo is absolute or relative to parent
308 # dereference source url relative to parent's url
309 realrepo=$(resolve_relative_url "$repo") || exit
316 die "$(eval_gettext "repo URL: '\$repo' must be absolute or begin with ./|../")"
321 # multiple //; leading ./; /./; /../; trailing /
322 sm_path=$(printf '%s/\n' "$sm_path" |
332 git ls-files --error-unmatch "$sm_path" > /dev/null 2>&1 &&
333 die "$(eval_gettext "'\$sm_path' already exists in the index")"
335 if test -z "$force" && ! git add --dry-run --ignore-missing "$sm_path" > /dev/null 2>&1
337 eval_gettextln "The following path is ignored by one of your .gitignore files:
339 Use -f if you really want to add it." >&2
343 if test -n "$custom_name"
345 sm_name="$custom_name"
350 # perhaps the path exists and is already a git repo, else clone it
351 if test -e "$sm_path"
353 if test -d "$sm_path"/.git -o -f "$sm_path"/.git
355 eval_gettextln "Adding existing repo at '\$sm_path' to the index"
357 die "$(eval_gettext "'\$sm_path' already exists and is not a valid git repo")"
361 if test -d ".git/modules/$sm_name"
365 echo >&2 "$(eval_gettext "A git directory for '\$sm_name' is found locally with remote(s):")"
366 GIT_DIR=".git/modules/$sm_name" GIT_WORK_TREE=. git remote -v | grep '(fetch)' | sed -e s,^," ", -e s,' (fetch)',, >&2
367 echo >&2 "$(eval_gettext "If you want to reuse this local git directory instead of cloning again from")"
368 echo >&2 " $realrepo"
369 echo >&2 "$(eval_gettext "use the '--force' option. If the local git directory is not the correct repo")"
370 die "$(eval_gettext "or you are unsure what this means choose another name with the '--name' option.")"
372 echo "$(eval_gettext "Reactivating local git directory for submodule '\$sm_name'.")"
375 module_clone "$sm_path" "$sm_name" "$realrepo" "$reference" || exit
379 # ash fails to wordsplit ${branch:+-b "$branch"...}
381 '') git checkout -f -q ;;
382 ?*) git checkout -f -q -B "$branch" "origin/$branch" ;;
384 ) || die "$(eval_gettext "Unable to checkout submodule '\$sm_path'")"
386 git config submodule."$sm_name".url "$realrepo"
388 git add $force "$sm_path" ||
389 die "$(eval_gettext "Failed to add submodule '\$sm_path'")"
391 git config -f .gitmodules submodule."$sm_name".path "$sm_path" &&
392 git config -f .gitmodules submodule."$sm_name".url "$repo" &&
393 git add --force .gitmodules ||
394 die "$(eval_gettext "Failed to register submodule '\$sm_path'")"
398 # Execute an arbitrary command sequence in each checked out
401 # $@ = command to execute
405 # parse $args after "submodule ... foreach".
427 # dup stdin so that it can be restored when running the external
428 # command in the subshell (and a recursive call to this function)
432 while read mode sha1 stage sm_path
434 die_if_unmatched "$mode"
435 if test -e "$sm_path"/.git
437 say "$(eval_gettext "Entering '\$prefix\$sm_path'")"
438 name=$(module_name "$sm_path")
440 prefix="$prefix$sm_path/"
442 # we make $path available to scripts ...
446 if test -n "$recursive"
448 cmd_foreach "--recursive" "$@"
451 die "$(eval_gettext "Stopping at '\$sm_path'; script returned non-zero status.")"
457 # Register submodules in .git/config
459 # $@ = requested paths (default to all)
463 # parse $args after "submodule ... init".
485 while read mode sha1 stage sm_path
487 die_if_unmatched "$mode"
488 name=$(module_name "$sm_path") || exit
490 # Copy url setting when it is not set yet
491 if test -z "$(git config "submodule.$name.url")"
493 url=$(git config -f .gitmodules submodule."$name".url)
495 die "$(eval_gettext "No url found for submodule path '\$sm_path' in .gitmodules")"
497 # Possibly a url relative to parent
500 url=$(resolve_relative_url "$url") || exit
503 git config submodule."$name".url "$url" ||
504 die "$(eval_gettext "Failed to register url for submodule path '\$sm_path'")"
506 say "$(eval_gettext "Submodule '\$name' (\$url) registered for path '\$sm_path'")"
509 # Copy "update" setting when it is not set yet
510 upd="$(git config -f .gitmodules submodule."$name".update)"
512 test -n "$(git config submodule."$name".update)" ||
513 git config submodule."$name".update "$upd" ||
514 die "$(eval_gettext "Failed to register update mode for submodule path '\$sm_path'")"
519 # Update each submodule path to correct revision, using clone and checkout as needed
521 # $@ = requested paths (default to all)
525 # parse $args after "submodule ... update".
546 case "$2" in '') usage ;; esac
547 reference="--reference=$2"
548 orig_flags="$orig_flags $(git rev-parse --sq-quote "$1")"
574 orig_flags="$orig_flags $(git rev-parse --sq-quote "$1")"
580 cmd_init "--" "$@" || return
586 while read mode sha1 stage sm_path
588 die_if_unmatched "$mode"
591 echo >&2 "Skipping unmerged submodule $sm_path"
594 name=$(module_name "$sm_path") || exit
595 url=$(git config submodule."$name".url)
596 if ! test -z "$update"
598 update_module=$update
600 update_module=$(git config submodule."$name".update)
603 if test "$update_module" = "none"
605 echo "Skipping submodule '$sm_path'"
611 # Only mention uninitialized submodules when its
612 # path have been specified
614 say "$(eval_gettext "Submodule path '\$sm_path' not initialized
615 Maybe you want to use 'update --init'?")"
619 if ! test -d "$sm_path"/.git -o -f "$sm_path"/.git
621 module_clone "$sm_path" "$name" "$url" "$reference" || exit
622 cloned_modules="$cloned_modules;$name"
625 subsha1=$(clear_local_git_env; cd "$sm_path" &&
626 git rev-parse --verify HEAD) ||
627 die "$(eval_gettext "Unable to find current revision in submodule path '\$sm_path'")"
630 if test "$subsha1" != "$sha1" -o -n "$force"
633 # If we don't already have a -f flag and the submodule has never been checked out
634 if test -z "$subsha1" -a -z "$force"
639 if test -z "$nofetch"
641 # Run fetch only if $sha1 isn't present or it
642 # is not reachable from a ref.
643 (clear_local_git_env; cd "$sm_path" &&
644 ( (rev=$(git rev-list -n 1 $sha1 --not --all 2>/dev/null) &&
645 test -z "$rev") || git-fetch)) ||
646 die "$(eval_gettext "Unable to fetch in submodule path '\$sm_path'")"
649 # Is this something we just cloned?
650 case ";$cloned_modules;" in
652 # then there is no local change to integrate
657 case "$update_module" in
660 die_msg="$(eval_gettext "Unable to rebase '\$sha1' in submodule path '\$sm_path'")"
661 say_msg="$(eval_gettext "Submodule path '\$sm_path': rebased into '\$sha1'")"
662 must_die_on_failure=yes
666 die_msg="$(eval_gettext "Unable to merge '\$sha1' in submodule path '\$sm_path'")"
667 say_msg="$(eval_gettext "Submodule path '\$sm_path': merged in '\$sha1'")"
668 must_die_on_failure=yes
671 command="git checkout $subforce -q"
672 die_msg="$(eval_gettext "Unable to checkout '\$sha1' in submodule path '\$sm_path'")"
673 say_msg="$(eval_gettext "Submodule path '\$sm_path': checked out '\$sha1'")"
677 if (clear_local_git_env; cd "$sm_path" && $command "$sha1")
680 elif test -n "$must_die_on_failure"
682 die_with_status 2 "$die_msg"
684 err="${err};$die_msg"
689 if test -n "$recursive"
691 (clear_local_git_env; cd "$sm_path" && eval cmd_update "$orig_flags")
695 die_msg="$(eval_gettext "Failed to recurse into submodule path '\$sm_path'")"
698 err="${err};$die_msg"
701 die_with_status $res "$die_msg"
728 git describe "$2" 2>/dev/null ||
729 git describe --tags "$2" 2>/dev/null ||
730 git describe --contains "$2" 2>/dev/null ||
731 git describe --all --always "$2"
734 test -z "$revname" || revname=" ($revname)"
737 # Show commit summary for submodules in index or working tree
739 # If '--cached' is given, show summary between index and given commit,
740 # or between working tree and given commit
742 # $@ = [commit (default 'HEAD'),] requested paths (default all)
749 # parse $args after "submodule ... summary".
763 if summary_limit=$(($2 + 0)) 2>/dev/null && test "$summary_limit" = "$2"
785 test $summary_limit = 0 && return
787 if rev=$(git rev-parse -q --verify --default HEAD ${1+"$1"})
791 elif test -z "$1" -o "$1" = "HEAD"
793 # before the first commit: compare with an empty tree
794 head=$(git hash-object -w -t tree --stdin </dev/null)
795 test -z "$1" || shift
803 die "$(gettext "The --cached option cannot be used with the --files option")"
809 # Get modified modules cared by user
810 modules=$(git $diff_cmd $cached --ignore-submodules=dirty --raw $head -- "$@" |
811 sane_egrep '^:([0-7]* )?160000' |
812 while read mod_src mod_dst sha1_src sha1_dst status name
814 # Always show modules deleted or type-changed (blob<->module)
815 test $status = D -o $status = T && echo "$name" && continue
816 # Also show added or modified modules which are checked out
817 GIT_DIR="$name/.git" git-rev-parse --git-dir >/dev/null 2>&1 &&
822 test -z "$modules" && return
824 git $diff_cmd $cached --ignore-submodules=dirty --raw $head -- $modules |
825 sane_egrep '^:([0-7]* )?160000' |
827 while read mod_src mod_dst sha1_src sha1_dst status name
829 if test -z "$cached" &&
830 test $sha1_dst = 0000000000000000000000000000000000000000
834 sha1_dst=$(GIT_DIR="$name/.git" git rev-parse HEAD)
836 100644 | 100755 | 120000)
837 sha1_dst=$(git hash-object $name)
843 eval_gettextln "unexpected mode \$mod_dst" >&2
850 test $mod_src = 160000 &&
851 ! GIT_DIR="$name/.git" git-rev-parse -q --verify $sha1_src^0 >/dev/null &&
854 test $mod_dst = 160000 &&
855 ! GIT_DIR="$name/.git" git-rev-parse -q --verify $sha1_dst^0 >/dev/null &&
859 case "$missing_src,$missing_dst" in
861 errmsg="$(eval_gettext " Warn: \$name doesn't contain commit \$sha1_src")"
864 errmsg="$(eval_gettext " Warn: \$name doesn't contain commit \$sha1_dst")"
867 errmsg="$(eval_gettext " Warn: \$name doesn't contain commits \$sha1_src and \$sha1_dst")"
872 if test $mod_src = 160000 -a $mod_dst = 160000
874 range="$sha1_src...$sha1_dst"
875 elif test $mod_src = 160000
881 GIT_DIR="$name/.git" \
882 git rev-list --first-parent $range -- | wc -l
884 total_commits=" ($(($total_commits + 0)))"
888 sha1_abbr_src=$(echo $sha1_src | cut -c1-7)
889 sha1_abbr_dst=$(echo $sha1_dst | cut -c1-7)
892 blob="$(gettext "blob")"
893 submodule="$(gettext "submodule")"
894 if test $mod_dst = 160000
896 echo "* $name $sha1_abbr_src($blob)->$sha1_abbr_dst($submodule)$total_commits:"
898 echo "* $name $sha1_abbr_src($submodule)->$sha1_abbr_dst($blob)$total_commits:"
901 echo "* $name $sha1_abbr_src...$sha1_abbr_dst$total_commits:"
905 # Don't give error msg for modification whose dst is not submodule
906 # i.e. deleted or changed to blob
907 test $mod_dst = 160000 && echo "$errmsg"
909 if test $mod_src = 160000 -a $mod_dst = 160000
912 test $summary_limit -gt 0 && limit="-$summary_limit"
913 GIT_DIR="$name/.git" \
914 git log $limit --pretty='format: %m %s' \
915 --first-parent $sha1_src...$sha1_dst
916 elif test $mod_dst = 160000
918 GIT_DIR="$name/.git" \
919 git log --pretty='format: > %s' -1 $sha1_dst
921 GIT_DIR="$name/.git" \
922 git log --pretty='format: < %s' -1 $sha1_src
928 if test -n "$for_status"; then
929 if [ -n "$files" ]; then
930 gettextln "# Submodules changed but not updated:"
932 gettextln "# Submodule changes to be committed:"
935 sed -e 's|^|# |' -e 's|^# $|#|'
941 # List all submodules, prefixed with:
942 # - submodule not initialized
943 # + different revision checked out
945 # If --cached was specified the revision in the index will be printed
946 # instead of the currently checked out revision.
948 # $@ = requested paths (default to all)
952 # parse $args after "submodule ... status".
980 while read mode sha1 stage sm_path
982 die_if_unmatched "$mode"
983 name=$(module_name "$sm_path") || exit
984 url=$(git config submodule."$name".url)
985 displaypath="$prefix$sm_path"
988 say "U$sha1 $displaypath"
991 if test -z "$url" || ! test -d "$sm_path"/.git -o -f "$sm_path"/.git
993 say "-$sha1 $displaypath"
996 set_name_rev "$sm_path" "$sha1"
997 if git diff-files --ignore-submodules=dirty --quiet -- "$sm_path"
999 say " $sha1 $displaypath$revname"
1001 if test -z "$cached"
1003 sha1=$(clear_local_git_env; cd "$sm_path" && git rev-parse --verify HEAD)
1004 set_name_rev "$sm_path" "$sha1"
1006 say "+$sha1 $displaypath$revname"
1009 if test -n "$recursive"
1012 prefix="$displaypath/"
1017 die "$(eval_gettext "Failed to recurse into submodule path '\$sm_path'")"
1022 # Sync remote urls for submodules
1023 # This makes the value for remote.$remote.url match the value
1024 # specified in .gitmodules.
1053 while read mode sha1 stage sm_path
1055 die_if_unmatched "$mode"
1056 name=$(module_name "$sm_path")
1057 url=$(git config -f .gitmodules --get submodule."$name".url)
1059 # Possibly a url relative to parent
1062 # rewrite foo/bar as ../.. to find path from
1063 # submodule work tree to superproject work tree
1064 up_path="$(echo "$sm_path" | sed "s/[^/][^/]*/../g")" &&
1065 # guarantee a trailing /
1066 up_path=${up_path%/}/ &&
1067 # path from submodule work tree to submodule origin repo
1068 sub_origin_url=$(resolve_relative_url "$url" "$up_path") &&
1069 # path from superproject work tree to submodule origin repo
1070 super_config_url=$(resolve_relative_url "$url") || exit
1073 sub_origin_url="$url"
1074 super_config_url="$url"
1078 if git config "submodule.$name.url" >/dev/null 2>/dev/null
1080 say "$(eval_gettext "Synchronizing submodule url for '\$prefix\$sm_path'")"
1081 git config submodule."$name".url "$super_config_url"
1083 if test -e "$sm_path"/.git
1088 remote=$(get_default_remote)
1089 git config remote."$remote".url "$sub_origin_url"
1091 if test -n "$recursive"
1093 prefix="$prefix$sm_path/"
1102 # This loop parses the command line arguments to find the
1103 # subcommand name to dispatch. Parsing of the subcommand specific
1104 # options are primarily done by the subcommand implementations.
1105 # Subcommand specific options such as --branch and --cached are
1106 # parsed here as well, for backward compatibility.
1108 while test $# != 0 && test -z "$command"
1111 add | foreach | init | update | status | summary | sync)
1141 # No command word defaults to "status"
1142 if test -z "$command"
1152 # "-b branch" is accepted only by "add"
1153 if test -n "$branch" && test "$command" != add
1158 # "--cached" is accepted only by "status" and "summary"
1159 if test -n "$cached" && test "$command" != status -a "$command" != summary