From 6cee99f4e326df0aad5880f7138ff766a18e7a4d Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 08:53:45 -0500 Subject: [PATCH] data: data/ini (configparser-compatible reading: comments, ':' / '=', continuations, duplicates, top-level keys; inline comments / no-value keys / types / strict options; configparser layout on encode); configparser fixtures --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 ++ src/Formats/data/ini/init.luau | 250 +++++++++++++++++++++++++++++++++ tests/data/ini.luau | 71 ++++++++++ tools/fixtures/ini.py | 62 ++++++++ 5 files changed, 396 insertions(+) create mode 100644 src/Formats/data/ini/init.luau create mode 100644 tests/data/ini.luau create mode 100644 tools/fixtures/ini.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index ed07a12..03c5f3c 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -8,6 +8,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | image | png | .png .apng | yes | yes | animation: false, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` | | data | cbor | .cbor | yes | yes | binary: true, ordered: true, tags: true | `tests/data/cbor.luau` | | data | csv | .csv .tsv | yes | yes | header: true | `tests/data/csv.luau` | +| data | ini | .ini .cfg .conf .inf .desktop | yes | yes | ordered: true | `tests/data/ini.luau` | | data | json | .json .jsonl .ndjson .geojson | yes | yes | ordered: true, streaming: true | `tests/data/json.luau` | | data | msgpack | .msgpack .mpk | yes | yes | binary: true, ordered: true | `tests/data/msgpack.luau` | | data | toml | .toml | yes | yes | ordered: true, dates: true | `tests/data/toml.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index ef4ce9b..e589d61 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -50,6 +50,18 @@ local list: { Entry } = { return require("@formats/data/csv") end, }, + { + name = "ini", + category = "data", + path = "data/ini", + extensions = { "ini", "cfg", "conf", "inf", "desktop" }, + mime = { "text/plain" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Json" }, + caps = { decode = true, encode = true, ordered = true }, + load = function() + return require("@formats/data/ini") + end, + }, { name = "json", category = "data", diff --git a/src/Formats/data/ini/init.luau b/src/Formats/data/ini/init.luau new file mode 100644 index 0000000..fe48955 --- /dev/null +++ b/src/Formats/data/ini/init.luau @@ -0,0 +1,250 @@ +--!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, 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 .. " 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 diff --git a/tests/data/ini.luau b/tests/data/ini.luau new file mode 100644 index 0000000..0cf8e6d --- /dev/null +++ b/tests/data/ini.luau @@ -0,0 +1,71 @@ +-- data/ini tests: configs written by Python's configparser read back to configparser's values and re-encoded byte for +-- byte, messy hand-written files read as configparser(strict = false) reads them, options (inline comments, keys +-- without values, types, strict), top-level keys, error codes, and the fuzz pass. Fixtures: tools/fixtures/ini.py. +local T = require("@tests/T") +local Ini = require("@formats/data/ini") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Canon = require("@tests/data/Canon") +local Fx = require("@tests/gen/ini") + +local t = T.suite("data/ini") + +t:eq(Ini.name, "ini", "name") +t:check(Ini.caps.decode and Ini.caps.encode, "caps") + +local function dec(s: string, opts: any?): (any, any) + return Ini.decode(Bytes.reader(buffer.fromstring(s)), opts) +end + +for i, c in Fx.written do + local v, err = dec(c.data) + t:check(v ~= nil, "written " .. i .. ": " .. tostring(err)) + t:eq(Canon.of(v), c.canon, "written " .. i .. ": values") + t:eq(buffer.tostring(Ini.encode(v) :: buffer), c.data, "written " .. i .. ": same text") +end +for i, c in Fx.read do + local v, err = dec(c.data) + t:check(v ~= nil, "messy " .. i .. ": " .. tostring(err)) + t:eq(Canon.of(v), c.canon, "messy " .. i .. ": values") +end + +do + local v = dec("top = 1\n[s]\na = 2 ; c\nflag\nn = 0x10\nb = Yes\n", { inlineComments = true, allowNoValue = true, types = true }) + t:eq(v.top, 1, "top-level key, typed") + t:eq(v.s.a, 2, "inline comment stripped") + t:eq(v.s.flag, true, "key without value") + t:eq(v.s.n, 16, "hex number") + t:eq(v.s.b, true, "yes -> true") + t:eq(table.concat(Types.keys(v), ","), "top,s", "order") + local o = Types.object() + Types.set(o, "name", "x") + local sub = Types.object() + Types.set(sub, "k", "multi\nline") + Types.set(sub, "inner", { z = 1 }) + Types.set(o, "sec", sub) + t:eq(buffer.tostring(Ini.encode(o) :: buffer), "name = x\n\n[sec]\nk = multi\n\tline\n\n[sec.inner]\nz = 1\n\n", "encode nested") + local function code(s: string, opts: any?): string? + local _, e = dec(s, opts) + return e and e.code + end + t:eq(code("[a]\njunk line\n"), Err.CORRUPT, "line without delimiter") + t:eq(code("[a]\nk=1\nk=2\n", { strict = true }), Err.CORRUPT, "strict duplicate key") + t:eq(code("[a]\n[a]\n", { strict = true }), Err.CORRUPT, "strict duplicate section") + t:eq(code("[a]\n= v\n"), Err.CORRUPT, "empty key") + local _, ee = Ini.encode({ ["bad=key"] = "v" }) + t:eq(ee and ee.code, Err.ARG, "unwritable key") + t:eq(Ini.sniff(Bytes.reader(buffer.fromstring("; c\n[section]\nk=v"))), 0.2, "sniff") +end + +local samples = {} +for _, c in Fx.read do + table.insert(samples, c.data) +end +for i = 1, 20 do + table.insert(samples, Fx.written[i].data) +end +t:fuzz("decode", function(b: buffer) + return Ini.decode(Bytes.reader(b), { types = true, inlineComments = true }) +end, samples) +t:done() diff --git a/tools/fixtures/ini.py b/tools/fixtures/ini.py new file mode 100644 index 0000000..412d4f7 --- /dev/null +++ b/tools/fixtures/ini.py @@ -0,0 +1,62 @@ +# data/ini fixtures: random configs written by Python's configparser (interpolation off, key case kept), and +# hand-written messy files (comments, ':' delimiters, continuation lines, odd spacing, duplicates) with what +# configparser(strict=False) reads from them. +# tests/gen/ini.luau { written = { { data, canon } }, read = { { data, canon } } } +import configparser, importlib.util, io, os + +_spec = importlib.util.spec_from_file_location("_data_common", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_data_common.py")) +C = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(C) + + +def parser(): + p = configparser.ConfigParser(interpolation=None, strict=False) + p.optionxform = str + return p + + +def as_dict(p): + return {s: dict(p.items(s, raw=True)) for s in p.sections()} + + +MESSY = [ + "[a]\nx=1\ny : two words \n; comment\n # indented comment\nz =\n", + "[s]\nkey = line one\n line two\n\tline three\nk2: v\n", + "# top comment\n[one]\na = 1\n[two]\nb = 2\n[one]\nc = 3\n", + "[dup]\na = 1\na = 2\n", + "[weird name with spaces]\n key with spaces = value with = sign \n", + "[s]\nurl = http://x:8080/p?a=b\npath: C:\\dir\n", + "[x]\r\nwin = yes\r\nmore = no\r\n", + "[\u00e9]\n\u4e2d = \u00fc\n", + "[a]\nk = v ; not a comment by default\n", + "[e]\nempty =\nalso:\n", +] + + +def generate(ctx): + rng = ctx.rng(17) + written = [] + alph = "ab xyz09_-.\u00e9/=:;#" + for i in range(80): + p = parser() + for s in range(rng.randrange(1, 5)): + name = "sec%d %s" % (s, rng.choice(["", "x", "\u00e9"])) + p.add_section(name) + for k in range(rng.randrange(0, 6)): + key = "k%d%s" % (k, rng.choice(["", "_a", ".b"])) + val = "".join(rng.choice(alph) for _ in range(rng.randrange(0, 12))).strip() + if rng.random() < 0.15: + val = val + "\nsecond line" + rng.choice(["", "\nthird"]) + p.set(name, key, val) + buf = io.StringIO() + p.write(buf) + data = buf.getvalue() + back = parser() + back.read_string(data) + written.append({"data": data.encode(), "canon": C.canon(as_dict(back))}) + read = [] + for m in MESSY: + p = parser() + p.read_string(m) + read.append({"data": m.encode(), "canon": C.canon(as_dict(p))}) + ctx.emit("ini", {"written": written, "read": read})