helpers.lua 23 KB

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