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 [--] [<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"
276 case "$2" in '') usage ;; esac
297 if test -z "$sm_path"; then
298 sm_path=$(echo "$repo" |
299 sed -e 's|/$||' -e 's|:*/*\.git$||' -e 's|.*[/:]||g')
302 if test -z "$repo" -o -z "$sm_path"; then
306 # assure repo is absolute or relative to parent
309 # dereference source url relative to parent's url
310 realrepo=$(resolve_relative_url "$repo") || exit
317 die "$(eval_gettext "repo URL: '\$repo' must be absolute or begin with ./|../")"
322 # multiple //; leading ./; /./; /../; trailing /
323 sm_path=$(printf '%s/\n' "$sm_path" |
333 git ls-files --error-unmatch "$sm_path" > /dev/null 2>&1 &&
334 die "$(eval_gettext "'\$sm_path' already exists in the index")"
336 if test -z "$force" && ! git add --dry-run --ignore-missing "$sm_path" > /dev/null 2>&1
338 eval_gettextln "The following path is ignored by one of your .gitignore files:
340 Use -f if you really want to add it." >&2
344 if test -n "$custom_name"
346 sm_name="$custom_name"
351 # perhaps the path exists and is already a git repo, else clone it
352 if test -e "$sm_path"
354 if test -d "$sm_path"/.git -o -f "$sm_path"/.git
356 eval_gettextln "Adding existing repo at '\$sm_path' to the index"
358 die "$(eval_gettext "'\$sm_path' already exists and is not a valid git repo")"
363 module_clone "$sm_path" "$sm_name" "$realrepo" "$reference" || exit
367 # ash fails to wordsplit ${branch:+-b "$branch"...}
369 '') git checkout -f -q ;;
370 ?*) git checkout -f -q -B "$branch" "origin/$branch" ;;
372 ) || die "$(eval_gettext "Unable to checkout submodule '\$sm_path'")"
374 git config submodule."$sm_name".url "$realrepo"
376 git add $force "$sm_path" ||
377 die "$(eval_gettext "Failed to add submodule '\$sm_path'")"
379 git config -f .gitmodules submodule."$sm_name".path "$sm_path" &&
380 git config -f .gitmodules submodule."$sm_name".url "$repo" &&
381 git add --force .gitmodules ||
382 die "$(eval_gettext "Failed to register submodule '\$sm_path'")"
386 # Execute an arbitrary command sequence in each checked out
389 # $@ = command to execute
393 # parse $args after "submodule ... foreach".
415 # dup stdin so that it can be restored when running the external
416 # command in the subshell (and a recursive call to this function)
420 while read mode sha1 stage sm_path
422 die_if_unmatched "$mode"
423 if test -e "$sm_path"/.git
425 say "$(eval_gettext "Entering '\$prefix\$sm_path'")"
426 name=$(module_name "$sm_path")
428 prefix="$prefix$sm_path/"
430 # we make $path available to scripts ...
434 if test -n "$recursive"
436 cmd_foreach "--recursive" "$@"
439 die "$(eval_gettext "Stopping at '\$sm_path'; script returned non-zero status.")"
445 # Register submodules in .git/config
447 # $@ = requested paths (default to all)
451 # parse $args after "submodule ... init".
473 while read mode sha1 stage sm_path
475 die_if_unmatched "$mode"
476 name=$(module_name "$sm_path") || exit
478 # Copy url setting when it is not set yet
479 if test -z "$(git config "submodule.$name.url")"
481 url=$(git config -f .gitmodules submodule."$name".url)
483 die "$(eval_gettext "No url found for submodule path '\$sm_path' in .gitmodules")"
485 # Possibly a url relative to parent
488 url=$(resolve_relative_url "$url") || exit
491 git config submodule."$name".url "$url" ||
492 die "$(eval_gettext "Failed to register url for submodule path '\$sm_path'")"
494 say "$(eval_gettext "Submodule '\$name' (\$url) registered for path '\$sm_path'")"
497 # Copy "update" setting when it is not set yet
498 upd="$(git config -f .gitmodules submodule."$name".update)"
500 test -n "$(git config submodule."$name".update)" ||
501 git config submodule."$name".update "$upd" ||
502 die "$(eval_gettext "Failed to register update mode for submodule path '\$sm_path'")"
507 # Update each submodule path to correct revision, using clone and checkout as needed
509 # $@ = requested paths (default to all)
513 # parse $args after "submodule ... update".
534 case "$2" in '') usage ;; esac
535 reference="--reference=$2"
536 orig_flags="$orig_flags $(git rev-parse --sq-quote "$1")"
562 orig_flags="$orig_flags $(git rev-parse --sq-quote "$1")"
568 cmd_init "--" "$@" || return
574 while read mode sha1 stage sm_path
576 die_if_unmatched "$mode"
579 echo >&2 "Skipping unmerged submodule $sm_path"
582 name=$(module_name "$sm_path") || exit
583 url=$(git config submodule."$name".url)
584 if ! test -z "$update"
586 update_module=$update
588 update_module=$(git config submodule."$name".update)
591 if test "$update_module" = "none"
593 echo "Skipping submodule '$sm_path'"
599 # Only mention uninitialized submodules when its
600 # path have been specified
602 say "$(eval_gettext "Submodule path '\$sm_path' not initialized
603 Maybe you want to use 'update --init'?")"
607 if ! test -d "$sm_path"/.git -o -f "$sm_path"/.git
609 module_clone "$sm_path" "$name" "$url" "$reference" || exit
610 cloned_modules="$cloned_modules;$name"
613 subsha1=$(clear_local_git_env; cd "$sm_path" &&
614 git rev-parse --verify HEAD) ||
615 die "$(eval_gettext "Unable to find current revision in submodule path '\$sm_path'")"
618 if test "$subsha1" != "$sha1" -o -n "$force"
621 # If we don't already have a -f flag and the submodule has never been checked out
622 if test -z "$subsha1" -a -z "$force"
627 if test -z "$nofetch"
629 # Run fetch only if $sha1 isn't present or it
630 # is not reachable from a ref.
631 (clear_local_git_env; cd "$sm_path" &&
632 ( (rev=$(git rev-list -n 1 $sha1 --not --all 2>/dev/null) &&
633 test -z "$rev") || git-fetch)) ||
634 die "$(eval_gettext "Unable to fetch in submodule path '\$sm_path'")"
637 # Is this something we just cloned?
638 case ";$cloned_modules;" in
640 # then there is no local change to integrate
645 case "$update_module" in
648 die_msg="$(eval_gettext "Unable to rebase '\$sha1' in submodule path '\$sm_path'")"
649 say_msg="$(eval_gettext "Submodule path '\$sm_path': rebased into '\$sha1'")"
650 must_die_on_failure=yes
654 die_msg="$(eval_gettext "Unable to merge '\$sha1' in submodule path '\$sm_path'")"
655 say_msg="$(eval_gettext "Submodule path '\$sm_path': merged in '\$sha1'")"
656 must_die_on_failure=yes
659 command="git checkout $subforce -q"
660 die_msg="$(eval_gettext "Unable to checkout '\$sha1' in submodule path '\$sm_path'")"
661 say_msg="$(eval_gettext "Submodule path '\$sm_path': checked out '\$sha1'")"
665 if (clear_local_git_env; cd "$sm_path" && $command "$sha1")
668 elif test -n "$must_die_on_failure"
670 die_with_status 2 "$die_msg"
672 err="${err};$die_msg"
677 if test -n "$recursive"
679 (clear_local_git_env; cd "$sm_path" && eval cmd_update "$orig_flags")
683 die_msg="$(eval_gettext "Failed to recurse into submodule path '\$sm_path'")"
686 err="${err};$die_msg"
689 die_with_status $res "$die_msg"
716 git describe "$2" 2>/dev/null ||
717 git describe --tags "$2" 2>/dev/null ||
718 git describe --contains "$2" 2>/dev/null ||
719 git describe --all --always "$2"
722 test -z "$revname" || revname=" ($revname)"
725 # Show commit summary for submodules in index or working tree
727 # If '--cached' is given, show summary between index and given commit,
728 # or between working tree and given commit
730 # $@ = [commit (default 'HEAD'),] requested paths (default all)
737 # parse $args after "submodule ... summary".
751 if summary_limit=$(($2 + 0)) 2>/dev/null && test "$summary_limit" = "$2"
773 test $summary_limit = 0 && return
775 if rev=$(git rev-parse -q --verify --default HEAD ${1+"$1"})
779 elif test -z "$1" -o "$1" = "HEAD"
781 # before the first commit: compare with an empty tree
782 head=$(git hash-object -w -t tree --stdin </dev/null)
783 test -z "$1" || shift
791 die "$(gettext "The --cached option cannot be used with the --files option")"
797 # Get modified modules cared by user
798 modules=$(git $diff_cmd $cached --ignore-submodules=dirty --raw $head -- "$@" |
799 sane_egrep '^:([0-7]* )?160000' |
800 while read mod_src mod_dst sha1_src sha1_dst status name
802 # Always show modules deleted or type-changed (blob<->module)
803 test $status = D -o $status = T && echo "$name" && continue
804 # Also show added or modified modules which are checked out
805 GIT_DIR="$name/.git" git-rev-parse --git-dir >/dev/null 2>&1 &&
810 test -z "$modules" && return
812 git $diff_cmd $cached --ignore-submodules=dirty --raw $head -- $modules |
813 sane_egrep '^:([0-7]* )?160000' |
815 while read mod_src mod_dst sha1_src sha1_dst status name
817 if test -z "$cached" &&
818 test $sha1_dst = 0000000000000000000000000000000000000000
822 sha1_dst=$(GIT_DIR="$name/.git" git rev-parse HEAD)
824 100644 | 100755 | 120000)
825 sha1_dst=$(git hash-object $name)
831 eval_gettextln "unexpected mode \$mod_dst" >&2
838 test $mod_src = 160000 &&
839 ! GIT_DIR="$name/.git" git-rev-parse -q --verify $sha1_src^0 >/dev/null &&
842 test $mod_dst = 160000 &&
843 ! GIT_DIR="$name/.git" git-rev-parse -q --verify $sha1_dst^0 >/dev/null &&
847 case "$missing_src,$missing_dst" in
849 errmsg="$(eval_gettext " Warn: \$name doesn't contain commit \$sha1_src")"
852 errmsg="$(eval_gettext " Warn: \$name doesn't contain commit \$sha1_dst")"
855 errmsg="$(eval_gettext " Warn: \$name doesn't contain commits \$sha1_src and \$sha1_dst")"
860 if test $mod_src = 160000 -a $mod_dst = 160000
862 range="$sha1_src...$sha1_dst"
863 elif test $mod_src = 160000
869 GIT_DIR="$name/.git" \
870 git rev-list --first-parent $range -- | wc -l
872 total_commits=" ($(($total_commits + 0)))"
876 sha1_abbr_src=$(echo $sha1_src | cut -c1-7)
877 sha1_abbr_dst=$(echo $sha1_dst | cut -c1-7)
880 blob="$(gettext "blob")"
881 submodule="$(gettext "submodule")"
882 if test $mod_dst = 160000
884 echo "* $name $sha1_abbr_src($blob)->$sha1_abbr_dst($submodule)$total_commits:"
886 echo "* $name $sha1_abbr_src($submodule)->$sha1_abbr_dst($blob)$total_commits:"
889 echo "* $name $sha1_abbr_src...$sha1_abbr_dst$total_commits:"
893 # Don't give error msg for modification whose dst is not submodule
894 # i.e. deleted or changed to blob
895 test $mod_dst = 160000 && echo "$errmsg"
897 if test $mod_src = 160000 -a $mod_dst = 160000
900 test $summary_limit -gt 0 && limit="-$summary_limit"
901 GIT_DIR="$name/.git" \
902 git log $limit --pretty='format: %m %s' \
903 --first-parent $sha1_src...$sha1_dst
904 elif test $mod_dst = 160000
906 GIT_DIR="$name/.git" \
907 git log --pretty='format: > %s' -1 $sha1_dst
909 GIT_DIR="$name/.git" \
910 git log --pretty='format: < %s' -1 $sha1_src
916 if test -n "$for_status"; then
917 if [ -n "$files" ]; then
918 gettextln "# Submodules changed but not updated:"
920 gettextln "# Submodule changes to be committed:"
923 sed -e 's|^|# |' -e 's|^# $|#|'
929 # List all submodules, prefixed with:
930 # - submodule not initialized
931 # + different revision checked out
933 # If --cached was specified the revision in the index will be printed
934 # instead of the currently checked out revision.
936 # $@ = requested paths (default to all)
940 # parse $args after "submodule ... status".
965 orig_flags="$orig_flags $(git rev-parse --sq-quote "$1")"
970 while read mode sha1 stage sm_path
972 die_if_unmatched "$mode"
973 name=$(module_name "$sm_path") || exit
974 url=$(git config submodule."$name".url)
975 displaypath="$prefix$sm_path"
978 say "U$sha1 $displaypath"
981 if test -z "$url" || ! test -d "$sm_path"/.git -o -f "$sm_path"/.git
983 say "-$sha1 $displaypath"
986 set_name_rev "$sm_path" "$sha1"
987 if git diff-files --ignore-submodules=dirty --quiet -- "$sm_path"
989 say " $sha1 $displaypath$revname"
993 sha1=$(clear_local_git_env; cd "$sm_path" && git rev-parse --verify HEAD)
994 set_name_rev "$sm_path" "$sha1"
996 say "+$sha1 $displaypath$revname"
999 if test -n "$recursive"
1002 prefix="$displaypath/"
1005 eval cmd_status "$orig_args"
1007 die "$(eval_gettext "Failed to recurse into submodule path '\$sm_path'")"
1012 # Sync remote urls for submodules
1013 # This makes the value for remote.$remote.url match the value
1014 # specified in .gitmodules.
1039 while read mode sha1 stage sm_path
1041 die_if_unmatched "$mode"
1042 name=$(module_name "$sm_path")
1043 url=$(git config -f .gitmodules --get submodule."$name".url)
1045 # Possibly a url relative to parent
1048 # rewrite foo/bar as ../.. to find path from
1049 # submodule work tree to superproject work tree
1050 up_path="$(echo "$sm_path" | sed "s/[^/][^/]*/../g")" &&
1051 # guarantee a trailing /
1052 up_path=${up_path%/}/ &&
1053 # path from submodule work tree to submodule origin repo
1054 sub_origin_url=$(resolve_relative_url "$url" "$up_path") &&
1055 # path from superproject work tree to submodule origin repo
1056 super_config_url=$(resolve_relative_url "$url") || exit
1059 sub_origin_url="$url"
1060 super_config_url="$url"
1064 if git config "submodule.$name.url" >/dev/null 2>/dev/null
1066 say "$(eval_gettext "Synchronizing submodule url for '\$name'")"
1067 git config submodule."$name".url "$super_config_url"
1069 if test -e "$sm_path"/.git
1074 remote=$(get_default_remote)
1075 git config remote."$remote".url "$sub_origin_url"
1082 # This loop parses the command line arguments to find the
1083 # subcommand name to dispatch. Parsing of the subcommand specific
1084 # options are primarily done by the subcommand implementations.
1085 # Subcommand specific options such as --branch and --cached are
1086 # parsed here as well, for backward compatibility.
1088 while test $# != 0 && test -z "$command"
1091 add | foreach | init | update | status | summary | sync)
1121 # No command word defaults to "status"
1122 test -n "$command" || command=status
1124 # "-b branch" is accepted only by "add"
1125 if test -n "$branch" && test "$command" != add
1130 # "--cached" is accepted only by "status" and "summary"
1131 if test -n "$cached" && test "$command" != status -a "$command" != summary