module Hish.SysInfo
(
uid
, hostname
, pwd
, time
, date
, status
, branch
, isRepo
, simpleCmd
, argedCmd
) where
import qualified System.Process as SP
import System.Exit (ExitCode (..))
import Data.List (lines)
import qualified Data.String.Utils as S (split,replace)
import qualified Data.Time.LocalTime as LT (getZonedTime)
import Data.Time.Format as TF (formatTime, defaultTimeLocale)
import Hish.VCS
uid :: IO (Maybe String)
uid = simpleCmd (Just . init) "whoami"
hostname :: IO (Maybe String)
hostname = argedCmd (Just . init) "hostname" ["-s"]
pwd :: Int
-> IO (Maybe String)
pwd width = do
(code,out,_) <- exeCmd "pwd" [] ""
mName <- uid
case (code, mName) of
(ExitSuccess, Just name) -> return $ return $
( (\str -> case head str of
'~' -> str
'/' -> str
_ -> '/':str )
. (\str -> if (length str) > width
then shortDir $ S.split "/" str
else str)
. S.replace ("/Users/"++name) "~"
. filter (/='\n')
) $ out
otherwise -> return Nothing
shortDir :: [String]
-> String
shortDir [] = ""
shortDir [l] = l
shortDir ("":xs) = shortDir xs
shortDir (('.':s):xs) = '.' : (head s) : '/' : shortDir xs
shortDir (x:xs) = (head x) : '/' : shortDir xs
time :: String
-> IO String
time format = do
ztime <- LT.getZonedTime
return $ TF.formatTime TF.defaultTimeLocale format ztime
date :: String -> IO String
date = time
status :: VCS a => a
-> IO (Maybe String,
Maybe String,
Maybe String)
status vcs = do
maybeText <- argedCmd (Just . id) (statusCmd vcs) (statusArgs vcs)
case maybeText of
Nothing -> return
( Nothing
, Nothing
, Nothing )
(Just text) -> return
( vcsCleanliness vcs text
, vcsAhead vcs text
, vcsBehind vcs text )
branch :: VCS a => a
-> IO (Maybe String)
branch vcs = argedCmd (vcsCurrentBranch vcs) (branchCmd vcs) (branchArgs vcs)
isRepo :: VCS a => a -> IO Bool
isRepo vcs = do
(code,_,_) <- exeCmd (statusCmd vcs) (statusArgs vcs) ""
case code of
ExitFailure _ -> return False
ExitSuccess -> return True
exeCmd :: String
-> [String]
-> String
-> IO (ExitCode, String, String)
exeCmd = SP.readProcessWithExitCode
simpleCmd :: (String -> Maybe String)
-> String
-> IO (Maybe String)
simpleCmd handler cmd = argedCmd handler cmd []
argedCmd :: (String -> Maybe String)
-> String
-> [String]
-> IO (Maybe String)
argedCmd handler cmd args = do
(code,stdout,_) <- exeCmd cmd args ""
case code of
ExitFailure _ -> return Nothing
ExitSuccess -> return $ (Just stdout) >>= handler