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> <ref>
35 P,prefix= the name of the subdir to split out
36 m,message= use the given message as the commit message for the merge commit
38 annotate= add a prefix to commit message of new commits
39 b,branch= create a new branch from the split subtree
40 ignore-joins ignore prior --rejoin commits
41 onto= try connecting new tree to an existing one
42 rejoin merge the new branch back into HEAD
43 options for 'add' and 'merge' (also: 'pull')
44 squash merge subtree changes as a single commit
53 arg_split_ignore_joins=
60 # Usage: debug [MSG...]
62 if test -n "$arg_debug"
64 printf "%$(($indent * 2))s%s\n" '' "$*" >&2
68 # Usage: progress [MSG...]
70 if test -z "$GIT_QUIET"
72 if test -z "$arg_debug"
76 # Print one progress line that we keep updating (use
77 # "\r" to return to the beginning of the line, rather
78 # than "\n" to start a new line). This only really
79 # works when stderr is a terminal.
80 printf "%s\r" "$*" >&2
82 # Debug mode is on. The `debug` function is regularly
85 # Don't do the one-line-with-"\r" thing, because on a
86 # terminal the debug output would overwrite and hide the
87 # progress output. Add a "progress:" prefix to make the
88 # progress output and the debug output easy to
89 # distinguish. This ensures maximum readability whether
90 # stderr is a terminal or a file.
91 printf "progress: %s\n" "$*" >&2
96 # Usage: assert CMD...
100 die "assertion failed: $*"
109 eval "$(echo "$OPTS_SPEC" | git rev-parse --parseopt -- "$@" || echo exit $?)"
126 arg_split_annotate="$1"
133 arg_split_branch="$1"
141 arg_addmerge_message="$1"
161 arg_split_ignore_joins=1
164 arg_split_ignore_joins=
167 arg_addmerge_squash=1
176 die "Unexpected option: $opt"
184 case "$arg_command" in
185 add|merge|pull|split|push)
189 die "Unknown command '$arg_command'"
193 if test -z "$arg_prefix"
195 die "You must provide the --prefix option."
198 case "$arg_command" in
200 test -e "$arg_prefix" &&
201 die "prefix '$arg_prefix' already exists."
204 test -e "$arg_prefix" ||
205 die "'$arg_prefix' does not exist; use 'git subtree add'"
209 dir="$(dirname "$arg_prefix/.")"
211 debug "command: {$arg_command}"
212 debug "quiet: {$GIT_QUIET}"
217 "cmd_$arg_command" "$@"
223 cachedir="$GIT_DIR/subtree-cache/$$"
224 rm -rf "$cachedir" ||
225 die "Can't delete old cachedir: $cachedir"
226 mkdir -p "$cachedir" ||
227 die "Can't create new cachedir: $cachedir"
228 mkdir -p "$cachedir/notree" ||
229 die "Can't create new cachedir: $cachedir/notree"
230 debug "Using cachedir: $cachedir" >&2
233 # Usage: cache_get [REVS...]
237 if test -r "$cachedir/$oldrev"
239 read newrev <"$cachedir/$oldrev"
245 # Usage: cache_miss [REVS...]
249 if ! test -r "$cachedir/$oldrev"
256 # Usage: check_parents PARENTS_EXPR
259 missed=$(cache_miss "$1") || exit $?
260 local indent=$(($indent + 1))
263 if ! test -r "$cachedir/notree/$miss"
265 debug "incorrect order: $miss"
266 process_split_commit "$miss" ""
271 # Usage: set_notree REV
274 echo "1" > "$cachedir/notree/$1"
277 # Usage: cache_set OLDREV NEWREV
282 if test "$oldrev" != "latest_old" &&
283 test "$oldrev" != "latest_new" &&
284 test -e "$cachedir/$oldrev"
286 die "cache for $oldrev already exists!"
288 echo "$newrev" >"$cachedir/$oldrev"
291 # Usage: rev_exists REV
294 if git rev-parse "$1" >/dev/null 2>&1
302 # Usage: try_remove_previous REV
304 # If a commit doesn't have a parent, this might not work. But we only want
305 # to remove the parent from the rev-list, and since it doesn't exist, it won't
306 # be there anyway, so do nothing in that case.
307 try_remove_previous () {
315 # Usage: find_latest_squash DIR
316 find_latest_squash () {
318 debug "Looking for latest squash ($dir)..."
319 local indent=$(($indent + 1))
325 git log --grep="^git-subtree-dir: $dir/*\$" \
326 --no-show-signature --pretty=format:'START %H%n%s%n%n%b%nEND%n' HEAD |
330 debug "{{$sq/$main/$sub}}"
335 git-subtree-mainline:)
339 sub="$(git rev-parse "$b^{commit}")" ||
340 die "could not rev-parse split hash $b from commit $sq"
348 # Pretend its sub was a squash.
351 debug "Squash found: $sq $sub"
363 # Usage: find_existing_splits DIR REV
364 find_existing_splits () {
366 debug "Looking for prior splits..."
367 local indent=$(($indent + 1))
373 local grep_format="^git-subtree-dir: $dir/*\$"
374 if test -n "$arg_split_ignore_joins"
376 grep_format="^Add '$dir/' from commit '"
378 git log --grep="$grep_format" \
379 --no-show-signature --pretty=format:'START %H%n%s%n%n%b%nEND%n' "$rev" |
386 git-subtree-mainline:)
390 sub="$(git rev-parse "$b^{commit}")" ||
391 die "could not rev-parse split hash $b from commit $sq"
394 debug "Main is: '$main'"
395 if test -z "$main" -a -n "$sub"
397 # squash commits refer to a subtree
398 debug " Squash: $sq from $sub"
399 cache_set "$sq" "$sub"
401 if test -n "$main" -a -n "$sub"
403 debug " Prior: $main -> $sub"
406 try_remove_previous "$main"
407 try_remove_previous "$sub"
416 # Usage: copy_commit REV TREE FLAGS_STR
419 # We're going to set some environment vars here, so
420 # do it in a subshell to get rid of them safely later
421 debug copy_commit "{$1}" "{$2}" "{$3}"
422 git log -1 --no-show-signature --pretty=format:'%an%n%ae%n%aD%n%cn%n%ce%n%cD%n%B' "$1" |
425 read GIT_AUTHOR_EMAIL
427 read GIT_COMMITTER_NAME
428 read GIT_COMMITTER_EMAIL
429 read GIT_COMMITTER_DATE
430 export GIT_AUTHOR_NAME \
434 GIT_COMMITTER_EMAIL \
437 printf "%s" "$arg_split_annotate"
440 git commit-tree "$2" $3 # reads the rest of stdin
441 ) || die "Can't copy commit $1"
444 # Usage: add_msg DIR LATEST_OLD LATEST_NEW
450 if test -n "$arg_addmerge_message"
452 commit_message="$arg_addmerge_message"
454 commit_message="Add '$dir/' from commit '$latest_new'"
459 git-subtree-dir: $dir
460 git-subtree-mainline: $latest_old
461 git-subtree-split: $latest_new
465 # Usage: add_squashed_msg REV DIR
466 add_squashed_msg () {
468 if test -n "$arg_addmerge_message"
470 echo "$arg_addmerge_message"
472 echo "Merge commit '$1' as '$2'"
476 # Usage: rejoin_msg DIR LATEST_OLD LATEST_NEW
482 if test -n "$arg_addmerge_message"
484 commit_message="$arg_addmerge_message"
486 commit_message="Split '$dir/' into commit '$latest_new'"
491 git-subtree-dir: $dir
492 git-subtree-mainline: $latest_old
493 git-subtree-split: $latest_new
497 # Usage: squash_msg DIR OLD_SUBTREE_COMMIT NEW_SUBTREE_COMMIT
503 newsub_short=$(git rev-parse --short "$newsub")
507 oldsub_short=$(git rev-parse --short "$oldsub")
508 echo "Squashed '$dir/' changes from $oldsub_short..$newsub_short"
510 git log --no-show-signature --pretty=tformat:'%h %s' "$oldsub..$newsub"
511 git log --no-show-signature --pretty=tformat:'REVERT: %h %s' "$newsub..$oldsub"
513 echo "Squashed '$dir/' content from commit $newsub_short"
517 echo "git-subtree-dir: $dir"
518 echo "git-subtree-split: $newsub"
521 # Usage: toptree_for_commit COMMIT
522 toptree_for_commit () {
525 git rev-parse --verify "$commit^{tree}" || exit $?
528 # Usage: subtree_for_commit COMMIT DIR
529 subtree_for_commit () {
533 git ls-tree "$commit" -- "$dir" |
534 while read mode type tree name
536 assert test "$name" = "$dir"
537 assert test "$type" = "tree" -o "$type" = "commit"
538 test "$type" = "commit" && continue # ignore submodules
544 # Usage: tree_changed TREE [PARENTS...]
551 return 0 # weird parents, consider it changed
553 ptree=$(toptree_for_commit $1) || exit $?
554 if test "$ptree" != "$tree"
558 return 1 # not changed
563 # Usage: new_squash_commit OLD_SQUASHED_COMMIT OLD_NONSQUASHED_COMMIT NEW_NONSQUASHED_COMMIT
564 new_squash_commit () {
569 tree=$(toptree_for_commit $newsub) || exit $?
572 squash_msg "$dir" "$oldsub" "$newsub" |
573 git commit-tree "$tree" -p "$old" || exit $?
575 squash_msg "$dir" "" "$newsub" |
576 git commit-tree "$tree" || exit $?
580 # Usage: copy_or_skip REV TREE NEWPARENTS
586 assert test -n "$tree"
593 for parent in $newparents
595 ptree=$(toptree_for_commit $parent) || exit $?
596 test -z "$ptree" && continue
597 if test "$ptree" = "$tree"
599 # an identical parent could be used in place of this rev.
600 if test -n "$identical"
602 # if a previous identical parent was found, check whether
603 # one is already an ancestor of the other
604 mergebase=$(git merge-base $identical $parent)
605 if test "$identical" = "$mergebase"
607 # current identical commit is an ancestor of parent
609 elif test "$parent" != "$mergebase"
611 # no common history; commit must be copied
615 # first identical parent detected
619 nonidentical="$parent"
622 # sometimes both old parents map to the same newparent;
623 # eliminate duplicates
625 for gp in $gotparents
627 if test "$gp" = "$parent"
635 gotparents="$gotparents $parent"
640 if test -n "$identical" && test -n "$nonidentical"
642 extras=$(git rev-list --count $identical..$nonidentical)
643 if test "$extras" -ne 0
645 # we need to preserve history along the other branch
649 if test -n "$identical" && test -z "$copycommit"
653 copy_commit "$rev" "$tree" "$p" || exit $?
657 # Usage: ensure_clean
660 if ! git diff-index HEAD --exit-code --quiet 2>&1
662 die "Working tree has modifications. Cannot add."
664 if ! git diff-index --cached HEAD --exit-code --quiet 2>&1
666 die "Index has modifications. Cannot add."
670 # Usage: ensure_valid_ref_format REF
671 ensure_valid_ref_format () {
673 git check-ref-format "refs/heads/$1" ||
674 die "'$1' does not look like a ref"
677 # Usage: process_split_commit REV PARENTS
678 process_split_commit () {
683 if test $indent -eq 0
685 revcount=$(($revcount + 1))
687 # processing commit without normal parent information;
689 parents=$(git rev-parse "$rev^@")
690 extracount=$(($extracount + 1))
693 progress "$revcount/$revmax ($createcount) [$extracount]"
695 debug "Processing commit: $rev"
696 local indent=$(($indent + 1))
697 exists=$(cache_get "$rev") || exit $?
700 debug "prior: $exists"
703 createcount=$(($createcount + 1))
704 debug "parents: $parents"
705 check_parents "$parents"
706 newparents=$(cache_get $parents) || exit $?
707 debug "newparents: $newparents"
709 tree=$(subtree_for_commit "$rev" "$dir") || exit $?
710 debug "tree is: $tree"
712 # ugly. is there no better way to tell if this is a subtree
713 # vs. a mainline commit? Does it matter?
717 if test -n "$newparents"
719 cache_set "$rev" "$rev"
724 newrev=$(copy_or_skip "$rev" "$tree" "$newparents") || exit $?
725 debug "newrev is: $newrev"
726 cache_set "$rev" "$newrev"
727 cache_set latest_new "$newrev"
728 cache_set latest_old "$rev"
732 # Or: cmd_add REPOSITORY REF
739 git rev-parse -q --verify "$1^{commit}" >/dev/null ||
740 die "'$1' does not refer to a commit"
746 # Technically we could accept a refspec here but we're
747 # just going to turn around and add FETCH_HEAD under the
748 # specified directory. Allowing a refspec might be
749 # misleading because we won't do anything with any other
750 # branches fetched via the refspec.
751 ensure_valid_ref_format "$2"
753 cmd_add_repository "$@"
755 say >&2 "error: parameters were '$*'"
756 die "Provide either a commit or a repository and commit."
760 # Usage: cmd_add_repository REPOSITORY REFSPEC
761 cmd_add_repository () {
763 echo "git fetch" "$@"
766 git fetch "$@" || exit $?
767 cmd_add_commit FETCH_HEAD
770 # Usage: cmd_add_commit REV
772 # The rev has already been validated by cmd_add(), we just
773 # need to normalize it.
775 rev=$(git rev-parse --verify "$1^{commit}") || exit $?
777 debug "Adding $dir as '$rev'..."
778 git read-tree --prefix="$dir" $rev || exit $?
779 git checkout -- "$dir" || exit $?
780 tree=$(git write-tree) || exit $?
782 headrev=$(git rev-parse HEAD) || exit $?
783 if test -n "$headrev" && test "$headrev" != "$rev"
790 if test -n "$arg_addmerge_squash"
792 rev=$(new_squash_commit "" "" "$rev") || exit $?
793 commit=$(add_squashed_msg "$rev" "$dir" |
794 git commit-tree "$tree" $headp -p "$rev") || exit $?
796 revp=$(peel_committish "$rev") || exit $?
797 commit=$(add_msg "$dir" $headrev "$rev" |
798 git commit-tree "$tree" $headp -p "$revp") || exit $?
800 git reset "$commit" || exit $?
802 say >&2 "Added dir '$dir'"
805 # Usage: cmd_split [REV]
809 rev=$(git rev-parse HEAD)
812 rev=$(git rev-parse -q --verify "$1^{commit}") ||
813 die "'$1' does not refer to a commit"
815 die "You must provide exactly one revision. Got: '$*'"
818 debug "Splitting $dir..."
819 cache_setup || exit $?
821 if test -n "$arg_split_onto"
823 debug "Reading history for --onto=$arg_split_onto..."
824 git rev-list $arg_split_onto |
827 # the 'onto' history is already just the subdir, so
828 # any parent we find there can be used verbatim
830 cache_set "$rev" "$rev"
834 unrevs="$(find_existing_splits "$dir" "$rev")" || exit $?
836 # We can't restrict rev-list to only $dir here, because some of our
837 # parents have the $dir contents the root, and those won't match.
838 # (and rev-list --follow doesn't seem to solve this)
839 grl='git rev-list --topo-order --reverse --parents $rev $unrevs'
840 revmax=$(eval "$grl" | wc -l)
845 while read rev parents
847 process_split_commit "$rev" "$parents"
850 latest_new=$(cache_get latest_new) || exit $?
851 if test -z "$latest_new"
853 die "No new revisions were found"
856 if test -n "$arg_split_rejoin"
858 debug "Merging split branch into HEAD..."
859 latest_old=$(cache_get latest_old) || exit $?
861 --allow-unrelated-histories \
862 -m "$(rejoin_msg "$dir" "$latest_old" "$latest_new")" \
863 "$latest_new" >&2 || exit $?
865 if test -n "$arg_split_branch"
867 if rev_exists "refs/heads/$arg_split_branch"
869 if ! git merge-base --is-ancestor "$arg_split_branch" "$latest_new"
871 die "Branch '$arg_split_branch' is not an ancestor of commit '$latest_new'."
877 git update-ref -m 'subtree split' \
878 "refs/heads/$arg_split_branch" "$latest_new" || exit $?
879 say >&2 "$action branch '$arg_split_branch'"
885 # Usage: cmd_merge REV
888 die "You must provide exactly one revision. Got: '$*'"
889 rev=$(git rev-parse -q --verify "$1^{commit}") ||
890 die "'$1' does not refer to a commit"
893 if test -n "$arg_addmerge_squash"
895 first_split="$(find_latest_squash "$dir")" || exit $?
896 if test -z "$first_split"
898 die "Can't squash-merge: '$dir' was never added."
903 if test "$sub" = "$rev"
905 say >&2 "Subtree is already at commit $rev."
908 new=$(new_squash_commit "$old" "$sub" "$rev") || exit $?
909 debug "New squash commit: $new"
913 if test -n "$arg_addmerge_message"
915 git merge -Xsubtree="$arg_prefix" \
916 --message="$arg_addmerge_message" "$rev"
918 git merge -Xsubtree="$arg_prefix" $rev
922 # Usage: cmd_pull REPOSITORY REMOTEREF
926 die "You must provide <repository> <ref>"
929 ensure_valid_ref_format "$2"
930 git fetch "$@" || exit $?
934 # Usage: cmd_push REPOSITORY REMOTEREF
938 die "You must provide <repository> <ref>"
940 ensure_valid_ref_format "$2"
945 echo "git push using: " "$repository" "$refspec"
946 localrev=$(git subtree split --prefix="$arg_prefix") || die
947 git push "$repository" "$localrev":"refs/heads/$refspec"
949 die "'$dir' must already exist. Try 'git subtree add'."