Skip to content

Instantly share code, notes, and snippets.

@Teino1978-Corp
Created November 16, 2015 04:39
Show Gist options
  • Save Teino1978-Corp/24f6f6c4bf26cd2d86f3 to your computer and use it in GitHub Desktop.
Save Teino1978-Corp/24f6f6c4bf26cd2d86f3 to your computer and use it in GitHub Desktop.
A lean approach to managing git subtrees manually
#!/usr/bin/env bash
# Add a subtree from a repository
#
# @param 1 - URL of repository
# @param 2 - prefix for repository directory (optional)
add()
{
local NAME=${1##*/}
NAME=${NAME%.*}
[ "$NAME" ] || return $?
git remote add $NAME $1 &&
git fetch --no-tags $NAME &&
git read-tree --prefix=$2$NAME/ -u $NAME/master
}
# Update subtree
#
# @param 1 - name of remote repository
update()
{
[ "$1" ] || return $?
git fetch --no-tags $1 &&
git merge -s subtree --squash $1/master
}
# Print help
help()
{
cat <<EOF
usage: git sub add <repository> <prefix>
or: git sub update <remote>
EOF
}
if [ "$0" == "$BASH_SOURCE" ]
then
${@:-help}
fi

Manage subtrees manually

A lean approach to managing git subtrees manually. Because git-subtree clutters the history graph and git-stree still does too much for me.

I wanted the simplest possible solution that does not require anything special and that does not modify a repository beyond what's required for the most basic approach.

So you may use this script to manage a subtree. But your repository won't depend on it.

Samples

Adding a subtree:

$ git sub add https://github.com/you/component.git

This clones the repository "component" into the directory "component". The directory is now in the staging area and ready to be committed. git-sub won't make any commits.

Later, when you want to update the "component" subtree do:

$ git sub update component

The updated files are now in the staging area and can be committed.

Usage

usage: git sub add    <repository> <prefix>
   or: git sub update <remote>

Use the optional prefix argument to put the repository into a subfolder. By default, repositories are put into the parent repository's root folder.

Cloning

Remotes don't get cloned. So after a repository is cloned, you need to add the remotes for the subtrees again:

$ git remote add component https://github.com/you/component.git

After that, you can use git sub update as before:

$ git sub update component
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment