aboutsummaryrefslogtreecommitdiffstats
path: root/app/Process.hs
blob: 2b3eaf61088e7384d3a9f913c8b24ec7ea0cfddc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
{-# LANGUAGE ImpredicativeTypes #-}
{-# LANGUAGE QuantifiedConstraints #-}

module Process
  ( sh,
    sh_,
    ProcessType,
    Quotable (..),
    proc,
    textInput,
  )
where

import Control.Exception (throwIO)
import Data.ByteString.Lazy.Char8 qualified as LB
import Data.List (intercalate)
import Data.String (fromString)
import Data.Text qualified as T
import Data.Text.Lazy qualified as LT
import Data.Text.Lazy.Encoding qualified as LT
import Exception qualified as E
import System.Exit (ExitCode (ExitSuccess))
import System.Process.Typed (ProcessConfig, StreamSpec, StreamType (STInput), byteStringInput, readProcess, readProcessStderr)

sh :: ProcessConfig stdin stdoutIgnored stderr -> IO LB.ByteString
sh processConfig = do
  (exitCode, out, err) <- readProcess processConfig
  if exitCode == ExitSuccess
    then pure out
    else throwIO $ E.ProcessException (show processConfig) exitCode err

sh_ :: ProcessConfig stdin stdoutIgnored stderr -> IO ()
sh_ processConfig = do
  (exitCode, err) <- readProcessStderr processConfig
  if exitCode == ExitSuccess
    then pure ()
    else throwIO $ E.ProcessException (show processConfig) exitCode err

class Quotable a where
  quote :: a -> String

instance {-# OVERLAPPING #-} Quotable String where
  quote s = "'" ++ escape s ++ "'"
    where
      escape [] = []
      escape ('\'' : cs) = '\'' : '\\' : '\'' : '\'' : escape cs
      escape (c : cs) = c : escape cs

instance Quotable T.Text where
  quote = quote . T.unpack

instance Quotable Int where
  quote = show

instance {-# OVERLAPPABLE #-} Quotable a => Quotable [a] where
  quote = intercalate " " . map quote

class ProcessType r where
  spr :: String -> [String] -> r

instance (Quotable a, ProcessType r) => ProcessType (a -> r) where
  spr fmt as = \a -> spr fmt (quote a : as)

instance (() ~ stdin, () ~ stdoutIgnored, () ~ stderr) => ProcessType (ProcessConfig stdin stdoutIgnored stderr) where
  spr fmt args = fromString (interp (reverse args) fmt)

interp :: [String] -> String -> String
interp (_ : _) "" = error "sh: extra arguments"
interp [] "" = ""
interp as ('%' : '%' : cs) = '%' : interp as cs
interp [] ('%' : _) = error "sh: insufficient arguments"
interp (a : as) ('%' : cs) = a ++ interp as cs
interp as (c : cs) = c : interp as cs

proc :: ProcessType r => String -> r
proc fmt = spr fmt []

textInput :: LT.Text -> StreamSpec 'STInput ()
textInput = byteStringInput . LT.encodeUtf8