Last active
November 8, 2024 18:23
-
-
Save coltenkrauter/3e6a2f71cc6e37b03f227b8c7a8f7825 to your computer and use it in GitHub Desktop.
Automatically switches to main, pulls latest changes, and creates a branch feature/user/YYYY-MM-DD/INDEX, incrementing the index if branches exist for the day. Streamlines date-indexed feature branch creation in Git.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Creates a feature branch with date-indexed naming based on $USER. | |
# Add this function to your .bashrc or .zshrc file for easy access in every terminal session. | |
# | |
# Example: | |
# If $USER is "ckrauter" and today is 2024-11-08: | |
# Running `fb` creates a branch like `feature/ckrauter/2024-11-08/1`. | |
# Running `fb utils package` creates `feature/ckrauter/utils-package/2024-11-08/1`. | |
feature_branch() { | |
local main_branch="main" | |
local prefix="feature" | |
local today=$(date +%Y-%m-%d) | |
local username=$(echo "$USER" | tr '[:upper:]' '[:lower:]') # Convert $USER to lowercase | |
local additional_path=$(echo "$*" | tr ' ' '-') # Convert arguments to hyphen-separated string | |
local index=1 | |
local new_branch | |
# Construct the branch path prefix with optional additional path | |
local branch_path="${prefix}/${username}" | |
[[ -n "$additional_path" ]] && branch_path="${branch_path}/${additional_path}" | |
branch_path="${branch_path}/${today}" | |
# Switch to main branch and pull latest changes if not on main | |
if [[ "$(git branch --show-current)" != "$main_branch" ]]; then | |
echo "Switching to ${main_branch} and pulling latest changes..." | |
git checkout $main_branch | |
git pull | |
fi | |
# Find the next available branch index for today | |
while git rev-parse --verify --quiet "${branch_path}/${index}"; do | |
index=$((index + 1)) | |
done | |
# Create and switch to the new branch | |
new_branch="${branch_path}/${index}" | |
echo "Creating and checking out ${new_branch}..." | |
git checkout -b $new_branch | |
} | |
alias fb="feature_branch" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment