module Lambdabot.File
( findLBFile
, findOrCreateLBFile
, outputDir
) where
import Lambdabot.Config.Core
import Lambdabot.Monad
import Lambdabot.Util
import Control.Applicative
import Control.Monad
import Paths_lambdabot
import System.Directory
import System.FilePath
lambdabot :: FilePath
lambdabot = ".lambdabot"
stateDir :: LB FilePath
stateDir = (lambdabot </>) <$> getConfig outputDir
maybeFileExists :: FilePath -> IO (Maybe FilePath)
maybeFileExists path = do
b <- doesFileExist path
return $! if b then Just path else Nothing
lookLocally :: FilePath -> LB (Maybe String)
lookLocally file = do
local <- getConfig outputDir
io $ maybeFileExists (local </> file)
lookHome :: FilePath -> LB (Maybe String)
lookHome f = do
home <- io getHomeDirectory
state <- stateDir
io (maybeFileExists $ home </> state </> f)
isHome :: LB Bool
isHome = do
home <- io getHomeDirectory
state <- stateDir
io . fmap and . mapM (doesDirectoryExist . (home </>)) $ [lambdabot, state]
mkdirL :: LB ()
mkdirL = do
home <- io getHomeDirectory
state <- stateDir
io . mapM_ (createDirectory . (home </>)) $ [lambdabot, state]
cpDataToHome :: FilePath -> LB ()
cpDataToHome f = do
local <- getConfig outputDir
state <- stateDir
rofile <- io (getDataFileName (local </> f))
home <- io getHomeDirectory
let outFile = home </> state </> f
exists <- io (doesFileExist rofile)
if exists
then io (copyFile rofile outFile)
else io (writeFile outFile "")
findLBFile :: FilePath -> LB (Maybe String)
findLBFile f = do
first <- lookLocally f
case first of
Just a -> return (Just a)
Nothing -> lookHome f
findOrCreateLBFile :: FilePath -> LB String
findOrCreateLBFile f = do
mbFile <- findLBFile f
case mbFile of
Just file -> return file
Nothing -> do
exists <- isHome
when (not exists) mkdirL
cpDataToHome f
g <- lookHome f
case g of
Just a -> return a
Nothing -> do
home <- io getHomeDirectory
state <- stateDir
fail $ "findOrCreateLBFile: couldn't find file "
++ f ++ " in " ++ home </> state