module Gitson.Util (module Gitson.Util) where
import Control.Monad (void, filterM)
import Control.Applicative
import Data.List (isSuffixOf, isPrefixOf)
import Data.Maybe
import System.FilePath
import System.Directory
import System.Process
import System.IO
entryPath :: FilePath -> String -> FilePath
entryPath collection key = collection </> key <.> "json"
lockPath :: FilePath
lockPath = ".git" </> "gitson-lock"
filterFilenamesAsKeys :: [FilePath] -> [String]
filterFilenamesAsKeys = map dropExtension . filter (isSuffixOf ".json")
filterDirs :: [FilePath] -> IO [FilePath]
filterDirs = (filterM doesDirectoryExist) . filter (not . isPrefixOf ".")
insideDirectory :: FilePath -> IO a -> IO a
insideDirectory path action = do
prevPath <- getCurrentDirectory
setCurrentDirectory path
result <- action
setCurrentDirectory prevPath
return result
lastCommitText :: IO String
lastCommitText = readProcess "git" ["log", "--max-count=1", "--pretty=format:%s"] []
shell :: String -> [String] -> IO ()
shell cmd args = void $ do
dnull <- openFile "/dev/null" ReadWriteMode
(_, _, _, pid) <- createProcess (proc cmd args){std_in = UseHandle dnull, std_out = UseHandle dnull, std_err = UseHandle dnull}
waitForProcess pid
intoMaybe :: Maybe a -> b -> Maybe (a, b)
intoMaybe (Just x) y = Just (x, y)
intoMaybe Nothing y = Nothing
maybeReadIntString :: String -> Maybe (Int, String)
maybeReadIntString x = listToMaybe (reads x :: [(Int, String)])
nextKeyId :: [String] -> Int
nextKeyId = (+1) . maxOrZero . catMaybes . map maybeReadInt
where maybeReadInt x = fst <$> maybeReadIntString x
maxOrZero [] = 0
maxOrZero xs = maximum xs