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] [--local-branch[=<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] [--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>...]"
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 # Map submodule path to submodule name
163 # Do we have "submodule.<something>.path = $1" defined in .gitmodules file?
165 re=$(printf '%s\n' "$1" | sed -e 's/[].[^$\\*]/\\&/g')
166 name=$( git config -f .gitmodules --get-regexp '^submodule\..*\.path$' |
167 sed -n -e 's|^submodule\.\(.*\)\.path '"$re"'$|\1|p' )
169 die "$(eval_gettext "No submodule mapping found in .gitmodules for path '\$sm_path'")"
176 # Prior to calling, cmd_update checks that a possibly existing
177 # path is not a git repository.
178 # Likewise, cmd_add checks that path does not exist at all,
179 # since it is the location of a new submodule.
187 if test -n "$GIT_QUIET"
194 name=$(module_name "$sm_path" 2>/dev/null)
195 test -n "$name" || name="$sm_path"
196 base_name=$(dirname "$name")
198 gitdir=$(git rev-parse --git-dir)
199 gitdir_base="$gitdir/modules/$base_name"
200 gitdir="$gitdir/modules/$name"
205 rm -f "$gitdir/index"
207 mkdir -p "$gitdir_base"
210 git clone $quiet -n ${reference:+"$reference"} \
211 --separate-git-dir "$gitdir" "$url" "$sm_path"
213 die "$(eval_gettext "Clone of '\$url' into submodule path '\$sm_path' failed")"
216 # We already are at the root of the work tree but cd_to_toplevel will
217 # resolve any symlinks that might be present in $PWD
218 a=$(cd_to_toplevel && cd "$gitdir" && pwd)/
219 b=$(cd_to_toplevel && cd "$sm_path" && pwd)/
220 # normalize Windows-style absolute paths to POSIX-style absolute paths
221 case $a in [a-zA-Z]:/*) a=/${a%%:*}${a#*:} ;; esac
222 case $b in [a-zA-Z]:/*) b=/${b%%:*}${b#*:} ;; esac
223 # Remove all common leading directories after a sanity check
224 if test "${a#$b}" != "$a" || test "${b#$a}" != "$b"; then
225 die "$(eval_gettext "Gitdir '\$a' is part of the submodule path '\$b' or vice versa")"
227 while test "${a%%/*}" = "${b%%/*}"
232 # Now chop off the trailing '/'s that were added in the beginning
236 # Turn each leading "*/" component into "../"
237 rel=$(echo $b | sed -e 's|[^/][^/]*|..|g')
238 echo "gitdir: $rel/$a" >"$sm_path/.git"
240 rel=$(echo $a | sed -e 's|[^/][^/]*|..|g')
241 (clear_local_git_env; cd "$sm_path" && GIT_WORK_TREE=. git config core.worktree "$rel/$b")
245 # Add a new submodule to the working tree, .gitmodules and the index
249 # optional branch is stored in global branch variable
253 # parse $args after "submodule ... add".
258 case "$2" in '') usage ;; esac
263 local_branch_empty=true
266 local_branch="${1#*=}"
275 case "$2" in '') usage ;; esac
276 reference="--reference=$2"
300 if test -z "$sm_path"; then
301 sm_path=$(echo "$repo" |
302 sed -e 's|/$||' -e 's|:*/*\.git$||' -e 's|.*[/:]||g')
305 if test -z "$repo" -o -z "$sm_path"; then
309 # assure repo is absolute or relative to parent
312 # dereference source url relative to parent's url
313 realrepo=$(resolve_relative_url "$repo") || exit
320 die "$(eval_gettext "repo URL: '\$repo' must be absolute or begin with ./|../")"
325 # multiple //; leading ./; /./; /../; trailing /
326 sm_path=$(printf '%s/\n' "$sm_path" |
336 git ls-files --error-unmatch "$sm_path" > /dev/null 2>&1 &&
337 die "$(eval_gettext "'\$sm_path' already exists in the index")"
339 if test -z "$local_branch" && test "$local_branch_empty" = "true"
341 local_branch="${branch:=HEAD}"
344 if test -z "$force" && ! git add --dry-run --ignore-missing "$sm_path" > /dev/null 2>&1
346 eval_gettextln "The following path is ignored by one of your .gitignore files:
348 Use -f if you really want to add it." >&2
352 # perhaps the path exists and is already a git repo, else clone it
353 if test -e "$sm_path"
355 if test -d "$sm_path"/.git -o -f "$sm_path"/.git
357 eval_gettextln "Adding existing repo at '\$sm_path' to the index"
359 die "$(eval_gettext "'\$sm_path' already exists and is not a valid git repo")"
364 module_clone "$sm_path" "$realrepo" "$reference" || exit
368 # ash fails to wordsplit ${branch:+-b "$branch"...}
370 '') git checkout -f -q ;;
371 ?*) git checkout -f -q -B "$branch" "origin/$branch" ;;
373 ) || die "$(eval_gettext "Unable to checkout submodule '\$sm_path'")"
375 git config submodule."$sm_path".url "$realrepo"
377 git add $force "$sm_path" ||
378 die "$(eval_gettext "Failed to add submodule '\$sm_path'")"
380 git config -f .gitmodules submodule."$sm_path".path "$sm_path" &&
381 git config -f .gitmodules submodule."$sm_path".url "$repo" &&
382 if test -n "$local_branch"
384 git config -f .gitmodules submodule."$sm_path".branch "$local_branch"
386 git add --force .gitmodules ||
387 die "$(eval_gettext "Failed to register submodule '\$sm_path'")"
391 # Execute an arbitrary command sequence in each checked out
394 # $@ = command to execute
398 # parse $args after "submodule ... foreach".
420 # dup stdin so that it can be restored when running the external
421 # command in the subshell (and a recursive call to this function)
425 while read mode sha1 stage sm_path
427 die_if_unmatched "$mode"
428 if test -e "$sm_path"/.git
430 say "$(eval_gettext "Entering '\$prefix\$sm_path'")"
431 name=$(module_name "$sm_path")
433 prefix="$prefix$sm_path/"
435 # we make $path available to scripts ...
439 if test -n "$recursive"
441 cmd_foreach "--recursive" "$@"
444 die "$(eval_gettext "Stopping at '\$sm_path'; script returned non-zero status.")"
450 # Register submodules in .git/config
452 # $@ = requested paths (default to all)
456 # parse $args after "submodule ... init".
478 while read mode sha1 stage sm_path
480 die_if_unmatched "$mode"
481 name=$(module_name "$sm_path") || exit
483 # Copy url setting when it is not set yet
484 if test -z "$(git config "submodule.$name.url")"
486 url=$(git config -f .gitmodules submodule."$name".url)
488 die "$(eval_gettext "No url found for submodule path '\$sm_path' in .gitmodules")"
490 # Possibly a url relative to parent
493 url=$(resolve_relative_url "$url") || exit
496 git config submodule."$name".url "$url" ||
497 die "$(eval_gettext "Failed to register url for submodule path '\$sm_path'")"
499 say "$(eval_gettext "Submodule '\$name' (\$url) registered for path '\$sm_path'")"
502 # Copy "update" setting when it is not set yet
503 upd="$(git config -f .gitmodules submodule."$name".update)"
505 test -n "$(git config submodule."$name".update)" ||
506 git config submodule."$name".update "$upd" ||
507 die "$(eval_gettext "Failed to register update mode for submodule path '\$sm_path'")"
512 # Update each submodule path to correct revision, using clone and checkout as needed
514 # $@ = requested paths (default to all)
518 # parse $args after "submodule ... update".
539 case "$2" in '') usage ;; esac
540 reference="--reference=$2"
541 orig_flags="$orig_flags $(git rev-parse --sq-quote "$1")"
567 orig_flags="$orig_flags $(git rev-parse --sq-quote "$1")"
573 cmd_init "--" "$@" || return
579 while read mode sha1 stage sm_path
581 die_if_unmatched "$mode"
584 echo >&2 "Skipping unmerged submodule $sm_path"
587 name=$(module_name "$sm_path") || exit
588 url=$(git config submodule."$name".url)
589 if ! test -z "$update"
591 update_module=$update
593 update_module=$(git config submodule."$name".update)
596 if test "$update_module" = "none"
598 echo "Skipping submodule '$sm_path'"
604 # Only mention uninitialized submodules when its
605 # path have been specified
607 say "$(eval_gettext "Submodule path '\$sm_path' not initialized
608 Maybe you want to use 'update --init'?")"
612 if ! test -d "$sm_path"/.git -o -f "$sm_path"/.git
614 module_clone "$sm_path" "$url" "$reference"|| exit
615 cloned_modules="$cloned_modules;$name"
618 subsha1=$(clear_local_git_env; cd "$sm_path" &&
619 git rev-parse --verify HEAD) ||
620 die "$(eval_gettext "Unable to find current revision in submodule path '\$sm_path'")"
623 if test "$subsha1" != "$sha1" -o -n "$force"
626 # If we don't already have a -f flag and the submodule has never been checked out
627 if test -z "$subsha1" -a -z "$force"
632 if test -z "$nofetch"
634 # Run fetch only if $sha1 isn't present or it
635 # is not reachable from a ref.
636 (clear_local_git_env; cd "$sm_path" &&
637 ( (rev=$(git rev-list -n 1 $sha1 --not --all 2>/dev/null) &&
638 test -z "$rev") || git-fetch)) ||
639 die "$(eval_gettext "Unable to fetch in submodule path '\$sm_path'")"
642 # Is this something we just cloned?
643 case ";$cloned_modules;" in
645 # then there is no local change to integrate
650 case "$update_module" in
653 die_msg="$(eval_gettext "Unable to rebase '\$sha1' in submodule path '\$sm_path'")"
654 say_msg="$(eval_gettext "Submodule path '\$sm_path': rebased into '\$sha1'")"
655 must_die_on_failure=yes
659 die_msg="$(eval_gettext "Unable to merge '\$sha1' in submodule path '\$sm_path'")"
660 say_msg="$(eval_gettext "Submodule path '\$sm_path': merged in '\$sha1'")"
661 must_die_on_failure=yes
664 command="git checkout $subforce -q"
665 die_msg="$(eval_gettext "Unable to checkout '\$sha1' in submodule path '\$sm_path'")"
666 say_msg="$(eval_gettext "Submodule path '\$sm_path': checked out '\$sha1'")"
670 if (clear_local_git_env; cd "$sm_path" && $command "$sha1")
673 elif test -n "$must_die_on_failure"
675 die_with_status 2 "$die_msg"
677 err="${err};$die_msg"
682 if test -n "$recursive"
684 (clear_local_git_env; cd "$sm_path" && eval cmd_update "$orig_flags")
688 die_msg="$(eval_gettext "Failed to recurse into submodule path '\$sm_path'")"
691 err="${err};$die_msg"
694 die_with_status $res "$die_msg"
721 git describe "$2" 2>/dev/null ||
722 git describe --tags "$2" 2>/dev/null ||
723 git describe --contains "$2" 2>/dev/null ||
724 git describe --all --always "$2"
727 test -z "$revname" || revname=" ($revname)"
730 # Show commit summary for submodules in index or working tree
732 # If '--cached' is given, show summary between index and given commit,
733 # or between working tree and given commit
735 # $@ = [commit (default 'HEAD'),] requested paths (default all)
742 # parse $args after "submodule ... summary".
756 if summary_limit=$(($2 + 0)) 2>/dev/null && test "$summary_limit" = "$2"
778 test $summary_limit = 0 && return
780 if rev=$(git rev-parse -q --verify --default HEAD ${1+"$1"})
784 elif test -z "$1" -o "$1" = "HEAD"
786 # before the first commit: compare with an empty tree
787 head=$(git hash-object -w -t tree --stdin </dev/null)
788 test -z "$1" || shift
796 die "$(gettext "The --cached option cannot be used with the --files option")"
802 # Get modified modules cared by user
803 modules=$(git $diff_cmd $cached --ignore-submodules=dirty --raw $head -- "$@" |
804 sane_egrep '^:([0-7]* )?160000' |
805 while read mod_src mod_dst sha1_src sha1_dst status name
807 # Always show modules deleted or type-changed (blob<->module)
808 test $status = D -o $status = T && echo "$name" && continue
809 # Also show added or modified modules which are checked out
810 GIT_DIR="$name/.git" git-rev-parse --git-dir >/dev/null 2>&1 &&
815 test -z "$modules" && return
817 git $diff_cmd $cached --ignore-submodules=dirty --raw $head -- $modules |
818 sane_egrep '^:([0-7]* )?160000' |
820 while read mod_src mod_dst sha1_src sha1_dst status name
822 if test -z "$cached" &&
823 test $sha1_dst = 0000000000000000000000000000000000000000
827 sha1_dst=$(GIT_DIR="$name/.git" git rev-parse HEAD)
829 100644 | 100755 | 120000)
830 sha1_dst=$(git hash-object $name)
836 eval_gettextln "unexpected mode \$mod_dst" >&2
843 test $mod_src = 160000 &&
844 ! GIT_DIR="$name/.git" git-rev-parse -q --verify $sha1_src^0 >/dev/null &&
847 test $mod_dst = 160000 &&
848 ! GIT_DIR="$name/.git" git-rev-parse -q --verify $sha1_dst^0 >/dev/null &&
852 case "$missing_src,$missing_dst" in
854 errmsg="$(eval_gettext " Warn: \$name doesn't contain commit \$sha1_src")"
857 errmsg="$(eval_gettext " Warn: \$name doesn't contain commit \$sha1_dst")"
860 errmsg="$(eval_gettext " Warn: \$name doesn't contain commits \$sha1_src and \$sha1_dst")"
865 if test $mod_src = 160000 -a $mod_dst = 160000
867 range="$sha1_src...$sha1_dst"
868 elif test $mod_src = 160000
874 GIT_DIR="$name/.git" \
875 git rev-list --first-parent $range -- | wc -l
877 total_commits=" ($(($total_commits + 0)))"
881 sha1_abbr_src=$(echo $sha1_src | cut -c1-7)
882 sha1_abbr_dst=$(echo $sha1_dst | cut -c1-7)
885 blob="$(gettext "blob")"
886 submodule="$(gettext "submodule")"
887 if test $mod_dst = 160000
889 echo "* $name $sha1_abbr_src($blob)->$sha1_abbr_dst($submodule)$total_commits:"
891 echo "* $name $sha1_abbr_src($submodule)->$sha1_abbr_dst($blob)$total_commits:"
894 echo "* $name $sha1_abbr_src...$sha1_abbr_dst$total_commits:"
898 # Don't give error msg for modification whose dst is not submodule
899 # i.e. deleted or changed to blob
900 test $mod_dst = 160000 && echo "$errmsg"
902 if test $mod_src = 160000 -a $mod_dst = 160000
905 test $summary_limit -gt 0 && limit="-$summary_limit"
906 GIT_DIR="$name/.git" \
907 git log $limit --pretty='format: %m %s' \
908 --first-parent $sha1_src...$sha1_dst
909 elif test $mod_dst = 160000
911 GIT_DIR="$name/.git" \
912 git log --pretty='format: > %s' -1 $sha1_dst
914 GIT_DIR="$name/.git" \
915 git log --pretty='format: < %s' -1 $sha1_src
921 if test -n "$for_status"; then
922 if [ -n "$files" ]; then
923 gettextln "# Submodules changed but not updated:"
925 gettextln "# Submodule changes to be committed:"
928 sed -e 's|^|# |' -e 's|^# $|#|'
934 # List all submodules, prefixed with:
935 # - submodule not initialized
936 # + different revision checked out
938 # If --cached was specified the revision in the index will be printed
939 # instead of the currently checked out revision.
941 # $@ = requested paths (default to all)
945 # parse $args after "submodule ... status".
970 orig_flags="$orig_flags $(git rev-parse --sq-quote "$1")"
975 while read mode sha1 stage sm_path
977 die_if_unmatched "$mode"
978 name=$(module_name "$sm_path") || exit
979 url=$(git config submodule."$name".url)
980 displaypath="$prefix$sm_path"
983 say "U$sha1 $displaypath"
986 if test -z "$url" || ! test -d "$sm_path"/.git -o -f "$sm_path"/.git
988 say "-$sha1 $displaypath"
991 set_name_rev "$sm_path" "$sha1"
992 if git diff-files --ignore-submodules=dirty --quiet -- "$sm_path"
994 say " $sha1 $displaypath$revname"
998 sha1=$(clear_local_git_env; cd "$sm_path" && git rev-parse --verify HEAD)
999 set_name_rev "$sm_path" "$sha1"
1001 say "+$sha1 $displaypath$revname"
1004 if test -n "$recursive"
1007 prefix="$displaypath/"
1010 eval cmd_status "$orig_args"
1012 die "$(eval_gettext "Failed to recurse into submodule path '\$sm_path'")"
1017 # Sync remote urls for submodules
1018 # This makes the value for remote.$remote.url match the value
1019 # specified in .gitmodules.
1044 while read mode sha1 stage sm_path
1046 die_if_unmatched "$mode"
1047 name=$(module_name "$sm_path")
1048 url=$(git config -f .gitmodules --get submodule."$name".url)
1050 # Possibly a url relative to parent
1053 # rewrite foo/bar as ../.. to find path from
1054 # submodule work tree to superproject work tree
1055 up_path="$(echo "$sm_path" | sed "s/[^/][^/]*/../g")" &&
1056 # guarantee a trailing /
1057 up_path=${up_path%/}/ &&
1058 # path from submodule work tree to submodule origin repo
1059 sub_origin_url=$(resolve_relative_url "$url" "$up_path") &&
1060 # path from superproject work tree to submodule origin repo
1061 super_config_url=$(resolve_relative_url "$url") || exit
1064 sub_origin_url="$url"
1065 super_config_url="$url"
1069 if git config "submodule.$name.url" >/dev/null 2>/dev/null
1071 say "$(eval_gettext "Synchronizing submodule url for '\$name'")"
1072 git config submodule."$name".url "$super_config_url"
1074 if test -e "$sm_path"/.git
1079 remote=$(get_default_remote)
1080 git config remote."$remote".url "$sub_origin_url"
1087 # This loop parses the command line arguments to find the
1088 # subcommand name to dispatch. Parsing of the subcommand specific
1089 # options are primarily done by the subcommand implementations.
1090 # Subcommand specific options such as --branch and --cached are
1091 # parsed here as well, for backward compatibility.
1093 while test $# != 0 && test -z "$command"
1096 add | foreach | init | update | status | summary | sync)
1126 # No command word defaults to "status"
1127 if test -z "$command"
1137 # "-b branch" is accepted only by "add"
1138 if test -n "$branch" && test "$command" != add
1143 # "--cached" is accepted only by "status" and "summary"
1144 if test -n "$cached" && test "$command" != status -a "$command" != summary