Skip to content

Instantly share code, notes, and snippets.

@jkantarek
Created March 6, 2024 15:47
Show Gist options
  • Select an option

  • Save jkantarek/d9ff8632e4c381d504415b7e3625c693 to your computer and use it in GitHub Desktop.

Select an option

Save jkantarek/d9ff8632e4c381d504415b7e3625c693 to your computer and use it in GitHub Desktop.
# Git commands that will make your life substantially easier when navigating re-bases. These are a core part of my personal dotfiles repo.
alias up="git pull --rebase --autostash" # Pulls the latest based on the old ruby shell app for more details see https://github.com/aanand/git-up
alias gcb="git checkout -b" # create a new branch
alias gcm="git commit -m" # create a new commit
alias current_branch="git rev-parse --abbrev-ref HEAD | tr -d '[[:space:]]'" # shows the current branch name, used later on
# shows clear log entries between now and the parent branch
gs() {
PARENT=$(parent_branch_name)
git show --stat --oneline origin/${PARENT}..HEAD
}
# lets me go up a branch and pull the latest
gcmu() {
PARENT=$(parent_branch_name)
git checkout $PARENT; up
}
# same as gcmu but deletes the previous branch so i don't have to wade through a mess
kgcmu() {
BRANCH=$(current_branch)
PARENT=$(parent_branch_name)
git checkout $PARENT
git branch -D $BRANCH
up
}
# the most powerful tool, allows me to rebase _only_ between where my code is and where i branched from
rebase() {
BRANCH=$(parent_branch_name)
COMMITS=$(git shortlog -s -n origin/${BRANCH}..HEAD | tr -dc '0-9')
git rebase HEAD~$COMMITS -i
}
# pushes the current branch i _only_ use `--force-with-lease` after a rebase
gpo() {
BRANCH=$(current_branch)
git push -u origin $1 $BRANCH
}
# all credit goes to chatgpt for this one, my previous version was unreliable in a lot of situations
# see https://chat.openai.com/share/28ad4fcc-2d25-4981-a6ad-51af07ddb366 for the refactor
parent_branch_name() {
# Get the current branch name
local cb=$(current_branch)
# Get all branch refs, excluding the current branch, directly into an array
local -a branches=("${(@f)$(git show-ref --heads | grep -v "refs/heads/$cb$" | awk '{print $2}' | sed 's!refs/heads/!!')}")
# Track the best candidate and its commit date for comparison
local best_candidate=""
local best_candidate_date=0
for branch in $branches; do
# Find the most recent common commit
local common_commit=$(git merge-base $cb $branch)
if [[ -n $common_commit ]]; then
# Get the commit date of the most recent common commit
local commit_date=$(git show -s --format=%ct $common_commit)
# If this is the most recent commit we've found so far, update the best candidate
if [[ $commit_date -gt $best_candidate_date ]]; then
best_candidate=$branch
best_candidate_date=$commit_date
fi
fi
done
# Return the best candidate's name without echoing any additional messages
if [[ -n $best_candidate ]]; then
echo $best_candidate
else
return 1
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment