git.iko.soy/typeable/cabal2nix
on master help sign in
Language/Nix/Path.hs: clean up the module and hide Path's constructor
653a901Peter Simons
src/Language/Nix/Path.hs+31−8
@@ -1,22 +1,45 @@
1−module Language.Nix.Path ( Path, mkPath, path ) where
1+module Language.Nix.Path ( Path, path ) where
2
2
3import Control.Lens
3import Control.Lens
4−import Distribution.Nixpkgs.Util.PrettyPrinting ( Pretty(..), punctuate, hcat, char )
4+import Distribution.Nixpkgs.Util.PrettyPrinting ( Pretty (..), char, hcat, punctuate )
5import Language.Nix.Identifier
5import Language.Nix.Identifier
6
6
7-- | Paths are non-empty lists of identifiers in Nix.
7-- | Paths are non-empty lists of identifiers in Nix.
8+--
9+-- >>> set path [set ident "yo" undefined] undefined
10+-- Path {_segments = [Identifier "yo"]}
11+--
12+-- Any attempt to construct the empty path throws an 'error':
13+--
14+-- >>> set path [] undefined
15+-- Path {_segments = *** Exception: Nix paths cannot be empty
16+--
17+-- 'Identifier' is an instance of 'IsString':
18+--
19+-- >>> :set -XOverloadedStrings
20+-- >>> pPrint $ set path ["yo","bar"] undefined
21+-- yo.bar
22+--
23+-- Freaky quoted identifiers are fine except in the first segment:
24+--
25+-- >>> pPrint $ set path ["yo","b\"ar"] undefined
26+-- yo."b\"ar"
27+-- >>> pPrint $ set path ["5ident"] undefined
28+-- *** Exception: invalid Nix path: [Identifier "5ident"]
29+-- >>> pPrint $ set path ["5ident","foo","bar"] undefined
30+-- *** Exception: invalid Nix path: [Identifier "5ident",Identifier "foo",Identifier "bar"]
8
31
9newtype Path = Path { _segments :: [Identifier] }
32newtype Path = Path { _segments :: [Identifier] }
10 deriving (Show, Eq, Ord)
33 deriving (Show, Eq, Ord)
11
34
12−mkPath :: [Identifier] -> Path
13−mkPath [] = error "Nix paths cannot be empty"
14−mkPath p
15− | [Identifier s] <- p, needsQuoting s = error ("invalid Nix path: " ++ show p)
16− | otherwise = Path p
17−
18path :: Lens' Path [Identifier]
35path :: Lens' Path [Identifier]
19path f (Path ids) = mkPath `fmap` f ids
36path f (Path ids) = mkPath `fmap` f ids
37+ where
38+ mkPath :: [Identifier] -> Path
39+ mkPath [] = error "Nix paths cannot be empty"
40+ mkPath p@(s0:_)
41+ | s0^.ident.to needsQuoting = error ("invalid Nix path: " ++ show p)
42+ | otherwise = Path p
20
43
21instance Pretty Path where
44instance Pretty Path where
22 pPrint p = hcat $ punctuate (char '.') $ pPrint <$> p^.path
45 pPrint p = hcat $ punctuate (char '.') $ pPrint <$> p^.path