Skip to content

Commit

Permalink
docs
Browse files Browse the repository at this point in the history
  • Loading branch information
Benjamin Peinhardt authored and Benjamin Peinhardt committed May 24, 2023
1 parent c446268 commit 84d64f8
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 8 deletions.
12 changes: 8 additions & 4 deletions gleam.toml
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
name = "gsv"
version = "0.1.0"
description = "A Gleam project"
description = "A simple csv parser written in gleam "

# Fill out these fields if you intend to generate HTML documentation or publish
# your project to the Hex package manager.
#
# licences = ["Apache-2.0"]
# repository = { type = "github", user = "username", repo = "project" }
# links = [{ title = "Website", href = "https://gleam.run" }]
licences = ["Apache-2.0"]
repository = { type = "github", user = "bcpeinhardt", repo = "gsv" }

internal_modules = [
"gsv/internal",
"gsv/internal/*",
]

[dependencies]
gleam_stdlib = "~> 0.28"
Expand Down
18 changes: 14 additions & 4 deletions src/gsv.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,17 @@ import internal/token
import gleam/list
import gleam/string

/// Parses a csv string to a list of lists of strings.
/// Automatically handles Windows and Unix line endings.
pub fn to_lists(input: String) -> Result(List(List(String)), Nil) {
input
|> token.scan
|> ast.parse
}

/// 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.
pub type LineEnding {
Windows
Unix
Expand All @@ -21,6 +26,11 @@ fn le_to_string(le: LineEnding) -> String {
}
}

/// Takes a list of lists of strings and writes it to a csv string.
/// Will automatically escape strings that contain double quotes or
/// line endings with double quotes (in csv, double quotes get escaped by doing
/// a double doublequote)
/// The string `he"llo\n` becomes `"he""llo\n"`
pub fn from_lists(
input: List(List(String)),
separator separator: String,
Expand All @@ -34,12 +44,12 @@ pub fn from_lists(
// Double quotes need to be escaped with an extra doublequote
let entry = string.replace(entry, "\"", "\"\"")

// If the string contains a , \n \r or " it needs to be escaped by wrapping in double quotes
// If the string contains a , \n \r\n or " it needs to be escaped by wrapping in double quotes
case
string.contains(entry, separator) || string.contains(
string.contains(entry, separator) || string.contains(entry, "\n") || string.contains(
entry,
le_to_string(line_ending),
) || string.contains(entry, "\"")
"\"",
)
{
True -> "\"" <> entry <> "\""
False -> entry
Expand Down

0 comments on commit 84d64f8

Please sign in to comment.