Created
November 13, 2024 15:08
-
-
Save aztack/4c2b4d8fdf737f175855495c87887e75 to your computer and use it in GitHub Desktop.
git-pick
This file contains hidden or 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/sh | |
# | |
# 'tig-pick' is a wrapper script that uses 'tig' to pick a Git commit from the | |
# history. On success, the script prints the ID of the commit to standard | |
# output, so that it can be used as a parameter for subsequent commands, e.g., | |
# 'git rebase -i $(tig-pick)' | |
# | |
# All parameters passed to the script will be forwarded to 'tig'. | |
# | |
set -e | |
CONFIG=$(mktemp) | |
trap "rm -f '$CONFIG'" EXIT | |
# Prepare config file: source user config, if present | |
if [ ! -z "$TIGRC_USER" ]; then | |
echo "source $TIGRC_USER" >> "$CONFIG" | |
elif [ -f "$HOME/.tigrc" ]; then | |
echo "source $HOME/.tigrc" >> "$CONFIG" | |
fi | |
# Bind Enter to print the selected commit ID to error output and exit after | |
# that. | |
echo 'bind main <Enter> <sh -c "echo %(commit) >&2"' >> "$CONFIG" | |
# Run tig with the standard and error output channels swapped. | |
export TIGRC_USER=$CONFIG | |
stderr=$(tig "$@" 3>&2 2>&1 1>&3 3>&-) || { | |
status=$? | |
echo "$stderr" >&2 | |
exit $status | |
} | |
# Extract the commit hash | |
commit_hash=$(echo "$stderr" | tail -n1) | |
# Check return value for valid commit hash | |
if ! printf '%s' "$commit_hash" | grep -iqE '^[0-9a-f]{40}$'; then | |
echo "$stderr" >&2 | |
exit 1 | |
fi | |
# Extract the commit message | |
commit_msg=$(git log --format=%B -n 1 "$commit_hash") | |
# Extract the repository group and name from the git remote URL | |
remote_url=$(git config --get remote.origin.url) | |
# If the remote URL is in SSH format (git@domain:group/repo.git), clean it up | |
if echo "$remote_url" | grep -q "git@"; then | |
# Convert SSH URL to HTTPS format | |
remote_url="https://$(echo "$remote_url" | sed -E 's#git@([^:]+):([^/]+)/([^/]+)\.git#\1/\2/\3#')" | |
else | |
# For HTTPS URLs, just strip out unnecessary parts | |
remote_url="https://$(echo "$remote_url" | sed -E 's#https?://([^/]+)/([^/]+)/([^/]+)\.git#\1/\2/\3#')" | |
fi | |
# Create the commit URL in the proper format | |
commit_url="$remote_url/commit/$commit_hash" | |
# Output the link in Markdown format and copy to clipboard if pbcopy is available | |
echo "[$commit_msg]($commit_url)" | |
echo "[$commit_msg]($commit_url)" | pbcopy |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment