helpers.lua 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824
  1. require('vim.compat')
  2. local shared = require('vim.shared')
  3. local assert = require('luassert')
  4. local luv = require('luv')
  5. local lfs = require('lfs')
  6. local relpath = require('pl.path').relpath
  7. local Paths = require('test.config.paths')
  8. assert:set_parameter('TableFormatLevel', 100)
  9. local quote_me = '[^.%w%+%-%@%_%/]' -- complement (needn't quote)
  10. local function shell_quote(str)
  11. if string.find(str, quote_me) or str == '' then
  12. return '"' .. str:gsub('[$%%"\\]', '\\%0') .. '"'
  13. else
  14. return str
  15. end
  16. end
  17. local module = {
  18. REMOVE_THIS = {},
  19. }
  20. function module.argss_to_cmd(...)
  21. local cmd = ''
  22. for i = 1, select('#', ...) do
  23. local arg = select(i, ...)
  24. if type(arg) == 'string' then
  25. cmd = cmd .. ' ' ..shell_quote(arg)
  26. else
  27. for _, subarg in ipairs(arg) do
  28. cmd = cmd .. ' ' .. shell_quote(subarg)
  29. end
  30. end
  31. end
  32. return cmd
  33. end
  34. function module.popen_r(...)
  35. return io.popen(module.argss_to_cmd(...), 'r')
  36. end
  37. function module.popen_w(...)
  38. return io.popen(module.argss_to_cmd(...), 'w')
  39. end
  40. -- sleeps the test runner (_not_ the nvim instance)
  41. function module.sleep(ms)
  42. luv.sleep(ms)
  43. end
  44. local check_logs_useless_lines = {
  45. ['Warning: noted but unhandled ioctl']=1,
  46. ['could cause spurious value errors to appear']=2,
  47. ['See README_MISSING_SYSCALL_OR_IOCTL for guidance']=3,
  48. }
  49. --- Invokes `fn` and includes the tail of `logfile` in the error message if it
  50. --- fails.
  51. ---
  52. ---@param logfile Log file, defaults to $NVIM_LOG_FILE or '.nvimlog'
  53. ---@param fn Function to invoke
  54. ---@param ... Function arguments
  55. local function dumplog(logfile, fn, ...)
  56. -- module.validate({
  57. -- logfile={logfile,'s',true},
  58. -- fn={fn,'f',false},
  59. -- })
  60. local status, rv = pcall(fn, ...)
  61. if status == false then
  62. logfile = logfile or os.getenv('NVIM_LOG_FILE') or '.nvimlog'
  63. local logtail = module.read_nvim_log(logfile)
  64. error(string.format('%s\n%s', tostring(rv), logtail))
  65. end
  66. end
  67. function module.eq(expected, actual, context, logfile)
  68. return dumplog(logfile, assert.are.same, expected, actual, context)
  69. end
  70. function module.neq(expected, actual, context, logfile)
  71. return dumplog(logfile, assert.are_not.same, expected, actual, context)
  72. end
  73. function module.ok(res, msg, logfile)
  74. return dumplog(logfile, assert.is_true, res, msg)
  75. end
  76. -- TODO(bfredl): this should "failure" not "error" (issue with dumplog() )
  77. local function epicfail(state, arguments, _)
  78. state.failure_message = arguments[1]
  79. return false
  80. end
  81. assert:register("assertion", "epicfail", epicfail)
  82. function module.fail(msg, logfile)
  83. return dumplog(logfile, assert.epicfail, msg)
  84. end
  85. function module.matches(pat, actual)
  86. if nil ~= string.match(actual, pat) then
  87. return true
  88. end
  89. error(string.format('Pattern does not match.\nPattern:\n%s\nActual:\n%s', pat, actual))
  90. end
  91. --- Asserts that `pat` matches one or more lines in the tail of $NVIM_LOG_FILE.
  92. ---
  93. ---@param pat (string) Lua pattern to search for in the log file.
  94. ---@param logfile (string, default=$NVIM_LOG_FILE) full path to log file.
  95. function module.assert_log(pat, logfile)
  96. logfile = logfile or os.getenv('NVIM_LOG_FILE') or '.nvimlog'
  97. local nrlines = 10
  98. local lines = module.read_file_list(logfile, -nrlines) or {}
  99. for _,line in ipairs(lines) do
  100. if line:match(pat) then return end
  101. end
  102. local logtail = module.read_nvim_log(logfile)
  103. error(string.format('Pattern %q not found in log (last %d lines): %s:\n%s',
  104. pat, nrlines, logfile, logtail))
  105. end
  106. -- Invokes `fn` and returns the error string (with truncated paths), or raises
  107. -- an error if `fn` succeeds.
  108. --
  109. -- Replaces line/column numbers with zero:
  110. -- shared.lua:0: in function 'gsplit'
  111. -- shared.lua:0: in function <shared.lua:0>'
  112. --
  113. -- Usage:
  114. -- -- Match exact string.
  115. -- eq('e', pcall_err(function(a, b) error('e') end, 'arg1', 'arg2'))
  116. -- -- Match Lua pattern.
  117. -- matches('e[or]+$', pcall_err(function(a, b) error('some error') end, 'arg1', 'arg2'))
  118. --
  119. function module.pcall_err_withfile(fn, ...)
  120. assert(type(fn) == 'function')
  121. local status, rv = pcall(fn, ...)
  122. if status == true then
  123. error('expected failure, but got success')
  124. end
  125. -- From:
  126. -- C:/long/path/foo.lua:186: Expected string, got number
  127. -- to:
  128. -- .../foo.lua:0: Expected string, got number
  129. local errmsg = tostring(rv):gsub('([%s<])vim[/\\]([^%s:/\\]+):%d+', '%1\xffvim\xff%2:0')
  130. :gsub('[^%s<]-[/\\]([^%s:/\\]+):%d+', '.../%1:0')
  131. :gsub('\xffvim\xff', 'vim/')
  132. -- Scrub numbers in paths/stacktraces:
  133. -- shared.lua:0: in function 'gsplit'
  134. -- shared.lua:0: in function <shared.lua:0>'
  135. errmsg = errmsg:gsub('([^%s]):%d+', '%1:0')
  136. -- Scrub tab chars:
  137. errmsg = errmsg:gsub('\t', ' ')
  138. -- In Lua 5.1, we sometimes get a "(tail call): ?" on the last line.
  139. -- We remove this so that the tests are not lua dependent.
  140. errmsg = errmsg:gsub('%s*%(tail call%): %?', '')
  141. return errmsg
  142. end
  143. function module.pcall_err_withtrace(fn, ...)
  144. local errmsg = module.pcall_err_withfile(fn, ...)
  145. return errmsg:gsub('.../helpers.lua:0: ', '')
  146. end
  147. function module.pcall_err(...)
  148. return module.remove_trace(module.pcall_err_withtrace(...))
  149. end
  150. function module.remove_trace(s)
  151. return (s:gsub("\n%s*stack traceback:.*", ""))
  152. end
  153. -- initial_path: directory to recurse into
  154. -- re: include pattern (string)
  155. -- exc_re: exclude pattern(s) (string or table)
  156. function module.glob(initial_path, re, exc_re)
  157. exc_re = type(exc_re) == 'table' and exc_re or { exc_re }
  158. local paths_to_check = {initial_path}
  159. local ret = {}
  160. local checked_files = {}
  161. local function is_excluded(path)
  162. for _, pat in pairs(exc_re) do
  163. if path:match(pat) then return true end
  164. end
  165. return false
  166. end
  167. if is_excluded(initial_path) then
  168. return ret
  169. end
  170. while #paths_to_check > 0 do
  171. local cur_path = paths_to_check[#paths_to_check]
  172. paths_to_check[#paths_to_check] = nil
  173. for e in lfs.dir(cur_path) do
  174. local full_path = cur_path .. '/' .. e
  175. local checked_path = full_path:sub(#initial_path + 1)
  176. if (not is_excluded(checked_path)) and e:sub(1, 1) ~= '.' then
  177. local attrs = lfs.attributes(full_path)
  178. if attrs then
  179. local check_key = attrs.dev .. ':' .. tostring(attrs.ino)
  180. if not checked_files[check_key] then
  181. checked_files[check_key] = true
  182. if attrs.mode == 'directory' then
  183. paths_to_check[#paths_to_check + 1] = full_path
  184. elseif not re or checked_path:match(re) then
  185. ret[#ret + 1] = full_path
  186. end
  187. end
  188. end
  189. end
  190. end
  191. end
  192. return ret
  193. end
  194. function module.check_logs()
  195. local log_dir = os.getenv('LOG_DIR')
  196. local runtime_errors = {}
  197. if log_dir and lfs.attributes(log_dir, 'mode') == 'directory' then
  198. for tail in lfs.dir(log_dir) do
  199. if tail:sub(1, 30) == 'valgrind-' or tail:find('san%.') then
  200. local file = log_dir .. '/' .. tail
  201. local fd = io.open(file)
  202. local start_msg = ('='):rep(20) .. ' File ' .. file .. ' ' .. ('='):rep(20)
  203. local lines = {}
  204. local warning_line = 0
  205. for line in fd:lines() do
  206. local cur_warning_line = check_logs_useless_lines[line]
  207. if cur_warning_line == warning_line + 1 then
  208. warning_line = cur_warning_line
  209. else
  210. lines[#lines + 1] = line
  211. end
  212. end
  213. fd:close()
  214. if #lines > 0 then
  215. local status, f
  216. local out = io.stdout
  217. if os.getenv('SYMBOLIZER') then
  218. status, f = pcall(module.popen_r, os.getenv('SYMBOLIZER'), '-l', file)
  219. end
  220. out:write(start_msg .. '\n')
  221. if status then
  222. for line in f:lines() do
  223. out:write('= '..line..'\n')
  224. end
  225. f:close()
  226. else
  227. out:write('= ' .. table.concat(lines, '\n= ') .. '\n')
  228. end
  229. out:write(select(1, start_msg:gsub('.', '=')) .. '\n')
  230. table.insert(runtime_errors, file)
  231. end
  232. os.remove(file)
  233. end
  234. end
  235. end
  236. assert(0 == #runtime_errors, string.format(
  237. 'Found runtime errors in logfile(s): %s',
  238. table.concat(runtime_errors, ', ')))
  239. end
  240. function module.iswin()
  241. return package.config:sub(1,1) == '\\'
  242. end
  243. -- Gets (lowercase) OS name from CMake, uname, or "win" if iswin().
  244. module.uname = (function()
  245. local platform = nil
  246. return (function()
  247. if platform then
  248. return platform
  249. end
  250. if os.getenv("SYSTEM_NAME") then -- From CMAKE_SYSTEM_NAME.
  251. platform = string.lower(os.getenv("SYSTEM_NAME"))
  252. return platform
  253. end
  254. local status, f = pcall(module.popen_r, 'uname', '-s')
  255. if status then
  256. platform = string.lower(f:read("*l"))
  257. f:close()
  258. elseif module.iswin() then
  259. platform = 'windows'
  260. else
  261. error('unknown platform')
  262. end
  263. return platform
  264. end)
  265. end)()
  266. function module.is_os(s)
  267. if not (s == 'win' or s == 'mac' or s == 'unix') then
  268. error('unknown platform: '..tostring(s))
  269. end
  270. return ((s == 'win' and module.iswin())
  271. or (s == 'mac' and module.uname() == 'darwin')
  272. or (s == 'unix'))
  273. end
  274. local function tmpdir_get()
  275. return os.getenv('TMPDIR') and os.getenv('TMPDIR') or os.getenv('TEMP')
  276. end
  277. -- Is temp directory `dir` defined local to the project workspace?
  278. local function tmpdir_is_local(dir)
  279. return not not (dir and string.find(dir, 'Xtest'))
  280. end
  281. module.tmpname = (function()
  282. local seq = 0
  283. local tmpdir = tmpdir_get()
  284. return (function()
  285. if tmpdir_is_local(tmpdir) then
  286. -- Cannot control os.tmpname() dir, so hack our own tmpname() impl.
  287. seq = seq + 1
  288. local fname = tmpdir..'/nvim-test-lua-'..seq
  289. io.open(fname, 'w'):close()
  290. return fname
  291. else
  292. local fname = os.tmpname()
  293. if module.uname() == 'windows' and fname:sub(1, 2) == '\\s' then
  294. -- In Windows tmpname() returns a filename starting with
  295. -- special sequence \s, prepend $TEMP path
  296. return tmpdir..fname
  297. elseif fname:match('^/tmp') and module.uname() == 'darwin' then
  298. -- In OS X /tmp links to /private/tmp
  299. return '/private'..fname
  300. else
  301. return fname
  302. end
  303. end
  304. end)
  305. end)()
  306. function module.hasenv(name)
  307. local env = os.getenv(name)
  308. if env and env ~= '' then
  309. return env
  310. end
  311. return nil
  312. end
  313. local function deps_prefix()
  314. local env = os.getenv('DEPS_PREFIX')
  315. return (env and env ~= '') and env or '.deps/usr'
  316. end
  317. local tests_skipped = 0
  318. function module.check_cores(app, force)
  319. app = app or 'build/bin/nvim'
  320. local initial_path, re, exc_re
  321. local gdb_db_cmd = 'gdb -n -batch -ex "thread apply all bt full" "$_NVIM_TEST_APP" -c "$_NVIM_TEST_CORE"'
  322. local lldb_db_cmd = 'lldb -Q -o "bt all" -f "$_NVIM_TEST_APP" -c "$_NVIM_TEST_CORE"'
  323. local random_skip = false
  324. -- Workspace-local $TMPDIR, scrubbed and pattern-escaped.
  325. -- "./Xtest-tmpdir/" => "Xtest%-tmpdir"
  326. local local_tmpdir = (tmpdir_is_local(tmpdir_get())
  327. and relpath(tmpdir_get()):gsub('^[ ./]+',''):gsub('%/+$',''):gsub('([^%w])', '%%%1')
  328. or nil)
  329. local db_cmd
  330. if module.hasenv('NVIM_TEST_CORE_GLOB_DIRECTORY') then
  331. initial_path = os.getenv('NVIM_TEST_CORE_GLOB_DIRECTORY')
  332. re = os.getenv('NVIM_TEST_CORE_GLOB_RE')
  333. exc_re = { os.getenv('NVIM_TEST_CORE_EXC_RE'), local_tmpdir }
  334. db_cmd = os.getenv('NVIM_TEST_CORE_DB_CMD') or gdb_db_cmd
  335. random_skip = os.getenv('NVIM_TEST_CORE_RANDOM_SKIP')
  336. elseif 'darwin' == module.uname() then
  337. initial_path = '/cores'
  338. re = nil
  339. exc_re = { local_tmpdir }
  340. db_cmd = lldb_db_cmd
  341. else
  342. initial_path = '.'
  343. if 'freebsd' == module.uname() then
  344. re = '/nvim.core$'
  345. else
  346. re = '/core[^/]*$'
  347. end
  348. exc_re = { '^/%.deps$', '^/%'..deps_prefix()..'$', local_tmpdir, '^/%node_modules$' }
  349. db_cmd = gdb_db_cmd
  350. random_skip = true
  351. end
  352. -- Finding cores takes too much time on linux
  353. if not force and random_skip and math.random() < 0.9 then
  354. tests_skipped = tests_skipped + 1
  355. return
  356. end
  357. local cores = module.glob(initial_path, re, exc_re)
  358. local found_cores = 0
  359. local out = io.stdout
  360. for _, core in ipairs(cores) do
  361. local len = 80 - #core - #('Core file ') - 2
  362. local esigns = ('='):rep(len / 2)
  363. out:write(('\n%s Core file %s %s\n'):format(esigns, core, esigns))
  364. out:flush()
  365. os.execute(db_cmd:gsub('%$_NVIM_TEST_APP', app):gsub('%$_NVIM_TEST_CORE', core) .. ' 2>&1')
  366. out:write('\n')
  367. found_cores = found_cores + 1
  368. os.remove(core)
  369. end
  370. if found_cores ~= 0 then
  371. out:write(('\nTests covered by this check: %u\n'):format(tests_skipped + 1))
  372. end
  373. tests_skipped = 0
  374. if found_cores > 0 then
  375. error("crash detected (see above)")
  376. end
  377. end
  378. function module.which(exe)
  379. local pipe = module.popen_r('which', exe)
  380. local ret = pipe:read('*a')
  381. pipe:close()
  382. if ret == '' then
  383. return nil
  384. else
  385. return ret:sub(1, -2)
  386. end
  387. end
  388. function module.repeated_read_cmd(...)
  389. for _ = 1, 10 do
  390. local stream = module.popen_r(...)
  391. local ret = stream:read('*a')
  392. stream:close()
  393. if ret then
  394. return ret
  395. end
  396. end
  397. print('ERROR: Failed to execute ' .. module.argss_to_cmd(...) .. ': nil return after 10 attempts')
  398. return nil
  399. end
  400. function module.shallowcopy(orig)
  401. if type(orig) ~= 'table' then
  402. return orig
  403. end
  404. local copy = {}
  405. for orig_key, orig_value in pairs(orig) do
  406. copy[orig_key] = orig_value
  407. end
  408. return copy
  409. end
  410. function module.mergedicts_copy(d1, d2)
  411. local ret = module.shallowcopy(d1)
  412. for k, v in pairs(d2) do
  413. if d2[k] == module.REMOVE_THIS then
  414. ret[k] = nil
  415. elseif type(d1[k]) == 'table' and type(v) == 'table' then
  416. ret[k] = module.mergedicts_copy(d1[k], v)
  417. else
  418. ret[k] = v
  419. end
  420. end
  421. return ret
  422. end
  423. -- dictdiff: find a diff so that mergedicts_copy(d1, diff) is equal to d2
  424. --
  425. -- Note: does not do copies of d2 values used.
  426. function module.dictdiff(d1, d2)
  427. local ret = {}
  428. local hasdiff = false
  429. for k, v in pairs(d1) do
  430. if d2[k] == nil then
  431. hasdiff = true
  432. ret[k] = module.REMOVE_THIS
  433. elseif type(v) == type(d2[k]) then
  434. if type(v) == 'table' then
  435. local subdiff = module.dictdiff(v, d2[k])
  436. if subdiff ~= nil then
  437. hasdiff = true
  438. ret[k] = subdiff
  439. end
  440. elseif v ~= d2[k] then
  441. ret[k] = d2[k]
  442. hasdiff = true
  443. end
  444. else
  445. ret[k] = d2[k]
  446. hasdiff = true
  447. end
  448. end
  449. local shallowcopy = module.shallowcopy
  450. for k, v in pairs(d2) do
  451. if d1[k] == nil then
  452. ret[k] = shallowcopy(v)
  453. hasdiff = true
  454. end
  455. end
  456. if hasdiff then
  457. return ret
  458. else
  459. return nil
  460. end
  461. end
  462. function module.updated(d, d2)
  463. for k, v in pairs(d2) do
  464. d[k] = v
  465. end
  466. return d
  467. end
  468. -- Concat list-like tables.
  469. function module.concat_tables(...)
  470. local ret = {}
  471. for i = 1, select('#', ...) do
  472. local tbl = select(i, ...)
  473. if tbl then
  474. for _, v in ipairs(tbl) do
  475. ret[#ret + 1] = v
  476. end
  477. end
  478. end
  479. return ret
  480. end
  481. function module.dedent(str, leave_indent)
  482. -- find minimum common indent across lines
  483. local indent = nil
  484. for line in str:gmatch('[^\n]+') do
  485. local line_indent = line:match('^%s+') or ''
  486. if indent == nil or #line_indent < #indent then
  487. indent = line_indent
  488. end
  489. end
  490. if indent == nil or #indent == 0 then
  491. -- no minimum common indent
  492. return str
  493. end
  494. local left_indent = (' '):rep(leave_indent or 0)
  495. -- create a pattern for the indent
  496. indent = indent:gsub('%s', '[ \t]')
  497. -- strip it from the first line
  498. str = str:gsub('^'..indent, left_indent)
  499. -- strip it from the remaining lines
  500. str = str:gsub('[\n]'..indent, '\n' .. left_indent)
  501. return str
  502. end
  503. local function format_float(v)
  504. -- On windows exponent appears to have three digits and not two
  505. local ret = ('%.6e'):format(v)
  506. local l, f, es, e = ret:match('^(%-?%d)%.(%d+)e([+%-])0*(%d%d+)$')
  507. return l .. '.' .. f .. 'e' .. es .. e
  508. end
  509. local SUBTBL = {
  510. '\\000', '\\001', '\\002', '\\003', '\\004',
  511. '\\005', '\\006', '\\007', '\\008', '\\t',
  512. '\\n', '\\011', '\\012', '\\r', '\\014',
  513. '\\015', '\\016', '\\017', '\\018', '\\019',
  514. '\\020', '\\021', '\\022', '\\023', '\\024',
  515. '\\025', '\\026', '\\027', '\\028', '\\029',
  516. '\\030', '\\031',
  517. }
  518. -- Formats Lua value `v`.
  519. --
  520. -- TODO(justinmk): redundant with vim.inspect() ?
  521. --
  522. -- "Nice table formatting similar to screen:snapshot_util()".
  523. -- Commit: 520c0b91a528
  524. function module.format_luav(v, indent, opts)
  525. opts = opts or {}
  526. local linesep = '\n'
  527. local next_indent_arg = nil
  528. local indent_shift = opts.indent_shift or ' '
  529. local next_indent
  530. local nl = '\n'
  531. if indent == nil then
  532. indent = ''
  533. linesep = ''
  534. next_indent = ''
  535. nl = ' '
  536. else
  537. next_indent_arg = indent .. indent_shift
  538. next_indent = indent .. indent_shift
  539. end
  540. local ret = ''
  541. if type(v) == 'string' then
  542. if opts.literal_strings then
  543. ret = v
  544. else
  545. local quote = opts.dquote_strings and '"' or '\''
  546. ret = quote .. tostring(v):gsub(
  547. opts.dquote_strings and '["\\]' or '[\'\\]',
  548. '\\%0'):gsub(
  549. '[%z\1-\31]', function(match)
  550. return SUBTBL[match:byte() + 1]
  551. end) .. quote
  552. end
  553. elseif type(v) == 'table' then
  554. if v == module.REMOVE_THIS then
  555. ret = 'REMOVE_THIS'
  556. else
  557. local processed_keys = {}
  558. ret = '{' .. linesep
  559. local non_empty = false
  560. local format_luav = module.format_luav
  561. for i, subv in ipairs(v) do
  562. ret = ('%s%s%s,%s'):format(ret, next_indent,
  563. format_luav(subv, next_indent_arg, opts), nl)
  564. processed_keys[i] = true
  565. non_empty = true
  566. end
  567. for k, subv in pairs(v) do
  568. if not processed_keys[k] then
  569. if type(k) == 'string' and k:match('^[a-zA-Z_][a-zA-Z0-9_]*$') then
  570. ret = ret .. next_indent .. k .. ' = '
  571. else
  572. ret = ('%s%s[%s] = '):format(ret, next_indent,
  573. format_luav(k, nil, opts))
  574. end
  575. ret = ret .. format_luav(subv, next_indent_arg, opts) .. ',' .. nl
  576. non_empty = true
  577. end
  578. end
  579. if nl == ' ' and non_empty then
  580. ret = ret:sub(1, -3)
  581. end
  582. ret = ret .. indent .. '}'
  583. end
  584. elseif type(v) == 'number' then
  585. if v % 1 == 0 then
  586. ret = ('%d'):format(v)
  587. else
  588. ret = format_float(v)
  589. end
  590. elseif type(v) == 'nil' then
  591. ret = 'nil'
  592. elseif type(v) == 'boolean' then
  593. ret = (v and 'true' or 'false')
  594. else
  595. print(type(v))
  596. -- Not implemented yet
  597. assert(false)
  598. end
  599. return ret
  600. end
  601. -- Like Python repr(), "{!r}".format(s)
  602. --
  603. -- Commit: 520c0b91a528
  604. function module.format_string(fmt, ...)
  605. local i = 0
  606. local args = {...}
  607. local function getarg()
  608. i = i + 1
  609. return args[i]
  610. end
  611. local ret = fmt:gsub('%%[0-9*]*%.?[0-9*]*[cdEefgGiouXxqsr%%]', function(match)
  612. local subfmt = match:gsub('%*', function()
  613. return tostring(getarg())
  614. end)
  615. local arg = nil
  616. if subfmt:sub(-1) ~= '%' then
  617. arg = getarg()
  618. end
  619. if subfmt:sub(-1) == 'r' or subfmt:sub(-1) == 'q' then
  620. -- %r is like built-in %q, but it is supposed to single-quote strings and
  621. -- not double-quote them, and also work not only for strings.
  622. -- Builtin %q is replaced here as it gives invalid and inconsistent with
  623. -- luajit results for e.g. "\e" on lua: luajit transforms that into `\27`,
  624. -- lua leaves as-is.
  625. arg = module.format_luav(arg, nil, {dquote_strings = (subfmt:sub(-1) == 'q')})
  626. subfmt = subfmt:sub(1, -2) .. 's'
  627. end
  628. if subfmt == '%e' then
  629. return format_float(arg)
  630. else
  631. return subfmt:format(arg)
  632. end
  633. end)
  634. return ret
  635. end
  636. function module.intchar2lua(ch)
  637. ch = tonumber(ch)
  638. return (20 <= ch and ch < 127) and ('%c'):format(ch) or ch
  639. end
  640. local fixtbl_metatable = {
  641. __newindex = function()
  642. assert(false)
  643. end,
  644. }
  645. function module.fixtbl(tbl)
  646. return setmetatable(tbl, fixtbl_metatable)
  647. end
  648. function module.fixtbl_rec(tbl)
  649. local fixtbl_rec = module.fixtbl_rec
  650. for _, v in pairs(tbl) do
  651. if type(v) == 'table' then
  652. fixtbl_rec(v)
  653. end
  654. end
  655. return module.fixtbl(tbl)
  656. end
  657. function module.hexdump(str)
  658. local len = string.len(str)
  659. local dump = ""
  660. local hex = ""
  661. local asc = ""
  662. for i = 1, len do
  663. if 1 == i % 8 then
  664. dump = dump .. hex .. asc .. "\n"
  665. hex = string.format("%04x: ", i - 1)
  666. asc = ""
  667. end
  668. local ord = string.byte(str, i)
  669. hex = hex .. string.format("%02x ", ord)
  670. if ord >= 32 and ord <= 126 then
  671. asc = asc .. string.char(ord)
  672. else
  673. asc = asc .. "."
  674. end
  675. end
  676. return dump .. hex .. string.rep(" ", 8 - len % 8) .. asc
  677. end
  678. -- Reads text lines from `filename` into a table.
  679. --
  680. -- filename: path to file
  681. -- start: start line (1-indexed), negative means "lines before end" (tail)
  682. function module.read_file_list(filename, start)
  683. local lnum = (start ~= nil and type(start) == 'number') and start or 1
  684. local tail = (lnum < 0)
  685. local maxlines = tail and math.abs(lnum) or nil
  686. local file = io.open(filename, 'r')
  687. if not file then
  688. return nil
  689. end
  690. local lines = {}
  691. local i = 1
  692. for line in file:lines() do
  693. if i >= start then
  694. table.insert(lines, line)
  695. if #lines > maxlines then
  696. table.remove(lines, 1)
  697. end
  698. end
  699. i = i + 1
  700. end
  701. file:close()
  702. return lines
  703. end
  704. -- Reads the entire contents of `filename` into a string.
  705. --
  706. -- filename: path to file
  707. function module.read_file(filename)
  708. local file = io.open(filename, 'r')
  709. if not file then
  710. return nil
  711. end
  712. local ret = file:read('*a')
  713. file:close()
  714. return ret
  715. end
  716. -- Dedent the given text and write it to the file name.
  717. function module.write_file(name, text, no_dedent, append)
  718. local file = io.open(name, (append and 'a' or 'w'))
  719. if type(text) == 'table' then
  720. -- Byte blob
  721. local bytes = text
  722. text = ''
  723. for _, char in ipairs(bytes) do
  724. text = ('%s%c'):format(text, char)
  725. end
  726. elseif not no_dedent then
  727. text = module.dedent(text)
  728. end
  729. file:write(text)
  730. file:flush()
  731. file:close()
  732. end
  733. function module.isCI(name)
  734. local any = (name == nil)
  735. assert(any or name == 'appveyor' or name == 'travis' or name == 'sourcehut' or name == 'github')
  736. local av = ((any or name == 'appveyor') and nil ~= os.getenv('APPVEYOR'))
  737. local tr = ((any or name == 'travis') and nil ~= os.getenv('TRAVIS'))
  738. local sh = ((any or name == 'sourcehut') and nil ~= os.getenv('SOURCEHUT'))
  739. local gh = ((any or name == 'github') and nil ~= os.getenv('GITHUB_ACTIONS'))
  740. return tr or av or sh or gh
  741. end
  742. -- Gets the (tail) contents of `logfile`.
  743. -- Also moves the file to "${NVIM_LOG_FILE}.displayed" on CI environments.
  744. function module.read_nvim_log(logfile, ci_rename)
  745. logfile = logfile or os.getenv('NVIM_LOG_FILE') or '.nvimlog'
  746. local is_ci = module.isCI()
  747. local keep = is_ci and 999 or 10
  748. local lines = module.read_file_list(logfile, -keep) or {}
  749. local log = (('-'):rep(78)..'\n'
  750. ..string.format('$NVIM_LOG_FILE: %s\n', logfile)
  751. ..(#lines > 0 and '(last '..tostring(keep)..' lines)\n' or '(empty)\n'))
  752. for _,line in ipairs(lines) do
  753. log = log..line..'\n'
  754. end
  755. log = log..('-'):rep(78)..'\n'
  756. if is_ci and ci_rename then
  757. os.rename(logfile, logfile .. '.displayed')
  758. end
  759. return log
  760. end
  761. module = shared.tbl_extend('error', module, Paths, shared, require('test.deprecated'))
  762. return module