hablo/src/Blog.hs

76 lines
2.3 KiB
Haskell

{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE FlexibleContexts #-}
module Blog (
Blog(..)
, Path(..)
, Skin(..)
, build
, get
) where
import Arguments (Arguments)
import qualified Arguments (name)
import Article (Article)
import qualified Article (at, getKey)
import Blog.Path (Path(..))
import qualified Blog.Path as Path (build)
import Blog.Skin (Skin(..))
import qualified Blog.Skin as Skin (build)
import Control.Monad ((>=>), filterM, forM)
import Control.Monad.Reader (MonadReader, ask)
import Data.Either (rights)
import Data.Map (Map)
import qualified Data.Map as Map (fromList, member)
import Data.Set (Set)
import qualified Data.Set as Set (empty, null, singleton, union)
import qualified Files (find)
import System.Directory (doesFileExist, withCurrentDirectory)
import System.FilePath ((</>), dropTrailingPathSeparator, takeExtension, takeFileName)
type Collection = Map String Article
data Blog = Blog {
articles :: Collection
, name :: String
, path :: Path
, skin :: Skin
, tags :: Map String (Set String)
}
get :: MonadReader Blog m => (Blog -> a) -> m a
get = (<$> ask)
findArticles :: FilePath -> IO (Map String Article)
findArticles =
Files.find
>=> filterM isMarkDownFile
>=> mapM Article.at
>=> return . Map.fromList . rights
where
isMarkDownFile path = do
let correctExtension = takeExtension path == ".md"
(correctExtension &&) <$> doesFileExist path
tagged :: Collection -> FilePath -> IO (String, Set String)
tagged collection path = do
links <- Files.find path
keys <- forM links $ \link -> do
fileExists <- doesFileExist link
return $ if fileExists
then let articleKey = Article.getKey link in
if Map.member articleKey collection then Set.singleton articleKey else Set.empty
else Set.empty
return (takeFileName path, foldl Set.union Set.empty keys)
build :: Arguments -> IO Blog
build arguments = withCurrentDirectory (root path) $ do
skin <- Skin.build name arguments
articles <- findArticles $ articlesPath path
tags <- Map.fromList . filter (not . Set.null . snd)
<$> (Files.find (articlesPath path </> "tags") >>= mapM (articles `tagged`))
return $ Blog {articles, name, path, skin, tags}
where
path = Path.build arguments
name = maybe (takeFileName . dropTrailingPathSeparator $ root path) id
$ Arguments.name arguments