module Utils ( basename , errorsAndResults , escapeHTML , lookupMeta' , makeFullFilePath , sortByDate ) where import Data.Aeson ( toJSON , Value ) import Data.List import Data.Ord import qualified Data.Text as T import System.Directory import System.FilePath import Text.Pandoc basename :: FilePath -> String basename = dropExtension . takeFileName errorsAndResults :: [(FilePath, Either PandocError a)] -> ([PandocError], [(FilePath, a)]) errorsAndResults xs = let errors = [ error | result@(_, Left error) <- xs ] results = [ (path, a) | result@(path, Right a) <- xs ] in (errors, results) lookupMeta' :: String -> Meta -> T.Text lookupMeta' key meta = case lookupMeta key meta of Just value -> renderMeta value Nothing -> T.empty makeFullFilePath :: FilePath -> FilePath -> IO FilePath makeFullFilePath root path = makeAbsolute $ joinPath [root, path] renderMeta :: MetaValue -> T.Text renderMeta (MetaInlines meta) = case runPure $ writePlain (def Nothing) (Pandoc nullMeta [Plain meta]) of Left err -> T.empty Right text -> text getDate :: Pandoc -> T.Text getDate (Pandoc m _) = lookupMeta' "date" m sortByDate :: [(FilePath, Pandoc)] -> [(FilePath, Pandoc)] sortByDate = sortBy (flip (comparing $ getDate . snd)) escapeHTML :: String -> String escapeHTML = concatMap f where f '>' = ">" f '<' = "<" f '&' = "&" f '\"' = """ f '\'' = "'" f x = [x]