robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
17.7 KiB604 linesraw
1local api = vim.api
2local uv = vim.uv
3local notify = require('vim._core.util').notify
4
5local M = {}
6
7---@return string?, string?
8local function unzip()
9  local command = vim.fn.exepath('unzip')
10  if command == '' then
11    return nil, 'unzip executable not found'
12  end
13  -- Windows searches the current directory before $PATH, so an archive could be opened with an
14  -- `unzip` shipped next to it.
15  if vim.fn.has('win32') == 1 then
16    local dir = uv.fs_realpath(vim.fs.dirname(vim.fs.normalize(command)))
17    local cwd = uv.fs_realpath(vim.fn.getcwd())
18    if dir and cwd and dir == cwd then
19      return nil, 'refusing to run unzip from the current directory'
20    end
21  end
22  return command
23end
24
25--- Escape a path so that Info-ZIP matches it literally.
26---
27--- Info-ZIP matches `*`, `?`, and `[]` in a member selector itself, so this is not shell
28--- quoting: passing argv already avoids the shell. For example, unescaped `a[a].txt`
29--- silently reads `aa.txt`, and `a?.txt` matches every four-character name. A literal `[`
30--- cannot be backslash-escaped, so it is wrapped in a class instead, as is a leading `-`,
31--- which would otherwise parse as an option.
32--- https://github.com/neovim/neovim/blob/7ba955fe079d4aa2554fea8e7235651fafd40efb/runtime/autoload/zip.vim#L316-L339
33---@param value string
34---@return string
35local function literal_pattern(value)
36  return (
37    value
38      :gsub('\\', '\\\\')
39      :gsub('%?', '\\?')
40      :gsub('%*', '\\*')
41      :gsub('%[', '[[]')
42      :gsub('^%-', '[-]')
43  )
44end
45
46---@param source string
47---@return string[]?, string?, boolean?
48local function list_archive(source)
49  local command, command_err = unzip()
50  if not command then
51    return nil, command_err, false
52  end
53  local ok, system = pcall(
54    vim.system,
55    { command, '-Z1', '--', literal_pattern(source) },
56    { text = true }
57  )
58  if not ok then
59    return nil, tostring(system), false
60  end
61  local result = system:wait()
62  if result.code ~= 0 then
63    if vim.trim(result.stdout or '') == 'Empty zipfile.' then
64      return {}
65    end
66    return nil, vim.trim(result.stderr or ''), true
67  end
68  return vim.split(result.stdout or '', '\n', { plain = true, trimempty = true })
69end
70
71--- Keep absolute and dot-segment entries visible without treating them as UI navigation.
72---@param path string
73---@return boolean
74local function opaque_path(path)
75  if path:sub(1, 1) == '/' or path:match('^%a:[/\\]') then
76    return true
77  end
78  for component in path:gmatch('[^/]+') do
79    if component == '.' or component == '..' then
80      return true
81    end
82  end
83  return false
84end
85
86--- Project the flat archive path list into one navigable directory level.
87---@param paths string[] Raw entry paths from the archive.
88---@param prefix string Raw archive-directory prefix, including its trailing slash.
89---@return nvim.dir.Entry[]
90local function entries_at(paths, prefix)
91  local entries = {} ---@type nvim.dir.Entry[]
92  local seen = {} ---@type table<string,true>
93  for _, path in ipairs(paths) do
94    if prefix == '' and opaque_path(path) then
95      local key = 'opaque:' .. path
96      if not seen[key] then
97        seen[key] = true
98        entries[#entries + 1] = { name = path, dir = false }
99      end
100    elseif vim.startswith(path, prefix) then
101      local rest = path:sub(#prefix + 1)
102      local separator = rest:find('/', 1, true)
103      local name = separator and rest:sub(1, separator - 1) or rest
104      if name ~= '' then
105        local dir = separator ~= nil
106        local entry_path = ('%s%s%s'):format(prefix, name, dir and '/' or '')
107        local key = (dir and 'dir:' or 'file:') .. entry_path
108        if not seen[key] then
109          seen[key] = true
110          entries[#entries + 1] = { name = name, dir = dir }
111        end
112      end
113    end
114  end
115  return entries
116end
117
118---@param source string
119---@return boolean?, string?
120local function has_magic(source)
121  local fd, err = uv.fs_open(source, 'r', 438)
122  if not fd then
123    return nil, err
124  end
125  local magic, read_err = uv.fs_read(fd, 2, 0)
126  uv.fs_close(fd)
127  if not magic then
128    return nil, read_err
129  end
130  return magic == 'PK'
131end
132
133---@param buf integer
134---@param source string
135local function read_normally(buf, source)
136  api.nvim_buf_call(buf, function()
137    api.nvim_cmd({
138      cmd = 'edit',
139      args = { source },
140      mods = { noautocmd = true, noswapfile = true },
141      magic = { file = false, bar = false },
142    }, {})
143  end)
144end
145
146--- Describe an Info-ZIP failure. It reports some conditions only through the exit code, and
147--- says nothing on stderr, so the code is preferred where it is meaningful.
148---@param code integer
149---@param stderr string
150---@return string
151local function unzip_error(code, stderr)
152  if code == 81 then
153    return 'unsupported compression or encryption'
154  elseif code == 82 then
155    return 'incorrect password'
156  end
157  return stderr ~= '' and stderr or ('unzip exited with %d'):format(code)
158end
159
160--- Returned when the empty password `extract_path` supplies is rejected, so a real one is
161--- needed. It cannot go in `-P`, which would expose it in the process arguments, and Info-ZIP
162--- reads a password from nowhere but a terminal, so it is asked for on a pty.
163local ENCRYPTED = 'zip:encrypted'
164
165--- Extract one entry into `dir`, prompting for the archive password on a pty.
166---
167--- Info-ZIP writes the prompt to the terminal and re-prompts on a wrong password, so the
168--- exchange is driven until it extracts, gives up, or the user cancels. The password reaches
169--- it over the pty and never appears in the process arguments.
170---@param command string
171---@param source string
172---@param path string
173---@param dir string Empty directory to extract into.
174---@return string? error
175local function extract_with_password(command, source, path, dir)
176  local buffered, exited = '', nil ---@type string, integer?
177  local ok, job = pcall(vim.fn.jobstart, {
178    command,
179    '-o',
180    '-j',
181    '-d',
182    dir,
183    '--',
184    literal_pattern(source),
185    literal_pattern(path),
186  }, {
187    pty = true,
188    env = { LC_ALL = 'C' },
189    on_stdout = function(_, data)
190      buffered = buffered .. table.concat(data, '')
191    end,
192    on_exit = function(_, code)
193      exited = code
194    end,
195  })
196  if not ok or job <= 0 then
197    return 'could not start unzip'
198  end
199
200  -- Info-ZIP prints the prompt before disabling echo, and disables it with TCSAFLUSH, which
201  -- drops a password sent in that window. Echo is still on there, so an echo means "resend".
202  local sent = ''
203  local function echoed()
204    return sent ~= '' and buffered:find(sent .. '\r', 1, true) ~= nil
205  end
206
207  local function wanted()
208    return exited ~= nil
209      or buffered:find('password: ', 1, true) ~= nil
210      or buffered:find('reenter: ', 1, true) ~= nil
211      or echoed()
212  end
213
214  local reenter = false
215  while exited == nil do
216    local ready, reason = vim.wait(10000, wanted, 50)
217    if not ready then
218      vim.fn.jobstop(job)
219      -- -2 is CTRL-C.
220      return reason == -2 and 'cancelled' or 'timed out waiting for unzip'
221    end
222    if exited ~= nil then
223      break
224    end
225    if echoed() then
226      -- Wait for its read(), else the resend is dropped too.
227      vim.wait(10)
228    else
229      local label = reenter and 'Password incorrect, try again: '
230        or ('Password for %s: '):format(path)
231      sent = vim.fn.inputsecret(label)
232      if sent == '' then
233        vim.fn.jobstop(job)
234        return 'cancelled'
235      end
236      reenter = true
237    end
238    buffered = ''
239    vim.fn.chansend(job, sent .. '\r')
240  end
241  --- @cast exited -?
242
243  if exited ~= 0 then
244    return unzip_error(exited, '')
245  end
246end
247
248---@param command string
249---@param source string
250---@param path string
251---@param target string
252---@return string?
253local function extract_path(command, source, path, target)
254  local file, err = io.open(target, 'wb')
255  if not file then
256    return err
257  end
258  local write_err ---@type string?
259  -- An empty `-P` inhibits the prompt Info-ZIP would open a terminal for.
260  local ok, system = pcall(
261    vim.system,
262    { command, '-p', '-P', '', '--', literal_pattern(source), literal_pattern(path) },
263    {
264      stdout = function(pipe_err, data)
265        if pipe_err then
266          write_err = pipe_err
267        elseif data and not write_err then
268          local written, file_err = file:write(data)
269          if not written then
270            write_err = file_err
271          end
272        end
273      end,
274    }
275  )
276  if not ok then
277    file:close()
278    return tostring(system)
279  end
280  local result = system:wait()
281  file:close()
282  if write_err then
283    return write_err
284  end
285  if result.code == 82 then
286    return ENCRYPTED
287  end
288  if result.code ~= 0 then
289    return unzip_error(result.code, vim.trim(result.stderr or ''))
290  end
291end
292
293---@param buf integer
294local function set_readonly(buf)
295  if not api.nvim_buf_is_valid(buf) then
296    return
297  end
298  api.nvim_set_option_value('swapfile', false, { buf = buf })
299  api.nvim_set_option_value('modified', false, { buf = buf })
300  api.nvim_set_option_value('buftype', 'nowrite', { buf = buf })
301  api.nvim_set_option_value('readonly', true, { buf = buf })
302  api.nvim_set_option_value('modifiable', false, { buf = buf })
303end
304
305--- Read extracted bytes through Nvim's normal reader to preserve encoding, EOL, and binary behavior.
306---@param buf integer Target archive entry buffer.
307---@param temp string Temporary file containing the extracted bytes.
308local function read_tempfile(buf, temp)
309  api.nvim_buf_call(buf, function()
310    local name = api.nvim_buf_get_name(buf)
311    api.nvim_set_option_value('swapfile', false, { buf = buf })
312    api.nvim_cmd({
313      cmd = 'file',
314      args = { temp },
315      mods = { keepalt = true, silent = true },
316      magic = { file = false, bar = false },
317    }, {})
318    api.nvim_cmd({ cmd = 'edit', bang = true, mods = { keepjumps = true, silent = true } }, {})
319    api.nvim_cmd({
320      cmd = 'file',
321      args = { name },
322      mods = { keepalt = true, silent = true },
323      magic = { file = false, bar = false },
324    }, {})
325    api.nvim_cmd({ cmd = 'filetype', args = { 'detect' } }, {})
326  end)
327  set_readonly(buf)
328end
329
330--- Resolve a `zip://` buffer name, as used by quickfix and direct `:edit`.
331---
332--- The archive path and the entry path are simply joined, so the split is found by walking
333--- components: the first one that is a regular file is the archive, because a regular file
334--- cannot have children on disk. Entry paths may therefore contain any character.
335---@param name string `zip://{archive}/{path}`
336---@return string?, string? archive and entry path
337local function resolve_uri(name)
338  if not vim.startswith(name, 'zip://') then
339    return
340  end
341  local value = name:sub(7)
342  local offset = 1
343  while true do
344    local separator = value:find('/', offset + 1, true)
345    if not separator then
346      return
347    end
348    local archive = value:sub(1, separator - 1)
349    local stat = uv.fs_stat(archive)
350    if stat and stat.type == 'file' then
351      return archive, value:sub(separator + 1)
352    end
353    offset = separator
354  end
355end
356
357---@class (private) nvim.zip.State
358---@field source string Path to the archive.
359---@field path? string Archive path shown by a `zip://` buffer.
360---@field paths? string[] Entry paths carried over from the initial listing.
361---@field prefix? string Archive directory currently listed.
362---@field pending_prefix? string Prefix to commit once the backend succeeds.
363
364---@param buf integer
365---@return nvim.zip.State?
366local function get_state(buf)
367  return vim.b[buf].nvim_zip
368end
369
370---@param buf integer
371---@param state nvim.zip.State
372local function set_state(buf, state)
373  vim.b[buf].nvim_zip = state
374end
375
376--- Open a local archive as a read-only `nvim.dir` listing.
377---@param buf integer Target archive buffer.
378---@param source string Expanded path to the archive.
379function M.browse(buf, source)
380  buf = vim._resolve_bufnr(buf)
381  if vim.b[buf].nvim_dir ~= nil and get_state(buf) ~= nil then
382    return
383  end
384  local magic, magic_err = has_magic(source)
385  if magic == nil then
386    notify('zip', ('File not readable <%s>: %s'):format(source, magic_err))
387    return
388  end
389  if not magic then
390    read_normally(buf, source)
391    return
392  end
393  local paths, err, fallback = list_archive(source)
394  if not paths then
395    if err then
396      notify(
397        'zip',
398        fallback and ('%s is not a zip file: %s'):format(source, err) or err,
399        fallback and vim.log.levels.WARN or vim.log.levels.ERROR
400      )
401    end
402    if fallback then
403      read_normally(buf, source)
404    end
405    return
406  end
407  set_state(buf, { source = source, paths = paths, prefix = '' })
408  local name = vim.fn.bufname(buf)
409  require('nvim.dir').open(buf, name ~= '' and name or source, M)
410end
411
412--- Read one archive entry into a read-only buffer.
413---@param buf integer Target entry buffer.
414---@param name string `zip://` buffer name.
415function M.read(buf, name)
416  buf = vim._resolve_bufnr(buf)
417  local state = get_state(buf)
418  local source, path = state and state.source, state and state.path
419  if not source or not path then
420    source, path = resolve_uri(name)
421  end
422  if not source or not path then
423    set_readonly(buf)
424    notify('zip', ('could not parse buffer name %q'):format(name))
425    return
426  end
427  local command, command_err = unzip()
428  if not command then
429    set_readonly(buf)
430    notify('zip', command_err or 'unzip executable not found')
431    return
432  end
433  local temp = vim.fn.tempname()
434  local dir ---@type string?
435  local err = extract_path(command, source, path, temp)
436  if err == ENCRYPTED then
437    vim.fn.delete(temp)
438    dir = vim.fn.tempname()
439    vim.fn.mkdir(dir, 'p')
440    err = extract_with_password(command, source, path, dir)
441    -- `-j` discards the archive path, so the directory holds exactly the extracted entry.
442    local entry = not err and vim.iter(vim.fs.dir(dir)):next() or nil
443    if entry then
444      temp = vim.fs.joinpath(dir, entry)
445    else
446      err = err or 'no entry was extracted'
447    end
448  end
449  if err then
450    vim.fn.delete(dir or temp, dir and 'rf' or '')
451    set_readonly(buf)
452    notify('zip', ('unable to read %s from %s: %s'):format(path, source, err))
453    return
454  end
455  local ok, read_err = pcall(read_tempfile, buf, temp)
456  vim.fn.delete(dir or temp, dir and 'rf' or '')
457  if not ok then
458    set_readonly(buf)
459    notify('zip', tostring(read_err))
460  end
461end
462
463--- List the requested archive level and commit its prefix only after the backend succeeds.
464---@param buf integer
465---@param _ string
466---@param cb fun(err?: string, entries?: nvim.dir.Entry[])
467function M.list(buf, _, cb)
468  local state = get_state(buf)
469  if not state then
470    cb('zip source is not set')
471    return
472  end
473  local paths = state.paths
474  state.paths = nil
475  local err ---@type string?
476  if not paths then
477    paths, err = list_archive(state.source)
478  end
479  if not paths then
480    state.pending_prefix = nil
481    set_state(buf, state)
482    cb(err)
483    return
484  end
485  state.prefix = state.pending_prefix or state.prefix or ''
486  state.pending_prefix = nil
487  set_state(buf, state)
488  cb(nil, entries_at(paths, state.prefix))
489end
490
491---@param buf integer
492---@param name string
493---@param entry nvim.dir.Entry
494function M.open(buf, name, entry)
495  local state = get_state(buf)
496  if not state then
497    return
498  end
499  local path = (state.prefix or '') .. entry.name .. (entry.dir and '/' or '')
500  if entry.dir then
501    state.pending_prefix = path
502    set_state(buf, state)
503    require('nvim.dir').open(buf, name, M)
504    return
505  end
506  local uri = ('zip://%s/%s'):format(state.source, path)
507  local entry_buf = vim.fn.bufadd(uri)
508  set_state(entry_buf, { source = state.source, path = path })
509  api.nvim_cmd({
510    cmd = 'edit',
511    args = { uri },
512    mods = { noswapfile = true, keepalt = true },
513    magic = { file = false, bar = false },
514  }, {})
515end
516
517---@param buf integer
518---@param name string
519function M.open_parent(buf, name)
520  local state = get_state(buf)
521  if not state then
522    return
523  end
524  local prefix = state.prefix or ''
525  if prefix ~= '' then
526    local path = prefix:sub(1, -2)
527    local child = assert(path:match('([^/]+)$'))
528    state.pending_prefix = path:match('^(.*[/])') or ''
529    set_state(buf, state)
530    require('nvim.dir').open(buf, name, M, { name = child, dir = true })
531    return
532  end
533  if name:match('^%a[%w+.-]*://') then
534    return
535  end
536  require('nvim.dir.fs').open_parent_path(state.source)
537end
538
539--- Extract the entry under the cursor into the current directory.
540--- `-j` discards the archive path, so the destination is always a name in the
541--- current directory and cannot be redirected by a hostile entry.
542function M._extract()
543  local buf = api.nvim_get_current_buf()
544  local state = get_state(buf)
545  if not state then
546    return
547  end
548  local command, command_err = unzip()
549  if not command then
550    notify('zip', command_err or 'unzip executable not found')
551    return
552  end
553  local line = api.nvim_get_current_line()
554  if line == '' then
555    return
556  end
557  if line:sub(-1) == '/' then
558    notify('zip', 'please specify a file, not a directory')
559    return
560  end
561  local path = (state.prefix or '') .. line
562  local directory = vim.fn.getcwd()
563  local target = vim.fs.joinpath(directory, vim.fs.basename(path))
564  if uv.fs_stat(target) then
565    notify('zip', ('%s already exists, not overwriting'):format(target))
566    return
567  end
568  local ok, system = pcall(vim.system, {
569    command,
570    '-o',
571    '-j',
572    '-P',
573    '',
574    '--',
575    literal_pattern(state.source),
576    literal_pattern(path),
577  }, { cwd = directory, text = true })
578  if not ok then
579    notify('zip', tostring(system))
580    return
581  end
582  local result = system:wait()
583  if not uv.fs_stat(target) then
584    notify(
585      'zip',
586      ('unable to extract %s from %s: %s'):format(path, state.source, vim.trim(result.stderr or ''))
587    )
588    return
589  end
590  notify('zip', ('extracted %s'):format(target), vim.log.levels.INFO)
591end
592
593---@param buf integer
594function M.init(buf)
595  api.nvim_set_option_value('filetype', 'zip', { buf = buf })
596  if vim.fn.hasmapto('<Plug>(nvim-zip-extract)', 'n') == 0 then
597    vim.keymap.set('n', 'x', '<Plug>(nvim-zip-extract)', { buffer = buf, silent = true })
598  end
599  api.nvim_buf_call(buf, function()
600    vim.wo.wrap = false
601  end)
602end
603
604return M