
module Root (
  root
  ) where

import qualified Data.Text as T
import GHC.IO.Exception
import System.Directory
import System.IO.Unsafe
import System.Process

root::FilePath
root = unsafePerformIO getRoot


getGitRoot::IO (Maybe FilePath)
getGitRoot = do
  (exitCode, path, _) <-
      readProcessWithExitCode "git" ["rev-parse", "--show-toplevel"] ""
  case exitCode of
    ExitFailure _ -> return Nothing
    _ -> return $ Just $ T.unpack $ T.strip $ T.pack path

getRoot'::IO (Maybe FilePath)
getRoot' = do
    maybeGitRoot <- getGitRoot
    case maybeGitRoot of
      Nothing -> return Nothing
      Just gitRoot -> do
            setCurrentDirectory gitRoot
            setCurrentDirectory ".."
            maybeParentRoot <- getRoot'

            case maybeParentRoot of
              Nothing -> return $ Just gitRoot
              Just parentRoot -> return $ Just parentRoot

getRoot::IO FilePath
getRoot = do
  before <- getCurrentDirectory
  maybeRoot <- getRoot'
  setCurrentDirectory before
  case maybeRoot of
    Nothing -> error "You are not in a git repository."
    Just x -> return x
               
