git.iko.soy/typeable/validationt
on master help sign in
7 files changed+360−59
since splitsnapshots
unifiedsplit
.travis.yml+38 ChangeLog.md+16−2 README.md+76 src/Control/Monad/Validation.hs+181−43 stack.yaml+2−2 test/Doc.hs+6 validationt.cabal+41−12
.travis.ymlnew file+38
@@ -0,0 +1,38 @@
1+sudo: true
2+language: haskell
3+
4+git:
5+ depth: 5
6+
7+cache:
8+ directories:
9+ - "$HOME/.cabal/store"
10+ - "$HOME/.stack"
11+ - "$TRAVIS_BUILD_DIR/.stack-work"
12+
13+jobs:
14+ include:
15+ - ghc: 8.10.2
16+ env: SNAPSHOT="nightly-2020-11-03"
17+ - ghc: 8.8.4
18+ env: SNAPSHOT="lts-16.20"
19+ - ghc: 8.6.5
20+ env: SNAPSHOT="lts-14.22"
21+ - ghc: 8.4.4
22+ env: SNAPSHOT="lts-12.26"
23+
24+install:
25+ - |
26+ # install stack
27+ curl -sSL https://get.haskellstack.org/ | sh
28+
29+ # build project with stack
30+ stack --version
31+ stack build --system-ghc --test --bench --no-run-tests --no-run-benchmarks --resolver=$SNAPSHOT
32+
33+script:
34+ - |
35+ stack test --system-ghc
36+
37+notifications:
38+ email: false
ChangeLog.md+16−2
@@ -1,5 +1,19 @@
11# Revision history for validationt
22
3−## 0.1.0.0 -- YYYY-mm-dd
3+## 0.3.0
44
5−* First version. Released on an unsuspecting world.
5+* Added documentation.
6+* Fixed `textErrors` behaviour.
7+* Dropped `transformers-lift` dependency.
8+
9+## 0.2.1.0
10+
11+* GHC 8.4 support
12+
13+## 0.2.0.0
14+
15+* Fixes
16+
17+## 0.1.0.0
18+
19+* Initial release
README.mdnew file+76
@@ -0,0 +1,76 @@
1+![Travis CI Badge](https://img.shields.io/travis/typeable/validationt)
2+
3+# ValidationT
4+
5+A simple data validation library. The main idea is to provide an easy way to
6+validate web form data by aggregating errors for each field.
7+
8+## Usage
9+
10+Suppose you want to validate some data from the user. Say, that the password adheres to some rules.
11+
12+You might do something like this:
13+
14+```haskell
15+validatePassword :: Monad m => String -> ValidationT [String] m ()
16+validatePassword password = do
17+ vLength password
18+ vAlpha password
19+ vNum password
20+ where
21+ vLength p = when (length p < 8)
22+ $ vWarning ["The password should be at least 8 characters long."]
23+ vAlpha p = unless (any isAlpha p)
24+ $ vWarning ["The password should contain at least one alphabetic character."]
25+ vNum p = unless (any isDigit p)
26+ $ vWarning ["The password should contain at least one numeric character."]
27+```
28+
29+`ValidationT e m a` essentially just gathers the errors thrown by `vWarning`.
30+
31+```haskell
32+vWarning :: (Monad m, Monoid e) => e -> ValidationT e m ()
33+```
34+
35+`vWarning` `mappend`s the given `e` to the already collected errors. This is why the warnings are contained inside a list.
36+
37+There is also `vError`. The only difference between `vWarning` and `vError` is that `vError` stops further execution (and further collection of errors and warnings).
38+
39+You would use the validation like this:
40+
41+```haskell
42+main :: IO ()
43+main = do
44+ password <- getLine
45+ result <- runValidationTEither . validatePassword $ password
46+ putStrLn $ case result of
47+ Left errs -> unlines err
48+ Right () -> "You are fine."
49+```
50+
51+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.
52+
53+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:
54+
55+```haskell
56+data Piece
57+ = Password
58+ | UserName
59+ deriving (Eq, Show, Ord)
60+
61+validatePassword :: Monad m => String -> ValidationT (MonoidMap Piece [String]) m ()
62+validatePassword password = do
63+ vLength password
64+ vAlpha password
65+ vNum password
66+ where
67+ warning = mmSingleton UserName
68+ vLength p = when (length p < 8)
69+ $ warning ["The password should be at least 8 characters long."]
70+ vAlpha p = unless (any isAlpha p)
71+ $ warning ["The password should contain at least one alphabetic character."]
72+ vNum p = unless (any isDigit p)
73+ $ warning ["The password should contain at least one numeric character."]
74+```
75+
76+(`mmSingleton` is a covenience initializer for `MonoidMap`.)
src/Control/Monad/Validation.hs+181−43
@@ -1,43 +1,77 @@
1+{-# LANGUAGE CPP #-}
12{-# LANGUAGE GeneralizedNewtypeDeriving #-}
23{-# LANGUAGE OverloadedStrings #-}
34{-# LANGUAGE TemplateHaskell #-}
45{-# LANGUAGE TypeFamilies #-}
6+{-# LANGUAGE UndecidableInstances #-}
57
6−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+ , vPromote
20+ , mmSingleton
21+ , setMempty
22+ , neConcat
23+ , textErrors
24+ , _MonoidMap
25+ , MonoidMap(..)
26+ ) where
727
28+import Control.Applicative
829import Control.Lens hiding ((.=))
930import Control.Monad.Base
1031import Control.Monad.Catch
1132import Control.Monad.Except
33+import Control.Monad.Fail
1234import Control.Monad.State.Strict
13−import Control.Monad.Trans.Lift.Local
35+import Control.Monad.Trans.Control
1436import Data.Aeson
1537import Data.Foldable as F
38+import Data.Functor
1639import Data.List as L
1740import Data.Map.Strict as M
18−import Data.Monoid
19−import qualified Data.Semigroup as S
2041import Data.Text as T
2142import Data.Vector as V
2243import Test.QuickCheck
2344
24−-- | Collects all throwed "warnings" throwed through StateT and "errors" throwed
25−-- through ExceptT to single value using Monoid
26−-- FIXME: give more instances like HReaderT and MonadBaseControl/MonadMask
45+#if MIN_VERSION_mtl(2,3,0)
46+import Control.Monad
47+import Control.Monad.Fix
48+#endif
49+
50+-- | Collects all thrown warnings in 'StateT' and errors
51+-- in 'ExceptT' into a single value using 'Monoid'.
2752newtype ValidationT e m a = ValidationT
2853 { unValidationT :: ExceptT e (StateT e m) a
2954 } deriving ( Functor, Applicative, Monad, MonadThrow, MonadCatch
30− , MonadBase b )
55+ , MonadBase b, Alternative, MonadFix, MonadFail, Contravariant
56+ , MonadIO, MonadPlus, MonadBaseControl b, MonadMask )
3157
3258instance MonadTrans (ValidationT e) where
3359 lift = ValidationT . lift . lift
3460
35−instance LiftLocal (ValidationT e) where
36− liftLocal _ l f = ValidationT . mapExceptT (mapStateT $ l f) . unValidationT
37−
3861-- | Map with 'Monoid' instance which 'mappend' its values
62+--
63+-- This can be used as the `e` in `ValidationT e m a` to provide different
64+-- sets of errors and warnings for different keys.
65+--
66+-- >>> :{
67+-- mconcat
68+-- [ MonoidMap $ M.fromList [(1, "foo"), (2, "hello, "), (3, "oh no")]
69+-- , MonoidMap $ M.fromList [(1, "bar"), (2, "world")]
70+-- ]
71+-- :}
72+-- MonoidMap (fromList [(1,"foobar"),(2,"hello, world"),(3,"oh no")])
3973newtype MonoidMap k v = MonoidMap (Map k v)
40− deriving (Eq, Ord, Show, Arbitrary)
74+ deriving (Eq, Ord, Show, Arbitrary, Foldable)
4175
4276makePrisms ''MonoidMap
4377
@@ -48,14 +82,14 @@ instance (Ord k) => Ixed (MonoidMap k v) where
4882instance (Ord k) => At (MonoidMap k v) where
4983 at key = _MonoidMap . at key
5084
51−instance (Ord k, S.Semigroup v) => S.Semigroup (MonoidMap k v) where
52− (MonoidMap a) <> (MonoidMap b) =
53− MonoidMap $ M.unionWith (S.<>) a b
85+#if MIN_VERSION_base(4,11,0)
86+instance (Ord k, Semigroup v) => Semigroup (MonoidMap k v) where
87+ (<>) = mmAppend
88+#endif
5489
5590instance (Ord k, Monoid v) => Monoid (MonoidMap k v) where
5691 mempty = MonoidMap M.empty
57− mappend (MonoidMap a) (MonoidMap b) =
58− MonoidMap $ M.unionWith (<>) a b
92+ mappend = (<>)
5993
6094instance (ToJSON k, ToJSON v) => ToJSON (MonoidMap k v) where
6195 toJSON (MonoidMap m) = toJSON $ L.map toObj $ M.toList m
@@ -65,7 +99,7 @@ instance (ToJSON k, ToJSON v) => ToJSON (MonoidMap k v) where
6599 , "value" .= v ]
66100
67101instance (Ord k, FromJSON k, FromJSON v) => FromJSON (MonoidMap k v) where
68− parseJSON v = withArray "MonoidMap" go v
102+ parseJSON = withArray "MonoidMap" go
69103 where
70104 go arr = do
71105 keyvals <- traverse fromObj arr
@@ -75,35 +109,67 @@ instance (Ord k, FromJSON k, FromJSON v) => FromJSON (MonoidMap k v) where
75109 val <- obj .: "value"
76110 return (key, val)
77111
78−-- | Convenient for 'vZoom' as first artument. Will prevent generation
79−-- of map with 'mempty' values
112+#if MIN_VERSION_base(4,11,0)
113+mmAppend :: (Ord k, Semigroup v) => MonoidMap k v -> MonoidMap k v -> MonoidMap k v
114+#else
115+mmAppend :: (Ord k, Monoid v) => MonoidMap k v -> MonoidMap k v -> MonoidMap k v
116+#endif
117+mmAppend (MonoidMap a) (MonoidMap b) = MonoidMap $ M.unionWith (<>) a b
118+
119+-- | Convenient for 'vZoom' as first argument. Will prevent generation
120+-- of map with 'mempty' values.
80121mmSingleton :: (Eq v, Monoid v, Ord k) => k -> v -> MonoidMap k v
81−mmSingleton k = memptyWrap mempty $ MonoidMap . M.singleton k
122+mmSingleton k v
123+ | v == mempty = mempty
124+ | otherwise = MonoidMap . M.singleton k $ v
82125
83−-- | Set given value to 'mempty'
126+-- | Sets given value to 'mempty'.
84127setMempty :: (Monoid s) => ASetter' s a -> a -> s
85128setMempty setter a = set setter a mempty
86129
87−memptyWrap :: (Eq a, Monoid a) => b -> (a -> b) -> a -> b
88−memptyWrap b f a
89− | a == mempty = b
90− | otherwise = f a
91−
92−-- | If given container is not 'mempty', then use given function to
93−-- append all its elements and return 'Just' result
94−neConcat
95− :: (Foldable f, Eq (f a), Monoid a, Monoid (f a))
96− => (a -> a -> a)
97− -> f a
98− -> Maybe a
99−neConcat f = memptyWrap Nothing (Just . F.foldl' f mempty)
130+neConcat :: Foldable f => (a -> a -> a) -> f a -> Maybe a
131+neConcat f a
132+ | F.null a = Nothing
133+ | otherwise = Just $ F.foldr1 f a
100134
135+-- | Returns the strings, concatanated with @", "@ if the list is not empty.
136+--
137+-- Returns Nothing if the list is empty
138+--
139+-- >>> textErrors ["foo", "bar"]
140+-- Just "foo, bar"
141+--
142+-- >>> textErrors ["foo"]
143+-- Just "foo"
144+--
145+-- >>> textErrors []
146+-- Nothing
101147textErrors :: [Text] -> Maybe Text
102148textErrors = neConcat (\a b -> a <> ", " <> b)
103149
104−-- | Returns `mempty` instead of error if no warnings was occured. So, your
105−-- error should have `Eq` instance to detect that any error was occured. Returns
106−-- Nothing for second element of tuple if compuration was interruped by 'vError'
150+-- | Returns 'mempty' instead of error if no warnings have occurred.
151+-- Returns 'Nothing' as the second element of tuple if computation was
152+-- interrupted by 'vError'.
153+--
154+-- Returns all concatenated errors and warnings and the result if no
155+-- errors have occurred (warnings could have occurred).
156+--
157+-- >>> :{
158+-- runValidationT $ do
159+-- vWarning ["warning1"]
160+-- vError ["error"]
161+-- vWarning ["warning2"]
162+-- return 8
163+-- :}
164+-- (["error","warning1"],Nothing)
165+--
166+-- >>> :{
167+-- runValidationT $ do
168+-- vWarning ["warning1"]
169+-- vWarning ["warning2"]
170+-- return 8
171+-- :}
172+-- (["warning1","warning2"],Just 8)
107173runValidationT :: (Monoid e, Monad m) => ValidationT e m a -> m (e, Maybe a)
108174runValidationT (ValidationT m) = do
109175 (res, warnings) <- runStateT (runExceptT m) mempty
@@ -111,6 +177,25 @@ runValidationT (ValidationT m) = do
111177 Left err -> (err <> warnings, Nothing)
112178 Right a -> (warnings, Just a)
113179
180+-- | Like 'runValidationT' but doesn't return the result
181+-- if any warning has occurred.
182+--
183+-- >>> :{
184+-- runValidationTEither $ do
185+-- vWarning ["warning1"]
186+-- vError ["error"]
187+-- vWarning ["warning2"]
188+-- return 8
189+-- :}
190+-- Left ["error","warning1"]
191+--
192+-- >>> :{
193+-- runValidationTEither $ do
194+-- vWarning ["warning1"]
195+-- vWarning ["warning2"]
196+-- return 8
197+-- :}
198+-- Left ["warning1","warning2"]
114199runValidationTEither
115200 :: (Monoid e, Eq e, Monad m)
116201 => ValidationT e m a
@@ -121,28 +206,71 @@ runValidationTEither action = do
121206 Just a | err == mempty -> Right a
122207 _ -> Left err
123208
209+-- | Like 'runValidationTEither', but takes an error handler instead of
210+-- returning errors and warnings.
211+--
212+-- >>> :{
213+-- handleValidationT (\_ -> return 11) $ do
214+-- vWarning ["warning1"]
215+-- vError ["error"]
216+-- vWarning ["warning2"]
217+-- return 8
218+-- :}
219+-- 11
220+--
221+-- >>> :{
222+-- handleValidationT (\_ -> return 11) $ do
223+-- vWarning ["warning1"]
224+-- vWarning ["warning2"]
225+-- return 8
226+-- :}
227+-- 11
124228handleValidationT
125229 :: (Monoid e, Monad m, Eq e)
126230 => (e -> m a)
127231 -> ValidationT e m a
128232 -> m a
129−handleValidationT handler action = do
233+handleValidationT handler action =
130234 runValidationTEither action >>= either handler return
131235
132−-- | Stops further execution of validation
236+-- | Stops further execution and appends the given error.
133237vError :: (Monad m) => e -> ValidationT e m a
134238vError e = ValidationT $ throwError e
135239
136−-- | Does not stop further execution, append warning to
240+-- | Does not stop further execution and appends the given warning.
137241vWarning :: (Monad m, Monoid e) => e -> ValidationT e m ()
138242vWarning e = ValidationT $ modify' (<> e)
139243
244+-- | Like 'vError' but allows you to use a setter to insert an error somewhere
245+-- deeper into an empty ('mempty') "e" from "ValidationT e m x", which is then
246+-- combined with all gathered warnings.
140247vErrorL :: (Monad m, Monoid e) => ASetter' e a -> a -> ValidationT e m x
141248vErrorL l a = vError $ setMempty l a
142249
250+-- | Like 'vWarning' but allows you to use a setter to insert an error somewhere
251+-- deeper into an empty ('mempty') "e" from "ValidationT e m x", which is then
252+-- combined with all gathered warnings.
143253vWarningL :: (Monad m, Monoid e) => ASetter' e a -> a -> ValidationT e m ()
144254vWarningL l a = vWarning $ setMempty l a
145255
256+-- | Allows you apply a transformation to the "e" in "ValidationT e m x".
257+--
258+-- >>> :{
259+--runValidationT . vZoom (Data.Map.singleton "password errors") $ do
260+-- vWarning ["warning1"]
261+-- vError ["error"]
262+-- vWarning ["warning2"]
263+-- return 8
264+-- :}
265+-- (fromList [("password errors",["error","warning1"])],Nothing)
266+--
267+-- >>> :{
268+-- runValidationT . vZoom (Data.Map.singleton "password errors") $ do
269+-- vWarning ["warning1"]
270+-- vWarning ["warning2"]
271+-- return 8
272+-- :}
273+-- (fromList [("password errors",["warning1","warning2"])],Just 8)
146274vZoom
147275 :: (Monad m, Monoid a, Monoid b)
148276 => (a -> b)
@@ -152,11 +280,21 @@ vZoom up action = do
152280 (err, res) <- lift $ runValidationT action
153281 case res of
154282 Nothing -> vError $ up err
155− Just a -> vWarning (up err) *> return a
283+ Just a -> vWarning (up err) $> a
156284
285+-- | Like 'vZoom' but takes a setter instead of a function.
157286vZoomL
158287 :: (Monad m, Monoid a, Monoid b)
159288 => ASetter' b a
160289 -> ValidationT a m x
161290 -> ValidationT b m x
162−vZoomL l action = vZoom (setMempty l) action
291+vZoomL l = vZoom (setMempty l)
292+
293+-- | Turn any warnings the have occurred into errors.
294+vPromote
295+ :: (Monad m, Monoid a, Eq a)
296+ => ValidationT a m x
297+ -> ValidationT a m x
298+vPromote m = do
299+ err <- lift $ runValidationTEither m
300+ either vError return err
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-22.4
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+41−12
@@ -2,10 +2,12 @@
22-- documentation, see http://haskell.org/cabal/users-guide/
33
44name: validationt
5−version: 0.2.0.0
6−synopsis: Straightforward validation monad. Convenient solution for validating web forms and APIs.
7−-- description:
8−homepage: typeable.io
5+version: 0.3.0
6+synopsis: Straightforward validation monad
7+description:
8+ A simple data validation library. The main idea is to provide an easy way to validate web form data by aggregating errors for each field.
9+ .
10+homepage: https://github.com/typeable/validationt
911license: BSD3
1012license-file: LICENSE
1113author: Typeable.io contributors
@@ -14,24 +16,51 @@ maintainer: makeit@typeable.io
1416category: Control
1517build-type: Simple
1618extra-source-files: ChangeLog.md
19+ , README.md
1720cabal-version: >=1.10
21+tested-with: GHC == 8.4.4
22+ , GHC == 8.6.5
23+ , GHC == 8.8.4
24+ , GHC == 8.10.2
25+
26+source-repository head
27+ type: git
28+ location: git@github.com:typeable/validationt.git
1829
1930library
2031 exposed-modules: Control.Monad.Validation
21− build-depends: base >=4.8 && < 5
22− , aeson >= 1.0
32+ build-depends: base >=4.10 && < 5
33+ , aeson >=1.0
2334 , containers
24− , exceptions
35+ , exceptions >=0.9
2536 , lens
2637 , monad-control
27− , mtl
28− , QuickCheck
38+ , mtl <2.3 || >2.3
39+ , QuickCheck >=2.8.2
2940 , text
3041 , transformers
3142 , transformers-base
32− , transformers-lift
3343 , vector
34− if impl(ghc < 8.0)
35− build-depends: semigroups == 0.18.*
3644 hs-source-dirs: src
3745 default-language: Haskell2010
46+ ghc-options: -fwarn-unused-binds
47+ -Wall
48+ -Wincomplete-uni-patterns
49+ -Wincomplete-record-updates
50+ -Wpartial-fields
51+ -Werror=missing-home-modules
52+ -Wmissing-home-modules
53+ -Widentities
54+ -Wredundant-constraints
55+ -Wmissing-export-lists
56+
57+test-suite doctest
58+ default-language: Haskell2010
59+ type: exitcode-stdio-1.0
60+ hs-source-dirs: test
61+ ghc-options: -Wall
62+ main-is: Doc.hs
63+ build-depends:
64+ base >= 4.10.0.0
65+ , doctest >= 0.11.4
66+ , validationt