fix problem with escaping zero and other control characters

This commit is contained in:
Andreas Hofer 2016-03-29 21:58:17 +02:00
parent a998635207
commit 2a5205e53c
2 changed files with 13 additions and 3 deletions

View File

@ -41,12 +41,17 @@ local function smartQuote(str)
end end
local controlCharsTranslation = { local controlCharsTranslation = {
["\a"] = "\\a", ["\b"] = "\\b", ["\f"] = "\\f", ["\n"] = "\\n", ["\\7"] = "\\a", ["\\007"] = "\\a",
["\r"] = "\\r", ["\t"] = "\\t", ["\v"] = "\\v" ["\\8"] = "\\b", ["\\008"] = "\\b",
["\\12"] = "\\f", ["\\012"] = "\\f",
["\\13"] = "\\r", ["\\013"] = "\\r",
["\\9"] = "\\t", ["\\009"] = "\\t",
["\\11"] = "\\v", ["\\011"] = "\\v",
} }
local function escape(str) local function escape(str)
local result = str:gsub("\\", "\\\\"):gsub("(%c)", controlCharsTranslation) local f = string.format("%q", str)
local result = f:gsub("\\%d%d?%d?", controlCharsTranslation):gsub("\\\n", "\\n"):gsub('\\"', '"'):sub(2,-2)
return result return result
end end

View File

@ -38,6 +38,11 @@ describe( 'inspect', function()
assert.equals('"I have \\b a back space"', inspect('I have \b a back space')) assert.equals('"I have \\b a back space"', inspect('I have \b a back space'))
end) end)
it('escapes zeroes and other control characters properly', function()
assert.equals('"I have \\0 zeroes \\0000 and other \\1 control \\0010 characters"',
inspect('I have \0 zeroes \0000 and other \1 control \0010 characters'))
end)
it('backslashes its backslashes', function() it('backslashes its backslashes', function()
assert.equals('"I have \\\\ a backslash"', inspect('I have \\ a backslash')) assert.equals('"I have \\\\ a backslash"', inspect('I have \\ a backslash'))
assert.equals('"I have \\\\\\\\ two backslashes"', inspect('I have \\\\ two backslashes')) assert.equals('"I have \\\\\\\\ two backslashes"', inspect('I have \\\\ two backslashes'))