lewis6991 / gitsigns.nvim

Git integration for buffers
MIT License
4.87k stars 186 forks source link

Auto-attach (or exclude from auto-attach) based on pattern #1083

Closed NickHarvey2 closed 1 month ago

NickHarvey2 commented 1 month ago

I have autocmds for SOPS files that automatically decrypt them and update the buffer with decrypted contents, then re-encrypt before writing

example (implementation of Sops.decrypt is elided for brevity):

vim.api.nvim_create_autocmd({'BufReadPost', 'BufWritePost'}, {
    pattern = {'*/secrets/secrets.yaml', '*/secrets/secrets.json', '*/secrets/secrets.env', '*/secrets/secrets.ini'},
    callback = function() Sops.decrypt() end,
})

This is great for working with SOPS files, but gitsigns is showing signs in the gutter based on the diff between the buffer (cleartext) and the index (encrypted), making the signs rather useless and potentially misleading. Worse, the commands to stage chunks are a vector for leaking cleartext versions of the file.

It would be nice if I could exclude certain files from the auto_attach feature based on pattern in a similar way.

As a workaround, I imagine it would be fairly straightforward to create an autocmd calling Gitsigns detach for files matching the pattern. I haven't tested every event, but it seems like attaching happens after the BufReadPost event, so I wasn't sure what event to tie this autcmd to.

(Tangentially, I think it would be possible to actually make the signs be correct, using an approach like the one outlined here in the SOPS repo that allows git diffs to show the diffs in cleartext. But that seemed like it was both more complex and less potentially useful as a general feature.)

lewis6991 commented 1 month ago

There's already two methods:

require('gitsigns').setup { auto_attach = false }

vim.api.nvim_create_autocmd({ 'BufFilePost', 'BufRead', 'BufNewFile' }, {
  callback = function()
    if vim.bo[bufnr].filetype == 'foo' then
      return -- do not attach
    end
    require('gitsigns').attach()
  end
})

or

require('gitsigns').setup {
  on_attach = function(bufnr)
    if vim.bo[bufnr].filetype == 'foo' then
      return false -- do not attach
    end
  end
}
lewis6991 commented 1 month ago

(Tangentially, I think it would be possible to actually make the signs be correct, using an approach like the one outlined here in the SOPS repo that allows git diffs to show the diffs in cleartext. But that seemed like it was both more complex and less potentially useful as a general feature.)

This relates to #480 where git allows you to define smudge/clean filters in .gitattributes which people user to encode/decode files stored in git.