on master help sign in
handle true/y/on/yes/false/n/off/no as booleans, with tests
commit2df8ad9d15f44ba44fa1d223dae48e2e2920dfa3 authorPatrick Hurst <phurst@amateurtopologist.com> dateWed 30 May 2012, 06:15 (14 years ago) parentc6f31c9
2 files changed+19−2
Data/Yaml.hs+7−2 test/main.hs+12
Data/Yaml.hs+7−2
@@ -54,8 +54,10 @@ import qualified Data.Conduit.List as CL
5454import Control.Monad.Trans.Class (MonadTrans, lift)
5555import Control.Monad.IO.Class (MonadIO, liftIO)
5656import Control.Monad (liftM)
57+import Data.Char (toUpper)
5758import qualified Data.Vector as V
5859import Data.Text (Text, pack)
60+import qualified Data.Text as T
5961import Data.Text.Read (signed, decimal, double)
6062import Data.Text.Encoding (encodeUtf8, decodeUtf8With)
6163import Data.Text.Encoding.Error (lenientDecode)
@@ -161,13 +163,16 @@ textToValue :: Style -> Text -> Value
161163textToValue SingleQuoted t = String t
162164textToValue DoubleQuoted t = String t
163165textToValue Folded t = String t
164−textToValue _ "true" = Bool True
165−textToValue _ "false" = Bool False
166166textToValue _ "null" = Null
167167textToValue _ t
168+ | any (t `isLike`) ["y", "yes", "on", "true"] = Bool True
169+ | any (t `isLike`) ["n", "no", "off", "false"] = Bool False
168170 | Right (x, "") <- signed decimal t = Number $ I x
169171 | Right (x, "") <- double t = Number $ D x
170172 | otherwise = String t
173+ where x `isLike` ref = x `elem` [ref, T.toUpper ref, titleCased]
174+ where titleCased = toUpper (T.head ref) `T.cons` T.tail ref
175+
171176
172177parseO :: C.Sink Event Parse Value
173178parseO = do
test/main.hs+12
@@ -56,6 +56,10 @@ main = hspecX $ do
5656 describe "numbers" $ do
5757 it "parses as string when quoted" caseQuotedNumber
5858 it "parses as number when unquoted" caseUnquotedNumber
59+ describe "booleans" $ do
60+ it "parses when all lowercase" caseLowercaseBool
61+ it "parses when all uppercase" caseUppercaseBool
62+ it "parses when titlecase" caseTitlecaseBool
5963
6064counter :: Monad m => (Y.Event -> Bool) -> C.Sink Y.Event m Int
6165counter pred' =
@@ -308,3 +312,11 @@ caseDataTypes =
308312caseQuotedNumber, caseUnquotedNumber :: Assertion
309313caseQuotedNumber = D.decode "foo: \"1234\"" @?= Just (object [("foo", D.String "1234")])
310314caseUnquotedNumber = D.decode "foo: 1234" @?= Just (object [("foo", D.Number 1234)])
315+
316+obj :: Maybe D.Value
317+obj = Just (object [("foo", D.Bool False), ("bar", D.Bool True), ("baz", D.Bool True)])
318+
319+caseLowercaseBool, caseUppercaseBool, caseTitlecaseBool :: Assertion
320+caseLowercaseBool = D.decode "foo: off\nbar: y\nbaz: true" @?= obj
321+caseUppercaseBool = D.decode "foo: FALSE\nbar: Y\nbaz: ON" @?= obj
322+caseTitlecaseBool = D.decode "foo: No\nbar: Yes\nbaz: True" @?= obj