robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
14.0 KiB504 linesraw
1--- @brief
2---<pre>help
3---:DiffTool {left} {right}                                           *:DiffTool*
4---Compares two directories or files side-by-side.
5---Supports directory diffing, rename detection, and highlights changes
6---in quickfix list. Replaces the built-in `nvim -d` diff mode with this interface.
7---</pre>
8---
9--- The plugin is not loaded by default; use `:packadd` to activate it:
10--- ```
11--- :packadd nvim.difftool
12--- ```
13---
14--- Example `git difftool -d` integration using `nvim -d` replacement:
15---
16--- ```ini
17--- [difftool "nvim_difftool"]
18---   cmd = nvim -c \"packadd nvim.difftool\" -d \"$LOCAL\" \"$REMOTE\"
19--- [diff]
20---   tool = nvim_difftool
21--- ```
22
23local highlight_groups = {
24  A = 'DiffAdd',
25  D = 'DiffDelete',
26  M = 'DiffText',
27  R = 'DiffChange',
28}
29
30local layout = {
31  group = nil, --- @type integer?
32  left_win = nil, --- @type integer?
33  right_win = nil, --- @type integer?
34}
35
36local util = require('vim._core.util')
37
38--- Clean up the layout state, autocmds and quickfix list
39--- @param with_qf boolean whether the layout included a quickfix window
40local function cleanup_layout(with_qf)
41  if layout.group then
42    vim.api.nvim_del_augroup_by_id(layout.group)
43    layout.group = nil
44  end
45  layout.left_win = nil
46  layout.right_win = nil
47
48  if with_qf then
49    vim.fn.setqflist({})
50    vim.cmd.cclose()
51  end
52end
53
54--- Set up a consistent layout with two diff windows
55--- @param with_qf boolean whether to open the quickfix window
56local function setup_layout(with_qf)
57  local left_valid = layout.left_win and vim.api.nvim_win_is_valid(layout.left_win)
58  local right_valid = layout.right_win and vim.api.nvim_win_is_valid(layout.right_win)
59
60  if left_valid and right_valid then
61    return false
62  end
63
64  vim.cmd.only({ mods = { silent = true } })
65  layout.left_win = vim.api.nvim_get_current_win()
66  vim.cmd('rightbelow vsplit')
67  layout.right_win = vim.api.nvim_get_current_win()
68
69  if with_qf then
70    vim.cmd('botright copen')
71  end
72  vim.api.nvim_set_current_win(layout.right_win)
73
74  -- When one of the windows is closed, clean up the layout
75  vim.api.nvim_create_autocmd('WinClosed', {
76    group = layout.group,
77    pattern = tostring(layout.left_win),
78    callback = function()
79      cleanup_layout(with_qf)
80    end,
81  })
82  vim.api.nvim_create_autocmd('WinClosed', {
83    group = layout.group,
84    pattern = tostring(layout.right_win),
85    callback = function()
86      cleanup_layout(with_qf)
87    end,
88  })
89end
90
91--- Diff two files
92--- @param left_file string
93--- @param right_file string
94--- @param with_qf boolean? whether to open the quickfix window
95local function diff_files(left_file, right_file, with_qf)
96  setup_layout(with_qf or false)
97
98  util.edit_in(assert(layout.left_win), left_file)
99  util.edit_in(assert(layout.right_win), right_file)
100
101  vim.cmd('diffoff!')
102  vim.api.nvim_win_call(assert(layout.left_win), vim.cmd.diffthis)
103  vim.api.nvim_win_call(assert(layout.right_win), vim.cmd.diffthis)
104end
105
106--- Diff two directories using external `diff` command
107--- @param left_dir string
108--- @param right_dir string
109--- @param opt difftool.opt
110--- @return table[] list of quickfix entries
111local function diff_dirs_diffr(left_dir, right_dir, opt)
112  local args = { 'diff', '-qrN' }
113  for _, pattern in ipairs(opt.ignore) do
114    table.insert(args, '-x')
115    table.insert(args, pattern)
116  end
117  table.insert(args, left_dir)
118  table.insert(args, right_dir)
119
120  -- Force English locale so that we can rely on the output format
121  local result = vim.system(args, { text = true, env = { LC_ALL = 'C' } }):wait()
122  local lines = vim.split(result.stdout or '', '\n', { trimempty = true })
123  local qf_entries = {}
124
125  for _, line in ipairs(lines) do
126    local modified_left, modified_right = line:match("^Files '?(.-)'? and '?(.-)'? differ$")
127    if modified_left and modified_right then
128      local left_exists = vim.fn.filereadable(modified_left) == 1
129      local right_exists = vim.fn.filereadable(modified_right) == 1
130      local status = '?'
131      if left_exists and right_exists then
132        status = 'M'
133      elseif left_exists then
134        status = 'D'
135      elseif right_exists then
136        status = 'A'
137      end
138      local left = vim.fn.resolve(vim.fs.abspath(modified_left))
139      local right = vim.fn.resolve(vim.fs.abspath(modified_right))
140      table.insert(qf_entries, {
141        filename = right,
142        text = status,
143        user_data = {
144          diff = true,
145          rel = vim.fs.relpath(left_dir, modified_left),
146          left = left,
147          right = right,
148        },
149      })
150    end
151  end
152
153  return qf_entries
154end
155
156--- Diff two directories using built-in Lua implementation
157--- @param left_dir string
158--- @param right_dir string
159--- @param opt difftool.opt
160--- @return table[] list of quickfix entries
161local function diff_dirs_builtin(left_dir, right_dir, opt)
162  --- @param rel_path string?
163  --- @param ignore string[]
164  --- @return boolean
165  local function is_ignored(rel_path, ignore)
166    if not rel_path then
167      return false
168    end
169    for _, pat in ipairs(ignore) do
170      if vim.fn.match(rel_path, pat) >= 0 then
171        return true
172      end
173    end
174    return false
175  end
176
177  --- @param file1 string
178  --- @param file2 string
179  --- @param chunk_size integer
180  --- @param chunk_cache table<string, any>
181  --- @return number similarity ratio (0 to 1)
182  local function calculate_similarity(file1, file2, chunk_size, chunk_cache)
183    -- Get or read chunk for file1
184    local chunk1 = chunk_cache[file1]
185    if not chunk1 then
186      chunk1 = util.read_chunk(file1, chunk_size)
187      chunk_cache[file1] = chunk1
188    end
189
190    -- Get or read chunk for file2
191    local chunk2 = chunk_cache[file2]
192    if not chunk2 then
193      chunk2 = util.read_chunk(file2, chunk_size)
194      chunk_cache[file2] = chunk2
195    end
196
197    if not chunk1 or not chunk2 then
198      return 0
199    end
200    if chunk1 == chunk2 then
201      return 1
202    end
203    local matches = 0
204    local len = math.min(#chunk1, #chunk2)
205    for i = 1, len do
206      if chunk1:sub(i, i) == chunk2:sub(i, i) then
207        matches = matches + 1
208      end
209    end
210    return matches / len
211  end
212
213  -- Create a map of all relative paths
214
215  --- @type table<string, {left: string?, right: string?}>
216  local all_paths = {}
217  --- @type table<string, string>
218  local left_only = {}
219  --- @type table<string, string>
220  local right_only = {}
221
222  --- @param dir_path string
223  --- @param is_left boolean
224  local function process_files_in_directory(dir_path, is_left)
225    local files = vim.fs.find(function(name, path)
226      local rel_path = vim.fs.relpath(dir_path, vim.fs.joinpath(path, name))
227      return not is_ignored(rel_path, opt.ignore)
228    end, { limit = math.huge, path = dir_path, follow = false })
229
230    for _, full_path in ipairs(files) do
231      local rel_path = vim.fs.relpath(dir_path, full_path)
232      if rel_path then
233        full_path = vim.fn.resolve(full_path)
234
235        if vim.fn.isdirectory(full_path) == 0 then
236          all_paths[rel_path] = all_paths[rel_path] or { left = nil, right = nil }
237
238          if is_left then
239            all_paths[rel_path].left = full_path
240            if not all_paths[rel_path].right then
241              left_only[rel_path] = full_path
242            end
243          else
244            all_paths[rel_path].right = full_path
245            if not all_paths[rel_path].left then
246              right_only[rel_path] = full_path
247            end
248          end
249        end
250      end
251    end
252  end
253
254  -- Process both directories
255  process_files_in_directory(left_dir, true)
256  process_files_in_directory(right_dir, false)
257
258  --- @type table<string, string>
259  local renamed = {}
260  --- @type table<string, string>
261  local chunk_cache = {}
262
263  -- Detect possible renames
264  if opt.rename.detect then
265    for left_rel, left_path in pairs(left_only) do
266      ---@type {similarity: number, path: string?, rel: string?}
267      local best_match = { similarity = opt.rename.similarity, path = nil }
268
269      for right_rel, right_path in pairs(right_only) do
270        local similarity =
271          calculate_similarity(left_path, right_path, opt.rename.chunk_size, chunk_cache)
272
273        if similarity > best_match.similarity then
274          best_match = {
275            similarity = similarity,
276            path = right_path,
277            rel = right_rel,
278          }
279        end
280      end
281
282      if best_match.path and best_match.rel then
283        renamed[left_rel] = best_match.rel
284        all_paths[left_rel].right = best_match.path
285        all_paths[best_match.rel] = nil
286        left_only[left_rel] = nil
287        right_only[best_match.rel] = nil
288      end
289    end
290  end
291
292  local qf_entries = {}
293
294  -- Convert to quickfix entries
295  for rel_path, files in pairs(all_paths) do
296    local status = nil
297    if files.left and files.right then
298      --- @type number
299      local similarity
300      if opt.rename.detect then
301        similarity =
302          calculate_similarity(files.left, files.right, opt.rename.chunk_size, chunk_cache)
303      else
304        similarity = vim.fn.getfsize(files.left) == vim.fn.getfsize(files.right) and 1 or 0
305      end
306      if similarity < 1 then
307        status = renamed[rel_path] and 'R' or 'M'
308      end
309    elseif files.left then
310      status = 'D'
311      files.right = right_dir .. rel_path
312    elseif files.right then
313      status = 'A'
314      files.left = left_dir .. rel_path
315    end
316
317    if status then
318      table.insert(qf_entries, {
319        filename = files.right,
320        text = status,
321        user_data = {
322          diff = true,
323          rel = rel_path,
324          left = files.left,
325          right = files.right,
326        },
327      })
328    end
329  end
330
331  return qf_entries
332end
333
334--- Diff two directories
335--- @param left_dir string
336--- @param right_dir string
337--- @param opt difftool.opt
338local function diff_dirs(left_dir, right_dir, opt)
339  local method = opt.method
340  if method == 'auto' then
341    if not opt.rename.detect and vim.fn.executable('diff') == 1 then
342      method = 'diffr'
343    else
344      method = 'builtin'
345    end
346  end
347
348  --- @type table[]
349  local qf_entries
350  if method == 'diffr' then
351    qf_entries = diff_dirs_diffr(left_dir, right_dir, opt)
352  elseif method == 'builtin' then
353    qf_entries = diff_dirs_builtin(left_dir, right_dir, opt)
354  else
355    vim.notify('Unknown diff method: ' .. method, vim.log.levels.ERROR)
356    return
357  end
358
359  -- Early exit if no differences found
360  if #qf_entries == 0 then
361    vim.notify('No differences found', vim.log.levels.INFO)
362    return
363  end
364
365  -- Sort entries by filename for consistency
366  table.sort(qf_entries, function(a, b)
367    return a.user_data.rel < b.user_data.rel
368  end)
369
370  vim.fn.setqflist({}, 'r', {
371    nr = '$',
372    title = 'DiffTool',
373    items = qf_entries,
374    ---@param info {id: integer, start_idx: integer, end_idx: integer}
375    quickfixtextfunc = function(info)
376      local items = assert(vim.fn.getqflist({ id = info.id, items = 1 }).items)
377      local out = {}
378      for item = info.start_idx, info.end_idx do
379        local entry = assert(items[item])
380        table.insert(out, entry.text .. ' ' .. entry.user_data.rel)
381      end
382      return out
383    end,
384  })
385
386  setup_layout(true)
387  vim.cmd.cfirst()
388end
389
390local M = {}
391
392--- @class difftool.opt
393--- @inlinedoc
394---
395--- Diff method to use
396--- (default: `auto`)
397--- @field method 'auto'|'builtin'|'diffr'
398---
399--- List of file patterns to ignore (for example: `'.git', '*.log'`)
400--- (default: `{}`)
401--- @field ignore string[]
402---
403--- Rename detection options (supported only by `builtin` method)
404--- @field rename table Controls rename detection
405---
406---   - {rename.detect} (`boolean`, default: `false`) Whether to detect renames
407---   - {rename.similarity} (`number`, default: `0.5`) Minimum similarity for rename detection (0 to 1)
408---   - {rename.chunk_size} (`number`, default: `4096`) Maximum chunk size to read from files for similarity calculation
409
410--- Diff two files or directories
411--- @param left string
412--- @param right string
413--- @param opt? difftool.opt
414function M.open(left, right, opt)
415  if not left or not right then
416    vim.notify('Both arguments are required', vim.log.levels.ERROR)
417    return
418  end
419
420  local config = vim.tbl_deep_extend('force', {
421    method = 'auto',
422    ignore = {},
423    rename = {
424      detect = false,
425      similarity = 0.5,
426      chunk_size = 4096,
427    },
428  }, opt or {})
429
430  layout.group = vim.api.nvim_create_augroup('nvim.difftool.events', { clear = true })
431  local hl_id = vim.api.nvim_create_namespace('nvim.difftool.hl')
432
433  --- @param bufnr? integer
434  local function get_diff_entry(bufnr)
435    local qf_info = vim.fn.getqflist({ idx = 0, items = 1, size = 1 })
436    if qf_info.size == 0 then
437      return false
438    end
439
440    local entry = assert(qf_info.items)[assert(qf_info.idx)]
441    if
442      not entry
443      or not entry.user_data
444      or not entry.user_data.diff
445      or (bufnr and entry.bufnr ~= bufnr)
446    then
447      return nil
448    end
449
450    return entry
451  end
452
453  vim.api.nvim_create_autocmd('BufWinEnter', {
454    group = layout.group,
455    pattern = 'quickfix',
456    callback = function(ev)
457      if not get_diff_entry() then
458        return
459      end
460
461      vim.api.nvim_buf_clear_namespace(ev.buf, hl_id, 0, -1)
462      local lines = vim.api.nvim_buf_get_lines(ev.buf, 0, -1, false)
463
464      -- Map status codes to highlight groups
465      for i, line in ipairs(lines) do
466        local status = line:match('^(%a) ')
467        local hl_group = highlight_groups[status]
468        if hl_group then
469          vim.hl.range(ev.buf, hl_id, hl_group, { i - 1, 0 }, { i - 1, 1 })
470        end
471      end
472    end,
473  })
474
475  vim.api.nvim_create_autocmd('BufWinEnter', {
476    group = layout.group,
477    pattern = '*',
478    callback = function(ev)
479      local entry = get_diff_entry(ev.buf)
480      if not entry then
481        return
482      end
483
484      vim.w.lazyredraw = true
485      vim.schedule(function()
486        diff_files(entry.user_data.left, entry.user_data.right)
487        vim.w.lazyredraw = false
488      end)
489    end,
490  })
491
492  left = vim.fs.normalize(left)
493  right = vim.fs.normalize(right)
494
495  if vim.fn.isdirectory(left) == 1 and vim.fn.isdirectory(right) == 1 then
496    diff_dirs(left, right, config)
497  elseif vim.fn.filereadable(left) == 1 and vim.fn.filereadable(right) == 1 then
498    diff_files(left, right)
499  else
500    vim.notify('Both arguments must be files or directories', vim.log.levels.ERROR)
501  end
502end
503
504return M