3 # git-submodules.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] [--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>...]"
33 # The function takes at most 2 arguments. The first argument is the
34 # URL that navigates to the submodule origin repo. When relative, this URL
35 # is relative to the superproject origin URL repo. The second up_path
36 # argument, if specified, is the relative path that navigates
37 # from the submodule working tree to the superproject working tree.
39 # The output of the function is the origin URL of the submodule.
41 # The output will either be an absolute URL or filesystem path (if the
42 # superproject origin URL is an absolute URL or filesystem path,
43 # respectively) or a relative file system path (if the superproject
44 # origin URL is a relative file system path).
46 # When the output is a relative file system path, the path is either
47 # relative to the submodule working tree, if up_path is specified, or to
48 # the superproject working tree otherwise.
49 resolve_relative_url ()
51 remote=$(get_default_remote)
52 remoteurl=$(git config "remote.$remote.url") ||
53 remoteurl=$(pwd) # the repository is its own authoritative upstream
55 remoteurl=${remoteurl%/}
75 remoteurl="${remoteurl%/*}"
78 remoteurl="${remoteurl%:*}"
82 die "$(eval_gettext "cannot strip one component off url '\$remoteurl'")"
93 echo "${is_relative:+${up_path}}$remoteurl$sep${url%/}"
97 # Get submodule info for registered submodules
98 # $@ = path to limit submodule list
102 git ls-files --error-unmatch --stage -- "$@" |
105 my ($null_sha1) = ("0" x 40);
108 my ($mode, $sha1, $stage, $path) =
109 /^([0-7]+) ([0-9a-f]{40}) ([0-3])\t(.*)$/;
110 next unless $mode eq "160000";
112 if (!$unmerged{$path}++) {
113 print "$mode $null_sha1 U\t$path\n";
123 # Map submodule path to submodule name
129 # Do we have "submodule.<something>.path = $1" defined in .gitmodules file?
131 re=$(printf '%s\n' "$1" | sed -e 's/[].[^$\\*]/\\&/g')
132 name=$( git config -f .gitmodules --get-regexp '^submodule\..*\.path$' |
133 sed -n -e 's|^submodule\.\(.*\)\.path '"$re"'$|\1|p' )
135 die "$(eval_gettext "No submodule mapping found in .gitmodules for path '\$sm_path'")"
142 # Prior to calling, cmd_update checks that a possibly existing
143 # path is not a git repository.
144 # Likewise, cmd_add checks that path does not exist at all,
145 # since it is the location of a new submodule.
153 if test -n "$GIT_QUIET"
160 name=$(module_name "$sm_path" 2>/dev/null)
161 test -n "$name" || name="$sm_path"
162 base_name=$(dirname "$name")
164 gitdir=$(git rev-parse --git-dir)
165 gitdir_base="$gitdir/modules/$base_name"
166 gitdir="$gitdir/modules/$name"
171 rm -f "$gitdir/index"
173 mkdir -p "$gitdir_base"
174 git clone $quiet -n ${reference:+"$reference"} \
175 --separate-git-dir "$gitdir" "$url" "$sm_path" ||
176 die "$(eval_gettext "Clone of '\$url' into submodule path '\$sm_path' failed")"
179 a=$(cd "$gitdir" && pwd)/
180 b=$(cd "$sm_path" && pwd)/
181 # normalize Windows-style absolute paths to POSIX-style absolute paths
182 case $a in [a-zA-Z]:/*) a=/${a%%:*}${a#*:} ;; esac
183 case $b in [a-zA-Z]:/*) b=/${b%%:*}${b#*:} ;; esac
184 # Remove all common leading directories after a sanity check
185 if test "${a#$b}" != "$a" || test "${b#$a}" != "$b"; then
186 die "$(eval_gettext "Gitdir '\$a' is part of the submodule path '\$b' or vice versa")"
188 while test "${a%%/*}" = "${b%%/*}"
193 # Now chop off the trailing '/'s that were added in the beginning
197 # Turn each leading "*/" component into "../"
198 rel=$(echo $b | sed -e 's|[^/][^/]*|..|g')
199 echo "gitdir: $rel/$a" >"$sm_path/.git"
201 rel=$(echo $a | sed -e 's|[^/][^/]*|..|g')
202 (clear_local_git_env; cd "$sm_path" && GIT_WORK_TREE=. git config core.worktree "$rel/$b")
206 # Add a new submodule to the working tree, .gitmodules and the index
210 # optional branch is stored in global branch variable
214 # parse $args after "submodule ... add".
219 case "$2" in '') usage ;; esac
230 case "$2" in '') usage ;; esac
231 reference="--reference=$2"
255 if test -z "$sm_path"; then
256 sm_path=$(echo "$repo" |
257 sed -e 's|/$||' -e 's|:*/*\.git$||' -e 's|.*[/:]||g')
260 if test -z "$repo" -o -z "$sm_path"; then
264 # assure repo is absolute or relative to parent
267 # dereference source url relative to parent's url
268 realrepo=$(resolve_relative_url "$repo") || exit
275 die "$(eval_gettext "repo URL: '\$repo' must be absolute or begin with ./|../")"
280 # multiple //; leading ./; /./; /../; trailing /
281 sm_path=$(printf '%s/\n' "$sm_path" |
291 git ls-files --error-unmatch "$sm_path" > /dev/null 2>&1 &&
292 die "$(eval_gettext "'\$sm_path' already exists in the index")"
294 if test -z "$force" && ! git add --dry-run --ignore-missing "$sm_path" > /dev/null 2>&1
296 eval_gettextln "The following path is ignored by one of your .gitignore files:
298 Use -f if you really want to add it." >&2
302 # perhaps the path exists and is already a git repo, else clone it
303 if test -e "$sm_path"
305 if test -d "$sm_path"/.git -o -f "$sm_path"/.git
307 eval_gettextln "Adding existing repo at '\$sm_path' to the index"
309 die "$(eval_gettext "'\$sm_path' already exists and is not a valid git repo")"
314 module_clone "$sm_path" "$realrepo" "$reference" || exit
318 # ash fails to wordsplit ${branch:+-b "$branch"...}
320 '') git checkout -f -q ;;
321 ?*) git checkout -f -q -B "$branch" "origin/$branch" ;;
323 ) || die "$(eval_gettext "Unable to checkout submodule '\$sm_path'")"
325 git config submodule."$sm_path".url "$realrepo"
327 git add $force "$sm_path" ||
328 die "$(eval_gettext "Failed to add submodule '\$sm_path'")"
330 git config -f .gitmodules submodule."$sm_path".path "$sm_path" &&
331 git config -f .gitmodules submodule."$sm_path".url "$repo" &&
332 git add --force .gitmodules ||
333 die "$(eval_gettext "Failed to register submodule '\$sm_path'")"
337 # Execute an arbitrary command sequence in each checked out
340 # $@ = command to execute
344 # parse $args after "submodule ... foreach".
366 # dup stdin so that it can be restored when running the external
367 # command in the subshell (and a recursive call to this function)
371 while read mode sha1 stage sm_path
373 if test -e "$sm_path"/.git
375 say "$(eval_gettext "Entering '\$prefix\$sm_path'")"
376 name=$(module_name "$sm_path")
378 prefix="$prefix$sm_path/"
380 # we make $path available to scripts ...
384 if test -n "$recursive"
386 cmd_foreach "--recursive" "$@"
389 die "$(eval_gettext "Stopping at '\$sm_path'; script returned non-zero status.")"
395 # Register submodules in .git/config
397 # $@ = requested paths (default to all)
401 # parse $args after "submodule ... init".
423 while read mode sha1 stage sm_path
425 # Skip already registered paths
426 name=$(module_name "$sm_path") || exit
427 if test -z "$(git config "submodule.$name.url")"
429 url=$(git config -f .gitmodules submodule."$name".url)
431 die "$(eval_gettext "No url found for submodule path '\$sm_path' in .gitmodules")"
433 # Possibly a url relative to parent
436 url=$(resolve_relative_url "$url") || exit
439 git config submodule."$name".url "$url" ||
440 die "$(eval_gettext "Failed to register url for submodule path '\$sm_path'")"
443 # Copy "update" setting when it is not set yet
444 upd="$(git config -f .gitmodules submodule."$name".update)"
446 test -n "$(git config submodule."$name".update)" ||
447 git config submodule."$name".update "$upd" ||
448 die "$(eval_gettext "Failed to register update mode for submodule path '\$sm_path'")"
450 say "$(eval_gettext "Submodule '\$name' (\$url) registered for path '\$sm_path'")"
455 # Update each submodule path to correct revision, using clone and checkout as needed
457 # $@ = requested paths (default to all)
461 # parse $args after "submodule ... update".
482 case "$2" in '') usage ;; esac
483 reference="--reference=$2"
484 orig_flags="$orig_flags $(git rev-parse --sq-quote "$1")"
510 orig_flags="$orig_flags $(git rev-parse --sq-quote "$1")"
516 cmd_init "--" "$@" || return
522 while read mode sha1 stage sm_path
526 echo >&2 "Skipping unmerged submodule $sm_path"
529 name=$(module_name "$sm_path") || exit
530 url=$(git config submodule."$name".url)
531 if ! test -z "$update"
533 update_module=$update
535 update_module=$(git config submodule."$name".update)
538 if test "$update_module" = "none"
540 echo "Skipping submodule '$sm_path'"
546 # Only mention uninitialized submodules when its
547 # path have been specified
549 say "$(eval_gettext "Submodule path '\$sm_path' not initialized
550 Maybe you want to use 'update --init'?")"
554 if ! test -d "$sm_path"/.git -o -f "$sm_path"/.git
556 module_clone "$sm_path" "$url" "$reference"|| exit
557 cloned_modules="$cloned_modules;$name"
560 subsha1=$(clear_local_git_env; cd "$sm_path" &&
561 git rev-parse --verify HEAD) ||
562 die "$(eval_gettext "Unable to find current revision in submodule path '\$sm_path'")"
565 if test "$subsha1" != "$sha1"
568 # If we don't already have a -f flag and the submodule has never been checked out
569 if test -z "$subsha1" -a -z "$force"
574 if test -z "$nofetch"
576 # Run fetch only if $sha1 isn't present or it
577 # is not reachable from a ref.
578 (clear_local_git_env; cd "$sm_path" &&
579 ( (rev=$(git rev-list -n 1 $sha1 --not --all 2>/dev/null) &&
580 test -z "$rev") || git-fetch)) ||
581 die "$(eval_gettext "Unable to fetch in submodule path '\$sm_path'")"
584 # Is this something we just cloned?
585 case ";$cloned_modules;" in
587 # then there is no local change to integrate
592 case "$update_module" in
595 die_msg="$(eval_gettext "Unable to rebase '\$sha1' in submodule path '\$sm_path'")"
596 say_msg="$(eval_gettext "Submodule path '\$sm_path': rebased into '\$sha1'")"
597 must_die_on_failure=yes
601 die_msg="$(eval_gettext "Unable to merge '\$sha1' in submodule path '\$sm_path'")"
602 say_msg="$(eval_gettext "Submodule path '\$sm_path': merged in '\$sha1'")"
603 must_die_on_failure=yes
606 command="git checkout $subforce -q"
607 die_msg="$(eval_gettext "Unable to checkout '\$sha1' in submodule path '\$sm_path'")"
608 say_msg="$(eval_gettext "Submodule path '\$sm_path': checked out '\$sha1'")"
612 if (clear_local_git_env; cd "$sm_path" && $command "$sha1")
615 elif test -n "$must_die_on_failure"
617 die_with_status 2 "$die_msg"
619 err="${err};$die_msg"
624 if test -n "$recursive"
626 (clear_local_git_env; cd "$sm_path" && eval cmd_update "$orig_flags")
630 die_msg="$(eval_gettext "Failed to recurse into submodule path '\$sm_path'")"
633 err="${err};$die_msg"
636 die_with_status $res "$die_msg"
663 git describe "$2" 2>/dev/null ||
664 git describe --tags "$2" 2>/dev/null ||
665 git describe --contains "$2" 2>/dev/null ||
666 git describe --all --always "$2"
669 test -z "$revname" || revname=" ($revname)"
672 # Show commit summary for submodules in index or working tree
674 # If '--cached' is given, show summary between index and given commit,
675 # or between working tree and given commit
677 # $@ = [commit (default 'HEAD'),] requested paths (default all)
684 # parse $args after "submodule ... summary".
698 if summary_limit=$(($2 + 0)) 2>/dev/null && test "$summary_limit" = "$2"
720 test $summary_limit = 0 && return
722 if rev=$(git rev-parse -q --verify --default HEAD ${1+"$1"})
726 elif test -z "$1" -o "$1" = "HEAD"
728 # before the first commit: compare with an empty tree
729 head=$(git hash-object -w -t tree --stdin </dev/null)
730 test -z "$1" || shift
738 die "$(gettext -- "--cached cannot be used with --files")"
744 # Get modified modules cared by user
745 modules=$(git $diff_cmd $cached --ignore-submodules=dirty --raw $head -- "$@" |
746 sane_egrep '^:([0-7]* )?160000' |
747 while read mod_src mod_dst sha1_src sha1_dst status name
749 # Always show modules deleted or type-changed (blob<->module)
750 test $status = D -o $status = T && echo "$name" && continue
751 # Also show added or modified modules which are checked out
752 GIT_DIR="$name/.git" git-rev-parse --git-dir >/dev/null 2>&1 &&
757 test -z "$modules" && return
759 git $diff_cmd $cached --ignore-submodules=dirty --raw $head -- $modules |
760 sane_egrep '^:([0-7]* )?160000' |
762 while read mod_src mod_dst sha1_src sha1_dst status name
764 if test -z "$cached" &&
765 test $sha1_dst = 0000000000000000000000000000000000000000
769 sha1_dst=$(GIT_DIR="$name/.git" git rev-parse HEAD)
771 100644 | 100755 | 120000)
772 sha1_dst=$(git hash-object $name)
778 eval_gettextln "unexpected mode \$mod_dst" >&2
785 test $mod_src = 160000 &&
786 ! GIT_DIR="$name/.git" git-rev-parse -q --verify $sha1_src^0 >/dev/null &&
789 test $mod_dst = 160000 &&
790 ! GIT_DIR="$name/.git" git-rev-parse -q --verify $sha1_dst^0 >/dev/null &&
794 case "$missing_src,$missing_dst" in
796 errmsg="$(eval_gettext " Warn: \$name doesn't contain commit \$sha1_src")"
799 errmsg="$(eval_gettext " Warn: \$name doesn't contain commit \$sha1_dst")"
802 errmsg="$(eval_gettext " Warn: \$name doesn't contain commits \$sha1_src and \$sha1_dst")"
807 if test $mod_src = 160000 -a $mod_dst = 160000
809 range="$sha1_src...$sha1_dst"
810 elif test $mod_src = 160000
816 GIT_DIR="$name/.git" \
817 git rev-list --first-parent $range -- | wc -l
819 total_commits=" ($(($total_commits + 0)))"
823 sha1_abbr_src=$(echo $sha1_src | cut -c1-7)
824 sha1_abbr_dst=$(echo $sha1_dst | cut -c1-7)
827 blob="$(gettext "blob")"
828 submodule="$(gettext "submodule")"
829 if test $mod_dst = 160000
831 echo "* $name $sha1_abbr_src($blob)->$sha1_abbr_dst($submodule)$total_commits:"
833 echo "* $name $sha1_abbr_src($submodule)->$sha1_abbr_dst($blob)$total_commits:"
836 echo "* $name $sha1_abbr_src...$sha1_abbr_dst$total_commits:"
840 # Don't give error msg for modification whose dst is not submodule
841 # i.e. deleted or changed to blob
842 test $mod_dst = 160000 && echo "$errmsg"
844 if test $mod_src = 160000 -a $mod_dst = 160000
847 test $summary_limit -gt 0 && limit="-$summary_limit"
848 GIT_DIR="$name/.git" \
849 git log $limit --pretty='format: %m %s' \
850 --first-parent $sha1_src...$sha1_dst
851 elif test $mod_dst = 160000
853 GIT_DIR="$name/.git" \
854 git log --pretty='format: > %s' -1 $sha1_dst
856 GIT_DIR="$name/.git" \
857 git log --pretty='format: < %s' -1 $sha1_src
863 if test -n "$for_status"; then
864 if [ -n "$files" ]; then
865 gettextln "# Submodules changed but not updated:"
867 gettextln "# Submodule changes to be committed:"
870 sed -e 's|^|# |' -e 's|^# $|#|'
876 # List all submodules, prefixed with:
877 # - submodule not initialized
878 # + different revision checked out
880 # If --cached was specified the revision in the index will be printed
881 # instead of the currently checked out revision.
883 # $@ = requested paths (default to all)
887 # parse $args after "submodule ... status".
912 orig_flags="$orig_flags $(git rev-parse --sq-quote "$1")"
917 while read mode sha1 stage sm_path
919 name=$(module_name "$sm_path") || exit
920 url=$(git config submodule."$name".url)
921 displaypath="$prefix$sm_path"
924 say "U$sha1 $displaypath"
927 if test -z "$url" || ! test -d "$sm_path"/.git -o -f "$sm_path"/.git
929 say "-$sha1 $displaypath"
932 set_name_rev "$sm_path" "$sha1"
933 if git diff-files --ignore-submodules=dirty --quiet -- "$sm_path"
935 say " $sha1 $displaypath$revname"
939 sha1=$(clear_local_git_env; cd "$sm_path" && git rev-parse --verify HEAD)
940 set_name_rev "$sm_path" "$sha1"
942 say "+$sha1 $displaypath$revname"
945 if test -n "$recursive"
948 prefix="$displaypath/"
951 eval cmd_status "$orig_args"
953 die "$(eval_gettext "Failed to recurse into submodule path '\$sm_path'")"
958 # Sync remote urls for submodules
959 # This makes the value for remote.$remote.url match the value
960 # specified in .gitmodules.
985 while read mode sha1 stage sm_path
987 name=$(module_name "$sm_path")
988 url=$(git config -f .gitmodules --get submodule."$name".url)
990 # Possibly a url relative to parent
993 # rewrite foo/bar as ../.. to find path from
994 # submodule work tree to superproject work tree
995 up_path="$(echo "$sm_path" | sed "s/[^/][^/]*/../g")" &&
996 # guarantee a trailing /
997 up_path=${up_path%/}/ &&
998 # path from submodule work tree to submodule origin repo
999 sub_origin_url=$(resolve_relative_url "$url" "$up_path") &&
1000 # path from superproject work tree to submodule origin repo
1001 super_config_url=$(resolve_relative_url "$url") || exit
1004 sub_origin_url="$url"
1005 super_config_url="$url"
1009 if git config "submodule.$name.url" >/dev/null 2>/dev/null
1011 say "$(eval_gettext "Synchronizing submodule url for '\$name'")"
1012 git config submodule."$name".url "$super_config_url"
1014 if test -e "$sm_path"/.git
1019 remote=$(get_default_remote)
1020 git config remote."$remote".url "$sub_origin_url"
1027 # This loop parses the command line arguments to find the
1028 # subcommand name to dispatch. Parsing of the subcommand specific
1029 # options are primarily done by the subcommand implementations.
1030 # Subcommand specific options such as --branch and --cached are
1031 # parsed here as well, for backward compatibility.
1033 while test $# != 0 && test -z "$command"
1036 add | foreach | init | update | status | summary | sync)
1066 # No command word defaults to "status"
1067 test -n "$command" || command=status
1069 # "-b branch" is accepted only by "add"
1070 if test -n "$branch" && test "$command" != add
1075 # "--cached" is accepted only by "status" and "summary"
1076 if test -n "$cached" && test "$command" != status -a "$command" != summary