diff --git a/libs/base/System.idr b/libs/base/System.idr index 3ee58c77a..625432d4c 100644 --- a/libs/base/System.idr +++ b/libs/base/System.idr @@ -5,7 +5,7 @@ import Data.List import Data.String import public System.Escape -import System.File.Process +import System.File %default total @@ -153,6 +153,24 @@ namespace Escaped system : HasIO io => List String -> io Int system = system . escapeCmd +||| Run a shell command, returning its stdout, and exit code. +export +covering +run : HasIO io => (cmd : String) -> io (String, Int) +run cmd = do + Right f <- popen cmd Read + | Left err => pure ("", 1) + Right resp <- fRead f + | Left err => pure ("", 1) + exitCode <- pclose f + pure (resp, exitCode) + +namespace Escaped + export + covering + run : HasIO io => (cmd : List String) -> io (String, Int) + run = run . escapeCmd + %foreign support "idris2_time" "javascript:lambda:() => Math.floor(new Date().getTime() / 1000)" prim__time : PrimIO Int diff --git a/tests/base/system_run/Run.idr b/tests/base/system_run/Run.idr new file mode 100644 index 000000000..f74b3b118 --- /dev/null +++ b/tests/base/system_run/Run.idr @@ -0,0 +1,19 @@ +import Data.String + +import System +import System.Info + +main : IO () +main = do + (contents, 0) <- run $ "echo " ++ escapeArg "Hello, world" + | (_, err) => printLn err + printLn $ trim contents + + let cmd : List String = if not isWindows + then ["printf", "Hello, %s", "$PATH"] + else ["echo", "Hello, $PATH"] + (contents, 0) <- run cmd + | (_, err) => printLn err + printLn $ trim contents + + printLn !(run ["exit", "17"]) diff --git a/tests/base/system_run/expected b/tests/base/system_run/expected new file mode 100644 index 000000000..96a4fbd9a --- /dev/null +++ b/tests/base/system_run/expected @@ -0,0 +1,5 @@ +1/1: Building Run (Run.idr) +Main> "Hello, world" +"Hello, $PATH" +("", 17) +Main> Bye for now! diff --git a/tests/base/system_run/input b/tests/base/system_run/input new file mode 100644 index 000000000..fc5992c29 --- /dev/null +++ b/tests/base/system_run/input @@ -0,0 +1,2 @@ +:exec main +:q diff --git a/tests/base/system_run/run b/tests/base/system_run/run new file mode 100644 index 000000000..b79096cc4 --- /dev/null +++ b/tests/base/system_run/run @@ -0,0 +1,3 @@ +rm -rf build + +$1 --no-color --console-width 0 --no-banner Run.idr < input