on master help sign in
7 files changed+279−63
since splitsnapshots
unifiedsplit
.travis.yml+14−28 ChangeLog.md+6 README.md+75 src/Control/Monad/Validation.hs+154−32 stack.yaml+2−2 test/Doc.hs+6 validationt.cabal+22−1
.travis.yml+14−28
@@ -4,49 +4,35 @@ language: haskell
44git:
55 depth: 5
66
7−cabal: "2.4"
8−
97cache:
108 directories:
119 - "$HOME/.cabal/store"
1210 - "$HOME/.stack"
1311 - "$TRAVIS_BUILD_DIR/.stack-work"
1412
15−matrix:
13+jobs:
1614 include:
17−
18− # Cabal
19− - ghc: 8.4.4
2015 - ghc: 8.6.5
21−
22− # Stack
23− - ghc: 8.6.5
24− env: STACK_YAML="$TRAVIS_BUILD_DIR/stack.yaml"
16+ env: SNAPSHOT="lts-14.22"
17+ - ghc: 8.6.4
18+ env: SNAPSHOT="lts-13.19"
19+ - ghc: 8.6.3
20+ env: SNAPSHOT="lts-13.11"
21+ - ghc: 8.4.4
22+ env: SNAPSHOT="lts-12.26"
2523
2624install:
2725 - |
28− if [ -z "$STACK_YAML" ]; then
29− ghc --version
30− cabal --version
31− cabal new-update
32− cabal new-build --enable-tests --enable-benchmarks
33− else
34− # install stack
35− curl -sSL https://get.haskellstack.org/ | sh
26+ # install stack
27+ curl -sSL https://get.haskellstack.org/ | sh
3628
37− # build project with stack
38− stack --version
39− stack build --system-ghc --test --bench --no-run-tests --no-run-benchmarks
40− fi
29+ # build project with stack
30+ stack --version
31+ stack build --system-ghc --test --bench --no-run-tests --no-run-benchmarks --resolver=$SNAPSHOT
4132
4233script:
4334 - |
44− if [ -z "$STACK_YAML" ]; then
45− echo 0
46− # cabal new-test --enable-tests
47− else
48− stack test --system-ghc
49− fi
35+ stack test --system-ghc
5036
5137notifications:
5238 email: false
ChangeLog.md+6
@@ -1,5 +1,11 @@
11# Revision history for validationt
22
3+## 0.3.0
4+
5+* Added documentation.
6+* Fixed `textErrors` behaviour.
7+* Dropped `transformers-lift` dependency.
8+
39## 0.2.1.0
410
511* GHC 8.4 support
README.mdnew file+75
@@ -0,0 +1,75 @@
1+![Travis CI Badge](https://img.shields.io/travis/typeable/validationt)
2+
3+# ValidationT
4+
5+A very small validation data library.
6+
7+## Usage
8+
9+Suppose you want to validate some data from the user. Say, that the password adheres to some rules.
10+
11+You might do something like this:
12+
13+```haskell
14+validatePassword :: Monad m => String -> ValidationT [String] m ()
15+validatePassword password = do
16+ vLength password
17+ vAlpha password
18+ vNum password
19+ where
20+ vLength p = when (length p < 8)
21+ $ vWarning ["The password should be at least 8 characters long."]
22+ vAlpha p = unless (any isAlpha p)
23+ $ vWarning ["The password should contain at least one alphabetic character."]
24+ vNum p = unless (any isDigit p)
25+ $ vWarning ["The password should contain at least one numeric character."]
26+```
27+
28+`ValidationT e m a` essentially just gathers the errors thrown by `vWarning`.
29+
30+```haskell
31+vWarning :: (Monad m, Monoid e) => e -> ValidationT e m ()
32+```
33+
34+`vWarning` `mappend`s the given `e` to the already collected errors. This is why the warnings are contained inside a list.
35+
36+There is also `vError`. The only difference between `vWarning` and `vError` is that `vError` stops further execution (and further collection of errors and warnings).
37+
38+You would use the validation like this:
39+
40+```haskell
41+main :: IO ()
42+main = do
43+ password <- getLine
44+ result <- runValidationTEither . validatePassword $ password
45+ putStrLn $ case result of
46+ Left errs -> unlines err
47+ Right () -> "You are fine."
48+```
49+
50+You could, of course, do more complicated things like use `vWarningL` and `vErrorL` to add an error to a `mempty` structure, which gets `mappend`ed with other errors.
51+
52+The library comes with a `MonoidMap` `newtype` wrapper around `Map`, which `mappend`s the values themselves on conflict. This can be useful if you have a multiple points of failure and you want to distinguich between them -- validating a username and a password for example:
53+
54+```haskell
55+data Piece
56+ = Password
57+ | UserName
58+ deriving (Eq, Show, Ord)
59+
60+validatePassword :: Monad m => String -> ValidationT (MonoidMap Piece [String]) m ()
61+validatePassword password = do
62+ vLength password
63+ vAlpha password
64+ vNum password
65+ where
66+ warning = mmSingleton UserName
67+ vLength p = when (length p < 8)
68+ $ warning ["The password should be at least 8 characters long."]
69+ vAlpha p = unless (any isAlpha p)
70+ $ warning ["The password should contain at least one alphabetic character."]
71+ vNum p = unless (any isDigit p)
72+ $ warning ["The password should contain at least one numeric character."]
73+```
74+
75+(`mmSingleton` is a covenience initializer for `MonoidMap`.)
src/Control/Monad/Validation.hs+154−32
@@ -3,16 +3,38 @@
33{-# LANGUAGE OverloadedStrings #-}
44{-# LANGUAGE TemplateHaskell #-}
55{-# LANGUAGE TypeFamilies #-}
6+{-# LANGUAGE UndecidableInstances #-}
67
7−module Control.Monad.Validation where
8+module Control.Monad.Validation
9+ ( ValidationT(..)
10+ , runValidationT
11+ , runValidationTEither
12+ , handleValidationT
13+ , vError
14+ , vWarning
15+ , vErrorL
16+ , vWarningL
17+ , vZoom
18+ , vZoomL
19+ , mmSingleton
20+ , setMempty
21+ , neConcat
22+ , textErrors
23+ , _MonoidMap
24+ , MonoidMap(..)
25+ ) where
826
27+import Control.Applicative
928import Control.Lens hiding ((.=))
1029import Control.Monad.Base
1130import Control.Monad.Catch
1231import Control.Monad.Except
32+import Control.Monad.Fail
1333import Control.Monad.State.Strict
34+import Control.Monad.Trans.Control
1435import Data.Aeson
1536import Data.Foldable as F
37+import Data.Functor
1638import Data.List as L
1739import Data.Map.Strict as M
1840import Data.Monoid
@@ -20,20 +42,32 @@ import Data.Text as T
2042import Data.Vector as V
2143import Test.QuickCheck
2244
23−-- | Collects all throwed "warnings" throwed through StateT and "errors" throwed
24−-- through ExceptT to single value using Monoid
25−-- FIXME: give more instances like HReaderT and MonadBaseControl/MonadMask
45+
46+-- | Collects all thrown warnings in 'StateT' and errors
47+-- in 'ExceptT' into a single value using 'Monoid'.
2648newtype ValidationT e m a = ValidationT
2749 { unValidationT :: ExceptT e (StateT e m) a
2850 } deriving ( Functor, Applicative, Monad, MonadThrow, MonadCatch
29− , MonadBase b )
51+ , MonadBase b, Alternative, MonadFix, MonadFail, Contravariant
52+ , MonadIO, MonadPlus, MonadBaseControl b, MonadMask )
3053
3154instance MonadTrans (ValidationT e) where
3255 lift = ValidationT . lift . lift
3356
3457-- | Map with 'Monoid' instance which 'mappend' its values
58+--
59+-- This can be used as the `e` in `ValidationT e m a` to provide different
60+-- sets of errors and warnings for different keys.
61+--
62+-- >>> :{
63+-- mconcat
64+-- [ MonoidMap $ M.fromList [(1, "foo"), (2, "hello, "), (3, "oh no")]
65+-- , MonoidMap $ M.fromList [(1, "bar"), (2, "world")]
66+-- ]
67+-- :}
68+-- MonoidMap (fromList [(1,"foobar"),(2,"hello, world"),(3,"oh no")])
3569newtype MonoidMap k v = MonoidMap (Map k v)
36− deriving (Eq, Ord, Show, Arbitrary)
70+ deriving (Eq, Ord, Show, Arbitrary, Foldable)
3771
3872makePrisms ''MonoidMap
3973
@@ -61,7 +95,7 @@ instance (ToJSON k, ToJSON v) => ToJSON (MonoidMap k v) where
6195 , "value" .= v ]
6296
6397instance (Ord k, FromJSON k, FromJSON v) => FromJSON (MonoidMap k v) where
64− parseJSON v = withArray "MonoidMap" go v
98+ parseJSON = withArray "MonoidMap" go
6599 where
66100 go arr = do
67101 keyvals <- traverse fromObj arr
@@ -78,35 +112,60 @@ mmAppend :: (Ord k, Monoid v) => MonoidMap k v -> MonoidMap k v -> MonoidMap k v
78112#endif
79113mmAppend (MonoidMap a) (MonoidMap b) = MonoidMap $ M.unionWith (<>) a b
80114
81−-- | Convenient for 'vZoom' as first artument. Will prevent generation
82−-- of map with 'mempty' values
115+-- | Convenient for 'vZoom' as first argument. Will prevent generation
116+-- of map with 'mempty' values.
83117mmSingleton :: (Eq v, Monoid v, Ord k) => k -> v -> MonoidMap k v
84−mmSingleton k = memptyWrap mempty $ MonoidMap . M.singleton k
118+mmSingleton k v
119+ | v == mempty = mempty
120+ | otherwise = MonoidMap . M.singleton k $ v
85121
86−-- | Set given value to 'mempty'
122+-- | Sets given value to 'mempty'.
87123setMempty :: (Monoid s) => ASetter' s a -> a -> s
88124setMempty setter a = set setter a mempty
89125
90−memptyWrap :: (Eq a, Monoid a) => b -> (a -> b) -> a -> b
91−memptyWrap b f a
92− | a == mempty = b
93− | otherwise = f a
94−
95−-- | If given container is not 'mempty', then use given function to
96−-- append all its elements and return 'Just' result
97−neConcat
98− :: (Foldable f, Eq (f a), Monoid a, Monoid (f a))
99− => (a -> a -> a)
100− -> f a
101− -> Maybe a
102−neConcat f = memptyWrap Nothing (Just . F.foldl' f mempty)
126+neConcat :: Foldable f => (a -> a -> a) -> f a -> Maybe a
127+neConcat f a
128+ | F.null a = Nothing
129+ | otherwise = Just $ F.foldr1 f a
103130
131+-- | Returns the strings, concatanated with @", "@ if the list is not empty.
132+--
133+-- Returns Nothing if the list is empty
134+--
135+-- >>> textErrors ["foo", "bar"]
136+-- Just "foo, bar"
137+--
138+-- >>> textErrors ["foo"]
139+-- Just "foo"
140+--
141+-- >>> textErrors []
142+-- Nothing
104143textErrors :: [Text] -> Maybe Text
105144textErrors = neConcat (\a b -> a <> ", " <> b)
106145
107−-- | Returns `mempty` instead of error if no warnings was occured. So, your
108−-- error should have `Eq` instance to detect that any error was occured. Returns
109−-- Nothing for second element of tuple if compuration was interruped by 'vError'
146+-- | Returns 'mempty' instead of error if no warnings have occured.
147+-- Returns 'Nothing' as the second element of tuple if computation was
148+-- interrupted by 'vError'.
149+--
150+-- Returns all concatenated errors and warnings and the result if no
151+-- errors have occured (warnings could have occured).
152+--
153+-- >>> :{
154+-- runValidationT $ do
155+-- vWarning ["warning1"]
156+-- vError ["error"]
157+-- vWarning ["warning2"]
158+-- return 8
159+-- :}
160+-- (["error","warning1"],Nothing)
161+--
162+-- >>> :{
163+-- runValidationT $ do
164+-- vWarning ["warning1"]
165+-- vWarning ["warning2"]
166+-- return 8
167+-- :}
168+-- (["warning1","warning2"],Just 8)
110169runValidationT :: (Monoid e, Monad m) => ValidationT e m a -> m (e, Maybe a)
111170runValidationT (ValidationT m) = do
112171 (res, warnings) <- runStateT (runExceptT m) mempty
@@ -114,6 +173,25 @@ runValidationT (ValidationT m) = do
114173 Left err -> (err <> warnings, Nothing)
115174 Right a -> (warnings, Just a)
116175
176+-- | Like 'runValidationT' but doesn't return the result
177+-- if any warning has occured.
178+--
179+-- >>> :{
180+-- runValidationTEither $ do
181+-- vWarning ["warning1"]
182+-- vError ["error"]
183+-- vWarning ["warning2"]
184+-- return 8
185+-- :}
186+-- Left ["error","warning1"]
187+--
188+-- >>> :{
189+-- runValidationTEither $ do
190+-- vWarning ["warning1"]
191+-- vWarning ["warning2"]
192+-- return 8
193+-- :}
194+-- Left ["warning1","warning2"]
117195runValidationTEither
118196 :: (Monoid e, Eq e, Monad m)
119197 => ValidationT e m a
@@ -124,28 +202,71 @@ runValidationTEither action = do
124202 Just a | err == mempty -> Right a
125203 _ -> Left err
126204
205+-- | Like 'runValidationTEither', but takes an error handler instead of
206+-- returning errors and warnings.
207+--
208+-- >>> :{
209+-- handleValidationT (\_ -> return 11) $ do
210+-- vWarning ["warning1"]
211+-- vError ["error"]
212+-- vWarning ["warning2"]
213+-- return 8
214+-- :}
215+-- 11
216+--
217+-- >>> :{
218+-- handleValidationT (\_ -> return 11) $ do
219+-- vWarning ["warning1"]
220+-- vWarning ["warning2"]
221+-- return 8
222+-- :}
223+-- 11
127224handleValidationT
128225 :: (Monoid e, Monad m, Eq e)
129226 => (e -> m a)
130227 -> ValidationT e m a
131228 -> m a
132−handleValidationT handler action = do
229+handleValidationT handler action =
133230 runValidationTEither action >>= either handler return
134231
135−-- | Stops further execution of validation
232+-- | Stops further execution and appends the given error.
136233vError :: (Monad m) => e -> ValidationT e m a
137234vError e = ValidationT $ throwError e
138235
139−-- | Does not stop further execution, append warning to
236+-- | Does not stop further execution and appends the given warning.
140237vWarning :: (Monad m, Monoid e) => e -> ValidationT e m ()
141238vWarning e = ValidationT $ modify' (<> e)
142239
240+-- | Like 'vError' but allows you to use a setter to insert an error somewhere
241+-- deeper into an empty ('mempty') "e" from "ValidationT e m x", which is then
242+-- combined with all gathered warnings.
143243vErrorL :: (Monad m, Monoid e) => ASetter' e a -> a -> ValidationT e m x
144244vErrorL l a = vError $ setMempty l a
145245
246+-- | Like 'vWarning' but allows you to use a setter to insert an error somewhere
247+-- deeper into an empty ('mempty') "e" from "ValidationT e m x", which is then
248+-- combined with all gathered warnings.
146249vWarningL :: (Monad m, Monoid e) => ASetter' e a -> a -> ValidationT e m ()
147250vWarningL l a = vWarning $ setMempty l a
148251
252+-- | Allows you apply a transformation to the "e" in "ValidationT e m x".
253+--
254+-- >>> :{
255+--runValidationT . vZoom (Data.Map.singleton "password errors") $ do
256+-- vWarning ["warning1"]
257+-- vError ["error"]
258+-- vWarning ["warning2"]
259+-- return 8
260+-- :}
261+-- (fromList [("password errors",["error","warning1"])],Nothing)
262+--
263+-- >>> :{
264+-- runValidationT . vZoom (Data.Map.singleton "password errors") $ do
265+-- vWarning ["warning1"]
266+-- vWarning ["warning2"]
267+-- return 8
268+-- :}
269+-- (fromList [("password errors",["warning1","warning2"])],Just 8)
149270vZoom
150271 :: (Monad m, Monoid a, Monoid b)
151272 => (a -> b)
@@ -155,11 +276,12 @@ vZoom up action = do
155276 (err, res) <- lift $ runValidationT action
156277 case res of
157278 Nothing -> vError $ up err
158− Just a -> vWarning (up err) *> return a
279+ Just a -> vWarning (up err) $> a
159280
281+-- | Like 'vZoom' but takes a setter instead of a function.
160282vZoomL
161283 :: (Monad m, Monoid a, Monoid b)
162284 => ASetter' b a
163285 -> ValidationT a m x
164286 -> ValidationT b m x
165−vZoomL l action = vZoom (setMempty l) action
287+vZoomL l = vZoom (setMempty l)
stack.yaml+2−2
@@ -15,7 +15,7 @@
1515# resolver:
1616# name: custom-snapshot
1717# location: "./custom-snapshot.yaml"
18−resolver: lts-8.14
18+resolver: lts-14.21
1919
2020# User packages to be built.
2121# Various formats can be used as shown in the example below.
@@ -63,4 +63,4 @@ extra-package-dbs: []
6363# extra-lib-dirs: [/path/to/dir]
6464#
6565# Allow a newer minor version of GHC than the snapshot specifies
66−# compiler-check: newer-minor
66+# compiler-check: newer-minor
test/Doc.hsnew file+6
@@ -0,0 +1,6 @@
1+module Main (main) where
2+
3+import Test.DocTest
4+
5+main :: IO ()
6+main = doctest [ "-XOverloadedStrings", "-isrc", "src" ]
validationt.cabal+22−1
@@ -2,7 +2,7 @@
22-- documentation, see http://haskell.org/cabal/users-guide/
33
44name: validationt
5−version: 0.2.1.0
5+version: 0.3.0
66synopsis: Straightforward validation monad.
77description: Convenient solution for validating web forms and APIs.
88homepage: https://github.com/typeable/validationt
@@ -38,3 +38,24 @@ library
3838 , vector
3939 hs-source-dirs: src
4040 default-language: Haskell2010
41+ ghc-options: -fwarn-unused-binds
42+ -Wall
43+ -Wincomplete-uni-patterns
44+ -Wincomplete-record-updates
45+ -Wpartial-fields
46+ -Werror=missing-home-modules
47+ -Wmissing-home-modules
48+ -Widentities
49+ -Wredundant-constraints
50+ -Wmissing-export-lists
51+
52+test-suite doctest
53+ default-language: Haskell2010
54+ type: exitcode-stdio-1.0
55+ hs-source-dirs: test
56+ ghc-options: -Wall
57+ main-is: Doc.hs
58+ build-depends:
59+ base >= 4.10.0.0
60+ , doctest >= 0.11.4
61+ , validationt