{-|
Module      : Shell
Description : Command evocation on the shell
Copyright   : (c) Harley Eades, 2026
Maintainer  : harley.eades@gmail.com

This is the API for accessing the users shell. All commands are ran in the login
shell with access to the @PATH@ environment variable, but the shell's rc-file is
not executed by default, and so aliases are not useable. If you need access to
your rc-file, then define a custom t`ShellConfig` for your project.
-}
module Configuration.Cfv.Shell 
  (CommandError(..)
  ,CommandProblem(..)
  ,ShellConfig(..)
  ,evalValue
  ,defaultShellConfig
  ,describeProblem) where

import qualified GHC.IO.Exception as E
import Data.Text.Encoding.Error (UnicodeException, lenientDecode)
import GHC.IO.Exception (ExitCode(..))
import qualified Data.ByteString as BS
import System.Process (CreateProcess(..), waitForProcess, proc, createProcess, StdStream (..))
import GHC.IO.Handle (Handle, hClose)
import Control.Concurrent (MVar, newEmptyMVar, forkIO, putMVar, takeMVar)
import qualified Control.Exception as E
import System.Environment (lookupEnv)
import qualified Data.Text.Encoding as TE
import Control.Exception (try)
import Data.Text (Text)
import qualified Data.Text as DT

-- | A backtick command that could not produce a value.
--
-- For a @Configuration.Cfv.AST.Secret@ variable anything that could contain or reveal the secret is
-- withheld: the command text (which may embed it) and the details of the
-- command's output (see 'CommandProblem').
data CommandError = CommandError
  { CommandError -> Text
cmdCommand  :: Text    
  , CommandError -> CommandProblem
cmdProblem  :: CommandProblem
  } deriving (CommandError -> CommandError -> Bool
(CommandError -> CommandError -> Bool)
-> (CommandError -> CommandError -> Bool) -> Eq CommandError
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: CommandError -> CommandError -> Bool
== :: CommandError -> CommandError -> Bool
$c/= :: CommandError -> CommandError -> Bool
/= :: CommandError -> CommandError -> Bool
Eq, Int -> CommandError -> ShowS
[CommandError] -> ShowS
CommandError -> FilePath
(Int -> CommandError -> ShowS)
-> (CommandError -> FilePath)
-> ([CommandError] -> ShowS)
-> Show CommandError
forall a.
(Int -> a -> ShowS) -> (a -> FilePath) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> CommandError -> ShowS
showsPrec :: Int -> CommandError -> ShowS
$cshow :: CommandError -> FilePath
show :: CommandError -> FilePath
$cshowList :: [CommandError] -> ShowS
showList :: [CommandError] -> ShowS
Show)

-- | Errors produced by running a command on the shell.
data CommandProblem
  = NoShell
    -- ^ No shell configured and @SHELL@ is unset or empty.
  | ShellLaunchFailed FilePath E.IOException
    -- ^ The shell could not be started (not found, not executable, ...).
  | NonZeroExit Int Text
    -- ^ The command exited with this status (negative: killed by that signal)
    -- and this standard error output, trimmed. The output is 'Nothing' for a
    -- '@Configuration.Cfv.AST.Secret' variable.
  | OutputNotUtf8 UnicodeException
    -- ^ The command's standard output is not valid UTF-8. The exception names
    -- the offending byte, so it is 'Nothing' for a '@Configuration.Cfv.AST.Secret' variable.
  deriving (CommandProblem -> CommandProblem -> Bool
(CommandProblem -> CommandProblem -> Bool)
-> (CommandProblem -> CommandProblem -> Bool) -> Eq CommandProblem
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: CommandProblem -> CommandProblem -> Bool
== :: CommandProblem -> CommandProblem -> Bool
$c/= :: CommandProblem -> CommandProblem -> Bool
/= :: CommandProblem -> CommandProblem -> Bool
Eq, Int -> CommandProblem -> ShowS
[CommandProblem] -> ShowS
CommandProblem -> FilePath
(Int -> CommandProblem -> ShowS)
-> (CommandProblem -> FilePath)
-> ([CommandProblem] -> ShowS)
-> Show CommandProblem
forall a.
(Int -> a -> ShowS) -> (a -> FilePath) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> CommandProblem -> ShowS
showsPrec :: Int -> CommandProblem -> ShowS
$cshow :: CommandProblem -> FilePath
show :: CommandProblem -> FilePath
$cshowList :: [CommandProblem] -> ShowS
showList :: [CommandProblem] -> ShowS
Show)

