Skip to content

Instantly share code, notes, and snippets.

@tschoffelen

tschoffelen/README.md

Last active May 30, 2020
Embed
What would you like to do?
Some of my personal Git utility bash commands.

Git utilities

A set of personal bash commands that help me with day-to-day Git operations.

master

Checkout and pull the master branch from origin.

feat <my-new-feature>

Checkout a new feature branch in the form of feat/my-new-feature from master.

browse

Open the repository in the browser (GitHub/GitLab).

pr

Open the GitHub or GitLab UI in the browser to create a new PR/MR based on the current branch.

cleanbranches

Fetches from remote and removes all merged branches.

#!/usr/bin/env bash
# Git-related helpers.
# --- Checkout master
master () {
# Get back to master branch
git checkout master
# Update local master
git pull
}
# --- Create a new feature branch
feat () {
# Check if the argument is set
if [ "$1" = "" ]; then
echo "Usage: $0 <feature-name>" 1>&2
return
fi
# Make sure we start from master
git checkout master
# And make sure our local master is up to date
git pull
# Then create new branch
git checkout -b "feat/$1"
}
# --- Open in browser (GitHub/GitLab)
browse () {
# Open browser
open "$(_git_repo_url)"
}
# --- Open new PR/MR for current branch
pr () {
# Get Git remote
REMOTE=$(git remote get-url --push origin)
# Depending on github.com/gitlab.com being present, open correct URL
if [[ "$REMOTE" == *"gitlab.com"* ]]; then
open "$(_git_repo_url)/-/merge_requests/new?merge_request%5Bsource_branch%5D=$(git rev-parse --abbrev-ref HEAD)"
else
open "$(_git_repo_url)/compare/$(git rev-parse --abbrev-ref HEAD)?expand=1"
fi
}
# --- Clean branches
cleanbranches () {
# Fetch and prune
git fetch --all --prune --prune-tags
# Delete merged brances
git branch --merged | egrep -v "(^\*|master|dev|release)" | xargs git branch -d
# Run garbage collection
git gc
}
# --- Helper function to determine repo URL
_git_repo_url () {
# Get remote URL for origin
REMOTE="$(git remote get-url --push origin)"
# Check for HTTP/HTTPS urls
if [[ "${REMOTE}" == *"https://"* ]]; then
echo "${REMOTE%.git}"
elif [[ "${REMOTE}" == *"http://"* ]]; then
echo "${REMOTE%.git}"
# Or gitlab SSH-style origin
elif [[ "${REMOTE}" == *"gitlab.com"* ]]; then
REMOTE="${REMOTE##*:}"
echo "https://gitlab.com/${REMOTE%.git}"
# Or github SSH-style origin
elif [[ "${REMOTE}" == *"github.com"* ]]; then
REMOTE="${REMOTE##*:}"
echo "https://github.com/${REMOTE%.git}"
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment