module Hish.SysInfo
(
uid
, hostname
, pwd
, time
, date
, simpleCmd
, argedCmd
) where
import qualified System.Process as SP
import System.Exit (ExitCode (..))
import Data.List (lines)
import Text.Regex.TDFA ((=~))
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)
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,_) <- SP.readProcessWithExitCode "pwd" [] ""
mName <- uid
case (code, mName) of
(ExitSuccess, Just name) -> return $ return $
( (\str -> if (length str) > width
then shortenDir "" $ S.split "/" str
else str)
. S.replace ("/Users/"++name) "~"
. filter (/='\n')
) $ out
otherwise -> return Nothing
shortenDir :: String
-> [String]
-> String
shortenDir rs [] = "/"
shortenDir rs [l] = rs ++ ('/' : l)
shortenDir rs ("":xs) = shortenDir rs xs
shortenDir rs (x:xs) =
if (x =~ "\\`[A-Za-z0-9]" :: Bool)
then shortenDir (rs ++ '/' : take 1 x) xs
else shortenDir (rs ++ '/' : take 2 x) xs
time :: String
-> IO String
time format = do
ztime <- LT.getZonedTime
return $ TF.formatTime TF.defaultTimeLocale format ztime
date :: String -> IO String
date = time
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,_) <- SP.readProcessWithExitCode cmd args ""
case code of
ExitFailure _ -> return Nothing
ExitSuccess -> return $ (Just stdout) >>= handler