-- | Shell configuration.
data ShellConfig = ShellConfig
  { ShellConfig -> Maybe FilePath
shellProgram :: Maybe FilePath
    -- ^ The shell to use. 'Nothing' means the @SHELL@ environment variable.
  , ShellConfig -> [FilePath]
shellFlags   :: [String]
    -- ^ Arguments placed before the command text, which is passed last.
  } deriving (ShellConfig -> ShellConfig -> Bool
(ShellConfig -> ShellConfig -> Bool)
-> (ShellConfig -> ShellConfig -> Bool) -> Eq ShellConfig
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: ShellConfig -> ShellConfig -> Bool
== :: ShellConfig -> ShellConfig -> Bool
$c/= :: ShellConfig -> ShellConfig -> Bool
/= :: ShellConfig -> ShellConfig -> Bool
Eq, Int -> ShellConfig -> ShowS
[ShellConfig] -> ShowS
ShellConfig -> FilePath
(Int -> ShellConfig -> ShowS)
-> (ShellConfig -> FilePath)
-> ([ShellConfig] -> ShowS)
-> Show ShellConfig
forall a.
(Int -> a -> ShowS) -> (a -> FilePath) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> ShellConfig -> ShowS
showsPrec :: Int -> ShellConfig -> ShowS
$cshow :: ShellConfig -> FilePath
show :: ShellConfig -> FilePath
$cshowList :: [ShellConfig] -> ShowS
showList :: [ShellConfig] -> ShowS
Show)

-- | Use @$SHELL@ as a login shell: @$SHELL -l -c cmd@. A login shell picks up
-- the user's profile (@PATH@ additions and so on). Add @"-i"@ to the flags if
-- you also need what the shell's interactive rc file sets up (aliases,
-- functions).
defaultShellConfig :: ShellConfig
defaultShellConfig :: ShellConfig
defaultShellConfig = ShellConfig {shellProgram :: Maybe FilePath
shellProgram = Maybe FilePath
forall a. Maybe a
Nothing, shellFlags :: [FilePath]
shellFlags = [FilePath
"-l", FilePath
"-c"]}

-- | Evaluate a shell command reading in its @System.IO.stdout@. 
evalValue :: ShellConfig -- ^ Shell configuration
          -> Text        -- ^ Command to execute
          -> IO (Either CommandError [Char])
evalValue :: ShellConfig -> Text -> IO (Either CommandError FilePath)
evalValue ShellConfig
shellCfg Text
cmd 
  = do let failWith :: CommandProblem -> Either CommandError b
failWith = CommandError -> Either CommandError b
forall a b. a -> Either a b
Left (CommandError -> Either CommandError b)
-> (CommandProblem -> CommandError)
-> CommandProblem
-> Either CommandError b
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> CommandProblem -> CommandError
CommandError Text
cmd
       Maybe FilePath
mShell <- ShellConfig -> IO (Maybe FilePath)
resolveShell ShellConfig
shellCfg
       case Maybe FilePath
mShell of
         Maybe FilePath
Nothing -> Either CommandError FilePath -> IO (Either CommandError FilePath)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (CommandProblem -> Either CommandError FilePath
forall {b}. CommandProblem -> Either CommandError b
failWith CommandProblem
NoShell)
         Just FilePath
shell -> do
          Either IOException (ExitCode, ByteString, ByteString)
result <- IO (ExitCode, ByteString, ByteString)
-> IO (Either IOException (ExitCode, ByteString, ByteString))
forall e a. Exception e => IO a -> IO (Either e a)
try (IO (ExitCode, ByteString, ByteString)
 -> IO (Either IOException (ExitCode, ByteString, ByteString)))
