module Text.Pandoc.Filter.Scripting (
runTempPythonScript
, addPlotCapture
, hasBlockingShowCall
, PythonScript
, ScriptResult(..)
) where
import System.Directory (getCurrentDirectory)
import System.Exit (ExitCode(..))
import System.FilePath ((</>), isAbsolute)
import System.IO.Temp (getCanonicalTemporaryDirectory)
import System.Process.Typed (runProcess, shell)
import Data.Monoid (Any(..))
type PythonScript = String
data ScriptResult = ScriptSuccess
| ScriptFailure Int
runTempPythonScript :: PythonScript
-> IO ScriptResult
runTempPythonScript script = do
scriptPath <- (</> "pandoc-pyplot.py") <$> getCanonicalTemporaryDirectory
writeFile scriptPath script
ec <- runProcess $ shell $ "python " <> (show scriptPath)
case ec of
ExitSuccess -> return ScriptSuccess
ExitFailure code -> return $ ScriptFailure code
addPlotCapture :: FilePath
-> PythonScript
-> IO PythonScript
addPlotCapture fname content = do
absFname <- if isAbsolute fname
then (return fname)
else (</> fname) <$> getCurrentDirectory
return $ mconcat [ content
, "\nimport matplotlib.pyplot as plt"
, "\nplt.savefig(" <> show absFname <> ")\n\n"
]
hasBlockingShowCall :: PythonScript -> Bool
hasBlockingShowCall script = anyOf
[ "plt.show()" `elem` scriptLines
, "matplotlib.pyplot.show()" `elem` scriptLines
]
where
scriptLines = lines script
anyOf xs = getAny $ mconcat $ Any <$> xs