File: unindent.lua

package info (click to toggle)
lua-inspect 3.1.1-2.1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 140 kB
  • sloc: makefile: 2
file content (39 lines) | stat: -rw-r--r-- 788 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
-- Unindenting transforms a string like this:
-- [[
--     {
--       foo = 1,
--       bar = 2
--     }
-- ]]
--
-- Into the same one without indentation, nor start/end newlines
--
-- [[{
--   foo = 1,
--   bar = 2
-- }]]
--
-- This makes the strings look and read better in the tests
--

local getIndentPreffix = function(str)
  local level = math.huge
  local minPreffix = ""
  local len
  for preffix in str:gmatch("\n( +)") do
    len = #preffix
    if len < level then
      level = len
      minPreffix = preffix
    end
  end
  return minPreffix
end

local unindent = function(str)
  str = str:gsub(" +$", ""):gsub("^ +", "") -- remove spaces at start and end
  local preffix = getIndentPreffix(str)
  return (str:gsub("\n" .. preffix, "\n"):gsub("\n$", ""))
end

return unindent