module BDCS.API.Workspace(workspaceRead,
workspaceWrite,
workspaceDelete,
workspaceDir,
WorkspaceError(..))
where
import BDCS.API.Recipe(Recipe(..), parseRecipe, recipeTOML, recipeTomlFilename)
import BDCS.API.Utils(maybeThrow)
import Control.Conditional(ifM, whenM)
import Control.Exception
import qualified Data.Text as T
import qualified Data.Text.IO as TIO
import GI.Gio(fileGetPath)
import qualified GI.Ggit as Git
import System.Directory(createDirectoryIfMissing, doesFileExist, removeFile)
import System.FilePath.Posix((</>))
data WorkspaceError =
RepoLocationError
| ParseRecipeError String
deriving (Eq, Show)
instance Exception WorkspaceError
workspaceDir :: Git.Repository -> T.Text -> IO FilePath
workspaceDir repo branch = do
location <- Git.repositoryGetLocation repo >>= maybeThrow RepoLocationError
path <- fileGetPath location >>= maybeThrow RepoLocationError
return $ path </> "workspace" </> T.unpack branch
workspaceRead :: Git.Repository -> T.Text -> T.Text -> IO (Maybe Recipe)
workspaceRead repo branch recipe_name = do
dir <- workspaceDir repo branch
createDirectoryIfMissing True dir
let filename = dir </> T.unpack (recipeTomlFilename $ T.unpack recipe_name)
ifM (doesFileExist filename)
(Just <$> readRecipe filename)
(return Nothing)
where
readRecipe :: FilePath -> IO Recipe
readRecipe filename = do
toml_in <- TIO.readFile filename
let erecipe = parseRecipe toml_in
case erecipe of
Left e -> throwIO $ ParseRecipeError e
Right recipe -> return recipe
workspaceWrite :: Git.Repository -> T.Text -> Recipe -> IO ()
workspaceWrite repo branch recipe = do
dir <- workspaceDir repo branch
createDirectoryIfMissing True dir
let toml_out = T.unpack $ recipeTOML recipe
let filename = dir </> T.unpack (recipeTomlFilename (rName recipe))
writeFile filename toml_out
workspaceDelete :: Git.Repository -> T.Text -> T.Text -> IO ()
workspaceDelete repo branch recipe_name = do
dir <- workspaceDir repo branch
let filename = dir </> T.unpack (recipeTomlFilename $ T.unpack recipe_name)
whenM (doesFileExist filename) (removeFile filename)