Skip to content

Instantly share code, notes, and snippets.

@jsr-p
Created June 21, 2024 11:17
Show Gist options
  • Save jsr-p/4ab2def679e8de538b86f96f8c30c412 to your computer and use it in GitHub Desktop.
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
#!/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
@jsr-p
Copy link
Author

jsr-p commented Jun 21, 2024

vim mappings

function GetFileRow()
	local row, _ = unpack(vim.api.nvim_win_get_cursor(0))
	local fp = vim.api.nvim_buf_get_name(0)
	return {
		file = fp,
		row = row,
	}
end
vim.keymap.set("n", "<leader>ghl", function()
	local file_row = GetFileRow()
	vim.fn.system({ "ghcp", file_row.file, tostring(file_row.row) })
	print("Copied github link with line number to clipboard!")
end, opts)

vim.keymap.set("n", "<leader>ghf", function()
	local file_row = GetFileRow()
	vim.fn.system({ "ghcp", file_row.file })
	print("Copied github link to clipboard!")
end, opts)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment