Created
October 2, 2024 17:52
-
-
Save davidgumberg/50c42abd59214a444b2117beb8648369 to your computer and use it in GitHub Desktop.
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
-- Useful for opening the github PR of a commit in fugitive's blame and commit views | |
vim.api.nvim_create_user_command('FindGH', function(opts) | |
local find_pr = true | |
if opts.args and opts.args == "commit" then | |
find_pr = false | |
end | |
local full_hash | |
if vim.b.fugitive_type == 'commit' then | |
local buffer = vim.api.nvim_get_current_buf() | |
local filename = vim.api.nvim_buf_get_name(buffer) | |
full_hash = vim.call('fugitive#Object', filename) | |
else | |
local short_hash = vim.fn.expand('<cword>') | |
full_hash = vim.fn.system(string.format("git rev-parse %s", short_hash)):gsub("\n", "") | |
end | |
local shortest_unique = vim.fn.system(string.format("git rev-parse --short=7 %s", full_hash)) | |
-- Trim whitespace | |
shortest_unique = shortest_unique:gsub("%s+", "") | |
local cmd = string.format("git log --merges --oneline --grep=\"%s\" --reverse", shortest_unique) | |
local output = vim.fn.system(cmd) | |
-- Command to open URL in default browser (this command varies by OS) | |
local open_cmd | |
if vim.fn.has('mac') == 1 then | |
open_cmd = 'open' | |
elseif vim.fn.has('unix') == 1 then | |
open_cmd = 'xdg-open' | |
elseif vim.fn.has('win32') == 1 then | |
open_cmd = 'start' | |
end | |
-- Get the GitHub repo URL | |
local repo_url = vim.fn.system("git config --get remote.origin.url"):gsub("\n", "") | |
repo_url = repo_url:gsub("%.git$", "") | |
repo_url = repo_url:gsub("^git@github%.com:", "https://github.com/") | |
local pr_number = output:match("#(%d+)") | |
local target_url | |
if pr_number and find_pr then | |
-- Construct the full PR URL | |
target_url = string.format("%s/pull/%s", repo_url, pr_number) | |
else | |
-- Couldn't find a PR number, let's open the git commit page | |
target_url = string.format("%s/commit/%s", repo_url, full_hash) | |
end | |
if open_cmd then | |
vim.fn.system(string.format("%s %s", open_cmd, target_url)) | |
else | |
vim.api.nvim_echo({{"Couldn't determine command to open URL", 'ErrorMsg'}}, true, {}) | |
end | |
end, { | |
nargs = '?', | |
}) | |
vim.api.nvim_set_keymap('n', '<leader>gp', ':FindGH<CR>', {noremap = true, silent = true}) | |
vim.api.nvim_set_keymap('n', '<leader>gP', ':FindGH commit<CR>', {noremap = true, silent = true}) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment