Created
January 6, 2025 18:01
-
-
Save raxityo/472463857fffe994819cd1a85bb1182e to your computer and use it in GitHub Desktop.
git_search - Search for a term in git history and return related GitHub PRs or commit links
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
#!/bin/bash | |
# Search for a term in git history and return related GitHub PRs or commit links | |
# Usage: git_search [-r] <search_string> | |
# -r: use regex pattern matching instead of exact string matching | |
# | |
# Examples: | |
# git_search "someFunction" | |
# git_search -r ".*Pattern.*" | |
function git_search() { | |
if [ -z "$1" ]; then | |
echo "Usage: git_search [-r] <search_string>" | |
echo " -r: use regex pattern matching" | |
return 1 | |
fi | |
local use_regex=0 | |
local search_term="" | |
# Parse arguments | |
while [[ $# -gt 0 ]]; do | |
case $1 in | |
-r) | |
use_regex=1 | |
shift | |
;; | |
*) | |
search_term="$1" | |
shift | |
;; | |
esac | |
done | |
if [ -z "$search_term" ]; then | |
echo "Error: No search term provided" | |
return 1 | |
fi | |
echo "π Finding changes for: $search_term" | |
echo "----------------------------------------" | |
# Get all matching commits | |
if [ $use_regex -eq 1 ]; then | |
# Use -G for regex search | |
commit_hashes=$(git log -G "$search_term" --pretty=format:"%H" --max-count=10) | |
else | |
# Use -S for exact string search | |
commit_hashes=$(git log -S "$search_term" --pretty=format:"%H" --max-count=10) | |
fi | |
if [ -z "$commit_hashes" ]; then | |
echo "β No commits found containing: $search_term" | |
return 1 | |
fi | |
repo_url=$(gh repo view --json url -q .url) | |
# For each commit hash | |
echo "$commit_hashes" | while read -r commit_hash; do | |
echo "\nπ¦ Commit: $commit_hash" | |
echo "----------------------------------------" | |
# Try to find associated PR using GitHub's search syntax | |
pr_info=$(gh search prs --json number,title,url,state --jq '.[0]' "$commit_hash") | |
if [ -n "$pr_info" ] && [ "$pr_info" != "null" ]; then | |
echo "π Pull Request:" | |
echo "$pr_info" | jq -r '"\(.title)\n\(.url) (\(.state))"' | |
else | |
# If no PR found, get the commit URL | |
echo "π Direct commit link (no PR found):" | |
echo "$repo_url/commit/$commit_hash" | |
# Show commit details | |
git log -1 --pretty=format:"Author: %an%nDate: %ad%nMessage: %s" $commit_hash | |
fi | |
echo "----------------------------------------" | |
done | |
} | |
# Aliases for git_search - exact string search and regex search | |
alias g_search='git_search' | |
alias g_grep='git_search -r' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment