/
Basedir.hs
50 lines (41 loc) · 1.5 KB
/
Basedir.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
module Basedir where
import Data.Maybe (fromMaybe)
import System.FilePath
import System.Directory
import System.Posix.Files (fileExist)
import Support
type SearchPath = [FilePath]
data Basedirs = Basedirs { share :: SearchPath
, cache :: SearchPath
, config :: SearchPath
} deriving Show
getPath :: VarName -> VarName -> SearchPath -> IO SearchPath
getPath homeVar dirsVar defaultPath =
case defaultPath of
(defaultHome:defaultSystem) -> do
userDir <- getEnvOpt homeVar
systemDirs <- getEnvOpt dirsVar
return $ (fromMaybe defaultHome userDir)
: (maybe defaultSystem splitSearchPath systemDirs)
[] -> error "No default!"
getDefaultConfig :: IO Basedirs
getDefaultConfig = do
home <- getHomeDirectory
shareDir <- getPath "XDG_DATA_HOME" "XDG_DATA_DIRS" [home </> ".local/share", "/usr/local/share", "/usr/share"]
cacheDir <- getPath "XDG_CACHE_HOME" "XDG_CACHE_DIRS" [home </> ".cache", "/var/cache"]
configDir <- getPath "XDG_CONFIG_HOME" "XDG_CONFIG_DIRS" [home </> ".config", "/etc/xdg"]
return $ Basedirs {
share = shareDir,
cache = cacheDir,
config = configDir
}
loadFirst :: FilePath -> SearchPath -> IO (Maybe FilePath)
loadFirst _ [] = return Nothing
loadFirst relPath (dir:xs) = do x <- fileExist fullPath
if x then return $ Just fullPath
else loadFirst relPath xs
where fullPath = dir </> relPath
save :: FilePath -> SearchPath -> IO FilePath
save relPath (dir:_) = do createDirectoryIfMissing True fullPath
return fullPath
where fullPath = dir </> relPath