{-# LANGUAGE OverloadedStrings #-}
module Text.Pandoc.Filter.Pyplot.Scripting
( runTempPythonScript
, hasBlockingShowCall
) where
import Data.Hashable (hash)
import Data.Monoid (Any(..))
import qualified Data.Text as T
import qualified Data.Text.IO as T
import System.Exit (ExitCode (..))
import System.FilePath ((</>))
import System.IO.Temp (getCanonicalTemporaryDirectory)
import System.Process.Typed (runProcess, shell)
import Text.Pandoc.Filter.Pyplot.Types
runTempPythonScript :: String
-> PythonScript
-> IO ScriptResult
runTempPythonScript interpreter' script' = do
scriptPath <- (</> hashedPath) <$> getCanonicalTemporaryDirectory
T.writeFile scriptPath script'
ec <- runProcess $ shell $ mconcat [interpreter', " ", show scriptPath]
case ec of
ExitSuccess -> return ScriptSuccess
ExitFailure code -> return $ ScriptFailure code
where
hashedPath = show . hash $ script'
hasBlockingShowCall :: PythonScript -> Bool
hasBlockingShowCall script' =
anyOf
[ "plt.show()" `elem` scriptLines
, "pyplot.show()" `elem` scriptLines
, "matplotlib.pyplot.show()" `elem` scriptLines
]
where
scriptLines = T.lines script'
anyOf xs = getAny $ mconcat $ Any <$> xs