-
-
Save jsr-p/4ab2def679e8de538b86f96f8c30c412 to your computer and use it in GitHub Desktop.
Script to get link to github for current file (with optional line number) and either copied to clipboard or printed to stdout
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 | |
usage() { | |
echo "Usage: ghcp [--stdout] <file_path> [line_number]" | |
exit 1 | |
} | |
# Initialize variables | |
STDOUT=false | |
# Parse the flags and arguments | |
while [[ "$1" =~ ^- ]]; do | |
case $1 in | |
--stdout ) | |
STDOUT=true | |
shift | |
;; | |
* ) | |
usage | |
;; | |
esac | |
done | |
# Check if the file path is provided | |
if [ -z "$1" ]; then | |
usage | |
fi | |
# Get the file path from the first positional argument | |
FILE_PATH=$1 | |
# Get the remote URL | |
REMOTE_URL=$(git remote get-url origin) | |
# Get the current branch name | |
BRANCH_NAME=$(git branch --show-current) | |
# Convert SSH URL to HTTPS URL | |
if [[ $REMOTE_URL == [email protected]:* ]]; then | |
REPO_NAME=$(echo "$REMOTE_URL" | sed 's|[email protected]:\(.*\)\.git|\1|') | |
HTTPS_URL="https://github.com/${REPO_NAME}" | |
else | |
HTTPS_URL="${REMOTE_URL%.git}" | |
fi | |
GITDIR=$(git rev-parse --show-toplevel) | |
RELATIVE_PATH=$(realpath "$FILE_PATH" --relative-to="$GITDIR") | |
# Construct the GitHub URL | |
GITHUB_URL="${HTTPS_URL}/blob/${BRANCH_NAME}/${RELATIVE_PATH}" | |
# Append line number if provided | |
if [ -n "$2" ]; then | |
GITHUB_URL="${GITHUB_URL}#L$2" | |
fi | |
# Echo to stdout or copy to clipboard based on the --stdout flag | |
if $STDOUT; then | |
echo "$GITHUB_URL" | |
else | |
echo "$GITHUB_URL" | wl-copy | |
fi | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
vim mappings