{-# LANGUAGE FlexibleInstances, FlexibleContexts #-}
module Propellor.Property.File where
import Propellor.Base
import Utility.FileMode
import qualified Data.ByteString.Lazy as L
import Data.List (isInfixOf, isPrefixOf)
import System.Posix.Files
import System.Exit
import Data.Char
type Line = String
hasContent :: FilePath -> [Line] -> Property UnixLike
f `hasContent` newcontent = fileProperty
("replace " ++ f)
(\_oldcontent -> newcontent) f
containsLine :: FilePath -> Line -> Property UnixLike
f `containsLine` l = f `containsLines` [l]
containsLines :: FilePath -> [Line] -> Property UnixLike
f `containsLines` ls = fileProperty (f ++ " contains:" ++ show ls) go f
where
go content = content ++ filter (`notElem` content) ls
containsBlock :: FilePath -> [Line] -> RevertableProperty UnixLike UnixLike
f `containsBlock` ls =
fileProperty (f ++ " contains block:" ++ show ls) add f
<!> fileProperty (f ++ " lacks block:" ++ show ls) remove f
where
add content
| ls `isInfixOf` content = content
| otherwise = content ++ ls
remove [] = []
remove content@(x:xs)
| ls `isPrefixOf` content = remove (drop (length ls) content)
| otherwise = x : remove xs
lacksLine :: FilePath -> Line -> Property UnixLike
f `lacksLine` l = fileProperty (f ++ " remove: " ++ l) (filter (/= l)) f
lacksLines :: FilePath -> [Line] -> Property UnixLike
f `lacksLines` ls = fileProperty (f ++ " remove: " ++ show [ls]) (filter (`notElem` ls)) f
hasContentProtected :: FilePath -> [Line] -> Property UnixLike
f `hasContentProtected` newcontent = fileProperty' ProtectedWrite
("replace " ++ f)
(\_oldcontent -> newcontent) f
hasPrivContent :: IsContext c => FilePath -> c -> Property (HasInfo + UnixLike)
hasPrivContent f = hasPrivContentFrom (PrivDataSourceFile (PrivFile f) f) f
hasPrivContentFrom :: (IsContext c, IsPrivDataSource s) => s -> FilePath -> c -> Property (HasInfo + UnixLike)
hasPrivContentFrom = hasPrivContent' ProtectedWrite
hasPrivContentExposed :: IsContext c => FilePath -> c -> Property (HasInfo + UnixLike)
hasPrivContentExposed f = hasPrivContentExposedFrom (PrivDataSourceFile (PrivFile f) f) f
hasPrivContentExposedFrom :: (IsContext c, IsPrivDataSource s) => s -> FilePath -> c -> Property (HasInfo + UnixLike)
hasPrivContentExposedFrom = hasPrivContent' NormalWrite
hasPrivContent' :: (IsContext c, IsPrivDataSource s) => FileWriteMode -> s -> FilePath -> c -> Property (HasInfo + UnixLike)
hasPrivContent' writemode source f context =
withPrivData source context $ \getcontent ->
property' desc $ \o -> getcontent $ \privcontent ->
ensureProperty o $ fileProperty' writemode desc
(\_oldcontent -> privDataByteString privcontent) f
where
desc = "privcontent " ++ f
basedOn :: FilePath -> (FilePath, [Line] -> [Line]) -> Property UnixLike
f `basedOn` (src, a) = property' desc $ \o -> do
tmpl <- liftIO $ readFile src
ensureProperty o $ fileProperty desc (\_ -> a $ lines $ tmpl) f
where
desc = f ++ " is based on " ++ src
notPresent :: FilePath -> Property UnixLike
notPresent f = check (doesFileExist f) $ property (f ++ " not present") $
makeChange $ nukeFile f
dirExists :: FilePath -> Property UnixLike
dirExists d = check (not <$> doesDirectoryExist d) $ property (d ++ " exists") $
makeChange $ createDirectoryIfMissing True d
newtype LinkTarget = LinkTarget FilePath
isSymlinkedTo :: FilePath -> LinkTarget -> RevertableProperty UnixLike UnixLike
link `isSymlinkedTo` (LinkTarget target) = linked <!> notLinked
where
linked = property (link ++ " is symlinked to " ++ target) $
go =<< getLinkStatus
go (Right stat) =
if isSymbolicLink stat
then checkLink
else nonSymlinkExists
go (Left _) = makeChange $ createSymbolicLink target link
notLinked = property (link ++ "does not exist as a symlink") $
stop =<< getLinkStatus
stop (Right stat) =
if isSymbolicLink stat
then makeChange $ nukeFile link
else nonSymlinkExists
stop (Left _) = noChange
nonSymlinkExists = do
warningMessage $ link ++ " exists and is not a symlink"
return FailedChange
checkLink = do
target' <- liftIO $ readSymbolicLink link
if target == target'
then noChange
else makeChange updateLink
updateLink = createSymbolicLink target `viaStableTmp` link
getLinkStatus = liftIO $ tryIO $ getSymbolicLinkStatus link
isCopyOf :: FilePath -> FilePath -> Property UnixLike
f `isCopyOf` src = property desc $ go =<< (liftIO $ tryIO $ getFileStatus src)
where
desc = f ++ " is copy of " ++ src
go (Right stat) = if isRegularFile stat
then ifM (liftIO $ doesFileExist f)
( gocmp =<< (liftIO $ cmp)
, doit
)
else warningMessage (src ++ " is not a regular file") >>
return FailedChange
go (Left e) = warningMessage (show e) >> return FailedChange
cmp = safeSystem "cmp" [Param "-s", Param "--", File f, File src]
gocmp ExitSuccess = noChange
gocmp (ExitFailure 1) = doit
gocmp _ = warningMessage "cmp failed" >> return FailedChange
doit = makeChange $ copy `viaStableTmp` f
copy dest = unlessM (runcp dest) $ errorMessage "cp failed"
runcp dest = boolSystem "cp"
[Param "--preserve=all", Param "--", File src, File dest]
ownerGroup :: FilePath -> User -> Group -> Property UnixLike
ownerGroup f (User owner) (Group group) = p `describe` (f ++ " owner " ++ og)
where
p = cmdProperty "chown" [og, f]
`changesFile` f
og = owner ++ ":" ++ group
applyPath :: Monoid (Property metatypes) => FilePath -> FilePath -> (FilePath -> Property metatypes) -> Property metatypes
applyPath basedir relpath mkp = mconcat $
map mkp (scanl (</>) basedir (splitPath relpath))
mode :: FilePath -> FileMode -> Property UnixLike
mode f v = p `changesFile` f
where
p = property (f ++ " mode " ++ show v) $ do
liftIO $ modifyFileMode f (const v)
return NoChange
class FileContent c where
emptyFileContent :: c
readFileContent :: FilePath -> IO c
writeFileContent :: FileWriteMode -> FilePath -> c -> IO ()
data FileWriteMode = NormalWrite | ProtectedWrite
instance FileContent [Line] where
emptyFileContent = []
readFileContent f = lines <$> readFile f
writeFileContent NormalWrite f ls = writeFile f (unlines ls)
writeFileContent ProtectedWrite f ls = writeFileProtected f (unlines ls)
instance FileContent L.ByteString where
emptyFileContent = L.empty
readFileContent = L.readFile
writeFileContent NormalWrite f c = L.writeFile f c
writeFileContent ProtectedWrite f c =
writeFileProtected' f (`L.hPutStr` c)
fileProperty :: (FileContent c, Eq c) => Desc -> (c -> c) -> FilePath -> Property UnixLike
fileProperty = fileProperty' NormalWrite
fileProperty' :: (FileContent c, Eq c) => FileWriteMode -> Desc -> (c -> c) -> FilePath -> Property UnixLike
fileProperty' writemode desc a f = property desc $ go =<< liftIO (doesFileExist f)
where
go True = do
old <- liftIO $ readFileContent f
let new = a old
if old == new
then noChange
else makeChange $ updatefile new `viaStableTmp` f
go False = makeChange $ writer f (a emptyFileContent)
updatefile content dest = do
writer dest content
s <- getFileStatus f
setFileMode dest (fileMode s)
setOwnerAndGroup dest (fileOwner s) (fileGroup s)
writer = writeFileContent writemode
stableTmpFor :: FilePath -> FilePath
stableTmpFor f = f ++ ".propellor-new~"
viaStableTmp :: (MonadMask m, MonadIO m) => (FilePath -> m ()) -> FilePath -> m ()
viaStableTmp a f = bracketIO setup cleanup go
where
setup = do
createDirectoryIfMissing True (takeDirectory f)
let tmpfile = stableTmpFor f
nukeFile tmpfile
return tmpfile
cleanup tmpfile = tryIO $ removeFile tmpfile
go tmpfile = do
a tmpfile
liftIO $ rename tmpfile f
configFileName :: String -> FilePath
configFileName = concatMap escape
where
escape c
| isAscii c && isAlphaNum c = [c]
| c == '.' = [c]
| otherwise = '_' : show (ord c)
showConfigFileName :: Show v => v -> FilePath
showConfigFileName = configFileName . show
readConfigFileName :: Read v => FilePath -> Maybe v
readConfigFileName = readish . unescape
where
unescape [] = []
unescape ('_':cs) = case break (not . isDigit) cs of
([], _) -> '_' : unescape cs
(ns, cs') -> case readish ns of
Nothing -> '_' : ns ++ unescape cs'
Just n -> chr n : unescape cs'
unescape (c:cs) = c : unescape cs
data Overwrite = OverwriteExisting | PreserveExisting
checkOverwrite :: Overwrite -> FilePath -> (FilePath -> Property i) -> Property i
checkOverwrite OverwriteExisting f mkp = mkp f
checkOverwrite PreserveExisting f mkp =
check (not <$> doesFileExist f) (mkp f)