Skip to content

Commit 23946f9

Browse files
committed
Handle headers properly when 2nd row in a CSV file is broken
1 parent 38427dc commit 23946f9

File tree

1 file changed

+14
-12
lines changed

1 file changed

+14
-12
lines changed

src/Data/CSV/Enumerator.hs

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -362,19 +362,19 @@ appendCSVFile :: (CSVeable r) => CSVSettings -- ^ CSV settings
362362
-> [r] -- ^ Data to be output
363363
-> IO Int -- ^ Number of rows written
364364
appendCSVFile s fp rs =
365-
let doOutput (c,h) = when c (writeHeaders s h rs) >> outputRowsIter h
365+
let doOutput (c,h) = when c (writeHeaders s h rs >> return ()) >> outputRowsIter h
366366
outputRowsIter h = foldM (step h) 0 . map (rowToStr s) $ rs
367367
step h acc x = (B.hPutStrLn h x) >> return (acc+1)
368368
chkOpen = do
369-
writeHeaders <- do
369+
wrHeader <- do
370370
fe <- doesFileExist fp
371371
if fe
372-
then do
373-
fs <- getFileStatus fp >>= return . fileSize
374-
return $ if fs > 0 then False else True
372+
then do
373+
fs <- getFileStatus fp >>= return . fileSize
374+
return $ if fs > 0 then False else True
375375
else return True
376376
h <- openFile fp AppendMode
377-
return (writeHeaders, h)
377+
return (wrHeader, h)
378378
in bracket
379379
(chkOpen)
380380
(hClose . snd)
@@ -405,10 +405,10 @@ outputColumns s h cs r = outputRow s h r'
405405

406406

407407

408-
writeHeaders :: CSVeable r => CSVSettings -> Handle -> [r] -> IO ()
408+
writeHeaders :: CSVeable r => CSVSettings -> Handle -> [r] -> IO Bool
409409
writeHeaders s h rs = case fileHeaders rs of
410-
Just hs -> B.hPutStrLn h . rowToStr s $ hs
411-
Nothing -> return ()
410+
Just hs -> (B.hPutStrLn h . rowToStr s) hs >> return True
411+
Nothing -> return False
412412

413413

414414
outputRowIter :: CSVeable r => CSVSettings -> Handle -> r -> E.Iteratee B.ByteString IO ()
@@ -493,10 +493,12 @@ mapIntoHandle csvs outh h f = do
493493
where
494494
f' acc EOF = return acc
495495
f' acc (ParsedRow Nothing) = return acc
496-
f' (False, _) r'@(ParsedRow (Just r)) = do
496+
f' (False, i) r'@(ParsedRow (Just r)) = do
497497
rs <- f r
498-
when outh $ writeHeaders csvs h rs
499-
f' (True, 0) r'
498+
headerDone <- if outh then writeHeaders csvs h rs else return True
499+
if headerDone
500+
then f' (headerDone, 0) r' -- Headers are done, now process row
501+
else return (False, i+1) -- Problem in this row, move on to next
500502
f' (True, !i) (ParsedRow (Just r)) = do
501503
rs <- f r
502504
outputRows csvs h rs

0 commit comments

Comments
 (0)