-> IO (ExitCode, ByteString, ByteString)
-> IO (Either IOException (ExitCode, ByteString, ByteString))
forall a b. (a -> b) -> a -> b
$ FilePath
-> [FilePath] -> FilePath -> IO (ExitCode, ByteString, ByteString)
execShell FilePath
shell (ShellConfig -> [FilePath]
shellFlags ShellConfig
shellCfg) (FilePath -> IO (ExitCode, ByteString, ByteString))
-> FilePath -> IO (ExitCode, ByteString, ByteString)
forall a b. (a -> b) -> a -> b
$ Text -> FilePath
DT.unpack Text
cmd
          Either CommandError FilePath -> IO (Either CommandError FilePath)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either CommandError FilePath -> IO (Either CommandError FilePath))
-> Either CommandError FilePath
-> IO (Either CommandError FilePath)
forall a b. (a -> b) -> a -> b
$ case Either IOException (ExitCode, ByteString, ByteString)
result of
                    Left IOException
e -> CommandProblem -> Either CommandError FilePath
forall {b}. CommandProblem -> Either CommandError b
failWith (FilePath -> IOException -> CommandProblem
ShellLaunchFailed FilePath
shell IOException
e)
                    Right (ExitFailure Int
n, ByteString
_, ByteString
err) ->
                      CommandProblem -> Either CommandError FilePath
forall {b}. CommandProblem -> Either CommandError b
failWith (CommandProblem -> Either CommandError FilePath)
-> (Text -> CommandProblem) -> Text -> Either CommandError FilePath
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> Text -> CommandProblem
NonZeroExit Int
n (Text -> CommandProblem)
-> (Text -> Text) -> Text -> CommandProblem
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Text
DT.strip (Text -> Either CommandError FilePath)
-> Text -> Either CommandError FilePath
forall a b. (a -> b) -> a -> b
$ OnDecodeError -> ByteString -> Text
TE.decodeUtf8With OnDecodeError
lenientDecode ByteString
err
                    Right (ExitCode
ExitSuccess, ByteString
out, ByteString
_) 
                      -> case ByteString -> Either UnicodeException Text
TE.decodeUtf8' ByteString
out of
                            Left UnicodeException
e  -> CommandProblem -> Either CommandError FilePath
forall {b}. CommandProblem -> Either CommandError b
failWith (UnicodeException -> CommandProblem
OutputNotUtf8 UnicodeException
e)
                            Right Text
t -> FilePath -> Either CommandError FilePath
forall a b. b -> Either a b
Right (Text -> FilePath
DT.unpack ((Char -> Bool) -> Text -> Text
DT.dropWhileEnd (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'\n') Text
t))

-- | Figure out the shell's path.
resolveShell :: ShellConfig -> IO (Maybe FilePath)
resolveShell :: ShellConfig -> IO (Maybe FilePath)
resolveShell ShellConfig
cfg = case ShellConfig -> Maybe FilePath
shellProgram ShellConfig
cfg of
  Just FilePath
p  -> Maybe FilePath -> IO (Maybe FilePath)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (FilePath -> Maybe FilePath
forall a. a -> Maybe a
Just FilePath
p)
  Maybe FilePath
Nothing -> do
    Maybe FilePath
v <- FilePath -> IO (Maybe FilePath)
lookupEnv FilePath
"SHELL"
    Maybe FilePath -> IO (Maybe FilePath)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Maybe FilePath -> IO (Maybe FilePath))
-> Maybe FilePath -> IO (Maybe FilePath)
forall a b. (a -> b) -> a -> b
$ case Maybe FilePath
v of
      Just FilePath
s | Bool -> Bool
not (FilePath -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null FilePath
s) -> FilePath -> Maybe FilePath
forall a. a -> Maybe a
Just FilePath
s
      Maybe FilePath
_                     -> Maybe FilePath
forall a. Maybe a
Nothing          

-- | Run @shell flags... cmd@ with stdin closed, collecting stdout and stderr as
-- raw bytes; to prevent deadlock we read both in concurrently.
execShell :: FilePath -> [String] -> String -> IO (ExitCode, BS.ByteString, BS.ByteString)
execShell :: FilePath
-> [FilePath] -> FilePath -> IO (ExitCode, ByteString, ByteString)
execShell FilePath
shell [FilePath]
flags FilePath
cmd = do
  (Maybe Handle
mIn, Maybe Handle
mOut, Maybe Handle
mErr, ProcessHandle
ph) <-
    CreateProcess
