dotfiles/functions/git.zsh

117 lines
3.1 KiB
Bash

# vim:ft=zsh ts=2 sw=2 sts=2
#
# Miscellaneous git helpers
# Create a gitignore for the given argument (e.g. python, cpp, etc)
function gi() { curl -sL https://www.toptal.com/developers/gitignore/api/$@; }
# Completion helper, from requires __completion_wrapper from `misc.zsh`
__git_completion_wrapper() {
# Wrapper for `__git_*` completion functions
# Can be used to force loading of specialized git completions
# When defining custom commands. See below for usage examples.
__completion_wrapper $1 _git
}
# remove local branches which have been merged into master/main
function git-prune-branches(){
local main=$(git_main_branch)
git branch --merged $main | grep -v '^[ * ]*'$main'$' | xargs git branch -d
}
# sort branches by latest commit
function git-sort-branch-by-usage(){
git for-each-ref --sort=committerdate refs/heads/ --format='%(refname:short)'
}
# switch to a recent branch
function git-switch-recent-branch(){
git switch $1
}
# compdef git-sort-branch-by-usage git-switch-recent-branch
compdef "__git_completion_wrapper __git_recent_branches" git-switch-recent-branch
# Runs git log with fzf with preview
function fgitlog() {
git showtool $(git log --oneline $@ | fzf --multi --preview 'git -p show --color=always {+1}' --preview-window=right,60% | awk '{print $1}')
}
compdef _git fgitlog=git-log
function git-commit-show() {
git log --graph --color=always --format="%C(auto)%h%d %s %C(black)%C(bold)%cr" $@ |
fzf --ansi --no-sort --reverse --tiebreak=index --preview \
'f() {
set -- $(echo -- "$@" | grep -o "[a-f0-9]\{7\}")
[ $# -eq 0 ] || git show --color=always $1
}
f {}' \
--bind "j:down,k:up,alt-j:preview-down,alt-k:preview-up,ctrl-f:preview-page-down,ctrl-b:preview-page-up,q:abort,ctrl-m:execute:
(grep -o '[a-f0-9]\{7\}' | head -1 |
xargs -I % sh -c 'git show --color=always % | less -R') << 'FZF-EOF'
{} FZF-EOF" \
--preview-window=right:60%
}
compdef "__git_completion_wrapper __git_recent_commits" git-commit-show
function git-fixup() {
git commit --fixup=$1
git -c sequence.editor=true rebase --interactive --autosquash $1^
}
compdef "__git_completion_wrapper __git_recent_commits" git-fixup
function git-diff-branch() {
git diff $@
}
compdef "__git_completion_wrapper __git_branch_names" git-diff-branch
function git-show-changes(){
git log --reverse HEAD^..
}
unalias gco
function gco() {
if [[ "$#" -ge 1 ]]; then
g checkout $@
elif [[ "$#" -eq 0 ]]; then
g checkout $(gb | fzf)
fi
}
unalias gcor
function gcor() {
if [[ "$#" -ge 1 ]]; then
g checkout $@
elif [[ "$#" -eq 0 ]]; then
g checkout --track $(gbr | fzf)
fi
}
unalias gbd
function gbd() {
if [[ "$#" -ge 1 ]]; then
g branch -d $@
elif [[ "$#" -eq 0 ]]; then
g branch -d $(gb | fzf -m)
fi
}
unalias gbD
function gbD() {
if [[ "$#" -ge 1 ]]; then
g branch -D $@
elif [[ "$#" -eq 0 ]]; then
g branch -D $(gb | fzf -m)
fi
}