on master help sign in
decodeEither (#6)
bcac9f6Michael Snoyman
Data/Yaml.hs+13−4
@@ -31,6 +31,8 @@ module Data.Yaml
31 , encodeFile
31 , encodeFile
32 , decode
32 , decode
33 , decodeFile
33 , decodeFile
34+ -- ** Better error information
35+ , decodeEither
34 ) where
36 ) where
35
37
36import qualified Text.Libyaml as Y
38import qualified Text.Libyaml as Y
@@ -231,16 +233,23 @@ parseM a front = do
231decode :: FromJSON a
233decode :: FromJSON a
232 => ByteString
234 => ByteString
233 -> Maybe a
235 -> Maybe a
234−decode bs = unsafePerformIO $ fmap (either (const Nothing) id) $ decodeHelper (Y.decode bs)
236+decode bs = unsafePerformIO
237+ $ fmap (either (const Nothing) (either (const Nothing) Just))
238+ $ decodeHelper (Y.decode bs)
235
239
236decodeFile :: FromJSON a
240decodeFile :: FromJSON a
237 => FilePath
241 => FilePath
238 -> IO (Maybe a)
242 -> IO (Maybe a)
239−decodeFile fp = decodeHelper (Y.decodeFile fp) >>= either throwIO return
243+decodeFile fp = decodeHelper (Y.decodeFile fp) >>= either throwIO (return . either (const Nothing) id)
244+
245+decodeEither :: FromJSON a => ByteString -> Either String a
246+decodeEither bs = unsafePerformIO
247+ $ fmap (either (Left . show) id)
248+ $ decodeHelper (Y.decode bs)
240
249
241decodeHelper :: FromJSON a
250decodeHelper :: FromJSON a
242 => C.Source Parse Y.Event
251 => C.Source Parse Y.Event
243− -> IO (Either ParseException (Maybe a))
252+ -> IO (Either ParseException (Either String a))
244decodeHelper src = do
253decodeHelper src = do
245 x <- try $ C.runResourceT $ flip evalStateT Map.empty $ src C.$$ parse
254 x <- try $ C.runResourceT $ flip evalStateT Map.empty $ src C.$$ parse
246 case x of
255 case x of
@@ -248,7 +257,7 @@ decodeHelper src = do
248 | Just pe <- fromException e -> return $ Left pe
257 | Just pe <- fromException e -> return $ Left pe
249 | Just ye <- fromException e -> return $ Left $ InvalidYaml $ Just $ show (ye :: YamlException)
258 | Just ye <- fromException e -> return $ Left $ InvalidYaml $ Just $ show (ye :: YamlException)
250 | otherwise -> throwIO e
259 | otherwise -> throwIO e
251− Right y -> return $ Right $ parseMaybe parseJSON y
260+ Right y -> return $ Right $ parseEither parseJSON y
252
261
253array :: [Value] -> Value
262array :: [Value] -> Value
254array = Array . V.fromList
263array = Array . V.fromList
yaml.cabal+1−1
@@ -1,5 +1,5 @@
1name: yaml
1name: yaml
2−version: 0.6.0
2+version: 0.6.1
3license: BSD3
3license: BSD3
4license-file: LICENSE
4license-file: LICENSE
5author: Michael Snoyman <michael@snoyman.com>, Anton Ageev <antage@gmail.com>,Kirill Simonov
5author: Michael Snoyman <michael@snoyman.com>, Anton Ageev <antage@gmail.com>,Kirill Simonov