Skip to content

Instantly share code, notes, and snippets.

@brunogama
Created September 6, 2024 14:21
Show Gist options
  • Save brunogama/9bd73c750db59f94dac55e1d5b666865 to your computer and use it in GitHub Desktop.
Save brunogama/9bd73c750db59f94dac55e1d5b666865 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Check if both directory name and branch name are provided
if [ $# -lt 2 ]; then
echo "Usage: $0 <worktree_directory> <branch_name>"
exit 1
fi
# Set the worktree directory name and branch name
WORKTREE_DIR="$1"
BRANCH_NAME="$2"
# Get the absolute path of the main repository
MAIN_REPO=$(git rev-parse --show-toplevel)
# Create the worktree for the main repository with the new branch
git worktree add -b "$BRANCH_NAME" "$WORKTREE_DIR"
# Change to the new worktree directory
cd "$WORKTREE_DIR" || exit
# Initialize submodules in the new worktree
git submodule update --init
# Function to create a worktree for a submodule
create_submodule_worktree() {
local submodule_path="$1"
local submodule_name=$(basename "$submodule_path")
local submodule_worktree="$WORKTREE_DIR/$submodule_name"
echo "Creating worktree for submodule: $submodule_name"
# Navigate to the original submodule directory
cd "$MAIN_REPO/$submodule_path" || return
# Get the current branch of the submodule
local current_branch=$(git rev-parse --abbrev-ref HEAD)
# Create a new worktree for the submodule with a new branch
git worktree add -b "${BRANCH_NAME}_${submodule_name}" "$submodule_worktree"
# Navigate back to the main worktree
cd "$WORKTREE_DIR" || return
# Remove the submodule directory and replace it with the new worktree
rm -rf "$submodule_name"
mv "$submodule_worktree" "$submodule_name"
# Navigate into the submodule worktree
cd "$submodule_name" || return
# Set the branch to track the original branch
git branch --set-upstream-to="origin/$current_branch" "${BRANCH_NAME}_${submodule_name}"
# Navigate back to the main worktree
cd "$WORKTREE_DIR" || return
}
# Get a list of submodules
SUBMODULES=$(git config --file .gitmodules --get-regexp path | awk '{ print $2 }')
# Create worktrees for each submodule
echo "$SUBMODULES" | while read -r submodule_path; do
create_submodule_worktree "$submodule_path"
done
echo "Worktree created at $WORKTREE_DIR with branch $BRANCH_NAME and submodule worktrees"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment