Skip to content

Instantly share code, notes, and snippets.

@dminuoso

dminuoso/foo.hs Secret

Last active October 20, 2021 12:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dminuoso/08e7b1aca8bb92fe84345adf3e0f1a10 to your computer and use it in GitHub Desktop.
Save dminuoso/08e7b1aca8bb92fe84345adf3e0f1a10 to your computer and use it in GitHub Desktop.
lookupBS :: Csv.NamedRecord -> BS.ByteString -> Csv.Parser BS.ByteString
lookupBS = Csv.lookup
lenientDecodeUtf8 :: BS.ByteString -> T.Text
lenientDecodeUtf8 = T.decodeUtf8With T.lenientDecode
(.:?) :: Csv.FromField a => Csv.NamedRecord -> BS.ByteString -> Csv.Parser a
rec .:? field = case Csv.runParser (rec .: field) of
Left err -> fail ("Failed to parse field " <> name <> ": " <> err)
Right r -> pure r
where
name = T.unpack (lenientDecodeUtf8 field)
(.:!) :: Csv.FromField a => Csv.NamedRecord -> BS.ByteString -> Csv.Parser a
rec .:! field = case Csv.runParser (lookupBS rec field) of
Left err -> fail ("Failed to parse field " <> name <> ": " <> err)
Right r | BS.null r
-> fail ("Missing field " <> name)
| otherwise
-> rec .:? field
where
name = T.unpack (lenientDecodeUtf8 field)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment