Back to Blog

Git Aliases, Hooks & Statistics from the Terminal — Zsh #29

Sandy LaneSandy Lane

Video: Git Aliases, Hooks & Statistics from the Terminal — Zsh #29 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Git Aliases, Hooks & Statistics from the Terminal — Zsh #29

Streamline your Git workflow by creating custom aliases, automating branch management, and using pre-commit hooks to maintain code quality. This guide demonstrates how to configure Git and Zsh scripts that simplify common tasks and generate insightful repository statistics right from your terminal.

Code

# Example: Define a Git alias to show a concise, colored log
git config --global alias.lg "log --color --graph --pretty=format:'%C(auto)%h%d %s %C(blue)<%an>%Creset' --abbrev-commit"

# Zsh function to clean up merged branches except main and develop
git_cleanup_branches() {
  local protected_branches="main develop"
  # Fetch remote updates
  git fetch --prune
  # List merged branches excluding protected ones and current branch
  git branch --merged | grep -vE "(^\*|$(echo $protected_branches | sed 's/ /|/g'))" | while read branch; do
    git branch -d "$branch"
  done
}

# Sample pre-commit hook script to prevent commits with TODO comments
cat > .git/hooks/pre-commit << 'EOF'
#!/bin/sh
if git diff --cached | grep -q 'TODO'; then
  echo "Error: Commit contains TODO comments. Please resolve them before committing."
  exit 1
fi
EOF
chmod +x .git/hooks/pre-commit

# Script to show contributor statistics by number of commits
git shortlog -s -n --all --no-merges

Key Points

  • Git aliases simplify complex commands, making your workflow faster and easier to remember.
  • Zsh functions can automate branch cleanup by deleting merged branches while protecting important ones.
  • Pre-commit hooks help enforce code quality by blocking commits with unwanted patterns like TODO comments.
  • Using git shortlog provides a quick overview of team contributions sorted by commit count.
  • Combining Git configuration and shell scripting empowers you to customize and automate your development process.