--!strict -- data/csv: comma-separated values (RFC 4180, read as leniently as Python's csv module). New code. Supports: any -- one-byte delimiter (opts.delimiter, or "auto" to pick , ; tab |), quoted fields with doubled quotes and embedded -- line breaks, CRLF / LF / CR line ends, a header row (opts.header: rows become Types.object keyed by the column -- names, in column order), number conversion by option; encode from arrays of arrays or of keyed rows, quoting only -- where needed (like Python's QUOTE_MINIMAL) or always. Blank lines are skipped. Not supported: escape characters -- other than the doubled quote, multi-byte delimiters. -- ------------------------------------------------------------------------------------------------ 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 Csv = { name = "csv", category = "data", extensions = { "csv", "tsv" }, mime = { "text/csv", "text/tab-separated-values" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/Json" }, caps = { decode = true, encode = true, header = true }, } export type DecodeOptions = { delimiter: string?, -- one byte (default ","; "auto" guesses from the first line among , ; tab |) quote: string?, -- the quote byte (default '"') header: boolean?, -- the first row names the columns: rows become Types.object (default false: arrays) numbers: boolean?, -- fields that are numbers become numbers (default false: every field is a string) maxRows: number?, -- refuse more rows (default unlimited) } export type EncodeOptions = { delimiter: string?, -- default "," quote: string?, -- default '"' newline: string?, -- the row terminator (default "\r\n", as RFC 4180 and Python's csv) quoteAll: boolean?, -- quote every field (default false: only those that need it) columns: { string }?, -- keyed rows: the column order (default: the keys of the rows in first-seen order) header: boolean?, -- keyed rows: write the header row (default true) } -- ------------------------------------------------------------------------------------------------ constants local find, sub, byte, gsub = string.find, string.sub, string.byte, string.gsub local function patEscape(c: string): string return (gsub(c, "[%^%$%(%)%%%.%[%]%*%+%-%?]", "%%%0")) end -- ------------------------------------------------------------------------------------------------ sniff function Csv.sniff(r: Bytes.Reader): number local head = r:peek(1024) if find(head, "%z") then return 0 end local l1, l2 = string.match(head, "^([^\r\n]*)\r?\n([^\r\n]*)") if not l1 or l1 == "" then return 0 end for _, d in { ",", "\t", ";" } do local _, c1 = gsub(l1, d, "") local _, c2 = gsub(l2, d, "") if c1 > 0 and c1 == c2 then return 0.15 end end return 0 end -- ------------------------------------------------------------------------------------------------ decode local function guess(s: string, q: string): string local line = string.match(s, "^[^\r\n]*") or "" line = gsub(line, patEscape(q) .. "[^" .. patEscape(q) .. "]*" .. patEscape(q), "") local best, bestN = ",", 0 for _, d in { ",", ";", "\t", "|" } do local _, n = gsub(line, patEscape(d), "") if n > bestN then best, bestN = d, n end end return best end -- rows(s, opts) -> { { string } } | nil, Err function Csv.parse(s: string, opts: DecodeOptions?): ({ { string } }?, Err.Err?) local o: DecodeOptions = opts or {} local q = o.quote or '"' local d = o.delimiter or "," if d == "auto" then d = guess(s, q) end if #d ~= 1 or #q ~= 1 or d == q or d == "\n" or d == "\r" then return nil, Err.new(Err.ARG, "delimiter and quote must be single, different bytes (not line ends)") end local qb, db = byte(q), byte(d) local stop = "[" .. patEscape(d) .. "\r\n]" local maxRows = o.maxRows or math.huge local rows: { { string } } = {} local row: { string } = {} local n = #s local i = 1 local rowEmpty = true -- the current line has no field text yet (blank lines are skipped) while true do local c = byte(s, i) local field: string if c == qb then local k = i + 1 local parts = {} while true do local j = find(s, q, k, true) if not j then return nil, Err.new(Err.TRUNCATED, "unterminated quoted field", i - 1) end if byte(s, j + 1) == qb then table.insert(parts, sub(s, k, j)) k = j + 2 else table.insert(parts, sub(s, k, j - 1)) i = j + 1 break end end -- text after the closing quote up to the delimiter is kept (Python's lenient reading) local e = find(s, stop, i) or (n + 1) if e > i then table.insert(parts, sub(s, i, e - 1)) end i = e field = table.concat(parts) rowEmpty = false else local e = find(s, stop, i) or (n + 1) field = sub(s, i, e - 1) if e > i then rowEmpty = false end i = e end table.insert(row, field) c = byte(s, i) if c == db then rowEmpty = false i += 1 else -- end of the row: CRLF / LF / CR / end of data if c == 13 and byte(s, i + 1) == 10 then i += 2 elseif c ~= nil then i += 1 end if not rowEmpty then table.insert(rows, row) if #rows > maxRows then return nil, Err.new(Err.LIMIT, "more than " .. maxRows .. " rows") end end row = {} rowEmpty = true if i > n then break end end end return rows, nil end local NUMBER = "^%s*[%-%+]?%d+%.?%d*[eE]?[%-%+]?%d*%s*$" local function convert(v: string): any if string.match(v, NUMBER) or string.match(v, "^%s*[%-%+]?%.%d+[eE]?[%-%+]?%d*%s*$") then local x = tonumber(v) if x then return x end end return v end function Csv.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local s = buffer.readstring(r.buf, r.base, r.limit - r.base) if sub(s, 1, 3) == "\239\187\191" then s = sub(s, 4) end local rows, err = Csv.parse(s, opts) if not rows then return nil, err end local o: DecodeOptions = opts or {} if o.numbers then for _, row in rows do for k, v in row do row[k] = convert(v) end end end if not o.header then return rows, nil end local names = rows[1] or {} local out = table.create(math.max(#rows - 1, 0)) for k = 2, #rows do local row = rows[k] local obj = Types.object() for c, name in names do if row[c] ~= nil then Types.set(obj, tostring(name), row[c]) end end out[k - 1] = obj end return out, nil end -- ------------------------------------------------------------------------------------------------ encode local function text(v: any): (string?, string?) local tv = type(v) if tv == "string" then return v, nil elseif tv == "number" then local s = Json.number(v) if not s then return if v ~= v then "nan" elseif v > 0 then "inf" else "-inf", nil end return s, nil elseif tv == "boolean" then return if v then "true" else "false", nil elseif v == nil or v == Types.null then return "", nil elseif tv == "table" and Types.Date.is(v) then return tostring(v), nil end return nil, "cannot write a " .. tv .. " as a field" end local function isArray(t: any): boolean if type(t) ~= "table" or Types.isObject(t) then return false end local n = #t return n > 0 or next(t) == nil end function Csv.encode(rows: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: EncodeOptions = opts or {} local d, q, nl = o.delimiter or ",", o.quote or '"', o.newline or "\r\n" if #d ~= 1 or #q ~= 1 or d == q then return nil, Err.new(Err.ARG, "delimiter and quote must be single, different bytes") end if type(rows) ~= "table" then return nil, Err.new(Err.ARG, "expected an array of rows") end local special = "[" .. patEscape(d) .. patEscape(q) .. "\r\n]" local qq = q .. q local out: { string } = {} local function writeRow(fields: { any }, count: number): Err.Err? local parts = table.create(count) for k = 1, count do local s, e = text(fields[k]) if not s then return Err.new(Err.ARG, "row " .. (#out + 1) .. ", field " .. k .. ": " .. tostring(e)) end if o.quoteAll or find(s, special) or (count == 1 and s == "") then s = q .. gsub(s, patEscape(q), qq) .. q end parts[k] = s end table.insert(out, table.concat(parts, d) .. nl) return nil end local keyed = rows[1] ~= nil and not isArray(rows[1]) if keyed then local cols = o.columns if not cols then local seen, list = {}, {} for _, row in rows do if type(row) ~= "table" then return nil, Err.new(Err.ARG, "rows must be tables") end for _, k in Types.keys(row) do if not seen[k] then seen[k] = true table.insert(list, k) end end end cols = list end local cl = cols :: { any } if o.header ~= false then local e = writeRow(cl, #cl) if e then return nil, e end end for _, row in rows do local fields = table.create(#cl) for k, name in cl do fields[k] = row[name] end local e = writeRow(fields, #cl) if e then return nil, e end end else for _, row in rows do if type(row) ~= "table" then return nil, Err.new(Err.ARG, "rows must be arrays of fields") end local e = writeRow(row, #row) if e then return nil, e end end end return buffer.fromstring(table.concat(out)), nil end return Csv