251 lines
8.5 KiB
Luau
251 lines
8.5 KiB
Luau
--!strict
|
|
-- data/ini: INI / config files, read the way Python's configparser does (interpolation off, key case kept). New code.
|
|
-- Supports: [sections] (name = everything between the first '[' and the last ']'), key = value and key: value,
|
|
-- ; and # comment lines (indented too), indented continuation lines (joined with "\n"), keys before any section (at
|
|
-- the top level), duplicate keys / sections (the last value wins, sections merge), inline comments, keys without a
|
|
-- value and typed values by option. Decodes to a Types.object of sections (each a Types.object of strings), top-level
|
|
-- keys beside them. Encode writes configparser's layout ("key = value", a blank line after each section, nested
|
|
-- tables as dotted section names). Not supported: interpolation, the DEFAULT section's inheritance, escapes.
|
|
|
|
-- ------------------------------------------------------------------------------------------------ requires
|
|
local Err = require("@formats/core/Err")
|
|
local Bytes = require("@formats/core/Bytes")
|
|
local Types = require("@formats/Types")
|
|
local Json = require("@formats/codecs/Json")
|
|
|
|
-- ------------------------------------------------------------------------------------------------ contract
|
|
local Ini = {
|
|
name = "ini",
|
|
category = "data",
|
|
extensions = { "ini", "cfg", "conf", "inf", "desktop" },
|
|
mime = { "text/plain" },
|
|
deps = { "core/Err", "core/Bytes", "Types", "codecs/Json" },
|
|
caps = { decode = true, encode = true, ordered = true },
|
|
}
|
|
|
|
export type DecodeOptions = {
|
|
inlineComments: boolean?, -- strip " ;..." / " #..." after values (default false, like configparser)
|
|
allowNoValue: boolean?, -- a line with a key and no delimiter is the key with value true (default false: an error)
|
|
types: boolean?, -- values that are numbers / true / false / yes / no / on / off become numbers / booleans
|
|
strict: boolean?, -- a duplicate section or key is an error (default false: last wins / merge)
|
|
}
|
|
export type EncodeOptions = {
|
|
delimiter: string?, -- default " = "
|
|
}
|
|
|
|
-- ------------------------------------------------------------------------------------------------ sniff
|
|
function Ini.sniff(r: Bytes.Reader): number
|
|
local head = r:peek(512)
|
|
if string.find(head, "%z") then
|
|
return 0
|
|
end
|
|
local first = string.match(head, "^[%s]*([^\r\n]*)")
|
|
while first and string.match(first, "^[;#]") do
|
|
head = string.match(head, "^[^\n]*\n(.*)$") or ""
|
|
first = string.match(head, "^[%s]*([^\r\n]*)")
|
|
end
|
|
if first and string.match(first, "^%[[^%]]+%]%s*$") then
|
|
return 0.2
|
|
end
|
|
return 0
|
|
end
|
|
|
|
-- ------------------------------------------------------------------------------------------------ decode
|
|
local BOOLS: { [string]: boolean } = { ["true"] = true, ["false"] = false, yes = true, no = false, on = true, off = false }
|
|
|
|
local function typed(v: any): any
|
|
if type(v) ~= "string" then
|
|
return v
|
|
end
|
|
local b = BOOLS[string.lower(v)]
|
|
if b ~= nil then
|
|
return b
|
|
end
|
|
if string.match(v, "^[%-%+]?%d+%.?%d*[eE]?[%-%+]?%d*$") or string.match(v, "^[%-%+]?%.%d+$") or string.match(v, "^0x%x+$") then
|
|
local n = tonumber(v)
|
|
if n then
|
|
return n
|
|
end
|
|
end
|
|
return v
|
|
end
|
|
|
|
function Ini.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
|
local o: DecodeOptions = opts or {}
|
|
local s = buffer.readstring(r.buf, r.base, r.limit - r.base)
|
|
if string.sub(s, 1, 3) == "\239\187\191" then
|
|
s = string.sub(s, 4)
|
|
end
|
|
local root = Types.object()
|
|
local cur = root
|
|
local lastKey: string? = nil
|
|
local lastIndent = 0
|
|
local lastTable: any = nil
|
|
local seenKeys: { [any]: { [string]: boolean } } = {}
|
|
local pos = 1
|
|
local lineStart = 0
|
|
for line in string.gmatch(s .. "\n", "([^\n]*)\n") do
|
|
lineStart = pos - 1
|
|
pos += #line + 1
|
|
line = string.gsub(line, "\r$", "")
|
|
local indent = #(string.match(line, "^[ \t]*") :: string)
|
|
local trimmed = string.match(line, "^%s*(.-)%s*$") :: string
|
|
if trimmed == "" then
|
|
lastKey = nil
|
|
elseif string.match(trimmed, "^[;#]") then
|
|
-- a comment line (configparser: also when indented); it does not end a continuation
|
|
elseif lastKey and indent > lastIndent then
|
|
-- continuation of the previous value
|
|
local v = trimmed
|
|
if o.inlineComments then
|
|
v = string.match(v, "^(.-)%s+[;#]") or v
|
|
end
|
|
local prev = lastTable[lastKey]
|
|
lastTable[lastKey] = (if type(prev) == "string" then prev else "") .. "\n" .. v
|
|
elseif string.sub(trimmed, 1, 1) == "[" and string.find(trimmed, "]", 2, true) then
|
|
local name = string.match(trimmed, "^%[(.*)%]") :: string
|
|
local existing = root[name]
|
|
if existing ~= nil and type(existing) ~= "table" then
|
|
return nil, Err.new(Err.CORRUPT, "section [" .. name .. "] has the name of a top-level key", lineStart)
|
|
end
|
|
if existing and o.strict then
|
|
return nil, Err.new(Err.CORRUPT, "duplicate section [" .. name .. "]", lineStart)
|
|
end
|
|
if not existing then
|
|
existing = Types.object()
|
|
Types.set(root, name, existing)
|
|
end
|
|
cur = existing
|
|
lastKey = nil
|
|
else
|
|
local key, value = string.match(trimmed, "^(.-)%s*[=:]%s*(.*)$")
|
|
if not key then
|
|
if not o.allowNoValue then
|
|
return nil, Err.new(Err.CORRUPT, "line without '=' or ':': " .. string.sub(trimmed, 1, 40), lineStart)
|
|
end
|
|
key, value = trimmed, true :: any
|
|
end
|
|
if key == "" then
|
|
return nil, Err.new(Err.CORRUPT, "empty key", lineStart)
|
|
end
|
|
if o.inlineComments and type(value) == "string" then
|
|
value = string.match(value, "^(.-)%s+[;#]") or (if string.match(value, "^[;#]") then "" else value)
|
|
end
|
|
local seen = seenKeys[cur]
|
|
if not seen then
|
|
seen = {}
|
|
seenKeys[cur] = seen
|
|
end
|
|
if seen[key :: string] and o.strict then
|
|
return nil, Err.new(Err.CORRUPT, "duplicate key " .. (key :: string), lineStart)
|
|
end
|
|
seen[key :: string] = true
|
|
if cur == root and type(root[key]) == "table" then
|
|
return nil, Err.new(Err.CORRUPT, "top-level key " .. (key :: string) .. " has the name of a section", lineStart)
|
|
end
|
|
Types.set(cur, key, value)
|
|
lastKey, lastIndent, lastTable = key, indent, cur
|
|
end
|
|
end
|
|
if o.types then
|
|
for _, k in Types.keys(root) do
|
|
local v = root[k]
|
|
if type(v) == "table" then
|
|
for _, k2 in Types.keys(v) do
|
|
v[k2] = typed(v[k2])
|
|
end
|
|
else
|
|
root[k] = typed(v)
|
|
end
|
|
end
|
|
end
|
|
return root, nil
|
|
end
|
|
|
|
-- ------------------------------------------------------------------------------------------------ encode
|
|
local function text(v: any): string?
|
|
local tv = type(v)
|
|
if tv == "string" then
|
|
return (string.gsub(v, "\n", "\n\t"))
|
|
elseif tv == "number" then
|
|
return Json.number(v) or tostring(v)
|
|
elseif tv == "boolean" then
|
|
return if v then "true" else "false"
|
|
elseif v == Types.null then
|
|
return ""
|
|
elseif tv == "table" and Types.Date.is(v) then
|
|
return tostring(v)
|
|
end
|
|
return nil
|
|
end
|
|
|
|
function Ini.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
|
if type(value) ~= "table" then
|
|
return nil, Err.new(Err.ARG, "expected a table of sections")
|
|
end
|
|
local delim = (opts and opts.delimiter) or " = "
|
|
local out: { string } = {}
|
|
local err: string? = nil
|
|
local function keyOk(k: any): boolean
|
|
if type(k) ~= "string" and type(k) ~= "number" then
|
|
err = "keys must be strings"
|
|
return false
|
|
end
|
|
local ks = tostring(k)
|
|
if ks == "" or string.find(ks, "[=:\r\n]") or string.match(ks, "^[%s;#%[]") or string.match(ks, "%s$") then
|
|
err = "key " .. string.format("%q", ks) .. " cannot be written"
|
|
return false
|
|
end
|
|
return true
|
|
end
|
|
local function pairsOf(t: any, prefix: string, depth: number): boolean
|
|
if depth > 32 then
|
|
err = "sections nested too deeply (a cycle?)"
|
|
return false
|
|
end
|
|
local subs = {}
|
|
local lines = {}
|
|
for _, k in Types.keys(t) do
|
|
local v = t[k]
|
|
if type(v) == "table" and not Types.Date.is(v) and v ~= Types.null then
|
|
table.insert(subs, k)
|
|
else
|
|
if not keyOk(k) then
|
|
return false
|
|
end
|
|
local s = text(v)
|
|
if not s then
|
|
err = "cannot write a " .. type(v) .. " value"
|
|
return false
|
|
end
|
|
table.insert(lines, tostring(k) .. delim .. s .. "\n")
|
|
end
|
|
end
|
|
if prefix ~= "" then
|
|
table.insert(out, "[" .. prefix .. "]\n")
|
|
table.move(lines, 1, #lines, #out + 1, out)
|
|
table.insert(out, "\n")
|
|
elseif #lines > 0 then
|
|
table.move(lines, 1, #lines, #out + 1, out)
|
|
table.insert(out, "\n")
|
|
end
|
|
for _, k in subs do
|
|
local name = tostring(k)
|
|
if string.find(name, "[\r\n%]]") then
|
|
err = "section name " .. string.format("%q", name) .. " cannot be written"
|
|
return false
|
|
end
|
|
if not pairsOf(t[k], if prefix == "" then name else prefix .. "." .. name, depth + 1) then
|
|
return false
|
|
end
|
|
end
|
|
return true
|
|
end
|
|
if not pairsOf(value, "", 0) then
|
|
return nil, Err.new(Err.ARG, err or "cannot encode")
|
|
end
|
|
return buffer.fromstring(table.concat(out)), nil
|
|
end
|
|
|
|
return Ini
|