3 # git-subtree.sh: split/join git repositories in subdirectories of this one
5 # Copyright (C) 2009 Avery Pennarun <apenwarr@gmail.com>
8 if test -z "$GIT_EXEC_PATH" || test "${PATH#"${GIT_EXEC_PATH}:"}" = "$PATH" || ! test -f "$GIT_EXEC_PATH/git-sh-setup"
10 echo >&2 'It looks like either your git installation or your'
11 echo >&2 'git-subtree installation is broken.'
14 echo >&2 " - If \`git --exec-path\` does not print the correct path to"
15 echo >&2 " your git install directory, then set the GIT_EXEC_PATH"
16 echo >&2 " environment variable to the correct directory."
17 echo >&2 " - Make sure that your \`${0##*/}\` file is either in your"
18 echo >&2 " PATH or in your git exec path (\`$(git --exec-path)\`)."
19 echo >&2 " - You should run git-subtree as \`git ${0##*/git-}\`,"
20 echo >&2 " not as \`${0##*/}\`." >&2
25 git subtree add --prefix=<prefix> <commit>
26 git subtree add --prefix=<prefix> <repository> <ref>
27 git subtree merge --prefix=<prefix> <commit>
28 git subtree split --prefix=<prefix> [<commit>]
29 git subtree pull --prefix=<prefix> <repository> <ref>
30 git subtree push --prefix=<prefix> <repository> <refspec>
35 P,prefix= the name of the subdir to split out
36 options for 'split' (also: 'push')
37 annotate= add a prefix to commit message of new commits
38 b,branch= create a new branch from the split subtree
39 ignore-joins ignore prior --rejoin commits
40 onto= try connecting new tree to an existing one
41 rejoin merge the new branch back into HEAD
42 options for 'add' and 'merge' (also: 'pull', 'split --rejoin', and 'push --rejoin')
43 squash merge subtree changes as a single commit
44 m,message= use the given message as the commit message for the merge commit
49 # Usage: debug [MSG...]
51 if test -n "$arg_debug"
53 printf "%$(($indent * 2))s%s\n" '' "$*" >&2
57 # Usage: progress [MSG...]
59 if test -z "$GIT_QUIET"
61 if test -z "$arg_debug"
65 # Print one progress line that we keep updating (use
66 # "\r" to return to the beginning of the line, rather
67 # than "\n" to start a new line). This only really
68 # works when stderr is a terminal.
69 printf "%s\r" "$*" >&2
71 # Debug mode is on. The `debug` function is regularly
74 # Don't do the one-line-with-"\r" thing, because on a
75 # terminal the debug output would overwrite and hide the
76 # progress output. Add a "progress:" prefix to make the
77 # progress output and the debug output easy to
78 # distinguish. This ensures maximum readability whether
79 # stderr is a terminal or a file.
80 printf "progress: %s\n" "$*" >&2
85 # Usage: assert CMD...
89 die "assertion failed: $*"
98 set_args="$(echo "$OPTS_SPEC" | git rev-parse --parseopt -- "$@" || echo exit $?)"
103 # First figure out the command and whether we use --rejoin, so
104 # that we can provide more helpful validation when we do the
105 # "real" flag parsing.
114 --annotate|-b|-P|-m|--onto)
129 case "$arg_command" in
135 allow_addmerge=$arg_split_rejoin
138 die "Unknown command '$arg_command'"
141 # Reset the arguments array for "real" flag parsing.
144 # Begin "real" flag parsing.
149 arg_split_ignore_joins=
152 arg_addmerge_message=
166 test -n "$allow_split" || die "The '$opt' flag does not make sense with 'git subtree $arg_command'."
167 arg_split_annotate="$1"
171 test -n "$allow_split" || die "The '$opt' flag does not make sense with 'git subtree $arg_command'."
175 test -n "$allow_split" || die "The '$opt' flag does not make sense with 'git subtree $arg_command'."
176 arg_split_branch="$1"
184 test -n "$allow_addmerge" || die "The '$opt' flag does not make sense with 'git subtree $arg_command'."
185 arg_addmerge_message="$1"
192 test -n "$allow_split" || die "The '$opt' flag does not make sense with 'git subtree $arg_command'."
197 test -n "$allow_split" || die "The '$opt' flag does not make sense with 'git subtree $arg_command'."
201 test -n "$allow_split" || die "The '$opt' flag does not make sense with 'git subtree $arg_command'."
204 test -n "$allow_split" || die "The '$opt' flag does not make sense with 'git subtree $arg_command'."
207 test -n "$allow_split" || die "The '$opt' flag does not make sense with 'git subtree $arg_command'."
208 arg_split_ignore_joins=1
211 test -n "$allow_split" || die "The '$opt' flag does not make sense with 'git subtree $arg_command'."
212 arg_split_ignore_joins=
215 test -n "$allow_addmerge" || die "The '$opt' flag does not make sense with 'git subtree $arg_command'."
216 arg_addmerge_squash=1
219 test -n "$allow_addmerge" || die "The '$opt' flag does not make sense with 'git subtree $arg_command'."
226 die "Unexpected option: $opt"
232 if test -z "$arg_prefix"
234 die "You must provide the --prefix option."
237 case "$arg_command" in
239 test -e "$arg_prefix" &&
240 die "prefix '$arg_prefix' already exists."
243 test -e "$arg_prefix" ||
244 die "'$arg_prefix' does not exist; use 'git subtree add'"
248 dir="$(dirname "$arg_prefix/.")"
250 debug "command: {$arg_command}"
251 debug "quiet: {$GIT_QUIET}"
256 "cmd_$arg_command" "$@"
262 cachedir="$GIT_DIR/subtree-cache/$$"
263 rm -rf "$cachedir" ||
264 die "Can't delete old cachedir: $cachedir"
265 mkdir -p "$cachedir" ||
266 die "Can't create new cachedir: $cachedir"
267 mkdir -p "$cachedir/notree" ||
268 die "Can't create new cachedir: $cachedir/notree"
269 debug "Using cachedir: $cachedir" >&2
272 # Usage: cache_get [REVS...]
276 if test -r "$cachedir/$oldrev"
278 read newrev <"$cachedir/$oldrev"
284 # Usage: cache_miss [REVS...]
288 if ! test -r "$cachedir/$oldrev"
295 # Usage: check_parents PARENTS_EXPR
298 missed=$(cache_miss "$1") || exit $?
299 local indent=$(($indent + 1))
302 if ! test -r "$cachedir/notree/$miss"
304 debug "incorrect order: $miss"
305 process_split_commit "$miss" ""
310 # Usage: set_notree REV
313 echo "1" > "$cachedir/notree/$1"
316 # Usage: cache_set OLDREV NEWREV
321 if test "$oldrev" != "latest_old" &&
322 test "$oldrev" != "latest_new" &&
323 test -e "$cachedir/$oldrev"
325 die "cache for $oldrev already exists!"
327 echo "$newrev" >"$cachedir/$oldrev"
330 # Usage: rev_exists REV
333 if git rev-parse "$1" >/dev/null 2>&1
341 # Usage: try_remove_previous REV
343 # If a commit doesn't have a parent, this might not work. But we only want
344 # to remove the parent from the rev-list, and since it doesn't exist, it won't
345 # be there anyway, so do nothing in that case.
346 try_remove_previous () {
354 # Usage: find_latest_squash DIR
355 find_latest_squash () {
357 debug "Looking for latest squash ($dir)..."
358 local indent=$(($indent + 1))
364 git log --grep="^git-subtree-dir: $dir/*\$" \
365 --no-show-signature --pretty=format:'START %H%n%s%n%n%b%nEND%n' HEAD |
369 debug "{{$sq/$main/$sub}}"
374 git-subtree-mainline:)
378 sub="$(git rev-parse "$b^{commit}")" ||
379 die "could not rev-parse split hash $b from commit $sq"
387 # Pretend its sub was a squash.
388 sq=$(git rev-parse --verify "$sq^2") ||
391 debug "Squash found: $sq $sub"
403 # Usage: find_existing_splits DIR REV
404 find_existing_splits () {
406 debug "Looking for prior splits..."
407 local indent=$(($indent + 1))
413 local grep_format="^git-subtree-dir: $dir/*\$"
414 if test -n "$arg_split_ignore_joins"
416 grep_format="^Add '$dir/' from commit '"
418 git log --grep="$grep_format" \
419 --no-show-signature --pretty=format:'START %H%n%s%n%n%b%nEND%n' "$rev" |
426 git-subtree-mainline:)
430 sub="$(git rev-parse "$b^{commit}")" ||
431 die "could not rev-parse split hash $b from commit $sq"
434 debug "Main is: '$main'"
435 if test -z "$main" -a -n "$sub"
437 # squash commits refer to a subtree
438 debug " Squash: $sq from $sub"
439 cache_set "$sq" "$sub"
441 if test -n "$main" -a -n "$sub"
443 debug " Prior: $main -> $sub"
446 try_remove_previous "$main"
447 try_remove_previous "$sub"
456 # Usage: copy_commit REV TREE FLAGS_STR
459 # We're going to set some environment vars here, so
460 # do it in a subshell to get rid of them safely later
461 debug copy_commit "{$1}" "{$2}" "{$3}"
462 git log -1 --no-show-signature --pretty=format:'%an%n%ae%n%aD%n%cn%n%ce%n%cD%n%B' "$1" |
465 read GIT_AUTHOR_EMAIL
467 read GIT_COMMITTER_NAME
468 read GIT_COMMITTER_EMAIL
469 read GIT_COMMITTER_DATE
470 export GIT_AUTHOR_NAME \
474 GIT_COMMITTER_EMAIL \
477 printf "%s" "$arg_split_annotate"
480 git commit-tree "$2" $3 # reads the rest of stdin
481 ) || die "Can't copy commit $1"
484 # Usage: add_msg DIR LATEST_OLD LATEST_NEW
490 if test -n "$arg_addmerge_message"
492 commit_message="$arg_addmerge_message"
494 commit_message="Add '$dir/' from commit '$latest_new'"
496 if test -n "$arg_split_rejoin"
498 # If this is from a --rejoin, then rejoin_msg has
499 # already inserted the `git-subtree-xxx:` tags
500 echo "$commit_message"
506 git-subtree-dir: $dir
507 git-subtree-mainline: $latest_old
508 git-subtree-split: $latest_new
512 # Usage: add_squashed_msg REV DIR
513 add_squashed_msg () {
515 if test -n "$arg_addmerge_message"
517 echo "$arg_addmerge_message"
519 echo "Merge commit '$1' as '$2'"
523 # Usage: rejoin_msg DIR LATEST_OLD LATEST_NEW
529 if test -n "$arg_addmerge_message"
531 commit_message="$arg_addmerge_message"
533 commit_message="Split '$dir/' into commit '$latest_new'"
538 git-subtree-dir: $dir
539 git-subtree-mainline: $latest_old
540 git-subtree-split: $latest_new
544 # Usage: squash_msg DIR OLD_SUBTREE_COMMIT NEW_SUBTREE_COMMIT
550 newsub_short=$(git rev-parse --short "$newsub")
554 oldsub_short=$(git rev-parse --short "$oldsub")
555 echo "Squashed '$dir/' changes from $oldsub_short..$newsub_short"
557 git log --no-show-signature --pretty=tformat:'%h %s' "$oldsub..$newsub"
558 git log --no-show-signature --pretty=tformat:'REVERT: %h %s' "$newsub..$oldsub"
560 echo "Squashed '$dir/' content from commit $newsub_short"
564 echo "git-subtree-dir: $dir"
565 echo "git-subtree-split: $newsub"
568 # Usage: toptree_for_commit COMMIT
569 toptree_for_commit () {
572 git rev-parse --verify "$commit^{tree}" || exit $?
575 # Usage: subtree_for_commit COMMIT DIR
576 subtree_for_commit () {
580 git ls-tree "$commit" -- "$dir" |
581 while read mode type tree name
583 assert test "$name" = "$dir"
584 assert test "$type" = "tree" -o "$type" = "commit"
585 test "$type" = "commit" && continue # ignore submodules
591 # Usage: tree_changed TREE [PARENTS...]
598 return 0 # weird parents, consider it changed
600 ptree=$(toptree_for_commit $1) || exit $?
601 if test "$ptree" != "$tree"
605 return 1 # not changed
610 # Usage: new_squash_commit OLD_SQUASHED_COMMIT OLD_NONSQUASHED_COMMIT NEW_NONSQUASHED_COMMIT
611 new_squash_commit () {
616 tree=$(toptree_for_commit $newsub) || exit $?
619 squash_msg "$dir" "$oldsub" "$newsub" |
620 git commit-tree "$tree" -p "$old" || exit $?
622 squash_msg "$dir" "" "$newsub" |
623 git commit-tree "$tree" || exit $?
627 # Usage: copy_or_skip REV TREE NEWPARENTS
633 assert test -n "$tree"
640 for parent in $newparents
642 ptree=$(toptree_for_commit $parent) || exit $?
643 test -z "$ptree" && continue
644 if test "$ptree" = "$tree"
646 # an identical parent could be used in place of this rev.
647 if test -n "$identical"
649 # if a previous identical parent was found, check whether
650 # one is already an ancestor of the other
651 mergebase=$(git merge-base $identical $parent)
652 if test "$identical" = "$mergebase"
654 # current identical commit is an ancestor of parent
656 elif test "$parent" != "$mergebase"
658 # no common history; commit must be copied
662 # first identical parent detected
666 nonidentical="$parent"
669 # sometimes both old parents map to the same newparent;
670 # eliminate duplicates
672 for gp in $gotparents
674 if test "$gp" = "$parent"
682 gotparents="$gotparents $parent"
687 if test -n "$identical" && test -n "$nonidentical"
689 extras=$(git rev-list --count $identical..$nonidentical)
690 if test "$extras" -ne 0
692 # we need to preserve history along the other branch
696 if test -n "$identical" && test -z "$copycommit"
700 copy_commit "$rev" "$tree" "$p" || exit $?
704 # Usage: ensure_clean
707 if ! git diff-index HEAD --exit-code --quiet 2>&1
709 die "Working tree has modifications. Cannot add."
711 if ! git diff-index --cached HEAD --exit-code --quiet 2>&1
713 die "Index has modifications. Cannot add."
717 # Usage: ensure_valid_ref_format REF
718 ensure_valid_ref_format () {
720 git check-ref-format "refs/heads/$1" ||
721 die "'$1' does not look like a ref"
724 # Usage: process_split_commit REV PARENTS
725 process_split_commit () {
730 if test $indent -eq 0
732 revcount=$(($revcount + 1))
734 # processing commit without normal parent information;
736 parents=$(git rev-parse "$rev^@")
737 extracount=$(($extracount + 1))
740 progress "$revcount/$revmax ($createcount) [$extracount]"
742 debug "Processing commit: $rev"
743 local indent=$(($indent + 1))
744 exists=$(cache_get "$rev") || exit $?
747 debug "prior: $exists"
750 createcount=$(($createcount + 1))
751 debug "parents: $parents"
752 check_parents "$parents"
753 newparents=$(cache_get $parents) || exit $?
754 debug "newparents: $newparents"
756 tree=$(subtree_for_commit "$rev" "$dir") || exit $?
757 debug "tree is: $tree"
759 # ugly. is there no better way to tell if this is a subtree
760 # vs. a mainline commit? Does it matter?
764 if test -n "$newparents"
766 cache_set "$rev" "$rev"
771 newrev=$(copy_or_skip "$rev" "$tree" "$newparents") || exit $?
772 debug "newrev is: $newrev"
773 cache_set "$rev" "$newrev"
774 cache_set latest_new "$newrev"
775 cache_set latest_old "$rev"
779 # Or: cmd_add REPOSITORY REF
786 git rev-parse -q --verify "$1^{commit}" >/dev/null ||
787 die "'$1' does not refer to a commit"
793 # Technically we could accept a refspec here but we're
794 # just going to turn around and add FETCH_HEAD under the
795 # specified directory. Allowing a refspec might be
796 # misleading because we won't do anything with any other
797 # branches fetched via the refspec.
798 ensure_valid_ref_format "$2"
800 cmd_add_repository "$@"
802 say >&2 "error: parameters were '$*'"
803 die "Provide either a commit or a repository and commit."
807 # Usage: cmd_add_repository REPOSITORY REFSPEC
808 cmd_add_repository () {
810 echo "git fetch" "$@"
813 git fetch "$@" || exit $?
814 cmd_add_commit FETCH_HEAD
817 # Usage: cmd_add_commit REV
819 # The rev has already been validated by cmd_add(), we just
820 # need to normalize it.
822 rev=$(git rev-parse --verify "$1^{commit}") || exit $?
824 debug "Adding $dir as '$rev'..."
825 if test -z "$arg_split_rejoin"
827 # Only bother doing this if this is a genuine 'add',
828 # not a synthetic 'add' from '--rejoin'.
829 git read-tree --prefix="$dir" $rev || exit $?
831 git checkout -- "$dir" || exit $?
832 tree=$(git write-tree) || exit $?
834 headrev=$(git rev-parse HEAD) || exit $?
835 if test -n "$headrev" && test "$headrev" != "$rev"
842 if test -n "$arg_addmerge_squash"
844 rev=$(new_squash_commit "" "" "$rev") || exit $?
845 commit=$(add_squashed_msg "$rev" "$dir" |
846 git commit-tree "$tree" $headp -p "$rev") || exit $?
848 revp=$(peel_committish "$rev") || exit $?
849 commit=$(add_msg "$dir" $headrev "$rev" |
850 git commit-tree "$tree" $headp -p "$revp") || exit $?
852 git reset "$commit" || exit $?
854 say >&2 "Added dir '$dir'"
857 # Usage: cmd_split [REV]
861 rev=$(git rev-parse HEAD)
864 rev=$(git rev-parse -q --verify "$1^{commit}") ||
865 die "'$1' does not refer to a commit"
867 die "You must provide exactly one revision. Got: '$*'"
870 if test -n "$arg_split_rejoin"
875 debug "Splitting $dir..."
876 cache_setup || exit $?
878 if test -n "$arg_split_onto"
880 debug "Reading history for --onto=$arg_split_onto..."
881 git rev-list $arg_split_onto |
884 # the 'onto' history is already just the subdir, so
885 # any parent we find there can be used verbatim
887 cache_set "$rev" "$rev"
891 unrevs="$(find_existing_splits "$dir" "$rev")" || exit $?
893 # We can't restrict rev-list to only $dir here, because some of our
894 # parents have the $dir contents the root, and those won't match.
895 # (and rev-list --follow doesn't seem to solve this)
896 grl='git rev-list --topo-order --reverse --parents $rev $unrevs'
897 revmax=$(eval "$grl" | wc -l)
902 while read rev parents
904 process_split_commit "$rev" "$parents"
907 latest_new=$(cache_get latest_new) || exit $?
908 if test -z "$latest_new"
910 die "No new revisions were found"
913 if test -n "$arg_split_rejoin"
915 debug "Merging split branch into HEAD..."
916 latest_old=$(cache_get latest_old) || exit $?
917 arg_addmerge_message="$(rejoin_msg "$dir" "$latest_old" "$latest_new")" || exit $?
918 if test -z "$(find_latest_squash "$dir")"
920 cmd_add "$latest_new" >&2 || exit $?
922 cmd_merge "$latest_new" >&2 || exit $?
925 if test -n "$arg_split_branch"
927 if rev_exists "refs/heads/$arg_split_branch"
929 if ! git merge-base --is-ancestor "$arg_split_branch" "$latest_new"
931 die "Branch '$arg_split_branch' is not an ancestor of commit '$latest_new'."
937 git update-ref -m 'subtree split' \
938 "refs/heads/$arg_split_branch" "$latest_new" || exit $?
939 say >&2 "$action branch '$arg_split_branch'"
945 # Usage: cmd_merge REV
948 die "You must provide exactly one revision. Got: '$*'"
949 rev=$(git rev-parse -q --verify "$1^{commit}") ||
950 die "'$1' does not refer to a commit"
953 if test -n "$arg_addmerge_squash"
955 first_split="$(find_latest_squash "$dir")" || exit $?
956 if test -z "$first_split"
958 die "Can't squash-merge: '$dir' was never added."
963 if test "$sub" = "$rev"
965 say >&2 "Subtree is already at commit $rev."
968 new=$(new_squash_commit "$old" "$sub" "$rev") || exit $?
969 debug "New squash commit: $new"
973 if test -n "$arg_addmerge_message"
975 git merge -Xsubtree="$arg_prefix" \
976 --message="$arg_addmerge_message" "$rev"
978 git merge -Xsubtree="$arg_prefix" $rev
982 # Usage: cmd_pull REPOSITORY REMOTEREF
986 die "You must provide <repository> <ref>"
989 ensure_valid_ref_format "$2"
990 git fetch "$@" || exit $?
994 # Usage: cmd_push REPOSITORY [+][LOCALREV:]REMOTEREF
998 die "You must provide <repository> <refspec>"
1004 remoteref=${refspec#*:}
1005 if test "$remoteref" = "$refspec"
1007 localrevname_presplit=HEAD
1009 localrevname_presplit=${refspec%%:*}
1011 ensure_valid_ref_format "$remoteref"
1012 localrev_presplit=$(git rev-parse -q --verify "$localrevname_presplit^{commit}") ||
1013 die "'$localrevname_presplit' does not refer to a commit"
1015 echo "git push using: " "$repository" "$refspec"
1016 localrev=$(cmd_split "$localrev_presplit") || die
1017 git push "$repository" "$localrev":"refs/heads/$remoteref"
1019 die "'$dir' must already exist. Try 'git subtree add'."