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] [--remote] [-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>...]"
35 # The function takes at most 2 arguments. The first argument is the
36 # URL that navigates to the submodule origin repo. When relative, this URL
37 # is relative to the superproject origin URL repo. The second up_path
38 # argument, if specified, is the relative path that navigates
39 # from the submodule working tree to the superproject working tree.
41 # The output of the function is the origin URL of the submodule.
43 # The output will either be an absolute URL or filesystem path (if the
44 # superproject origin URL is an absolute URL or filesystem path,
45 # respectively) or a relative file system path (if the superproject
46 # origin URL is a relative file system path).
48 # When the output is a relative file system path, the path is either
49 # relative to the submodule working tree, if up_path is specified, or to
50 # the superproject working tree otherwise.
51 resolve_relative_url ()
53 remote=$(get_default_remote)
54 remoteurl=$(git config "remote.$remote.url") ||
55 remoteurl=$(pwd) # the repository is its own authoritative upstream
57 remoteurl=${remoteurl%/}
70 remoteurl="./$remoteurl"
81 remoteurl="${remoteurl%/*}"
84 remoteurl="${remoteurl%:*}"
88 if test -z "$is_relative" || test "." = "$remoteurl"
90 die "$(eval_gettext "cannot strip one component off url '\$remoteurl'")"
104 remoteurl="$remoteurl$sep${url%/}"
105 echo "${is_relative:+${up_path}}${remoteurl#./}"
109 # Get submodule info for registered submodules
110 # $@ = path to limit submodule list
115 git ls-files --error-unmatch --stage -- "$@" ||
116 echo "unmatched pathspec exists"
120 my ($null_sha1) = ("0" x 40);
124 if (/^unmatched pathspec/) {
129 my ($mode, $sha1, $stage, $path) =
130 /^([0-7]+) ([0-9a-f]{40}) ([0-3])\t(.*)$/;
131 next unless $mode eq "160000";
133 if (!$unmerged{$path}++) {
134 push @out, "$mode $null_sha1 U\t$path\n";
141 print "#unmatched\n";
150 if test "$1" = "#unmatched"
157 # Print a submodule configuration setting
159 # $1 = submodule name
163 # Checks in the usual git-config places first (for overrides),
164 # otherwise it falls back on .gitmodules. This allows you to
165 # distribute project-wide defaults in .gitmodules, while still
166 # customizing individual repositories if necessary. If the option is
167 # not in .gitmodules either, print a default value.
169 get_submodule_config () {
173 value=$(git config submodule."$name"."$option")
176 value=$(git config -f .gitmodules submodule."$name"."$option")
178 printf '%s' "${value:-$default}"
183 # Map submodule path to submodule name
189 # Do we have "submodule.<something>.path = $1" defined in .gitmodules file?
191 re=$(printf '%s\n' "$1" | sed -e 's/[].[^$\\*]/\\&/g')
192 name=$( git config -f .gitmodules --get-regexp '^submodule\..*\.path$' |
193 sed -n -e 's|^submodule\.\(.*\)\.path '"$re"'$|\1|p' )
195 die "$(eval_gettext "No submodule mapping found in .gitmodules for path '\$sm_path'")"
202 # Prior to calling, cmd_update checks that a possibly existing
203 # path is not a git repository.
204 # Likewise, cmd_add checks that path does not exist at all,
205 # since it is the location of a new submodule.
214 if test -n "$GIT_QUIET"
221 base_name=$(dirname "$name")
223 gitdir=$(git rev-parse --git-dir)
224 gitdir_base="$gitdir/modules/$base_name"
225 gitdir="$gitdir/modules/$name"
230 rm -f "$gitdir/index"
232 mkdir -p "$gitdir_base"
235 git clone $quiet -n ${reference:+"$reference"} \
236 --separate-git-dir "$gitdir" "$url" "$sm_path"
238 die "$(eval_gettext "Clone of '\$url' into submodule path '\$sm_path' failed")"
241 # We already are at the root of the work tree but cd_to_toplevel will
242 # resolve any symlinks that might be present in $PWD
243 a=$(cd_to_toplevel && cd "$gitdir" && pwd)/
244 b=$(cd_to_toplevel && cd "$sm_path" && pwd)/
245 # normalize Windows-style absolute paths to POSIX-style absolute paths
246 case $a in [a-zA-Z]:/*) a=/${a%%:*}${a#*:} ;; esac
247 case $b in [a-zA-Z]:/*) b=/${b%%:*}${b#*:} ;; esac
248 # Remove all common leading directories after a sanity check
249 if test "${a#$b}" != "$a" || test "${b#$a}" != "$b"; then
250 die "$(eval_gettext "Gitdir '\$a' is part of the submodule path '\$b' or vice versa")"
252 while test "${a%%/*}" = "${b%%/*}"
257 # Now chop off the trailing '/'s that were added in the beginning
261 # Turn each leading "*/" component into "../"
262 rel=$(echo $b | sed -e 's|[^/][^/]*|..|g')
263 echo "gitdir: $rel/$a" >"$sm_path/.git"
265 rel=$(echo $a | sed -e 's|[^/][^/]*|..|g')
266 (clear_local_git_env; cd "$sm_path" && GIT_WORK_TREE=. git config core.worktree "$rel/$b")
270 # Add a new submodule to the working tree, .gitmodules and the index
274 # optional branch is stored in global branch variable
278 # parse $args after "submodule ... add".
283 case "$2" in '') usage ;; esac
294 case "$2" in '') usage ;; esac
295 reference="--reference=$2"
302 case "$2" in '') usage ;; esac
323 if test -z "$sm_path"; then
324 sm_path=$(echo "$repo" |
325 sed -e 's|/$||' -e 's|:*/*\.git$||' -e 's|.*[/:]||g')
328 if test -z "$repo" -o -z "$sm_path"; then
332 # assure repo is absolute or relative to parent
335 # dereference source url relative to parent's url
336 realrepo=$(resolve_relative_url "$repo") || exit
343 die "$(eval_gettext "repo URL: '\$repo' must be absolute or begin with ./|../")"
348 # multiple //; leading ./; /./; /../; trailing /
349 sm_path=$(printf '%s/\n' "$sm_path" |
359 git ls-files --error-unmatch "$sm_path" > /dev/null 2>&1 &&
360 die "$(eval_gettext "'\$sm_path' already exists in the index")"
362 if test -z "$force" && ! git add --dry-run --ignore-missing "$sm_path" > /dev/null 2>&1
364 eval_gettextln "The following path is ignored by one of your .gitignore files:
366 Use -f if you really want to add it." >&2
370 if test -n "$custom_name"
372 sm_name="$custom_name"
377 # perhaps the path exists and is already a git repo, else clone it
378 if test -e "$sm_path"
380 if test -d "$sm_path"/.git -o -f "$sm_path"/.git
382 eval_gettextln "Adding existing repo at '\$sm_path' to the index"
384 die "$(eval_gettext "'\$sm_path' already exists and is not a valid git repo")"
388 if test -d ".git/modules/$sm_name"
392 echo >&2 "$(eval_gettext "A git directory for '\$sm_name' is found locally with remote(s):")"
393 GIT_DIR=".git/modules/$sm_name" GIT_WORK_TREE=. git remote -v | grep '(fetch)' | sed -e s,^," ", -e s,' (fetch)',, >&2
394 echo >&2 "$(eval_gettext "If you want to reuse this local git directory instead of cloning again from")"
395 echo >&2 " $realrepo"
396 echo >&2 "$(eval_gettext "use the '--force' option. If the local git directory is not the correct repo")"
397 die "$(eval_gettext "or you are unsure what this means choose another name with the '--name' option.")"
399 echo "$(eval_gettext "Reactivating local git directory for submodule '\$sm_name'.")"
402 module_clone "$sm_path" "$sm_name" "$realrepo" "$reference" || exit
406 # ash fails to wordsplit ${branch:+-b "$branch"...}
408 '') git checkout -f -q ;;
409 ?*) git checkout -f -q -B "$branch" "origin/$branch" ;;
411 ) || die "$(eval_gettext "Unable to checkout submodule '\$sm_path'")"
413 git config submodule."$sm_name".url "$realrepo"
415 git add $force "$sm_path" ||
416 die "$(eval_gettext "Failed to add submodule '\$sm_path'")"
418 git config -f .gitmodules submodule."$sm_name".path "$sm_path" &&
419 git config -f .gitmodules submodule."$sm_name".url "$repo" &&
420 git add --force .gitmodules ||
421 die "$(eval_gettext "Failed to register submodule '\$sm_path'")"
425 # Execute an arbitrary command sequence in each checked out
428 # $@ = command to execute
432 # parse $args after "submodule ... foreach".
454 # dup stdin so that it can be restored when running the external
455 # command in the subshell (and a recursive call to this function)
459 while read mode sha1 stage sm_path
461 die_if_unmatched "$mode"
462 if test -e "$sm_path"/.git
464 say "$(eval_gettext "Entering '\$prefix\$sm_path'")"
465 name=$(module_name "$sm_path")
467 prefix="$prefix$sm_path/"
469 # we make $path available to scripts ...
473 if test -n "$recursive"
475 cmd_foreach "--recursive" "$@"
478 die "$(eval_gettext "Stopping at '\$sm_path'; script returned non-zero status.")"
484 # Register submodules in .git/config
486 # $@ = requested paths (default to all)
490 # parse $args after "submodule ... init".
512 while read mode sha1 stage sm_path
514 die_if_unmatched "$mode"
515 name=$(module_name "$sm_path") || exit
517 # Copy url setting when it is not set yet
518 if test -z "$(git config "submodule.$name.url")"
520 url=$(git config -f .gitmodules submodule."$name".url)
522 die "$(eval_gettext "No url found for submodule path '\$sm_path' in .gitmodules")"
524 # Possibly a url relative to parent
527 url=$(resolve_relative_url "$url") || exit
530 git config submodule."$name".url "$url" ||
531 die "$(eval_gettext "Failed to register url for submodule path '\$sm_path'")"
533 say "$(eval_gettext "Submodule '\$name' (\$url) registered for path '\$sm_path'")"
536 # Copy "update" setting when it is not set yet
537 upd="$(git config -f .gitmodules submodule."$name".update)"
539 test -n "$(git config submodule."$name".update)" ||
540 git config submodule."$name".update "$upd" ||
541 die "$(eval_gettext "Failed to register update mode for submodule path '\$sm_path'")"
546 # Update each submodule path to correct revision, using clone and checkout as needed
548 # $@ = requested paths (default to all)
552 # parse $args after "submodule ... update".
576 case "$2" in '') usage ;; esac
577 reference="--reference=$2"
578 orig_flags="$orig_flags $(git rev-parse --sq-quote "$1")"
604 orig_flags="$orig_flags $(git rev-parse --sq-quote "$1")"
610 cmd_init "--" "$@" || return
616 while read mode sha1 stage sm_path
618 die_if_unmatched "$mode"
621 echo >&2 "Skipping unmerged submodule $sm_path"
624 name=$(module_name "$sm_path") || exit
625 url=$(git config submodule."$name".url)
626 branch=$(get_submodule_config "$name" branch master)
627 if ! test -z "$update"
629 update_module=$update
631 update_module=$(git config submodule."$name".update)
634 if test "$update_module" = "none"
636 echo "Skipping submodule '$sm_path'"
642 # Only mention uninitialized submodules when its
643 # path have been specified
645 say "$(eval_gettext "Submodule path '\$sm_path' not initialized
646 Maybe you want to use 'update --init'?")"
650 if ! test -d "$sm_path"/.git -o -f "$sm_path"/.git
652 module_clone "$sm_path" "$name" "$url" "$reference" || exit
653 cloned_modules="$cloned_modules;$name"
656 subsha1=$(clear_local_git_env; cd "$sm_path" &&
657 git rev-parse --verify HEAD) ||
658 die "$(eval_gettext "Unable to find current revision in submodule path '\$sm_path'")"
663 if test -z "$nofetch"
665 # Fetch remote before determining tracking $sha1
666 (clear_local_git_env; cd "$sm_path" && git-fetch) ||
667 die "$(eval_gettext "Unable to fetch in submodule path '\$sm_path'")"
669 remote_name=$(clear_local_git_env; cd "$sm_path" && get_default_remote)
670 sha1=$(clear_local_git_env; cd "$sm_path" &&
671 git rev-parse --verify "${remote_name}/${branch}") ||
672 die "$(eval_gettext "Unable to find current ${remote_name}/${branch} revision in submodule path '\$sm_path'")"
675 if test "$subsha1" != "$sha1" -o -n "$force"
678 # If we don't already have a -f flag and the submodule has never been checked out
679 if test -z "$subsha1" -a -z "$force"
684 if test -z "$nofetch"
686 # Run fetch only if $sha1 isn't present or it
687 # is not reachable from a ref.
688 (clear_local_git_env; cd "$sm_path" &&
689 ( (rev=$(git rev-list -n 1 $sha1 --not --all 2>/dev/null) &&
690 test -z "$rev") || git-fetch)) ||
691 die "$(eval_gettext "Unable to fetch in submodule path '\$sm_path'")"
694 # Is this something we just cloned?
695 case ";$cloned_modules;" in
697 # then there is no local change to integrate
702 case "$update_module" in
705 die_msg="$(eval_gettext "Unable to rebase '\$sha1' in submodule path '\$sm_path'")"
706 say_msg="$(eval_gettext "Submodule path '\$sm_path': rebased into '\$sha1'")"
707 must_die_on_failure=yes
711 die_msg="$(eval_gettext "Unable to merge '\$sha1' in submodule path '\$sm_path'")"
712 say_msg="$(eval_gettext "Submodule path '\$sm_path': merged in '\$sha1'")"
713 must_die_on_failure=yes
716 command="git checkout $subforce -q"
717 die_msg="$(eval_gettext "Unable to checkout '\$sha1' in submodule path '\$sm_path'")"
718 say_msg="$(eval_gettext "Submodule path '\$sm_path': checked out '\$sha1'")"
722 if (clear_local_git_env; cd "$sm_path" && $command "$sha1")
725 elif test -n "$must_die_on_failure"
727 die_with_status 2 "$die_msg"
729 err="${err};$die_msg"
734 if test -n "$recursive"
736 (clear_local_git_env; cd "$sm_path" && eval cmd_update "$orig_flags")
740 die_msg="$(eval_gettext "Failed to recurse into submodule path '\$sm_path'")"
743 err="${err};$die_msg"
746 die_with_status $res "$die_msg"
773 git describe "$2" 2>/dev/null ||
774 git describe --tags "$2" 2>/dev/null ||
775 git describe --contains "$2" 2>/dev/null ||
776 git describe --all --always "$2"
779 test -z "$revname" || revname=" ($revname)"
782 # Show commit summary for submodules in index or working tree
784 # If '--cached' is given, show summary between index and given commit,
785 # or between working tree and given commit
787 # $@ = [commit (default 'HEAD'),] requested paths (default all)
794 # parse $args after "submodule ... summary".
808 if summary_limit=$(($2 + 0)) 2>/dev/null && test "$summary_limit" = "$2"
830 test $summary_limit = 0 && return
832 if rev=$(git rev-parse -q --verify --default HEAD ${1+"$1"})
836 elif test -z "$1" -o "$1" = "HEAD"
838 # before the first commit: compare with an empty tree
839 head=$(git hash-object -w -t tree --stdin </dev/null)
840 test -z "$1" || shift
848 die "$(gettext "The --cached option cannot be used with the --files option")"
854 # Get modified modules cared by user
855 modules=$(git $diff_cmd $cached --ignore-submodules=dirty --raw $head -- "$@" |
856 sane_egrep '^:([0-7]* )?160000' |
857 while read mod_src mod_dst sha1_src sha1_dst status name
859 # Always show modules deleted or type-changed (blob<->module)
860 test $status = D -o $status = T && echo "$name" && continue
861 # Also show added or modified modules which are checked out
862 GIT_DIR="$name/.git" git-rev-parse --git-dir >/dev/null 2>&1 &&
867 test -z "$modules" && return
869 git $diff_cmd $cached --ignore-submodules=dirty --raw $head -- $modules |
870 sane_egrep '^:([0-7]* )?160000' |
872 while read mod_src mod_dst sha1_src sha1_dst status name
874 if test -z "$cached" &&
875 test $sha1_dst = 0000000000000000000000000000000000000000
879 sha1_dst=$(GIT_DIR="$name/.git" git rev-parse HEAD)
881 100644 | 100755 | 120000)
882 sha1_dst=$(git hash-object $name)
888 eval_gettextln "unexpected mode \$mod_dst" >&2
895 test $mod_src = 160000 &&
896 ! GIT_DIR="$name/.git" git-rev-parse -q --verify $sha1_src^0 >/dev/null &&
899 test $mod_dst = 160000 &&
900 ! GIT_DIR="$name/.git" git-rev-parse -q --verify $sha1_dst^0 >/dev/null &&
904 case "$missing_src,$missing_dst" in
906 errmsg="$(eval_gettext " Warn: \$name doesn't contain commit \$sha1_src")"
909 errmsg="$(eval_gettext " Warn: \$name doesn't contain commit \$sha1_dst")"
912 errmsg="$(eval_gettext " Warn: \$name doesn't contain commits \$sha1_src and \$sha1_dst")"
917 if test $mod_src = 160000 -a $mod_dst = 160000
919 range="$sha1_src...$sha1_dst"
920 elif test $mod_src = 160000
926 GIT_DIR="$name/.git" \
927 git rev-list --first-parent $range -- | wc -l
929 total_commits=" ($(($total_commits + 0)))"
933 sha1_abbr_src=$(echo $sha1_src | cut -c1-7)
934 sha1_abbr_dst=$(echo $sha1_dst | cut -c1-7)
937 blob="$(gettext "blob")"
938 submodule="$(gettext "submodule")"
939 if test $mod_dst = 160000
941 echo "* $name $sha1_abbr_src($blob)->$sha1_abbr_dst($submodule)$total_commits:"
943 echo "* $name $sha1_abbr_src($submodule)->$sha1_abbr_dst($blob)$total_commits:"
946 echo "* $name $sha1_abbr_src...$sha1_abbr_dst$total_commits:"
950 # Don't give error msg for modification whose dst is not submodule
951 # i.e. deleted or changed to blob
952 test $mod_dst = 160000 && echo "$errmsg"
954 if test $mod_src = 160000 -a $mod_dst = 160000
957 test $summary_limit -gt 0 && limit="-$summary_limit"
958 GIT_DIR="$name/.git" \
959 git log $limit --pretty='format: %m %s' \
960 --first-parent $sha1_src...$sha1_dst
961 elif test $mod_dst = 160000
963 GIT_DIR="$name/.git" \
964 git log --pretty='format: > %s' -1 $sha1_dst
966 GIT_DIR="$name/.git" \
967 git log --pretty='format: < %s' -1 $sha1_src
973 if test -n "$for_status"; then
974 if [ -n "$files" ]; then
975 gettextln "# Submodules changed but not updated:"
977 gettextln "# Submodule changes to be committed:"
980 sed -e 's|^|# |' -e 's|^# $|#|'
986 # List all submodules, prefixed with:
987 # - submodule not initialized
988 # + different revision checked out
990 # If --cached was specified the revision in the index will be printed
991 # instead of the currently checked out revision.
993 # $@ = requested paths (default to all)
997 # parse $args after "submodule ... status".
1025 while read mode sha1 stage sm_path
1027 die_if_unmatched "$mode"
1028 name=$(module_name "$sm_path") || exit
1029 url=$(git config submodule."$name".url)
1030 displaypath="$prefix$sm_path"
1031 if test "$stage" = U
1033 say "U$sha1 $displaypath"
1036 if test -z "$url" || ! test -d "$sm_path"/.git -o -f "$sm_path"/.git
1038 say "-$sha1 $displaypath"
1041 set_name_rev "$sm_path" "$sha1"
1042 if git diff-files --ignore-submodules=dirty --quiet -- "$sm_path"
1044 say " $sha1 $displaypath$revname"
1046 if test -z "$cached"
1048 sha1=$(clear_local_git_env; cd "$sm_path" && git rev-parse --verify HEAD)
1049 set_name_rev "$sm_path" "$sha1"
1051 say "+$sha1 $displaypath$revname"
1054 if test -n "$recursive"
1057 prefix="$displaypath/"
1062 die "$(eval_gettext "Failed to recurse into submodule path '\$sm_path'")"
1067 # Sync remote urls for submodules
1068 # This makes the value for remote.$remote.url match the value
1069 # specified in .gitmodules.
1098 while read mode sha1 stage sm_path
1100 die_if_unmatched "$mode"
1101 name=$(module_name "$sm_path")
1102 url=$(git config -f .gitmodules --get submodule."$name".url)
1104 # Possibly a url relative to parent
1107 # rewrite foo/bar as ../.. to find path from
1108 # submodule work tree to superproject work tree
1109 up_path="$(echo "$sm_path" | sed "s/[^/][^/]*/../g")" &&
1110 # guarantee a trailing /
1111 up_path=${up_path%/}/ &&
1112 # path from submodule work tree to submodule origin repo
1113 sub_origin_url=$(resolve_relative_url "$url" "$up_path") &&
1114 # path from superproject work tree to submodule origin repo
1115 super_config_url=$(resolve_relative_url "$url") || exit
1118 sub_origin_url="$url"
1119 super_config_url="$url"
1123 if git config "submodule.$name.url" >/dev/null 2>/dev/null
1125 say "$(eval_gettext "Synchronizing submodule url for '\$prefix\$sm_path'")"
1126 git config submodule."$name".url "$super_config_url"
1128 if test -e "$sm_path"/.git
1133 remote=$(get_default_remote)
1134 git config remote."$remote".url "$sub_origin_url"
1136 if test -n "$recursive"
1138 prefix="$prefix$sm_path/"
1147 # This loop parses the command line arguments to find the
1148 # subcommand name to dispatch. Parsing of the subcommand specific
1149 # options are primarily done by the subcommand implementations.
1150 # Subcommand specific options such as --branch and --cached are
1151 # parsed here as well, for backward compatibility.
1153 while test $# != 0 && test -z "$command"
1156 add | foreach | init | update | status | summary | sync)
1186 # No command word defaults to "status"
1187 if test -z "$command"
1197 # "-b branch" is accepted only by "add"
1198 if test -n "$branch" && test "$command" != add
1203 # "--cached" is accepted only by "status" and "summary"
1204 if test -n "$cached" && test "$command" != status -a "$command" != summary