module Hish.SysInfo
(
uid
, hostname
, pwd
, time
, date
, status
, branch
, simpleCmd
, argedCmd
) where
import qualified System.Process as SP
import System.Exit (ExitCode (..))
import Data.List (lines,unlines)
import Data.Char (isSpace)
import qualified Data.String.Utils as S (split,replace,join)
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 -> if (head str) == '~' then str else '/':str )
. (\str -> if (length str) > width
then shortDir $ S.split "/" str
else str)
. S.replace ("/Users/"++name) "~"
. filter (/='\n')
) $ out
otherwise -> return Nothing
time :: String
-> IO String
time format = do
ztime <- LT.getZonedTime
return $ TF.formatTime TF.defaultTimeLocale format ztime
date :: String -> IO String
date = time
shortDir :: [String]
-> String
shortDir [] = ""
shortDir [l] = l
shortDir (x:xs) = (head x) : '/' : shortDir xs
status :: VCS a => a
-> IO (Maybe String,
Maybe String,
Maybe String)
status vcs = do
maybeText <- argedCmd (Just . id) "git" ["status","--porcelain","-sb"]
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) "git" ["branch"]
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