module Unison.Codebase.FileCodebase (codebaseExists) where

import System.FilePath ((</>))
import Unison.Codebase (CodebasePath)
import Unison.Prelude (MonadIO)
import UnliftIO.Directory (doesDirectoryExist)

-- checks if a minimal codebase structure exists at `path`
codebaseExists :: (MonadIO m) => CodebasePath -> m Bool
codebaseExists :: forall (m :: * -> *). MonadIO m => CodebasePath -> m Bool
codebaseExists CodebasePath
root =
  [Bool] -> Bool
forall (t :: * -> *). Foldable t => t Bool -> Bool
and ([Bool] -> Bool) -> m [Bool] -> m Bool
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (CodebasePath -> m Bool) -> [CodebasePath] -> m [Bool]
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse CodebasePath -> m Bool
forall (m :: * -> *). MonadIO m => CodebasePath -> m Bool
doesDirectoryExist (CodebasePath -> [CodebasePath]
minimalCodebaseStructure CodebasePath
root)
  where
    -- checks if `path` looks like a unison codebase
    minimalCodebaseStructure :: CodebasePath -> [FilePath]
    minimalCodebaseStructure :: CodebasePath -> [CodebasePath]
minimalCodebaseStructure CodebasePath
root = [CodebasePath -> CodebasePath
branchHeadDir CodebasePath
root]

    branchesDir :: CodebasePath -> CodebasePath
branchesDir CodebasePath
root = CodebasePath
root CodebasePath -> CodebasePath -> CodebasePath
</> CodebasePath
codebasePath CodebasePath -> CodebasePath -> CodebasePath
</> CodebasePath
"paths"
    branchHeadDir :: CodebasePath -> CodebasePath
branchHeadDir CodebasePath
root = CodebasePath -> CodebasePath
branchesDir CodebasePath
root CodebasePath -> CodebasePath -> CodebasePath
</> CodebasePath
"_head"

    codebasePath :: FilePath
    codebasePath :: CodebasePath
codebasePath = CodebasePath
".unison" CodebasePath -> CodebasePath -> CodebasePath
</> CodebasePath
"v1"