# csvkit: read and write CSV text, including quoted fields. # Pure: it needs no permissions, so it can be installed with no `allow` line. # (To read a file, use read() in your own code, which needs `read`, and pass the text in.) # # use csvkit from "cresset_packages/csvkit.crs" # rows = csvkit.parse("name,score\n\"Smith, Ada\",90\n").unwrap() # print(rows) # [["name", "score"], ["Smith, Ada", "90"]] # Text becomes a list of rows, each a list of text fields. Handles "quoted, fields", "" for a quote # inside quotes, line breaks inside quotes, and both \n and \r\n line endings. # An err comes back when a quote is never closed. fn parse(text, separator = ","): rows = [] row = [] field = "" quoted = false i = 0 chars = text.chars() count = chars.len() while i < count: ch = chars[i] if quoted: if ch == '"': if i + 1 < count and chars[i + 1] == '"': field += '"' i += 1 else: quoted = false else: field += ch elif ch == '"': quoted = true elif ch == separator: row.push(field) field = "" elif ch == "\n": row.push(field) rows.push(row) row = [] field = "" elif ch != "\r": field += ch i += 1 if quoted: return err("a quoted field is never closed") if field != "" or row.len() > 0: row.push(field) rows.push(row) return ok(rows) # rows with a header line become a list of maps: [{"name": "Ada", "score": "90"}, ...] fn with_header(rows): if rows.len() == 0: return err("there is no header row") header = rows[0] out = [] for row in rows.drop(1): entry = {} for i in range(header.len()): if i < row.len(): entry[header[i]] = row[i] else: entry[header[i]] = "" out.push(entry) return ok(out) fn needs_quotes(field, separator): return field.contains(separator) or field.contains('"') or field.contains("\n") or field.contains("\r") # the other way: rows become CSV text, quoting only the fields that need it fn stringify(rows, separator = ","): lines = [] for row in rows: fields = [] for value in row: field = str(value) if needs_quotes(field, separator): field = '"' + field.replace('"', '""') + '"' fields.push(field) lines.push(fields.join(separator)) return lines.join("\n") + "\n" test "plain rows": assert_eq(parse("a,b,c\n1,2,3\n"), ok([["a", "b", "c"], ["1", "2", "3"]])) assert_eq(parse("a,b"), ok([["a", "b"]])) assert_eq(parse(""), ok([])) test "quoted fields hold commas, quotes and line breaks": assert_eq(parse("\"Smith, Ada\",90\n"), ok([["Smith, Ada", "90"]])) assert_eq(parse("\"say \"\"hi\"\"\",x\n"), ok([["say \"hi\"", "x"]])) assert_eq(parse("\"two\nlines\",x\n"), ok([["two\nlines", "x"]])) test "empty fields and windows line endings": assert_eq(parse("a,,c\r\n,,\r\n"), ok([["a", "", "c"], ["", "", ""]])) assert_eq(parse("a,b\n\nc,d\n"), ok([["a", "b"], [""], ["c", "d"]])) test "other separators": assert_eq(parse("a;b;c\n", ";"), ok([["a", "b", "c"]])) assert_eq(parse("a\tb\n", "\t"), ok([["a", "b"]])) test "an unclosed quote is an error": assert_eq(parse("a,\"oops\n").is_err(), true) test "headers become maps": rows = parse("name,score\nAda,90\nBo,72\n").unwrap() assert_eq(with_header(rows), ok([{"name": "Ada", "score": "90"}, {"name": "Bo", "score": "72"}])) assert_eq(with_header([["a", "b"], ["1"]]), ok([{"a": "1", "b": ""}])) assert_eq(with_header([]).is_err(), true) test "writing quotes only when needed": assert_eq(stringify([["a", "b"], [1, 2.5]]), "a,b\n1,2.5\n") assert_eq(stringify([["Smith, Ada", "say \"hi\""]]), "\"Smith, Ada\",\"say \"\"hi\"\"\"\n") assert_eq(stringify([["a", "b"]], ";"), "a;b\n") test "parse and stringify round trip": rows = [["name", "note"], ["Ada", "likes, commas"], ["Bo", "and \"quotes\""], ["Cy", "two\nlines"]] assert_eq(parse(stringify(rows)), ok(rows))