Skip to content

Commit

Permalink
to_lists_or_error
Browse files Browse the repository at this point in the history
  • Loading branch information
bcpeinhardt committed Dec 30, 2023
1 parent 8b19313 commit 5511115
Show file tree
Hide file tree
Showing 5 changed files with 27 additions and 9 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
8 changes: 0 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion gleam.toml
Original file line number Diff line number Diff line change
@@ -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 "

Expand Down
14 changes: 14 additions & 0 deletions src/gsv.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
9 changes: 9 additions & 0 deletions test/gsv_test.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -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: ,",
))
}

0 comments on commit 5511115

Please sign in to comment.