summaryrefslogtreecommitdiff
path: root/src/CSV.hs
blob: ae2bbea8669b6da07410abced437139b179eab7e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
{-# LANGUAGE FlexibleContexts #-}

module CSV(
    Settings(..),
    specialChars,
    defaultSettings,
    parseRecord
    ) where




import Text.ParserCombinators.Parsec
import Data.Char




data Settings = Settings { separator :: Char
                         , quote     :: Char
                         , escape    :: Char }


specialChars :: Settings -> String
specialChars s = (separator s):(quote s):(escape s):[]


defaultSettings = Settings { separator = ',', quote = '\"', escape = '\\' }




parseRecord :: Settings -> String -> Either ParseError [String]
parseRecord settings input =
    parse (record settings) "error" input




record s = do
    f <- (field s) `sepBy` (char (separator s))
    optional eol
    eof
    return f


field s = many (try (quoted s) <|> many1 (fieldChar s)) >>= return . foldl1 (++)
quoted s = between (char (quote s)) (char (quote s)) (many (quotedChar s))
fieldChar s = allExcept s (specialChars s)
quotedChar s = allExcept s [quote s]
allExcept s c = try (escapeChar s) <|> satisfy (\x -> (not (isControl x)) && (x `notElem` c))
escapeChar s = char (escape s) >> oneOf (specialChars s)


eol  =  try (string "\r\n")
    <|> try (string "\r")
    <|> try (string "\n")
    <?> "end of line"