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] [--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] [--commit] [--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.
186 if test -n "$GIT_QUIET"
193 name=$(module_name "$sm_path" 2>/dev/null)
194 test -n "$name" || name="$sm_path"
195 base_name=$(dirname "$name")
197 gitdir=$(git rev-parse --git-dir)
198 gitdir_base="$gitdir/modules/$base_name"
199 gitdir="$gitdir/modules/$name"
204 rm -f "$gitdir/index"
206 mkdir -p "$gitdir_base"
209 git clone $quiet -n ${reference:+"$reference"} \
210 --separate-git-dir "$gitdir" "$url" "$sm_path"
212 die "$(eval_gettext "Clone of '\$url' into submodule path '\$sm_path' failed")"
215 # We already are at the root of the work tree but cd_to_toplevel will
216 # resolve any symlinks that might be present in $PWD
217 a=$(cd_to_toplevel && cd "$gitdir" && pwd)/
218 b=$(cd_to_toplevel && cd "$sm_path" && pwd)/
219 # normalize Windows-style absolute paths to POSIX-style absolute paths
220 case $a in [a-zA-Z]:/*) a=/${a%%:*}${a#*:} ;; esac
221 case $b in [a-zA-Z]:/*) b=/${b%%:*}${b#*:} ;; esac
222 # Remove all common leading directories after a sanity check
223 if test "${a#$b}" != "$a" || test "${b#$a}" != "$b"; then
224 die "$(eval_gettext "Gitdir '\$a' is part of the submodule path '\$b' or vice versa")"
226 while test "${a%%/*}" = "${b%%/*}"
231 # Now chop off the trailing '/'s that were added in the beginning
235 # Turn each leading "*/" component into "../"
236 rel=$(echo $b | sed -e 's|[^/][^/]*|..|g')
237 echo "gitdir: $rel/$a" >"$sm_path/.git"
239 rel=$(echo $a | sed -e 's|[^/][^/]*|..|g')
240 (clear_local_git_env; cd "$sm_path" && GIT_WORK_TREE=. git config core.worktree "$rel/$b")
244 # Commit changed submodule gitlinks
246 # $1 = name-a;sha1-a;subsha1-a\n[name-b;sha1-b;subsha1-b\n...]
254 while read name sm_path sha1 subsha1
260 while read name sm_path sha1 subsha1
265 summary="$(eval_gettext "Updated submodules:")$names"
267 while read name sm_path sha1 subsha1
269 if test "$name" = "$sm_path"
271 printf 'Changes to %s:\n\n' "$name"
273 printf 'Changes to %s (%s):\n\n' "$name" "$sm_path"
278 git shortlog "${sha1}..${subsha1}" ||
279 die "$(eval_gettext "Unable to generate shortlog in submodule path '\$sm_path'")"
284 message="$(printf '%s\n\n%s\n' "$summary" "$body")"
285 echo "message: [$message]"
286 git commit -m "$message" $paths
290 # Add a new submodule to the working tree, .gitmodules and the index
294 # optional branch is stored in global branch variable
298 # parse $args after "submodule ... add".
303 case "$2" in '') usage ;; esac
314 case "$2" in '') usage ;; esac
315 reference="--reference=$2"
339 if test -z "$sm_path"; then
340 sm_path=$(echo "$repo" |
341 sed -e 's|/$||' -e 's|:*/*\.git$||' -e 's|.*[/:]||g')
344 if test -z "$repo" -o -z "$sm_path"; then
348 # assure repo is absolute or relative to parent
351 # dereference source url relative to parent's url
352 realrepo=$(resolve_relative_url "$repo") || exit
359 die "$(eval_gettext "repo URL: '\$repo' must be absolute or begin with ./|../")"
364 # multiple //; leading ./; /./; /../; trailing /
365 sm_path=$(printf '%s/\n' "$sm_path" |
375 git ls-files --error-unmatch "$sm_path" > /dev/null 2>&1 &&
376 die "$(eval_gettext "'\$sm_path' already exists in the index")"
378 if test -z "$force" && ! git add --dry-run --ignore-missing "$sm_path" > /dev/null 2>&1
380 eval_gettextln "The following path is ignored by one of your .gitignore files:
382 Use -f if you really want to add it." >&2
386 # perhaps the path exists and is already a git repo, else clone it
387 if test -e "$sm_path"
389 if test -d "$sm_path"/.git -o -f "$sm_path"/.git
391 eval_gettextln "Adding existing repo at '\$sm_path' to the index"
393 die "$(eval_gettext "'\$sm_path' already exists and is not a valid git repo")"
398 module_clone "$sm_path" "$realrepo" "$reference" || exit
402 # ash fails to wordsplit ${branch:+-b "$branch"...}
404 '') git checkout -f -q ;;
405 ?*) git checkout -f -q -B "$branch" "origin/$branch" ;;
407 ) || die "$(eval_gettext "Unable to checkout submodule '\$sm_path'")"
409 git config submodule."$sm_path".url "$realrepo"
411 git add $force "$sm_path" ||
412 die "$(eval_gettext "Failed to add submodule '\$sm_path'")"
414 git config -f .gitmodules submodule."$sm_path".path "$sm_path" &&
415 git config -f .gitmodules submodule."$sm_path".url "$repo" &&
416 git add --force .gitmodules ||
417 die "$(eval_gettext "Failed to register submodule '\$sm_path'")"
421 # Execute an arbitrary command sequence in each checked out
424 # $@ = command to execute
428 # parse $args after "submodule ... foreach".
450 # dup stdin so that it can be restored when running the external
451 # command in the subshell (and a recursive call to this function)
455 while read mode sha1 stage sm_path
457 die_if_unmatched "$mode"
458 if test -e "$sm_path"/.git
460 say "$(eval_gettext "Entering '\$prefix\$sm_path'")"
461 name=$(module_name "$sm_path")
463 prefix="$prefix$sm_path/"
465 # we make $path available to scripts ...
469 if test -n "$recursive"
471 cmd_foreach "--recursive" "$@"
474 die "$(eval_gettext "Stopping at '\$sm_path'; script returned non-zero status.")"
480 # Register submodules in .git/config
482 # $@ = requested paths (default to all)
486 # parse $args after "submodule ... init".
508 while read mode sha1 stage sm_path
510 die_if_unmatched "$mode"
511 name=$(module_name "$sm_path") || exit
513 # Copy url setting when it is not set yet
514 if test -z "$(git config "submodule.$name.url")"
516 url=$(git config -f .gitmodules submodule."$name".url)
518 die "$(eval_gettext "No url found for submodule path '\$sm_path' in .gitmodules")"
520 # Possibly a url relative to parent
523 url=$(resolve_relative_url "$url") || exit
526 git config submodule."$name".url "$url" ||
527 die "$(eval_gettext "Failed to register url for submodule path '\$sm_path'")"
529 say "$(eval_gettext "Submodule '\$name' (\$url) registered for path '\$sm_path'")"
532 # Copy "update" setting when it is not set yet
533 upd="$(git config -f .gitmodules submodule."$name".update)"
535 test -n "$(git config submodule."$name".update)" ||
536 git config submodule."$name".update "$upd" ||
537 die "$(eval_gettext "Failed to register update mode for submodule path '\$sm_path'")"
542 # Update each submodule path to correct revision, using clone and checkout as needed
544 # $@ = requested paths (default to all)
548 # parse $args after "submodule ... update".
572 case "$2" in '') usage ;; esac
573 reference="--reference=$2"
574 orig_flags="$orig_flags $(git rev-parse --sq-quote "$1")"
600 orig_flags="$orig_flags $(git rev-parse --sq-quote "$1")"
606 cmd_init "--" "$@" || return
613 while read mode sha1 stage sm_path
615 die_if_unmatched "$mode"
618 echo >&2 "Skipping unmerged submodule $sm_path"
621 name=$(module_name "$sm_path") || exit
622 url=$(git config submodule."$name".url)
623 if ! test -z "$update"
625 update_module=$update
627 update_module=$(git config submodule."$name".update)
630 if test "$update_module" = "none"
632 echo "Skipping submodule '$sm_path'"
638 # Only mention uninitialized submodules when its
639 # path have been specified
641 say "$(eval_gettext "Submodule path '\$sm_path' not initialized
642 Maybe you want to use 'update --init'?")"
646 if ! test -d "$sm_path"/.git -o -f "$sm_path"/.git
648 module_clone "$sm_path" "$url" "$reference"|| exit
649 cloned_modules="$cloned_modules;$name"
652 subsha1=$(clear_local_git_env; cd "$sm_path" &&
653 git rev-parse --verify HEAD) ||
654 die "$(eval_gettext "Unable to find current revision in submodule path '\$sm_path'")"
657 if test "$subsha1" != "$sha1" -o -n "$force"
660 # If we don't already have a -f flag and the submodule has never been checked out
661 if test -z "$subsha1" -a -z "$force"
666 if test -z "$nofetch"
668 # Run fetch only if $sha1 isn't present or it
669 # is not reachable from a ref.
670 (clear_local_git_env; cd "$sm_path" &&
671 ( (rev=$(git rev-list -n 1 $sha1 --not --all 2>/dev/null) &&
672 test -z "$rev") || git-fetch)) ||
673 die "$(eval_gettext "Unable to fetch in submodule path '\$sm_path'")"
676 # Is this something we just cloned?
677 case ";$cloned_modules;" in
679 # then there is no local change to integrate
684 case "$update_module" in
687 die_msg="$(eval_gettext "Unable to rebase '\$sha1' in submodule path '\$sm_path'")"
688 say_msg="$(eval_gettext "Submodule path '\$sm_path': rebased into '\$sha1'")"
689 must_die_on_failure=yes
693 die_msg="$(eval_gettext "Unable to merge '\$sha1' in submodule path '\$sm_path'")"
694 say_msg="$(eval_gettext "Submodule path '\$sm_path': merged in '\$sha1'")"
695 must_die_on_failure=yes
698 command="git checkout $subforce -q"
699 die_msg="$(eval_gettext "Unable to checkout '\$sha1' in submodule path '\$sm_path'")"
700 say_msg="$(eval_gettext "Submodule path '\$sm_path': checked out '\$sha1'")"
704 if (clear_local_git_env; cd "$sm_path" && $command "$sha1")
707 elif test -n "$must_die_on_failure"
709 die_with_status 2 "$die_msg"
711 err="${err};$die_msg"
715 subsha1=$(clear_local_git_env; cd "$sm_path" &&
716 git rev-parse --verify HEAD) ||
717 die "$(eval_gettext "Unable to find new revision in submodule path '\$sm_path'")"
719 if test "$subsha1" != "$sha1"
721 changed_modules=$(printf '%s%s\n' "$changed_modules" "$name;$sm_path;$sha1;$subsha1")
725 if test -n "$recursive"
727 (clear_local_git_env; cd "$sm_path" && eval cmd_update "$orig_flags")
731 die_msg="$(eval_gettext "Failed to recurse into submodule path '\$sm_path'")"
734 err="${err};$die_msg"
737 die_with_status $res "$die_msg"
743 if test -z "$err" -a -n "$commit" -a -n "$changed_modules"
745 commit_changes "$changed_modules"
769 git describe "$2" 2>/dev/null ||
770 git describe --tags "$2" 2>/dev/null ||
771 git describe --contains "$2" 2>/dev/null ||
772 git describe --all --always "$2"
775 test -z "$revname" || revname=" ($revname)"
778 # Show commit summary for submodules in index or working tree
780 # If '--cached' is given, show summary between index and given commit,
781 # or between working tree and given commit
783 # $@ = [commit (default 'HEAD'),] requested paths (default all)
790 # parse $args after "submodule ... summary".
804 if summary_limit=$(($2 + 0)) 2>/dev/null && test "$summary_limit" = "$2"
826 test $summary_limit = 0 && return
828 if rev=$(git rev-parse -q --verify --default HEAD ${1+"$1"})
832 elif test -z "$1" -o "$1" = "HEAD"
834 # before the first commit: compare with an empty tree
835 head=$(git hash-object -w -t tree --stdin </dev/null)
836 test -z "$1" || shift
844 die "$(gettext "The --cached option cannot be used with the --files option")"
850 # Get modified modules cared by user
851 modules=$(git $diff_cmd $cached --ignore-submodules=dirty --raw $head -- "$@" |
852 sane_egrep '^:([0-7]* )?160000' |
853 while read mod_src mod_dst sha1_src sha1_dst status name
855 # Always show modules deleted or type-changed (blob<->module)
856 test $status = D -o $status = T && echo "$name" && continue
857 # Also show added or modified modules which are checked out
858 GIT_DIR="$name/.git" git-rev-parse --git-dir >/dev/null 2>&1 &&
863 test -z "$modules" && return
865 git $diff_cmd $cached --ignore-submodules=dirty --raw $head -- $modules |
866 sane_egrep '^:([0-7]* )?160000' |
868 while read mod_src mod_dst sha1_src sha1_dst status name
870 if test -z "$cached" &&
871 test $sha1_dst = 0000000000000000000000000000000000000000
875 sha1_dst=$(GIT_DIR="$name/.git" git rev-parse HEAD)
877 100644 | 100755 | 120000)
878 sha1_dst=$(git hash-object $name)
884 eval_gettextln "unexpected mode \$mod_dst" >&2
891 test $mod_src = 160000 &&
892 ! GIT_DIR="$name/.git" git-rev-parse -q --verify $sha1_src^0 >/dev/null &&
895 test $mod_dst = 160000 &&
896 ! GIT_DIR="$name/.git" git-rev-parse -q --verify $sha1_dst^0 >/dev/null &&
900 case "$missing_src,$missing_dst" in
902 errmsg="$(eval_gettext " Warn: \$name doesn't contain commit \$sha1_src")"
905 errmsg="$(eval_gettext " Warn: \$name doesn't contain commit \$sha1_dst")"
908 errmsg="$(eval_gettext " Warn: \$name doesn't contain commits \$sha1_src and \$sha1_dst")"
913 if test $mod_src = 160000 -a $mod_dst = 160000
915 range="$sha1_src...$sha1_dst"
916 elif test $mod_src = 160000
922 GIT_DIR="$name/.git" \
923 git rev-list --first-parent $range -- | wc -l
925 total_commits=" ($(($total_commits + 0)))"
929 sha1_abbr_src=$(echo $sha1_src | cut -c1-7)
930 sha1_abbr_dst=$(echo $sha1_dst | cut -c1-7)
933 blob="$(gettext "blob")"
934 submodule="$(gettext "submodule")"
935 if test $mod_dst = 160000
937 echo "* $name $sha1_abbr_src($blob)->$sha1_abbr_dst($submodule)$total_commits:"
939 echo "* $name $sha1_abbr_src($submodule)->$sha1_abbr_dst($blob)$total_commits:"
942 echo "* $name $sha1_abbr_src...$sha1_abbr_dst$total_commits:"
946 # Don't give error msg for modification whose dst is not submodule
947 # i.e. deleted or changed to blob
948 test $mod_dst = 160000 && echo "$errmsg"
950 if test $mod_src = 160000 -a $mod_dst = 160000
953 test $summary_limit -gt 0 && limit="-$summary_limit"
954 GIT_DIR="$name/.git" \
955 git log $limit --pretty='format: %m %s' \
956 --first-parent $sha1_src...$sha1_dst
957 elif test $mod_dst = 160000
959 GIT_DIR="$name/.git" \
960 git log --pretty='format: > %s' -1 $sha1_dst
962 GIT_DIR="$name/.git" \
963 git log --pretty='format: < %s' -1 $sha1_src
969 if test -n "$for_status"; then
970 if [ -n "$files" ]; then
971 gettextln "# Submodules changed but not updated:"
973 gettextln "# Submodule changes to be committed:"
976 sed -e 's|^|# |' -e 's|^# $|#|'
982 # List all submodules, prefixed with:
983 # - submodule not initialized
984 # + different revision checked out
986 # If --cached was specified the revision in the index will be printed
987 # instead of the currently checked out revision.
989 # $@ = requested paths (default to all)
993 # parse $args after "submodule ... status".
1018 orig_flags="$orig_flags $(git rev-parse --sq-quote "$1")"
1023 while read mode sha1 stage sm_path
1025 die_if_unmatched "$mode"
1026 name=$(module_name "$sm_path") || exit
1027 url=$(git config submodule."$name".url)
1028 displaypath="$prefix$sm_path"
1029 if test "$stage" = U
1031 say "U$sha1 $displaypath"
1034 if test -z "$url" || ! test -d "$sm_path"/.git -o -f "$sm_path"/.git
1036 say "-$sha1 $displaypath"
1039 set_name_rev "$sm_path" "$sha1"
1040 if git diff-files --ignore-submodules=dirty --quiet -- "$sm_path"
1042 say " $sha1 $displaypath$revname"
1044 if test -z "$cached"
1046 sha1=$(clear_local_git_env; cd "$sm_path" && git rev-parse --verify HEAD)
1047 set_name_rev "$sm_path" "$sha1"
1049 say "+$sha1 $displaypath$revname"
1052 if test -n "$recursive"
1055 prefix="$displaypath/"
1058 eval cmd_status "$orig_args"
1060 die "$(eval_gettext "Failed to recurse into submodule path '\$sm_path'")"
1065 # Sync remote urls for submodules
1066 # This makes the value for remote.$remote.url match the value
1067 # specified in .gitmodules.
1092 while read mode sha1 stage sm_path
1094 die_if_unmatched "$mode"
1095 name=$(module_name "$sm_path")
1096 url=$(git config -f .gitmodules --get submodule."$name".url)
1098 # Possibly a url relative to parent
1101 # rewrite foo/bar as ../.. to find path from
1102 # submodule work tree to superproject work tree
1103 up_path="$(echo "$sm_path" | sed "s/[^/][^/]*/../g")" &&
1104 # guarantee a trailing /
1105 up_path=${up_path%/}/ &&
1106 # path from submodule work tree to submodule origin repo
1107 sub_origin_url=$(resolve_relative_url "$url" "$up_path") &&
1108 # path from superproject work tree to submodule origin repo
1109 super_config_url=$(resolve_relative_url "$url") || exit
1112 sub_origin_url="$url"
1113 super_config_url="$url"
1117 if git config "submodule.$name.url" >/dev/null 2>/dev/null
1119 say "$(eval_gettext "Synchronizing submodule url for '\$name'")"
1120 git config submodule."$name".url "$super_config_url"
1122 if test -e "$sm_path"/.git
1127 remote=$(get_default_remote)
1128 git config remote."$remote".url "$sub_origin_url"
1135 # This loop parses the command line arguments to find the
1136 # subcommand name to dispatch. Parsing of the subcommand specific
1137 # options are primarily done by the subcommand implementations.
1138 # Subcommand specific options such as --branch and --cached are
1139 # parsed here as well, for backward compatibility.
1141 while test $# != 0 && test -z "$command"
1144 add | foreach | init | update | status | summary | sync)
1174 # No command word defaults to "status"
1175 if test -z "$command"
1185 # "-b branch" is accepted only by "add"
1186 if test -n "$branch" && test "$command" != add
1191 # "--cached" is accepted only by "status" and "summary"
1192 if test -n "$cached" && test "$command" != status -a "$command" != summary