Created
November 27, 2018 23:03
-
-
Save quasi-coherent/6f3ceaa4f77f3dcd0896acc6e2735cd7 to your computer and use it in GitHub Desktop.
Stream to port example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env stack | |
-- stack --resolver lts-12.7 script | |
import Conduit hiding (connect) | |
import qualified Data.Conduit.Binary as CB | |
import qualified Data.Conduit.Network as CN | |
import qualified Data.Conduit.Process as CP | |
import qualified Data.Text as T | |
import Network.Socket | |
import System.Directory | |
import System.Environment | |
import System.Exit | |
main :: IO () | |
main = do | |
let cmd = "" | |
code <- teeSock 8989 cmd "test.log" | |
putStrLn . show $ code | |
teeSock :: Int -- ^ Port to bind to on localhost. | |
-> String | |
-> FilePath | |
-> IO ExitCode | |
teeSock port cmd logFile = do | |
(sock, addr) <- getSocket "127.0.0.1" (show port) | |
connect sock $ addrAddress addr | |
(CP.Inherited, out, CP.ClosedStream, sph) <- execShellCommand cmd | |
runConduitRes $ out .| CN.sinkSocket sock | |
-- --.| CB.conduitFile logFile | |
-- --.| stdoutC | |
CP.waitForStreamingProcess sph | |
execShellCommand | |
:: (CP.InputSource stdin, CP.OutputSink stdout, CP.OutputSink stderr) | |
=> String | |
-> IO (stdin, stdout, stderr, CP.StreamingProcessHandle) | |
execShellCommand cmd = do | |
sourceProfile <- sourceProfileIfExists | |
env' <- getEnvironment | |
CP.streamingProcess (CP.shell $ sourceProfile ++ cmd ++ " 2>&1") {CP.env = Just env'} | |
sourceProfileIfExists :: IO String | |
sourceProfileIfExists = getEnv "HOME" >>= \root -> | |
doesFileExist (root ++ "/.profile") >>= \exists -> return $ | |
if exists then "source ~/.profile; " else "" | |
getSocket :: String -> String -> IO (Socket, AddrInfo) | |
getSocket host port = do | |
addr:_ <- getAddrInfo Nothing (Just host) (Just port) | |
sock <- socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr) | |
return (sock, addr) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment