From 4b48d2af52873a5cf1e2b516f2a7650545b596e4 Mon Sep 17 00:00:00 2001 From: Daniil Tsivinsky Date: Thu, 31 Mar 2022 23:24:25 +0300 Subject: [PATCH] add a bunch of git utility functions --- neovim/.config/nvim/lua/user/utils.lua | 60 ++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/neovim/.config/nvim/lua/user/utils.lua b/neovim/.config/nvim/lua/user/utils.lua index 807dc52..987e83a 100644 --- a/neovim/.config/nvim/lua/user/utils.lua +++ b/neovim/.config/nvim/lua/user/utils.lua @@ -1,3 +1,5 @@ +local Job = require("plenary.job") + local M = {} M.yank = function(message) @@ -51,4 +53,62 @@ M.lsp_organize_imports = function(bufnr, timeout) vim.lsp.buf_request_sync(bufnr, "workspace/executeCommand", params, timeout or 500) end +M.get_commit_hash_for_current_line = function() + local fullpath = vim.api.nvim_buf_get_name(0) + local cwd = vim.loop.cwd() + local relative_path = string.gsub(fullpath, cwd .. "/", "") + + local line = unpack(vim.api.nvim_win_get_cursor(0)) + + local f = io.popen("git blame -L " .. line .. ",+1 " .. relative_path, "r") + local data = f:read("*a") + f:close() + + local commit_hash = vim.split(data, " ")[1] + + return commit_hash +end + +M.get_git_remote_url = function() + local f = io.popen("git remote get-url origin", "r") + local remote_url = f:read("*l") + f:close() + + if string.sub(remote_url, 0, 4) == "git@" then + remote_url = string.gsub(remote_url, "git@", "") + remote_url = string.gsub(remote_url, ".git", "") + remote_url = string.gsub(remote_url, ":", "/") + end + + if string.sub(remote_url, 0, 5) ~= "https" then + remote_url = "https://" .. remote_url + end + + return remote_url +end + +M.open_url_in_browser = function(url) + if vim.fn.has("win32") == 1 then + print("windows not supported, sorry") + return + end + + local f = io.popen("xdg-open " .. url, "r") + f:close() +end + +M.open_commit_on_github = function() + local commit_hash = M.get_commit_hash_for_current_line() + local remote_url = M.get_git_remote_url() + + if commit_hash == "00000000" then + print("Not committed yet") + return + end + + local commit_url = remote_url .. "/commit/" .. commit_hash + + M.open_url_in_browser(commit_url) +end + return M