robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
27.2 KiB990 linesraw
1local test_assert = require('test.assert')
2---@type test.harness
3local harness = require('test.harness')
4local uv = vim.uv
5local Paths = require('test.cmakeconfig.paths')
6
7--- Functions executing in the context of the test runner (not the current nvim test session).
8--- @class test.testutil
9local M = {
10  paths = Paths,
11
12  -- Test framework:
13  after_each = harness.after_each,
14  before_each = harness.before_each,
15  describe = harness.describe,
16  finally = harness.finally,
17  it = harness.it,
18  pending = harness.pending,
19  setup = harness.setup,
20  teardown = harness.teardown,
21}
22
23--- @param path string
24--- @return boolean
25function M.isdir(path)
26  if not path then
27    return false
28  end
29  local stat = uv.fs_stat(path)
30  if not stat then
31    return false
32  end
33  return stat.type == 'directory'
34end
35
36--- (Only on Windows) Replaces yucky "\\" slashes with delicious "/" slashes in a string, or all
37--- string values in a table (recursively).
38---
39--- @generic T: string|table
40--- @param obj T
41--- @return T|nil
42function M.fix_slashes(obj)
43  if not M.is_os('win') then
44    return obj
45  end
46  if type(obj) == 'string' then
47    local ret = string.gsub(obj, '\\', '/')
48    return ret
49  elseif type(obj) == 'table' then
50    --- @cast obj table<any,any>
51    local ret = {} --- @type table<any,any>
52    for k, v in pairs(obj) do
53      ret[k] = M.fix_slashes(v)
54    end
55    return ret
56  end
57  assert(false, 'expected string or table of strings, got ' .. type(obj))
58end
59
60--- @param ... string|string[]
61--- @return string[]
62function M.argss_to_cmd(...)
63  local cmd = {} --- @type string[]
64  for i = 1, select('#', ...) do
65    local arg = select(i, ...)
66    if type(arg) == 'string' then
67      cmd[#cmd + 1] = arg
68    else
69      --- @cast arg string[]
70      for _, subarg in ipairs(arg) do
71        cmd[#cmd + 1] = subarg
72      end
73    end
74  end
75  return cmd
76end
77
78--- Calls fn() until it succeeds, up to `max` times or until `max_ms`
79--- milliseconds have passed.
80--- @param max integer?
81--- @param max_ms integer?
82--- @param fn function
83--- @return any
84function M.retry(max, max_ms, fn)
85  assert(max == nil or max > 0)
86  assert(max_ms == nil or max_ms > 0)
87  local tries = 1
88  local timeout = (max_ms and max_ms or 10000)
89  local start_time = uv.now()
90  while true do
91    --- @type boolean, any
92    local status, result = pcall(fn)
93    if status then
94      return result
95    end
96    uv.update_time() -- Update cached value of luv.now() (libuv: uv_now()).
97    if (max and tries >= max) or (uv.now() - start_time > timeout) then
98      error(string.format('retry() attempts: %d\n%s', tries, tostring(result)), 2)
99    end
100    tries = tries + 1
101    uv.sleep(20) -- Avoid hot loop...
102  end
103end
104
105local check_logs_useless_lines = {
106  ['Warning: noted but unhandled ioctl'] = 1,
107  ['could cause spurious value errors to appear'] = 2,
108  ['See README_MISSING_SYSCALL_OR_IOCTL for guidance'] = 3,
109}
110
111function M.eq(expected, actual, context)
112  return test_assert.eq(expected, actual, context)
113end
114function M.neq(expected, actual, context)
115  return test_assert.neq(expected, actual, context)
116end
117
118--- Compare paths after resolving symlinks with realpath.
119function M.eq_paths(expected, actual, context)
120  return M.eq(uv.fs_realpath(expected), uv.fs_realpath(actual), context)
121end
122
123--- Asserts that `cond` is true, or prints a message.
124---
125--- @param cond (boolean) expression to assert
126--- @param expected (any) description of expected result
127--- @param actual (any) description of actual result
128function M.ok(cond, expected, actual)
129  assert(
130    (not expected and not actual) or (expected and actual),
131    'if "expected" is given, "actual" is also required'
132  )
133  local msg = expected and ('expected %s, got: %s'):format(expected, tostring(actual)) or nil
134  return assert(cond, msg)
135end
136
137--- @param pat string
138--- @param actual string
139--- @param plain boolean? (default: false)
140--- @return boolean
141function M.matches(pat, actual, plain)
142  assert(pat and pat ~= '', 'pat must be a non-empty string')
143  assert(plain == nil or type(plain) == 'boolean', 'plain must be nil or boolean')
144  if nil ~= string.find(actual, pat, 1, plain) then
145    return true
146  end
147  error(('Pattern does not match.\nPattern:\n%s\nActual:\n%s'):format(pat, actual))
148end
149
150--- @param pat string
151--- @param actual string
152--- @param plain boolean? (default: false)
153--- @return boolean
154function M.not_matches(pat, actual, plain)
155  assert(pat and pat ~= '', 'pat must be a non-empty string')
156  if nil == string.find(actual, pat, 1, plain) then
157    return true
158  end
159  error(('Pattern does match.\nPattern:\n%s\nActual:\n%s'):format(pat, actual))
160end
161
162--- Asserts that `pat` matches (or *not* if inverse=true) any text in the tail of `logfile`.
163---
164--- Matches are not restricted to a single line.
165---
166--- Retries for 1 second in case of filesystem delay.
167---
168---@param pat (string) Lua pattern to match text in the log file
169---@param logfile? (string) Full path to log file (default=$NVIM_LOG_FILE)
170---@param nrlines? (number) Search up to this many log lines (default 10)
171---@param inverse? (boolean) Assert that the pattern does NOT match.
172function M.assert_log(pat, logfile, nrlines, inverse)
173  logfile = logfile or os.getenv('NVIM_LOG_FILE') or 'nvim.log'
174  assert(logfile ~= nil, 'no logfile')
175  nrlines = nrlines or 10
176
177  M.retry(nil, 1000, function()
178    local lines = M.read_file_list(logfile, -nrlines) or {}
179    local text = table.concat(lines, '\n')
180    local ismatch = not not text:match(pat)
181    if (ismatch and inverse) or not (ismatch or inverse) then
182      local msg = string.format(
183        'Pattern %s %sfound in log (last %d lines): %q:\n%s',
184        vim.inspect(pat),
185        (inverse and '' or 'not '),
186        nrlines,
187        logfile,
188        vim.text.indent(4, text)
189      )
190      error(msg)
191    end
192  end)
193end
194
195--- Asserts that `pat` does NOT match any line in the tail of `logfile`.
196---
197--- @see assert_log
198--- @param pat (string) Lua pattern to match lines in the log file
199--- @param logfile? (string) Full path to log file (default=$NVIM_LOG_FILE)
200--- @param nrlines? (number) Search up to this many log lines
201function M.assert_nolog(pat, logfile, nrlines)
202  return M.assert_log(pat, logfile, nrlines, true)
203end
204
205--- @param fn fun(...): any
206--- @param ... any
207--- @return boolean, any
208function M.pcall(fn, ...)
209  assert(type(fn) == 'function')
210  local status, rv = pcall(fn, ...)
211  if status then
212    return status, rv
213  end
214
215  -- From:
216  --    C:/long/path/foo.lua:186: Expected string, got number
217  -- to:
218  --    .../foo.lua:0: Expected string, got number
219  local errmsg = tostring(rv)
220    :gsub('([%s<])vim[/\\]([^%s:/\\]+):%d+', '%1\xffvim\xff%2:0')
221    :gsub('[^%s<]-[/\\]([^%s:/\\]+):%d+', '.../%1:0')
222    :gsub('\xffvim\xff', 'vim/')
223
224  -- Scrub numbers in paths/stacktraces:
225  --    shared.lua:0: in function 'gsplit'
226  --    shared.lua:0: in function <shared.lua:0>'
227  errmsg = errmsg:gsub('([^%s].lua):%d+', '%1:0')
228  --    [string "<nvim>"]:0:
229  --    [string ":lua"]:0:
230  --    [string ":luado"]:0:
231  errmsg = errmsg:gsub('(%[string "[^"]+"%]):%d+', '%1:0')
232
233  -- Scrub tab chars:
234  errmsg = errmsg:gsub('\t', '    ')
235  -- In Lua 5.1, we sometimes get a "(tail call): ?" on the last line.
236  --    We remove this so that the tests are not lua dependent.
237  errmsg = errmsg:gsub('%s*%(tail call%): %?', '')
238
239  return status, errmsg
240end
241
242-- Invokes `fn` and returns the error string (with truncated paths), or raises
243-- an error if `fn` succeeds.
244--
245-- Replaces line/column numbers with zero:
246--     shared.lua:0: in function 'gsplit'
247--     shared.lua:0: in function <shared.lua:0>'
248--
249-- Usage:
250--    -- Match exact string.
251--    eq('e', pcall_err(function(a, b) error('e') end, 'arg1', 'arg2'))
252--    -- Match Lua pattern.
253--    matches('e[or]+$', pcall_err(function(a, b) error('some error') end, 'arg1', 'arg2'))
254--
255--- @param fn function
256--- @return string
257function M.pcall_err_withfile(fn, ...)
258  assert(type(fn) == 'function')
259  local status, rv = M.pcall(fn, ...)
260  if status == true then
261    error('expected failure, but got success')
262  end
263  return rv
264end
265
266--- @param fn function
267--- @param ... any
268--- @return string
269function M.pcall_err_withtrace(fn, ...)
270  local errmsg = M.pcall_err_withfile(fn, ...)
271
272  return (
273    errmsg
274      :gsub('^%.%.%./testnvim%.lua:0: ', '')
275      :gsub('^Lua:- ', '')
276      :gsub('^%[string "<nvim>"%]:0: ', '')
277  )
278end
279
280--- @param fn function
281--- @param ... any
282--- @return string
283function M.pcall_err(fn, ...)
284  return M.remove_trace(M.pcall_err_withtrace(fn, ...))
285end
286
287--- @param s string
288--- @return string
289function M.remove_trace(s)
290  return (s:gsub('\n%s*stack traceback:.*', ''))
291end
292
293-- initial_path:  directory to recurse into
294-- re:            include pattern (string)
295-- exc_re:        exclude pattern(s) (string or table)
296function M.glob(initial_path, re, exc_re)
297  exc_re = type(exc_re) == 'table' and exc_re or { exc_re }
298  local paths_to_check = { initial_path } --- @type string[]
299  local ret = {} --- @type string[]
300  local checked_files = {} --- @type table<string,true>
301  local function is_excluded(path)
302    for _, pat in pairs(exc_re) do
303      if path:match(pat) then
304        return true
305      end
306    end
307    return false
308  end
309
310  if is_excluded(initial_path) then
311    return ret
312  end
313  while #paths_to_check > 0 do
314    local cur_path = paths_to_check[#paths_to_check]
315    paths_to_check[#paths_to_check] = nil
316    for e in vim.fs.dir(cur_path) do
317      local full_path = cur_path .. '/' .. e
318      local checked_path = full_path:sub(#initial_path + 1)
319      if (not is_excluded(checked_path)) and e:sub(1, 1) ~= '.' then
320        local stat = uv.fs_stat(full_path)
321        if stat then
322          local check_key = stat.dev .. ':' .. tostring(stat.ino)
323          if not checked_files[check_key] then
324            checked_files[check_key] = true
325            if stat.type == 'directory' then
326              paths_to_check[#paths_to_check + 1] = full_path
327            elseif not re or checked_path:match(re) then
328              ret[#ret + 1] = full_path
329            end
330          end
331        end
332      end
333    end
334  end
335  return ret
336end
337
338--- Reads sanitizer/valgrind log file lines, filtering out useless warnings.
339--- Waits briefly for the ASAN "SUMMARY" line so we don't read a truncated report
340--- (the crashing process may still be writing when we check).
341local function read_sanitizer_log(file)
342  local lines = {} --- @type string[]
343  local has_summary = false
344  -- Poll for up to 2 seconds for the log to be complete.
345  for _ = 1, 20 do
346    lines = {}
347    local warning_line = 0
348    local fd = assert(io.open(file))
349    for line in fd:lines() do
350      local cur_warning_line = check_logs_useless_lines[line]
351      if cur_warning_line == warning_line + 1 then
352        warning_line = cur_warning_line
353      else
354        lines[#lines + 1] = line
355      end
356      if line:find('SUMMARY') then
357        has_summary = true
358      end
359    end
360    fd:close()
361    if has_summary or #lines == 0 then
362      break
363    end
364    uv.sleep(100)
365  end
366  if not has_summary and #lines > 0 then
367    lines[#lines + 1] = '(WARNING: sanitizer log may be truncated, no SUMMARY line found)'
368  end
369  return lines
370end
371
372function M.check_logs()
373  local log_dir = os.getenv('LOG_DIR')
374  local runtime_errors = {} --- @type string[]
375  local runtime_errors_detail = {} --- @type string[]
376  if log_dir and M.isdir(log_dir) then
377    for tail in vim.fs.dir(log_dir) do
378      if tail:sub(1, 30) == 'valgrind-' or tail:find('san%.') then
379        local file = ('%s/%s'):format(log_dir, tail)
380        local lines = read_sanitizer_log(file)
381        if #lines > 0 then
382          local start_msg = ('%s File %s %s'):format(('='):rep(20), file, ('='):rep(20))
383          local end_msg = select(1, start_msg:gsub('.', '='))
384          local lines_str = ('= %s'):format(table.concat(lines, '\n= '))
385          local detail = ('%s\n%s\n%s'):format(start_msg, lines_str, end_msg)
386          --- @type boolean?, file*?
387          local status, f
388          if os.getenv('SYMBOLIZER') then
389            status, f = pcall(M.repeated_read_cmd, os.getenv('SYMBOLIZER'), '-l', file)
390          end
391          local out = io.stdout
392          out:write(start_msg .. '\n')
393          if status then
394            assert(f)
395            for line in f:lines() do
396              out:write(('= %s\n'):format(line))
397            end
398            f:close()
399          else
400            out:write(lines_str .. '\n')
401          end
402          out:write(end_msg .. '\n')
403          table.insert(runtime_errors, file)
404          table.insert(runtime_errors_detail, detail)
405        end
406        os.remove(file)
407      end
408    end
409  end
410  test_assert(
411    0 == #runtime_errors,
412    string.format(
413      'Found runtime errors in logfile(s):\n%s',
414      table.concat(runtime_errors_detail, '\n')
415    )
416  )
417end
418
419local sysname = uv.os_uname().sysname:lower()
420
421--- @param s 'win'|'mac'|'linux'|'freebsd'|'openbsd'|'bsd'
422--- @return boolean
423function M.is_os(s)
424  if
425    not (s == 'win' or s == 'mac' or s == 'linux' or s == 'freebsd' or s == 'openbsd' or s == 'bsd')
426  then
427    error('unknown platform: ' .. tostring(s))
428  end
429  return not not (
430    (s == 'win' and (sysname:find('windows') or sysname:find('mingw')))
431    or (s == 'mac' and sysname == 'darwin')
432    or (s == 'linux' and sysname == 'linux')
433    or (s == 'freebsd' and sysname == 'freebsd')
434    or (s == 'openbsd' and sysname == 'openbsd')
435    or (s == 'bsd' and sysname:find('bsd'))
436  )
437end
438
439local architecture = uv.os_uname().machine
440
441--- @param s 'x86_64'|'arm64'|'s390x'
442--- @return boolean
443function M.is_arch(s)
444  if not (s == 'x86_64' or s == 'arm64' or s == 's390x') then
445    error('unknown architecture: ' .. tostring(s))
446  end
447  return s == architecture
448end
449
450function M.is_asan()
451  return M.paths.is_asan
452end
453
454function M.is_zig_build()
455  return M.paths.is_zig_build
456end
457
458local tmpname_id = 0
459local tmpdir = os.getenv('TMPDIR') or os.getenv('TEMP')
460local tmpdir_is_local = not not (tmpdir and tmpdir:find('Xtest'))
461
462local function get_tmpname()
463  if tmpdir_is_local then
464    -- Cannot control os.tmpname() dir, so hack our own tmpname() impl.
465    tmpname_id = tmpname_id + 1
466    -- "…/Xtest_tmpdir/T42.7"
467    return ('%s/%s.%d'):format(tmpdir, (_G._nvim_test_id or 'nvim-test'), tmpname_id)
468  end
469
470  local fname = os.tmpname()
471
472  if M.is_os('win') and fname:sub(1, 2) == '\\s' then
473    -- In Windows tmpname() returns a filename starting with
474    -- special sequence \s, prepend $TEMP path
475    return tmpdir .. fname
476  elseif M.is_os('mac') and fname:match('^/tmp') then
477    -- In OS X /tmp links to /private/tmp
478    return '/private' .. fname
479  end
480  return fname
481end
482
483--- Generates a unique filepath for use by tests, in a test-specific "…/Xtest_tmpdir/T42.7"
484--- directory (which is cleaned up by the test runner).
485---
486--- @param create? boolean (default true) Create the file.
487--- @return string
488function M.tmpname(create)
489  local fname = get_tmpname()
490  os.remove(fname)
491  if create ~= false then
492    assert(io.open(fname, 'w')):close()
493  end
494  return fname
495end
496
497local function deps_prefix()
498  local env = os.getenv('DEPS_PREFIX')
499  return (env and env ~= '') and env or '.deps/usr'
500end
501
502local tests_skipped = 0
503
504function M.check_cores(app, force) -- luacheck: ignore
505  -- Temporary workaround: skip core check as it interferes with CI.
506  if true then
507    return
508  end
509  app = app or 'build/bin/nvim' -- luacheck: ignore
510  --- @type string, string?, string[]
511  local initial_path, re, exc_re
512  local gdb_db_cmd =
513    'gdb -n -batch -ex "thread apply all bt full" "$_NVIM_TEST_APP" -c "$_NVIM_TEST_CORE"'
514  local lldb_db_cmd = 'lldb -Q -o "bt all" -f "$_NVIM_TEST_APP" -c "$_NVIM_TEST_CORE"'
515  local random_skip = false
516  -- Workspace-local $TMPDIR, scrubbed and pattern-escaped.
517  -- "./Xtest-tmpdir/" => "Xtest%-tmpdir"
518  local local_tmpdir = nil
519  if tmpdir_is_local and tmpdir then
520    local_tmpdir =
521      vim.pesc(vim.fs.relpath(assert(vim.uv.cwd()), tmpdir):gsub('^[ ./]+', ''):gsub('%/+$', ''))
522  end
523
524  local db_cmd --- @type string
525  local test_glob_dir = os.getenv('NVIM_TEST_CORE_GLOB_DIRECTORY')
526  if test_glob_dir and test_glob_dir ~= '' then
527    initial_path = test_glob_dir
528    re = os.getenv('NVIM_TEST_CORE_GLOB_RE')
529    exc_re = { os.getenv('NVIM_TEST_CORE_EXC_RE'), local_tmpdir }
530    db_cmd = os.getenv('NVIM_TEST_CORE_DB_CMD') or gdb_db_cmd
531    random_skip = os.getenv('NVIM_TEST_CORE_RANDOM_SKIP') ~= ''
532  elseif M.is_os('mac') then
533    initial_path = '/cores'
534    re = nil
535    exc_re = { local_tmpdir }
536    db_cmd = lldb_db_cmd
537  else
538    initial_path = '.'
539    if M.is_os('freebsd') then
540      re = '/nvim.core$'
541    else
542      re = '/core[^/]*$'
543    end
544    exc_re = { '^/%.deps$', '^/%' .. deps_prefix() .. '$', local_tmpdir, '^/%node_modules$' }
545    db_cmd = gdb_db_cmd
546    random_skip = true
547  end
548  -- Finding cores takes too much time on linux
549  if not force and random_skip and math.random() < 0.9 then
550    tests_skipped = tests_skipped + 1
551    return
552  end
553  local cores = M.glob(initial_path, re, exc_re)
554  local found_cores = 0
555  local out = io.stdout
556  for _, core in ipairs(cores) do
557    local len = 80 - #core - #'Core file ' - 2
558    local esigns = ('='):rep(len / 2)
559    out:write(('\n%s Core file %s %s\n'):format(esigns, core, esigns))
560    out:flush()
561    os.execute(db_cmd:gsub('%$_NVIM_TEST_APP', app):gsub('%$_NVIM_TEST_CORE', core) .. ' 2>&1')
562    out:write('\n')
563    found_cores = found_cores + 1
564    os.remove(core)
565  end
566  if found_cores ~= 0 then
567    out:write(('\nTests covered by this check: %u\n'):format(tests_skipped + 1))
568  end
569  tests_skipped = 0
570  if found_cores > 0 then
571    error('crash detected (see above)')
572  end
573end
574
575--- @return string?
576function M.repeated_read_cmd(...)
577  local cmd = M.argss_to_cmd(...)
578  local data = {}
579  local got_code = nil
580  local stdout = assert(vim.uv.new_pipe(false))
581  local handle = assert(
582    vim.uv.spawn(
583      cmd[1],
584      { args = vim.list_slice(cmd, 2), stdio = { nil, stdout, 2 }, hide = true },
585      function(code, _signal)
586        got_code = code
587      end
588    )
589  )
590  stdout:read_start(function(err, chunk)
591    if err or chunk == nil then
592      stdout:read_stop()
593      stdout:close()
594    else
595      table.insert(data, chunk)
596    end
597  end)
598
599  while not stdout:is_closing() or got_code == nil do
600    vim.uv.run('once')
601  end
602
603  if got_code ~= 0 then
604    error('command ' .. vim.inspect(cmd) .. 'unexpectedly exited with status ' .. got_code)
605  end
606  handle:close()
607  return table.concat(data)
608end
609
610--- Projects the named fields of `t` (a nil field stays absent).
611--- @param t table<string,any>
612--- @param ... string Field names.
613--- @return table<string,any>
614function M.pick(t, ...)
615  local r = {} --- @type table<string,any>
616  for _, f in ipairs({ ... }) do
617    r[f] = t[f]
618  end
619  return r
620end
621
622--- @generic T
623--- @param orig T
624--- @return T
625function M.shallowcopy(orig)
626  if type(orig) ~= 'table' then
627    return orig
628  end
629  --- @cast orig table<any,any>
630  local copy = {} --- @type table<any,any>
631  for orig_key, orig_value in pairs(orig) do
632    copy[orig_key] = orig_value
633  end
634  return copy
635end
636
637--- @param d1 table<any,any>
638--- @param d2 table<any,any>
639--- @return table<any,any>
640function M.mergedicts_copy(d1, d2)
641  local ret = M.shallowcopy(d1)
642  for k, v in pairs(d2) do
643    if d2[k] == vim.NIL then
644      ret[k] = nil
645    elseif type(d1[k]) == 'table' and type(v) == 'table' then
646      ret[k] = M.mergedicts_copy(d1[k], v)
647    else
648      ret[k] = v
649    end
650  end
651  return ret
652end
653
654--- dictdiff: find a diff so that mergedicts_copy(d1, diff) is equal to d2
655---
656--- Note: does not do copies of d2 values used.
657--- @param d1 table<any,any>
658--- @param d2 table<any,any>
659function M.dictdiff(d1, d2)
660  local ret = {} --- @type table<any,any>
661  local hasdiff = false
662  for k, v in pairs(d1) do
663    if d2[k] == nil then
664      hasdiff = true
665      ret[k] = vim.NIL
666    elseif type(v) == type(d2[k]) then
667      if type(v) == 'table' then
668        local subdiff = M.dictdiff(v, d2[k])
669        if subdiff ~= nil then
670          hasdiff = true
671          ret[k] = subdiff
672        end
673      elseif v ~= d2[k] then
674        ret[k] = d2[k]
675        hasdiff = true
676      end
677    else
678      ret[k] = d2[k]
679      hasdiff = true
680    end
681  end
682  local shallowcopy = M.shallowcopy
683  for k, v in pairs(d2) do
684    if d1[k] == nil then
685      ret[k] = shallowcopy(v)
686      hasdiff = true
687    end
688  end
689  if hasdiff then
690    return ret
691  else
692    return nil
693  end
694end
695
696-- Concat list-like tables.
697function M.concat_tables(...)
698  local ret = {} --- @type table<any,any>
699  for i = 1, select('#', ...) do
700    --- @type table<any,any>
701    local tbl = select(i, ...)
702    if tbl then
703      for _, v in ipairs(tbl) do
704        ret[#ret + 1] = v
705      end
706    end
707  end
708  return ret
709end
710
711--- Get all permutations of an array.
712---
713--- @param arr any[]
714--- @return any[][]
715function M.permutations(arr)
716  local res = {} --- @type any[][]
717  --- @param a any[]
718  --- @param n integer
719  local function gen(a, n)
720    if n == 0 then
721      res[#res + 1] = M.shallowcopy(a)
722      return
723    end
724    for i = 1, n do
725      a[n], a[i] = a[i], a[n]
726      gen(a, n - 1)
727      a[n], a[i] = a[i], a[n]
728    end
729  end
730  gen(M.shallowcopy(arr), #arr)
731  return res
732end
733
734--- @param str string
735--- @param leave_indent? integer
736--- @return string
737function M.dedent(str, leave_indent)
738  -- Last blank line often has non-matching indent, so remove it.
739  str = str:gsub('\n[ ]+$', '\n')
740  return (vim.text.indent(leave_indent or 0, str))
741end
742
743function M.intchar2lua(ch)
744  ch = tonumber(ch)
745  return (20 <= ch and ch < 127) and ('%c'):format(ch) or ch
746end
747
748--- @param str string
749--- @return string
750function M.hexdump(str)
751  local len = string.len(str)
752  local dump = ''
753  local hex = ''
754  local asc = ''
755
756  for i = 1, len do
757    if 1 == i % 8 then
758      dump = dump .. hex .. asc .. '\n'
759      hex = string.format('%04x: ', i - 1)
760      asc = ''
761    end
762
763    local ord = string.byte(str, i)
764    hex = hex .. string.format('%02x ', ord)
765    if ord >= 32 and ord <= 126 then
766      asc = asc .. string.char(ord)
767    else
768      asc = asc .. '.'
769    end
770  end
771
772  return dump .. hex .. string.rep('   ', 8 - len % 8) .. asc
773end
774
775--- Reads text lines from `filename` into a table.
776--- @param filename string path to file
777--- @param start? integer start line (1-indexed), negative means "lines before end" (tail)
778--- @return string[]?
779function M.read_file_list(filename, start)
780  local lnum = (start ~= nil and type(start) == 'number') and start or 1
781  local tail = (lnum < 0)
782  local maxlines = tail and math.abs(lnum) or nil
783  local file = io.open(filename, 'r')
784  if not file then
785    return nil
786  end
787
788  -- There is no need to read more than the last 2MB of the log file, so seek
789  -- to that.
790  local file_size = file:seek('end')
791  local offset = file_size - 2000000
792  if offset < 0 then
793    offset = 0
794  end
795  file:seek('set', offset)
796
797  local lines = {}
798  local i = 1
799  local line = file:read('*l')
800  while line ~= nil do
801    if i >= lnum then
802      table.insert(lines, line)
803      if maxlines and #lines > maxlines then
804        table.remove(lines, 1)
805      end
806    end
807    i = i + 1
808    line = file:read('*l')
809  end
810  file:close()
811  return lines
812end
813
814--- Reads the entire contents of `filename` into a string.
815--- @param filename string
816--- @return string?
817function M.read_file(filename)
818  local file = io.open(filename, 'r')
819  if not file then
820    return nil
821  end
822  local ret = file:read('*a')
823  file:close()
824  return ret
825end
826
827-- Dedent the given text and write it to the file name.
828function M.write_file(name, text, no_dedent, append)
829  local file = assert(io.open(name, (append and 'a' or 'w')))
830  if type(text) == 'table' then
831    -- Byte blob
832    --- @type string[]
833    local bytes = text
834    text = ''
835    for _, char in ipairs(bytes) do
836      text = ('%s%c'):format(text, char)
837    end
838  elseif not no_dedent then
839    text = M.dedent(text)
840  end
841  file:write(text)
842  file:flush()
843  file:close()
844end
845
846--- @param name? 'github'
847--- @return boolean
848function M.is_ci(name)
849  return harness.is_ci(name)
850end
851
852-- Gets the (tail) contents of `logfile`.
853-- Also moves the file to "${NVIM_LOG_FILE}.displayed" on CI environments.
854function M.read_nvim_log(logfile, ci_rename)
855  logfile = logfile or os.getenv('NVIM_LOG_FILE') or 'nvim.log'
856  local log = harness.read_nvim_log(logfile, ci_rename)
857  assert(log, ('logfile not found: %q'):format(logfile))
858  return log
859end
860
861--- @param path string
862--- @return boolean?
863function M.mkdir(path)
864  -- 493 is 0755 in decimal
865  return (uv.fs_mkdir(path, 493))
866end
867
868--- @param expected any[]
869--- @param received any[]
870--- @param kind string
871--- @return any
872function M.expect_events(expected, received, kind)
873  if not pcall(M.eq, expected, received) then
874    local msg = 'unexpected ' .. kind .. ' received.\n\n'
875
876    msg = msg .. 'received events:\n'
877    for _, e in ipairs(received) do
878      msg = msg .. '  ' .. vim.inspect(e) .. ';\n'
879    end
880    msg = msg .. '\nexpected events:\n'
881    for _, e in ipairs(expected) do
882      msg = msg .. '  ' .. vim.inspect(e) .. ';\n'
883    end
884    error(msg, 2)
885  end
886  return received
887end
888
889--- @param cond boolean
890--- @param reason? string
891--- @return boolean
892function M.skip(cond, reason)
893  if cond then
894    M.pending(reason or 'FIXME')
895    return true
896  end
897  return false
898end
899
900-- Calls pending() and returns `true` if the system is too slow to
901-- run fragile or expensive tests. Else returns `false`.
902function M.skip_fragile(pending_fn, cond)
903  if pending_fn == nil or type(pending_fn) ~= type(function() end) then
904    error('invalid pending_fn')
905  end
906  if cond then
907    pending_fn('skipped (test is fragile on this system)', function() end)
908    return true
909  elseif os.getenv('TEST_SKIP_FRAGILE') then
910    pending_fn('skipped (TEST_SKIP_FRAGILE)', function() end)
911    return true
912  end
913  return false
914end
915
916function M.translations_enabled()
917  return M.paths.translations_enabled
918end
919
920--- Sorts timing `samples` and prints + returns min/q25/median/q75/max/mean.
921---
922--- Shared reporter for `test/benchmark/`. Pair it with `M.bench()` (in-process) or `n.bench()`
923--- (Nvim-under-test), or call it directly with samples you collected yourself.
924---
925--- @param samples number[]  Per-iteration durations, in nanoseconds. Sorted in place.
926--- @param opts? { label?: string, unit?: 'ms'|'us' }
927--- @return { n: integer, min: number, q25: number, median: number, q75: number, max: number, mean: number }
928function M.bench_report(samples, opts)
929  opts = opts or {}
930  local n = #samples
931  assert(n > 0, 'bench_report: no samples')
932  local unit = opts.unit or 'ms'
933  local scale = unit == 'us' and 1e3 or 1e6
934
935  table.sort(samples)
936  local sum = 0
937  for _, v in ipairs(samples) do
938    sum = sum + v
939  end
940  --- @param p number percentile in [0,1]
941  local function pct(p)
942    return samples[math.max(1, math.min(n, 1 + math.floor(n * p)))] / scale
943  end
944  local stats = {
945    n = n,
946    min = samples[1] / scale,
947    q25 = pct(0.25),
948    median = pct(0.5),
949    q75 = pct(0.75),
950    max = samples[n] / scale,
951    mean = (sum / n) / scale,
952  }
953
954  print(
955    ('\n%smin %.4f  q25 %.4f  median %.4f  q75 %.4f  max %.4f  mean %.4f  (%s, n=%d)'):format(
956      opts.label and (opts.label .. '\n  ') or '',
957      stats.min,
958      stats.q25,
959      stats.median,
960      stats.q75,
961      stats.max,
962      stats.mean,
963      unit,
964      n
965    )
966  )
967  return stats
968end
969
970--- Benchmarks `fn` in the test-runner process: runs it `opts.n` times, timing each run, then reports.
971---
972--- Note: see `testnvim.bench()` to run in the Nvim-under-test.
973---
974--- @param fn fun()
975--- @param opts { n: integer, label?: string, unit?: 'ms'|'us', warmup?: integer }
976--- @return table stats  See `M.bench_report()`.
977function M.bench(fn, opts)
978  for _ = 1, (opts.warmup or 0) do
979    fn()
980  end
981  local samples = {} --- @type number[]
982  for i = 1, opts.n do
983    local t0 = uv.hrtime()
984    fn()
985    samples[i] = uv.hrtime() - t0
986  end
987  return M.bench_report(samples, opts)
988end
989
990return M