submodule update: when using recursion, show full path
[git] / git-submodule.sh
1 #!/bin/sh
2 #
3 # git-submodule.sh: add, init, update or list git submodules
4 #
5 # Copyright (c) 2007 Lars Hjemli
6
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 [--recursive] [--] [<path>...]"
15 OPTIONS_SPEC=
16 . git-sh-setup
17 . git-sh-i18n
18 . git-parse-remote
19 require_work_tree
20
21 command=
22 branch=
23 force=
24 reference=
25 cached=
26 recursive=
27 init=
28 files=
29 nofetch=
30 update=
31 prefix=
32 custom_name=
33
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.
39 #
40 # The output of the function is the origin URL of the submodule.
41 #
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).
46 #
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 ()
51 {
52         remote=$(get_default_remote)
53         remoteurl=$(git config "remote.$remote.url") ||
54                 remoteurl=$(pwd) # the repository is its own authoritative upstream
55         url="$1"
56         remoteurl=${remoteurl%/}
57         sep=/
58         up_path="$2"
59
60         case "$remoteurl" in
61         *:*|/*)
62                 is_relative=
63                 ;;
64         ./*|../*)
65                 is_relative=t
66                 ;;
67         *)
68                 is_relative=t
69                 remoteurl="./$remoteurl"
70                 ;;
71         esac
72
73         while test -n "$url"
74         do
75                 case "$url" in
76                 ../*)
77                         url="${url#../}"
78                         case "$remoteurl" in
79                         */*)
80                                 remoteurl="${remoteurl%/*}"
81                                 ;;
82                         *:*)
83                                 remoteurl="${remoteurl%:*}"
84                                 sep=:
85                                 ;;
86                         *)
87                                 if test -z "$is_relative" || test "." = "$remoteurl"
88                                 then
89                                         die "$(eval_gettext "cannot strip one component off url '\$remoteurl'")"
90                                 else
91                                         remoteurl=.
92                                 fi
93                                 ;;
94                         esac
95                         ;;
96                 ./*)
97                         url="${url#./}"
98                         ;;
99                 *)
100                         break;;
101                 esac
102         done
103         remoteurl="$remoteurl$sep${url%/}"
104         echo "${is_relative:+${up_path}}${remoteurl#./}"
105 }
106
107 #
108 # Get submodule info for registered submodules
109 # $@ = path to limit submodule list
110 #
111 module_list()
112 {
113         (
114                 git ls-files --error-unmatch --stage -- "$@" ||
115                 echo "unmatched pathspec exists"
116         ) |
117         perl -e '
118         my %unmerged = ();
119         my ($null_sha1) = ("0" x 40);
120         my @out = ();
121         my $unmatched = 0;
122         while (<STDIN>) {
123                 if (/^unmatched pathspec/) {
124                         $unmatched = 1;
125                         next;
126                 }
127                 chomp;
128                 my ($mode, $sha1, $stage, $path) =
129                         /^([0-7]+) ([0-9a-f]{40}) ([0-3])\t(.*)$/;
130                 next unless $mode eq "160000";
131                 if ($stage ne "0") {
132                         if (!$unmerged{$path}++) {
133                                 push @out, "$mode $null_sha1 U\t$path\n";
134                         }
135                         next;
136                 }
137                 push @out, "$_\n";
138         }
139         if ($unmatched) {
140                 print "#unmatched\n";
141         } else {
142                 print for (@out);
143         }
144         '
145 }
146
147 die_if_unmatched ()
148 {
149         if test "$1" = "#unmatched"
150         then
151                 exit 1
152         fi
153 }
154
155 #
156 # Map submodule path to submodule name
157 #
158 # $1 = path
159 #
160 module_name()
161 {
162         # Do we have "submodule.<something>.path = $1" defined in .gitmodules file?
163         sm_path="$1"
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' )
167         test -z "$name" &&
168         die "$(eval_gettext "No submodule mapping found in .gitmodules for path '\$sm_path'")"
169         echo "$name"
170 }
171
172 #
173 # Clone a submodule
174 #
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.
179 #
180 module_clone()
181 {
182         sm_path=$1
183         name=$2
184         url=$3
185         reference="$4"
186         quiet=
187         if test -n "$GIT_QUIET"
188         then
189                 quiet=-q
190         fi
191
192         gitdir=
193         gitdir_base=
194         base_name=$(dirname "$name")
195
196         gitdir=$(git rev-parse --git-dir)
197         gitdir_base="$gitdir/modules/$base_name"
198         gitdir="$gitdir/modules/$name"
199
200         if test -d "$gitdir"
201         then
202                 mkdir -p "$sm_path"
203                 rm -f "$gitdir/index"
204         else
205                 mkdir -p "$gitdir_base"
206                 (
207                         clear_local_git_env
208                         git clone $quiet -n ${reference:+"$reference"} \
209                                 --separate-git-dir "$gitdir" "$url" "$sm_path"
210                 ) ||
211                 die "$(eval_gettext "Clone of '\$url' into submodule path '\$sm_path' failed")"
212         fi
213
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")"
224         fi
225         while test "${a%%/*}" = "${b%%/*}"
226         do
227                 a=${a#*/}
228                 b=${b#*/}
229         done
230         # Now chop off the trailing '/'s that were added in the beginning
231         a=${a%/}
232         b=${b%/}
233
234         # Turn each leading "*/" component into "../"
235         rel=$(echo $b | sed -e 's|[^/][^/]*|..|g')
236         echo "gitdir: $rel/$a" >"$sm_path/.git"
237
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")
240 }
241
242 #
243 # Add a new submodule to the working tree, .gitmodules and the index
244 #
245 # $@ = repo path
246 #
247 # optional branch is stored in global branch variable
248 #
249 cmd_add()
250 {
251         # parse $args after "submodule ... add".
252         while test $# -ne 0
253         do
254                 case "$1" in
255                 -b | --branch)
256                         case "$2" in '') usage ;; esac
257                         branch=$2
258                         shift
259                         ;;
260                 -f | --force)
261                         force=$1
262                         ;;
263                 -q|--quiet)
264                         GIT_QUIET=1
265                         ;;
266                 --reference)
267                         case "$2" in '') usage ;; esac
268                         reference="--reference=$2"
269                         shift
270                         ;;
271                 --reference=*)
272                         reference="$1"
273                         ;;
274                 --name)
275                         case "$2" in '') usage ;; esac
276                         custom_name=$2
277                         shift
278                         ;;
279                 --)
280                         shift
281                         break
282                         ;;
283                 -*)
284                         usage
285                         ;;
286                 *)
287                         break
288                         ;;
289                 esac
290                 shift
291         done
292
293         repo=$1
294         sm_path=$2
295
296         if test -z "$sm_path"; then
297                 sm_path=$(echo "$repo" |
298                         sed -e 's|/$||' -e 's|:*/*\.git$||' -e 's|.*[/:]||g')
299         fi
300
301         if test -z "$repo" -o -z "$sm_path"; then
302                 usage
303         fi
304
305         # assure repo is absolute or relative to parent
306         case "$repo" in
307         ./*|../*)
308                 # dereference source url relative to parent's url
309                 realrepo=$(resolve_relative_url "$repo") || exit
310                 ;;
311         *:*|/*)
312                 # absolute url
313                 realrepo=$repo
314                 ;;
315         *)
316                 die "$(eval_gettext "repo URL: '\$repo' must be absolute or begin with ./|../")"
317         ;;
318         esac
319
320         # normalize path:
321         # multiple //; leading ./; /./; /../; trailing /
322         sm_path=$(printf '%s/\n' "$sm_path" |
323                 sed -e '
324                         s|//*|/|g
325                         s|^\(\./\)*||
326                         s|/\./|/|g
327                         :start
328                         s|\([^/]*\)/\.\./||
329                         tstart
330                         s|/*$||
331                 ')
332         git ls-files --error-unmatch "$sm_path" > /dev/null 2>&1 &&
333         die "$(eval_gettext "'\$sm_path' already exists in the index")"
334
335         if test -z "$force" && ! git add --dry-run --ignore-missing "$sm_path" > /dev/null 2>&1
336         then
337                 eval_gettextln "The following path is ignored by one of your .gitignore files:
338 \$sm_path
339 Use -f if you really want to add it." >&2
340                 exit 1
341         fi
342
343         if test -n "$custom_name"
344         then
345                 sm_name="$custom_name"
346         else
347                 sm_name="$sm_path"
348         fi
349
350         # perhaps the path exists and is already a git repo, else clone it
351         if test -e "$sm_path"
352         then
353                 if test -d "$sm_path"/.git -o -f "$sm_path"/.git
354                 then
355                         eval_gettextln "Adding existing repo at '\$sm_path' to the index"
356                 else
357                         die "$(eval_gettext "'\$sm_path' already exists and is not a valid git repo")"
358                 fi
359
360         else
361                 if test -d ".git/modules/$sm_name"
362                 then
363                         if test -z "$force"
364                         then
365                                 echo >&2 "$(eval_gettext "A git directory for '\$sm_name' is found locally with remote(s):")"
366                                 GIT_DIR=".git/modules/$sm_name" GIT_WORK_TREE=. git remote -v | grep '(fetch)' | sed -e s,^,"  ", -e s,' (fetch)',, >&2
367                                 echo >&2 "$(eval_gettext "If you want to reuse this local git directory instead of cloning again from")"
368                                 echo >&2 "  $realrepo"
369                                 echo >&2 "$(eval_gettext "use the '--force' option. If the local git directory is not the correct repo")"
370                                 die "$(eval_gettext "or you are unsure what this means choose another name with the '--name' option.")"
371                         else
372                                 echo "$(eval_gettext "Reactivating local git directory for submodule '\$sm_name'.")"
373                         fi
374                 fi
375                 module_clone "$sm_path" "$sm_name" "$realrepo" "$reference" || exit
376                 (
377                         clear_local_git_env
378                         cd "$sm_path" &&
379                         # ash fails to wordsplit ${branch:+-b "$branch"...}
380                         case "$branch" in
381                         '') git checkout -f -q ;;
382                         ?*) git checkout -f -q -B "$branch" "origin/$branch" ;;
383                         esac
384                 ) || die "$(eval_gettext "Unable to checkout submodule '\$sm_path'")"
385         fi
386         git config submodule."$sm_name".url "$realrepo"
387
388         git add $force "$sm_path" ||
389         die "$(eval_gettext "Failed to add submodule '\$sm_path'")"
390
391         git config -f .gitmodules submodule."$sm_name".path "$sm_path" &&
392         git config -f .gitmodules submodule."$sm_name".url "$repo" &&
393         git add --force .gitmodules ||
394         die "$(eval_gettext "Failed to register submodule '\$sm_path'")"
395 }
396
397 #
398 # Execute an arbitrary command sequence in each checked out
399 # submodule
400 #
401 # $@ = command to execute
402 #
403 cmd_foreach()
404 {
405         # parse $args after "submodule ... foreach".
406         while test $# -ne 0
407         do
408                 case "$1" in
409                 -q|--quiet)
410                         GIT_QUIET=1
411                         ;;
412                 --recursive)
413                         recursive=1
414                         ;;
415                 -*)
416                         usage
417                         ;;
418                 *)
419                         break
420                         ;;
421                 esac
422                 shift
423         done
424
425         toplevel=$(pwd)
426
427         # dup stdin so that it can be restored when running the external
428         # command in the subshell (and a recursive call to this function)
429         exec 3<&0
430
431         module_list |
432         while read mode sha1 stage sm_path
433         do
434                 die_if_unmatched "$mode"
435                 if test -e "$sm_path"/.git
436                 then
437                         say "$(eval_gettext "Entering '\$prefix\$sm_path'")"
438                         name=$(module_name "$sm_path")
439                         (
440                                 prefix="$prefix$sm_path/"
441                                 clear_local_git_env
442                                 # we make $path available to scripts ...
443                                 path=$sm_path
444                                 cd "$sm_path" &&
445                                 eval "$@" &&
446                                 if test -n "$recursive"
447                                 then
448                                         cmd_foreach "--recursive" "$@"
449                                 fi
450                         ) <&3 3<&- ||
451                         die "$(eval_gettext "Stopping at '\$sm_path'; script returned non-zero status.")"
452                 fi
453         done
454 }
455
456 #
457 # Register submodules in .git/config
458 #
459 # $@ = requested paths (default to all)
460 #
461 cmd_init()
462 {
463         # parse $args after "submodule ... init".
464         while test $# -ne 0
465         do
466                 case "$1" in
467                 -q|--quiet)
468                         GIT_QUIET=1
469                         ;;
470                 --)
471                         shift
472                         break
473                         ;;
474                 -*)
475                         usage
476                         ;;
477                 *)
478                         break
479                         ;;
480                 esac
481                 shift
482         done
483
484         module_list "$@" |
485         while read mode sha1 stage sm_path
486         do
487                 die_if_unmatched "$mode"
488                 name=$(module_name "$sm_path") || exit
489
490                 # Copy url setting when it is not set yet
491                 if test -z "$(git config "submodule.$name.url")"
492                 then
493                         url=$(git config -f .gitmodules submodule."$name".url)
494                         test -z "$url" &&
495                         die "$(eval_gettext "No url found for submodule path '\$sm_path' in .gitmodules")"
496
497                         # Possibly a url relative to parent
498                         case "$url" in
499                         ./*|../*)
500                                 url=$(resolve_relative_url "$url") || exit
501                                 ;;
502                         esac
503                         git config submodule."$name".url "$url" ||
504                         die "$(eval_gettext "Failed to register url for submodule path '\$sm_path'")"
505
506                         say "$(eval_gettext "Submodule '\$name' (\$url) registered for path '\$sm_path'")"
507                 fi
508
509                 # Copy "update" setting when it is not set yet
510                 upd="$(git config -f .gitmodules submodule."$name".update)"
511                 test -z "$upd" ||
512                 test -n "$(git config submodule."$name".update)" ||
513                 git config submodule."$name".update "$upd" ||
514                 die "$(eval_gettext "Failed to register update mode for submodule path '\$sm_path'")"
515         done
516 }
517
518 #
519 # Update each submodule path to correct revision, using clone and checkout as needed
520 #
521 # $@ = requested paths (default to all)
522 #
523 cmd_update()
524 {
525         # parse $args after "submodule ... update".
526         orig_flags=
527         while test $# -ne 0
528         do
529                 case "$1" in
530                 -q|--quiet)
531                         GIT_QUIET=1
532                         ;;
533                 -i|--init)
534                         init=1
535                         ;;
536                 -N|--no-fetch)
537                         nofetch=1
538                         ;;
539                 -f|--force)
540                         force=$1
541                         ;;
542                 -r|--rebase)
543                         update="rebase"
544                         ;;
545                 --reference)
546                         case "$2" in '') usage ;; esac
547                         reference="--reference=$2"
548                         orig_flags="$orig_flags $(git rev-parse --sq-quote "$1")"
549                         shift
550                         ;;
551                 --reference=*)
552                         reference="$1"
553                         ;;
554                 -m|--merge)
555                         update="merge"
556                         ;;
557                 --recursive)
558                         recursive=1
559                         ;;
560                 --checkout)
561                         update="checkout"
562                         ;;
563                 --)
564                         shift
565                         break
566                         ;;
567                 -*)
568                         usage
569                         ;;
570                 *)
571                         break
572                         ;;
573                 esac
574                 orig_flags="$orig_flags $(git rev-parse --sq-quote "$1")"
575                 shift
576         done
577
578         if test -n "$init"
579         then
580                 cmd_init "--" "$@" || return
581         fi
582
583         cloned_modules=
584         module_list "$@" | {
585         err=
586         while read mode sha1 stage sm_path
587         do
588                 die_if_unmatched "$mode"
589                 if test "$stage" = U
590                 then
591                         echo >&2 "Skipping unmerged submodule $prefix$sm_path"
592                         continue
593                 fi
594                 name=$(module_name "$sm_path") || exit
595                 url=$(git config submodule."$name".url)
596                 if ! test -z "$update"
597                 then
598                         update_module=$update
599                 else
600                         update_module=$(git config submodule."$name".update)
601                 fi
602
603                 if test "$update_module" = "none"
604                 then
605                         echo "Skipping submodule '$prefix$sm_path'"
606                         continue
607                 fi
608
609                 if test -z "$url"
610                 then
611                         # Only mention uninitialized submodules when its
612                         # path have been specified
613                         test "$#" != "0" &&
614                         say "$(eval_gettext "Submodule path '\$prefix\$sm_path' not initialized
615 Maybe you want to use 'update --init'?")"
616                         continue
617                 fi
618
619                 if ! test -d "$sm_path"/.git -o -f "$sm_path"/.git
620                 then
621                         module_clone "$sm_path" "$name" "$url" "$reference" || exit
622                         cloned_modules="$cloned_modules;$name"
623                         subsha1=
624                 else
625                         subsha1=$(clear_local_git_env; cd "$sm_path" &&
626                                 git rev-parse --verify HEAD) ||
627                         die "$(eval_gettext "Unable to find current revision in submodule path '\$prefix\$sm_path'")"
628                 fi
629
630                 if test "$subsha1" != "$sha1" -o -n "$force"
631                 then
632                         subforce=$force
633                         # If we don't already have a -f flag and the submodule has never been checked out
634                         if test -z "$subsha1" -a -z "$force"
635                         then
636                                 subforce="-f"
637                         fi
638
639                         if test -z "$nofetch"
640                         then
641                                 # Run fetch only if $sha1 isn't present or it
642                                 # is not reachable from a ref.
643                                 (clear_local_git_env; cd "$sm_path" &&
644                                         ( (rev=$(git rev-list -n 1 $sha1 --not --all 2>/dev/null) &&
645                                          test -z "$rev") || git-fetch)) ||
646                                 die "$(eval_gettext "Unable to fetch in submodule path '\$prefix\$sm_path'")"
647                         fi
648
649                         # Is this something we just cloned?
650                         case ";$cloned_modules;" in
651                         *";$name;"*)
652                                 # then there is no local change to integrate
653                                 update_module= ;;
654                         esac
655
656                         must_die_on_failure=
657                         case "$update_module" in
658                         rebase)
659                                 command="git rebase"
660                                 die_msg="$(eval_gettext "Unable to rebase '\$sha1' in submodule path '\$prefix\$sm_path'")"
661                                 say_msg="$(eval_gettext "Submodule path '\$prefix\$sm_path': rebased into '\$sha1'")"
662                                 must_die_on_failure=yes
663                                 ;;
664                         merge)
665                                 command="git merge"
666                                 die_msg="$(eval_gettext "Unable to merge '\$sha1' in submodule path '\$prefix\$sm_path'")"
667                                 say_msg="$(eval_gettext "Submodule path '\$prefix\$sm_path': merged in '\$sha1'")"
668                                 must_die_on_failure=yes
669                                 ;;
670                         *)
671                                 command="git checkout $subforce -q"
672                                 die_msg="$(eval_gettext "Unable to checkout '\$sha1' in submodule path '\$prefix\$sm_path'")"
673                                 say_msg="$(eval_gettext "Submodule path '\$prefix\$sm_path': checked out '\$sha1'")"
674                                 ;;
675                         esac
676
677                         if (clear_local_git_env; cd "$sm_path" && $command "$sha1")
678                         then
679                                 say "$say_msg"
680                         elif test -n "$must_die_on_failure"
681                         then
682                                 die_with_status 2 "$die_msg"
683                         else
684                                 err="${err};$die_msg"
685                                 continue
686                         fi
687                 fi
688
689                 if test -n "$recursive"
690                 then
691                         (
692                                 prefix="$prefix$sm_path/"
693                                 clear_local_git_env
694                                 cd "$sm_path" &&
695                                 eval cmd_update "$orig_flags"
696                         )
697                         res=$?
698                         if test $res -gt 0
699                         then
700                                 die_msg="$(eval_gettext "Failed to recurse into submodule path '\$prefix\$sm_path'")"
701                                 if test $res -eq 1
702                                 then
703                                         err="${err};$die_msg"
704                                         continue
705                                 else
706                                         die_with_status $res "$die_msg"
707                                 fi
708                         fi
709                 fi
710         done
711
712         if test -n "$err"
713         then
714                 OIFS=$IFS
715                 IFS=';'
716                 for e in $err
717                 do
718                         if test -n "$e"
719                         then
720                                 echo >&2 "$e"
721                         fi
722                 done
723                 IFS=$OIFS
724                 exit 1
725         fi
726         }
727 }
728
729 set_name_rev () {
730         revname=$( (
731                 clear_local_git_env
732                 cd "$1" && {
733                         git describe "$2" 2>/dev/null ||
734                         git describe --tags "$2" 2>/dev/null ||
735                         git describe --contains "$2" 2>/dev/null ||
736                         git describe --all --always "$2"
737                 }
738         ) )
739         test -z "$revname" || revname=" ($revname)"
740 }
741 #
742 # Show commit summary for submodules in index or working tree
743 #
744 # If '--cached' is given, show summary between index and given commit,
745 # or between working tree and given commit
746 #
747 # $@ = [commit (default 'HEAD'),] requested paths (default all)
748 #
749 cmd_summary() {
750         summary_limit=-1
751         for_status=
752         diff_cmd=diff-index
753
754         # parse $args after "submodule ... summary".
755         while test $# -ne 0
756         do
757                 case "$1" in
758                 --cached)
759                         cached="$1"
760                         ;;
761                 --files)
762                         files="$1"
763                         ;;
764                 --for-status)
765                         for_status="$1"
766                         ;;
767                 -n|--summary-limit)
768                         if summary_limit=$(($2 + 0)) 2>/dev/null && test "$summary_limit" = "$2"
769                         then
770                                 :
771                         else
772                                 usage
773                         fi
774                         shift
775                         ;;
776                 --)
777                         shift
778                         break
779                         ;;
780                 -*)
781                         usage
782                         ;;
783                 *)
784                         break
785                         ;;
786                 esac
787                 shift
788         done
789
790         test $summary_limit = 0 && return
791
792         if rev=$(git rev-parse -q --verify --default HEAD ${1+"$1"})
793         then
794                 head=$rev
795                 test $# = 0 || shift
796         elif test -z "$1" -o "$1" = "HEAD"
797         then
798                 # before the first commit: compare with an empty tree
799                 head=$(git hash-object -w -t tree --stdin </dev/null)
800                 test -z "$1" || shift
801         else
802                 head="HEAD"
803         fi
804
805         if [ -n "$files" ]
806         then
807                 test -n "$cached" &&
808                 die "$(gettext "The --cached option cannot be used with the --files option")"
809                 diff_cmd=diff-files
810                 head=
811         fi
812
813         cd_to_toplevel
814         # Get modified modules cared by user
815         modules=$(git $diff_cmd $cached --ignore-submodules=dirty --raw $head -- "$@" |
816                 sane_egrep '^:([0-7]* )?160000' |
817                 while read mod_src mod_dst sha1_src sha1_dst status name
818                 do
819                         # Always show modules deleted or type-changed (blob<->module)
820                         test $status = D -o $status = T && echo "$name" && continue
821                         # Also show added or modified modules which are checked out
822                         GIT_DIR="$name/.git" git-rev-parse --git-dir >/dev/null 2>&1 &&
823                         echo "$name"
824                 done
825         )
826
827         test -z "$modules" && return
828
829         git $diff_cmd $cached --ignore-submodules=dirty --raw $head -- $modules |
830         sane_egrep '^:([0-7]* )?160000' |
831         cut -c2- |
832         while read mod_src mod_dst sha1_src sha1_dst status name
833         do
834                 if test -z "$cached" &&
835                         test $sha1_dst = 0000000000000000000000000000000000000000
836                 then
837                         case "$mod_dst" in
838                         160000)
839                                 sha1_dst=$(GIT_DIR="$name/.git" git rev-parse HEAD)
840                                 ;;
841                         100644 | 100755 | 120000)
842                                 sha1_dst=$(git hash-object $name)
843                                 ;;
844                         000000)
845                                 ;; # removed
846                         *)
847                                 # unexpected type
848                                 eval_gettextln "unexpected mode \$mod_dst" >&2
849                                 continue ;;
850                         esac
851                 fi
852                 missing_src=
853                 missing_dst=
854
855                 test $mod_src = 160000 &&
856                 ! GIT_DIR="$name/.git" git-rev-parse -q --verify $sha1_src^0 >/dev/null &&
857                 missing_src=t
858
859                 test $mod_dst = 160000 &&
860                 ! GIT_DIR="$name/.git" git-rev-parse -q --verify $sha1_dst^0 >/dev/null &&
861                 missing_dst=t
862
863                 total_commits=
864                 case "$missing_src,$missing_dst" in
865                 t,)
866                         errmsg="$(eval_gettext "  Warn: \$name doesn't contain commit \$sha1_src")"
867                         ;;
868                 ,t)
869                         errmsg="$(eval_gettext "  Warn: \$name doesn't contain commit \$sha1_dst")"
870                         ;;
871                 t,t)
872                         errmsg="$(eval_gettext "  Warn: \$name doesn't contain commits \$sha1_src and \$sha1_dst")"
873                         ;;
874                 *)
875                         errmsg=
876                         total_commits=$(
877                         if test $mod_src = 160000 -a $mod_dst = 160000
878                         then
879                                 range="$sha1_src...$sha1_dst"
880                         elif test $mod_src = 160000
881                         then
882                                 range=$sha1_src
883                         else
884                                 range=$sha1_dst
885                         fi
886                         GIT_DIR="$name/.git" \
887                         git rev-list --first-parent $range -- | wc -l
888                         )
889                         total_commits=" ($(($total_commits + 0)))"
890                         ;;
891                 esac
892
893                 sha1_abbr_src=$(echo $sha1_src | cut -c1-7)
894                 sha1_abbr_dst=$(echo $sha1_dst | cut -c1-7)
895                 if test $status = T
896                 then
897                         blob="$(gettext "blob")"
898                         submodule="$(gettext "submodule")"
899                         if test $mod_dst = 160000
900                         then
901                                 echo "* $name $sha1_abbr_src($blob)->$sha1_abbr_dst($submodule)$total_commits:"
902                         else
903                                 echo "* $name $sha1_abbr_src($submodule)->$sha1_abbr_dst($blob)$total_commits:"
904                         fi
905                 else
906                         echo "* $name $sha1_abbr_src...$sha1_abbr_dst$total_commits:"
907                 fi
908                 if test -n "$errmsg"
909                 then
910                         # Don't give error msg for modification whose dst is not submodule
911                         # i.e. deleted or changed to blob
912                         test $mod_dst = 160000 && echo "$errmsg"
913                 else
914                         if test $mod_src = 160000 -a $mod_dst = 160000
915                         then
916                                 limit=
917                                 test $summary_limit -gt 0 && limit="-$summary_limit"
918                                 GIT_DIR="$name/.git" \
919                                 git log $limit --pretty='format:  %m %s' \
920                                 --first-parent $sha1_src...$sha1_dst
921                         elif test $mod_dst = 160000
922                         then
923                                 GIT_DIR="$name/.git" \
924                                 git log --pretty='format:  > %s' -1 $sha1_dst
925                         else
926                                 GIT_DIR="$name/.git" \
927                                 git log --pretty='format:  < %s' -1 $sha1_src
928                         fi
929                         echo
930                 fi
931                 echo
932         done |
933         if test -n "$for_status"; then
934                 if [ -n "$files" ]; then
935                         gettextln "# Submodules changed but not updated:"
936                 else
937                         gettextln "# Submodule changes to be committed:"
938                 fi
939                 echo "#"
940                 sed -e 's|^|# |' -e 's|^# $|#|'
941         else
942                 cat
943         fi
944 }
945 #
946 # List all submodules, prefixed with:
947 #  - submodule not initialized
948 #  + different revision checked out
949 #
950 # If --cached was specified the revision in the index will be printed
951 # instead of the currently checked out revision.
952 #
953 # $@ = requested paths (default to all)
954 #
955 cmd_status()
956 {
957         # parse $args after "submodule ... status".
958         while test $# -ne 0
959         do
960                 case "$1" in
961                 -q|--quiet)
962                         GIT_QUIET=1
963                         ;;
964                 --cached)
965                         cached=1
966                         ;;
967                 --recursive)
968                         recursive=1
969                         ;;
970                 --)
971                         shift
972                         break
973                         ;;
974                 -*)
975                         usage
976                         ;;
977                 *)
978                         break
979                         ;;
980                 esac
981                 shift
982         done
983
984         module_list "$@" |
985         while read mode sha1 stage sm_path
986         do
987                 die_if_unmatched "$mode"
988                 name=$(module_name "$sm_path") || exit
989                 url=$(git config submodule."$name".url)
990                 displaypath="$prefix$sm_path"
991                 if test "$stage" = U
992                 then
993                         say "U$sha1 $displaypath"
994                         continue
995                 fi
996                 if test -z "$url" || ! test -d "$sm_path"/.git -o -f "$sm_path"/.git
997                 then
998                         say "-$sha1 $displaypath"
999                         continue;
1000                 fi
1001                 set_name_rev "$sm_path" "$sha1"
1002                 if git diff-files --ignore-submodules=dirty --quiet -- "$sm_path"
1003                 then
1004                         say " $sha1 $displaypath$revname"
1005                 else
1006                         if test -z "$cached"
1007                         then
1008                                 sha1=$(clear_local_git_env; cd "$sm_path" && git rev-parse --verify HEAD)
1009                                 set_name_rev "$sm_path" "$sha1"
1010                         fi
1011                         say "+$sha1 $displaypath$revname"
1012                 fi
1013
1014                 if test -n "$recursive"
1015                 then
1016                         (
1017                                 prefix="$displaypath/"
1018                                 clear_local_git_env
1019                                 cd "$sm_path" &&
1020                                 eval cmd_status
1021                         ) ||
1022                         die "$(eval_gettext "Failed to recurse into submodule path '\$sm_path'")"
1023                 fi
1024         done
1025 }
1026 #
1027 # Sync remote urls for submodules
1028 # This makes the value for remote.$remote.url match the value
1029 # specified in .gitmodules.
1030 #
1031 cmd_sync()
1032 {
1033         while test $# -ne 0
1034         do
1035                 case "$1" in
1036                 -q|--quiet)
1037                         GIT_QUIET=1
1038                         shift
1039                         ;;
1040                 --recursive)
1041                         recursive=1
1042                         shift
1043                         ;;
1044                 --)
1045                         shift
1046                         break
1047                         ;;
1048                 -*)
1049                         usage
1050                         ;;
1051                 *)
1052                         break
1053                         ;;
1054                 esac
1055         done
1056         cd_to_toplevel
1057         module_list "$@" |
1058         while read mode sha1 stage sm_path
1059         do
1060                 die_if_unmatched "$mode"
1061                 name=$(module_name "$sm_path")
1062                 url=$(git config -f .gitmodules --get submodule."$name".url)
1063
1064                 # Possibly a url relative to parent
1065                 case "$url" in
1066                 ./*|../*)
1067                         # rewrite foo/bar as ../.. to find path from
1068                         # submodule work tree to superproject work tree
1069                         up_path="$(echo "$sm_path" | sed "s/[^/][^/]*/../g")" &&
1070                         # guarantee a trailing /
1071                         up_path=${up_path%/}/ &&
1072                         # path from submodule work tree to submodule origin repo
1073                         sub_origin_url=$(resolve_relative_url "$url" "$up_path") &&
1074                         # path from superproject work tree to submodule origin repo
1075                         super_config_url=$(resolve_relative_url "$url") || exit
1076                         ;;
1077                 *)
1078                         sub_origin_url="$url"
1079                         super_config_url="$url"
1080                         ;;
1081                 esac
1082
1083                 if git config "submodule.$name.url" >/dev/null 2>/dev/null
1084                 then
1085                         say "$(eval_gettext "Synchronizing submodule url for '\$prefix\$sm_path'")"
1086                         git config submodule."$name".url "$super_config_url"
1087
1088                         if test -e "$sm_path"/.git
1089                         then
1090                         (
1091                                 clear_local_git_env
1092                                 cd "$sm_path"
1093                                 remote=$(get_default_remote)
1094                                 git config remote."$remote".url "$sub_origin_url"
1095
1096                                 if test -n "$recursive"
1097                                 then
1098                                         prefix="$prefix$sm_path/"
1099                                         eval cmd_sync
1100                                 fi
1101                         )
1102                         fi
1103                 fi
1104         done
1105 }
1106
1107 # This loop parses the command line arguments to find the
1108 # subcommand name to dispatch.  Parsing of the subcommand specific
1109 # options are primarily done by the subcommand implementations.
1110 # Subcommand specific options such as --branch and --cached are
1111 # parsed here as well, for backward compatibility.
1112
1113 while test $# != 0 && test -z "$command"
1114 do
1115         case "$1" in
1116         add | foreach | init | update | status | summary | sync)
1117                 command=$1
1118                 ;;
1119         -q|--quiet)
1120                 GIT_QUIET=1
1121                 ;;
1122         -b|--branch)
1123                 case "$2" in
1124                 '')
1125                         usage
1126                         ;;
1127                 esac
1128                 branch="$2"; shift
1129                 ;;
1130         --cached)
1131                 cached="$1"
1132                 ;;
1133         --)
1134                 break
1135                 ;;
1136         -*)
1137                 usage
1138                 ;;
1139         *)
1140                 break
1141                 ;;
1142         esac
1143         shift
1144 done
1145
1146 # No command word defaults to "status"
1147 if test -z "$command"
1148 then
1149     if test $# = 0
1150     then
1151         command=status
1152     else
1153         usage
1154     fi
1155 fi
1156
1157 # "-b branch" is accepted only by "add"
1158 if test -n "$branch" && test "$command" != add
1159 then
1160         usage
1161 fi
1162
1163 # "--cached" is accepted only by "status" and "summary"
1164 if test -n "$cached" && test "$command" != status -a "$command" != summary
1165 then
1166         usage
1167 fi
1168
1169 "cmd_$command" "$@"