script to build a GitHub selection link from Helix
0
git-github-link
edited
1#!/usr/bin/env bash
2set -euo pipefail
3
4# Parse -L start,end
5while [[ "${1:-}" == -* ]]; do
6 case "$1" in
7 -L) IFS=',' read -r start end <<< "$2"; shift 2 ;;
8 *) shift ;;
9 esac
10done
11
12file="$1"
13
14# Run git from the file's directory so it works with any CWD
15root=$(git -C "$(dirname "$file")" rev-parse --show-toplevel)
16hash=$(git -C "$(dirname "$file")" rev-parse HEAD)
17remote=$(git -C "$(dirname "$file")" remote get-url origin)
18
19# Normalise SSH or HTTPS remote → owner/repo
20remote="${remote#git@github.com:}"
21remote="${remote#https://github.com/}"
22remote="${remote%.git}"
23
24# Make file path relative to repo root
25relpath="${file#$root/}"
26
27# Build fragment: single line vs range
28if [[ "$start" == "$end" ]]; then
29 fragment="#L${start}"
30else
31 fragment="#L${start}-L${end}"
32fi
33
34url="https://github.com/${remote}/blob/${hash}/${relpath}${fragment}"
35
36if command -v pbcopy &>/dev/null; then
37 echo "$url" | pbcopy
38elif command -v xclip &>/dev/null; then
39 echo "$url" | xclip -selection clipboard
40elif command -v xsel &>/dev/null; then
41 echo "$url" | xsel --clipboard --input
42fi
43echo "$url"