all repos — dotfiles @ da7509d71e5f81a121cc94d3fd615fb9d6ad2f6c

my *nix dotfiles

config/nvim/lua/statusline/git.lua (view raw)

 1local M = {}
 2
 3local sep = package.config:sub(1,1)
 4
 5local function find_git_dir()
 6  local file_dir = vim.fn.expand('%:p:h') .. ';'
 7  local git_dir = vim.fn.finddir('.git', file_dir)
 8  if #git_dir > 0 then
 9    M.in_git = true
10  end
11  return git_dir
12end
13
14local function get_git_head(head_file)
15  local f_head = io.open(head_file)
16  if f_head then
17    local HEAD = f_head:read()
18    f_head:close()
19    local branch = HEAD:match('ref: refs/heads/(.+)$')
20    if branch then M.git_branch = branch
21    else M.git_branch =  HEAD:sub(1,7) end
22  end
23  return nil
24end
25
26-- event watcher to watch head file
27local file_changed = vim.loop.new_fs_event()
28local function watch_head()
29  file_changed:stop()
30  local git_dir = find_git_dir()
31  if #git_dir > 0 then
32    local head_file = git_dir..sep..'HEAD'
33    get_git_head(head_file)
34    file_changed:start(head_file, {}, vim.schedule_wrap(function()
35      -- reset file-watch
36      watch_head()
37    end))
38  else
39    M.git_branch = ''
40  end
41end
42
43watch_head()
44
45return M