-> IO (Maybe Handle, Maybe Handle, Maybe Handle, ProcessHandle)
createProcess
      (FilePath -> [FilePath] -> CreateProcess
proc FilePath
shell ([FilePath]
flags [FilePath] -> [FilePath] -> [FilePath]
forall a. [a] -> [a] -> [a]
++ [FilePath
cmd]))
        { std_in = CreatePipe, std_out = CreatePipe, std_err = CreatePipe }
  case (Maybe Handle
mIn, Maybe Handle
mOut, Maybe Handle
mErr) of
    (Just Handle
hin, Just Handle
hout, Just Handle
herr) -> do
      Handle -> IO ()
hClose Handle
hin
      MVar ByteString
outV <- Handle -> IO (MVar ByteString)
readAll Handle
hout
      MVar ByteString
errV <- Handle -> IO (MVar ByteString)
readAll Handle
herr
      ExitCode
code <- ProcessHandle -> IO ExitCode
waitForProcess ProcessHandle
ph
      (,,) ExitCode
code (ByteString -> ByteString -> (ExitCode, ByteString, ByteString))
-> IO ByteString
-> IO (ByteString -> (ExitCode, ByteString, ByteString))
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> MVar ByteString -> IO ByteString
forall a. MVar a -> IO a
takeMVar MVar ByteString
outV IO (ByteString -> (ExitCode, ByteString, ByteString))
-> IO ByteString -> IO (ExitCode, ByteString, ByteString)
forall a b. IO (a -> b) -> IO a -> IO b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> MVar ByteString -> IO ByteString
forall a. MVar a -> IO a
takeMVar MVar ByteString
errV
    (Maybe Handle, Maybe Handle, Maybe Handle)
_ -> IOException -> IO (ExitCode, ByteString, ByteString)
forall e a. Exception e => e -> IO a
E.throwIO (FilePath -> IOException
userError FilePath
"could not create pipes for the shell process")

-- | Read a handle until there is no more output to consume.
readAll :: Handle -> IO (MVar BS.ByteString)
readAll :: Handle -> IO (MVar ByteString)
readAll Handle
h = do
  MVar ByteString
v <- IO (MVar ByteString)
forall a. IO (MVar a)
newEmptyMVar
  ThreadId
_ <- IO () -> IO ThreadId
forkIO (IO () -> IO ThreadId) -> IO () -> IO ThreadId
forall a b. (a -> b) -> a -> b
$ (Handle -> IO ByteString
BS.hGetContents Handle
h IO ByteString -> (IOException -> IO ByteString) -> IO ByteString
forall e a. Exception e => IO a -> (e -> IO a) -> IO a
`E.catch` IOException -> IO ByteString
ignoreIO) IO ByteString -> (ByteString -> IO ()) -> IO ()
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= MVar ByteString -> ByteString -> IO ()
forall a. MVar a -> a -> IO ()
putMVar MVar ByteString
v
  MVar ByteString -> IO (MVar ByteString)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure MVar ByteString
v
  where
    ignoreIO :: E.IOException -> IO BS.ByteString
    ignoreIO :: IOException -> IO ByteString
ignoreIO IOException
_ = ByteString -> IO ByteString
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ByteString
BS.empty

-- | Converts a command problem into a 'Text'.
describeProblem :: CommandProblem -> Text
describeProblem :: CommandProblem -> Text
describeProblem CommandProblem
NoShell =
  Text
"cannot run command: no shell configured and $SHELL is not set"
describeProblem (ShellLaunchFailed FilePath
sh IOException
e) =
  Text
"cannot start shell " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> FilePath -> Text
forall a. Show a => a -> Text
DT.show FilePath
sh Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
": " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> IOException -> Text
forall a. Show a => a -> Text
DT.show IOException
e
describeProblem (NonZeroExit Int
n Text
err) =
  Text
"command exited with status " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Int -> Text
forall a. Show a => a -> Text
DT.show Int
n Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> (if Text -> Bool
DT.null Text
err then Text
"" else Text
": " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
err)
describeProblem (OutputNotUtf8 UnicodeException
e) =
  Text
"command output is not valid UTF-8: " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> UnicodeException -> Text
forall a. Show a => a -> Text
DT.show UnicodeException
e