nvim: after/plugin/statusline: Add a git branch ahead behind component

Taken from
https://www.reddit.com/r/neovim/comments/t48x5i/git_branch_aheadbehind_info_status_line_component
This commit is contained in:
Sanchayan Maity 2022-03-02 10:57:51 +05:30
parent 16d3b05a8f
commit 0246931b56
1 changed files with 39 additions and 0 deletions

View File

@ -2,6 +2,35 @@ local fn = vim.fn
local api = vim.api
local cmd = vim.cmd
local gstatus = { ahead = 0, behind = 0 }
local update_gstatus = function()
local Job = require 'plenary.job'
Job:new({
command = 'git',
args = { 'rev-list', '--left-right', '--count', 'HEAD...@{upstream}' },
on_exit = function(exit_job, _)
local res = exit_job:result()[1]
if type(res) ~= 'string' then
gstatus = { ahead = 0, behind = 0 };
return
end
local ok, ahead, behind = pcall(string.match, res, "(%d+)%s*(%d+)")
if not ok then
ahead, behind = 0, 0
end
gstatus = { ahead = ahead, behind = behind }
end,
}):start()
end
if _G.Gstatus_timer == nil then
_G.Gstatus_timer = vim.loop.new_timer()
else
_G.Gstatus_timer:stop()
end
_G.Gstatus_timer:start(0, 2000, vim.schedule_wrap(update_gstatus))
local M = {}
local colors = {
@ -29,6 +58,7 @@ highlight("Filename" , colors.blue , colors.bg)
highlight("Fileformat" , colors.purple , colors.bg)
highlight("GitBranch" , colors.orange , colors.bg)
highlight("GitStatus" , colors.magenta, colors.bg)
highlight("DiffAdded" , colors.green , colors.bg)
highlight("DiffChanged" , colors.orange , colors.bg)
highlight("DiffRemoved" , colors.red , colors.bg)
@ -166,10 +196,19 @@ M.progress = function()
return string.format(" %s%s", "%#Progress#", "%3p%% ")
end
M.git_ahead_behind_status = function()
return
vim.b.gitsigns_status_dict
and
string.format(" %s%s%d%s%d", '%#GitStatus#', '', gstatus.behind, '', gstatus.ahead)
or ""
end
M.set_active = function(self)
return table.concat {
self:get_filename(),
self:get_git_status(),
self:git_ahead_behind_status(),
"%=",
self:diagnostic_status(),
self:get_line_col(),