
module Config (
  currentBranch,
  getGitBranch
  ) where

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

import SubMods
import Tools
  
currentBranch::String
currentBranch = unsafePerformIO $ do
  before <- getCurrentDirectory

  rootAndBranches <-
    forM (map modDir subMods) $ \modRoot -> do
      branch <- inDir modRoot $ getGitBranch
      return (modRoot, branch)
                                 
  let branches = map snd rootAndBranches
  case nub branches of
   [branch] -> return branch
   _ -> error $ "Your submodules are in different branches, mgit can not work properly in this configuration" --  ++ unlines (map show rootAndBranches)
                                    


getGitBranch::IO String
getGitBranch = do
  (exitCode, path, stderr) <-
      readProcessWithExitCode "git" ["symbolic-ref", "--short", "-q", "HEAD"] ""
  case exitCode of
    ExitFailure _ -> return $ "HEAD detached"
    _ -> return $ T.unpack $ T.strip $ T.pack path

getGitTag::IO (Maybe String)
getGitTag = do
  (exitCode, tag, stderr) <-
      readProcessWithExitCode "git" ["describe", "--tags"] ""
  case exitCode of
    ExitFailure _ -> return Nothing
    _ -> return $ Just $ T.unpack $ T.strip $ T.pack tag

               
