propellor/Propellor/Property/File.hs

61 lines
2.0 KiB
Haskell
Raw Normal View History

2014-03-31 03:37:54 +00:00
module Propellor.Property.File where
2014-03-30 17:12:33 +00:00
2014-03-31 03:55:59 +00:00
import Propellor
2014-03-30 19:14:36 +00:00
2014-04-04 04:08:30 +00:00
import System.Posix.Files
2014-03-30 19:31:57 +00:00
type Line = String
2014-03-30 17:12:33 +00:00
2014-03-31 04:43:28 +00:00
-- | Replaces all the content of a file.
2014-03-30 17:12:33 +00:00
hasContent :: FilePath -> [Line] -> Property
2014-03-30 19:31:57 +00:00
f `hasContent` newcontent = fileProperty ("replace " ++ f)
(\_oldcontent -> newcontent) f
2014-03-30 17:12:33 +00:00
2014-04-08 20:58:11 +00:00
-- | Ensures a file has contents that comes from PrivData.
-- Note: Does not do anything with the permissions of the file to prevent
-- it from being seen.
hasPrivContent :: FilePath -> Property
hasPrivContent f = Property ("privcontent " ++ f) $
withPrivData (PrivFile f) (\v -> ensureProperty $ f `hasContent` lines v)
2014-03-31 04:43:28 +00:00
-- | Ensures that a line is present in a file, adding it to the end if not.
2014-03-30 17:12:33 +00:00
containsLine :: FilePath -> Line -> Property
2014-03-30 19:31:57 +00:00
f `containsLine` l = fileProperty (f ++ " contains:" ++ l) go f
2014-03-30 17:12:33 +00:00
where
go ls
| l `elem` ls = ls
| otherwise = ls++[l]
2014-03-31 04:43:28 +00:00
-- | Ensures that a line is not present in a file.
-- Note that the file is ensured to exist, so if it doesn't, an empty
2014-04-03 06:27:17 +00:00
-- file will be written.
2014-03-30 17:12:33 +00:00
lacksLine :: FilePath -> Line -> Property
2014-03-30 19:31:57 +00:00
f `lacksLine` l = fileProperty (f ++ " remove: " ++ l) (filter (/= l)) f
2014-03-30 19:14:36 +00:00
2014-03-31 04:43:28 +00:00
-- | Removes a file. Does not remove symlinks or non-plain-files.
2014-03-30 19:14:36 +00:00
notPresent :: FilePath -> Property
2014-03-30 19:31:57 +00:00
notPresent f = check (doesFileExist f) $ Property (f ++ " not present") $
2014-03-30 19:14:36 +00:00
makeChange $ nukeFile f
2014-03-30 19:31:57 +00:00
fileProperty :: Desc -> ([Line] -> [Line]) -> FilePath -> Property
fileProperty desc a f = Property desc $ go =<< doesFileExist f
where
go True = do
2014-04-04 04:08:30 +00:00
ls <- lines <$> readFile f
2014-03-30 19:31:57 +00:00
let ls' = a ls
if ls' == ls
then noChange
2014-04-04 04:08:30 +00:00
else makeChange $ viaTmp updatefile f (unlines ls')
2014-03-30 19:31:57 +00:00
go False = makeChange $ writeFile f (unlines $ a [])
2014-04-04 04:08:30 +00:00
-- viaTmp makes the temp file mode 600.
-- Replicate the original file mode before moving it into place.
updatefile f' content = do
writeFile f' content
getFileStatus f >>= setFileMode f' . fileMode
-- | Ensures a directory exists.
dirExists :: FilePath -> Property
2014-04-01 16:55:59 +00:00
dirExists d = check (not <$> doesDirectoryExist d) $ Property (d ++ " exists") $
makeChange $ createDirectoryIfMissing True d