From 5511115cf8a5283c9ea6b3433998cf23da8a19b5 Mon Sep 17 00:00:00 2001 From: BENJAMIN PEINHARDT Date: Fri, 29 Dec 2023 18:04:10 -0600 Subject: [PATCH] to_lists_or_error --- CHANGELOG.md | 3 +++ README.md | 8 -------- gleam.toml | 2 +- src/gsv.gleam | 14 ++++++++++++++ test/gsv_test.gleam | 9 +++++++++ 5 files changed, 27 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1647500..a3fbdd1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## Unreleased +## v1.2.0 - 29 December 2023 +- Add `to_lists_or_error` function + ## v1.1.0 - 29 December 2023 - Add a function which panics with an appropriate error message on failure to parse csv. This includes the token location. diff --git a/README.md b/README.md index f9e1f0e..23bf0fe 100644 --- a/README.md +++ b/README.md @@ -26,14 +26,6 @@ pub fn main() { } ``` -## Quick start - -```sh -gleam run # Run the project -gleam test # Run the tests -gleam shell # Run an Erlang shell -``` - ## Installation If available on Hex this package can be added to your Gleam project: diff --git a/gleam.toml b/gleam.toml index d22784b..b12ae8f 100644 --- a/gleam.toml +++ b/gleam.toml @@ -1,5 +1,5 @@ name = "gsv" -version = "1.1.0" +version = "1.2.0" gleam = ">= 0.32.0" description = "A simple csv parser and generator written in gleam " diff --git a/src/gsv.gleam b/src/gsv.gleam index b8555c8..1e1ce51 100644 --- a/src/gsv.gleam +++ b/src/gsv.gleam @@ -38,6 +38,20 @@ pub fn to_lists_or_panic(input: String) -> List(List(String)) { } } +/// Parses a csv string to a list of lists of strings. +/// Automatically handles Windows and Unix line endings. +/// Returns a string error msg if the string is not valid csv. +pub fn to_lists_or_error(input: String) -> Result(List(List(String)), String) { + input + |> token.scan + |> token.with_location + |> ast.parse + |> result.map_error(fn(e) { + let ParseError(Location(line, column), msg) = e + "[" <> "line " <> int.to_string(line) <> " column " <> int.to_string(column) <> "] of csv: " <> msg + }) +} + /// Option for using "\n = LF = Unix" or "\r\n = CRLF = Windows" /// line endings. Use with the `from_lists` function when /// writing to a csv string. diff --git a/test/gsv_test.gleam b/test/gsv_test.gleam index 4b6b326..0b04f7f 100644 --- a/test/gsv_test.gleam +++ b/test/gsv_test.gleam @@ -170,6 +170,15 @@ pub fn error_cases_test() { "Expected escaped or non-escaped string after comma, found: ,", )) } + // pub fn totally_panics_test() { // "Ben, 25,, TRUE" |> gsv.to_lists_or_panic // } + +pub fn totally_errors_test() { + "Ben, 25,, TRUE" + |> gsv.to_lists_or_error + |> should.equal(Error( + "[line 1 column 9] of csv: Expected escaped or non-escaped string after comma, found: ,", + )) +}