1 module Databrary.Web 2 ( WebFilePath 3 , webFileRel 4 , webFileAbs 5 , withWebDir 6 , splitWebExtensions 7 , splitWebExtension 8 , replaceWebExtension 9 , makeWebFilePath 10 ) where 11 12 import qualified Data.ByteString as BS 13 import qualified Data.ByteString.Char8 as BSC 14 import Data.Function (on) 15 import Data.Hashable (Hashable(..)) 16 import qualified System.Posix.FilePath as RFP 17 18 import Paths_databrary (getDataFileName) 19 import Databrary.Files 20 21 data WebFilePath = WebFilePath 22 { webFileRel :: RawFilePath 23 , webFileAbs :: RawFilePath 24 } 25 deriving (Show) 26 27 instance Eq WebFilePath where 28 (==) = (==) `on` webFileRel 29 (/=) = (/=) `on` webFileRel 30 instance Ord WebFilePath where 31 compare = compare `on` webFileRel 32 instance Hashable WebFilePath where 33 hashWithSalt n = hashWithSalt n . webFileRel 34 hash = hash . webFileRel 35 36 type WebDir = RawFilePath 37 38 getWebDir :: IO WebDir 39 getWebDir = do 40 webDir <- getDataFileName "web" 41 rawFilePath webDir 42 43 withWebDir :: (WebDir -> IO a) -> IO a 44 withWebDir f = getWebDir >>= (\rfp -> f rfp) 45 46 -- | Convert a relative path from the web root into an expanded path including web root 47 makeWebFilePath :: RawFilePath -> IO WebFilePath 48 makeWebFilePath r = withWebDir $ \webDirRaw -> do 49 return $ WebFilePath r (webDirRaw RFP.</> r) 50 51 splitWebExtensions :: WebFilePath -> IO (WebFilePath, BS.ByteString) 52 splitWebExtensions f = do 53 let (fn, ext) = RFP.splitExtensions $ webFileRel f 54 wfp <- makeWebFilePath fn 55 return (wfp, ext) 56 57 splitWebExtension :: WebFilePath -> IO (WebFilePath, BS.ByteString) 58 splitWebExtension f = do 59 let (fn, ext) = RFP.splitExtension $ webFileRel f 60 wfp <- makeWebFilePath fn 61 return (wfp, ext) 62 63 replaceWebExtension :: String -> WebFilePath -> WebFilePath 64 replaceWebExtension e (WebFilePath r ra) = WebFilePath (RFP.replaceExtension r re) (RFP.replaceExtension ra re) 65 where re = BSC.pack e