A peer-to-peer stack for code collaboration
More IO (#290)
Julian Arni5d50671bc589
diff --git a/docs/source/reference.rst b/docs/source/reference.rstindex 0cfc545..7c6e82f 100644--- a/docs/source/reference.rst+++ b/docs/source/reference.rst@@ -463,7 +463,13 @@ Reads the contents of a file and returns it as a string.``read-line-handle!``~~~~~~~~~~~~~~~~~~~~~-Read a single line from a handle.+Read a single line from a handle. Returns the string read, or the+keyword ``:eof`` if an EOF is encountered.++``close-handle!``+~~~~~~~~~~~~~~~~~++Close a handle``now!``~~~~~~~~@@ -669,8 +675,8 @@ user input is a security hazard! Example: ``(shell! "ls -Glah" "")``.~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Executes ``command`` using 'execvp'. with 'to-write' as input. Stdout-and stderr are inherit. See 'man exec' for more information on 'execvp'.-Example: ``(process! "ls" ["-Glah"] "")``.+and stderr are inherited. See 'man exec' for more information on+'execvp'. Example: ``(process! "ls" ["-Glah"] "")``.``(read-line!)``~~~~~~~~~~~~~~~~@@ -687,6 +693,16 @@ Send code from a file to a remote chain.Read code (as data) from a file. Returns a vector of expressions+``(shell-with-stdout! command to-write)``+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~++Like ``shell!``, but captures the stdout and returns it.++``(process-with-stdout! command args to-write)``+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~++Like ``process!``, but captures stdout.+``prelude/bool``----------------diff --git a/nix/shell.nix b/nix/shell.nixindex 1fec8c4..af57f22 100644--- a/nix/shell.nix+++ b/nix/shell.nix@@ -19,16 +19,18 @@ stdenv.mkDerivation {libraryPkgconfigDepends = [ zlib ];shellHook = ''export PATH=$PATH:`stack path --local-bin`+ export STACK_ARGS="--system-ghc --nix-packages 'zlib fzf moreutils'"+ export IS_NIX_SHELL="true"eval $(grep export ${ghc}/bin/ghc)alias check="pushd $PWD && ./scripts/check-fmt.sh && hlint . && popd"alias mkdocs="pushd $PWD/docs && make html && popd"- alias sb="stack build --fast --system-ghc --nix-packages zlib"- alias sbs="stack build --fast --system-ghc --nix-packages zlib radicle:exe:radicle-server"- alias sbrad="stack build --fast --system-ghc --nix-packages zlib radicle:exe:radicle"- alias st="stack test --fast --system-ghc --nix-packages zlib"- alias sts="stack test --fast --system-ghc --nix-packages zlib radicle:spec"- alias str="stack test --fast --system-ghc --nix-packages zlib radicle:spec --ta '--pattern \"Radicle source file tests\"'"- alias server="stack exec radicle-server -- "- alias rad="stack exec radicle -- rad/repl.rad"+ alias sb="stack build --fast $STACK_ARGS"+ alias sbs="stack build --fast $STACK_ARGS radicle:exe:radicle-server"+ alias sbrad="stack build --fast $STACK_ARGS radicle:exe:radicle"+ alias st="stack test --fast $STACK_ARGS"+ alias sts="stack test --fast $STACK_ARGS radicle:spec"+ alias str="stack test --fast $STACK_ARGS radicle:spec --ta '--pattern \"Radicle source file tests\"'"+ alias server="stack exec $STACK_ARGS radicle-server -- "+ alias rad="stack exec --silent $STACK_ARGS radicle -- rad/repl.rad"'';}diff --git a/package.yaml b/package.yamlindex 452936f..9e19db6 100644--- a/package.yaml+++ b/package.yaml@@ -77,8 +77,6 @@ tests:source-dirs:- test/docsghc-options: -threaded- other-modules:- - Paths_radicledependencies:- doctest- Globdiff --git a/rad/monadic/issues.rad b/rad/monadic/issues.radindex 5bc6f2d..962dcdd 100644--- a/rad/monadic/issues.rad+++ b/rad/monadic/issues.rad@@ -13,7 +13,7 @@"monadic/radicle/issues")(def issues-chain- (ref (chain/load-chain! "http://radicle.xyz/chains/radicle-issues")))+ (ref (chain/load-chain! "http://localhost:8000/chains/radicle-issues")))(def create-issues-chain!"Create a remote issue chain with the given url."diff --git a/rad/prelude/io-utils.rad b/rad/prelude/io-utils.radindex cc508ba..abad727 100644--- a/rad/prelude/io-utils.rad+++ b/rad/prelude/io-utils.rad@@ -1,6 +1,14 @@+{:module 'prelude/io-utils+ :doc "IO-related utilities"+ :exports '[fzf-select-by-key!]}++(import prelude/io '[shell-with-stdout!] :unqualified)+(import prelude/strings '[unlines] :unqualified)+(def fzf-select-by-key!- "Select from keys in `dict` with `fzf`, returning the corresponding values"+ "Select from keys in `dict` with `fzf`, returning the corresponding values.+ The keys of the dict must be strings.+ Requires that `fzf` be on the path."(fn [dict]- (def result (process! "/usr/bin/env" ["fzf"] (lines (keys dict))))- ;; TODO: pattern match on exit code when pattern matching is merged- (lookup (string-replace "\n" "" (nth 1 result)) dict)))+ (def result (process-with-stdout! "fzf" [] (string-append (unlines (keys dict)) "\n")))+ (lookup (string-replace "\n" "" (nth 0 result)) dict)))diff --git a/rad/prelude/io.rad b/rad/prelude/io.radindex ce13355..949fbf2 100644--- a/rad/prelude/io.rad+++ b/rad/prelude/io.rad@@ -1,6 +1,10 @@{:module 'prelude/io:doc "Some basic I/O functions."- :exports '[print! shell! process! read-line! send-code! read-code!]}+ :exports '[print! shell! process! read-line! send-code! read-code!+ shell-with-stdout! process-with-stdout!+ ]}++(import prelude/patterns :unqualified);; read-line(def read-line!@@ -22,6 +26,15 @@(fn [x](put-str! (show x))))+(def-rec read-contents-handle!+ "Read all the contents of a handle. A *vector* of strings is returned, one+ string for each line of output."+ (fn [hdl]+ (def this-line (read-line-handle! hdl))+ (if (eq? this-line :eof)+ []+ (add-left this-line (read-contents-handle! hdl)))))+(def shell!"Executes `command` using the shell with `to-write` as input. Stdout and stderr are inherited.WARNING: using `shell!` with unsanitized user input is a security hazard!@@ -42,8 +55,40 @@ Example: `(shell! \"ls -Glah\" \"\")`. "(wait-for-process! ph))_ (throw 'io-error "expected only stdin to be open"))))+(:test "shell!"+ [ (shell! "true" "") ==> :ok ]+ [ (shell! "false" "") ==> [:error 1] ]+)+++(def shell-with-stdout!+ "Like `shell!`, but captures the stdout and returns it."+ (fn [command to-write]+ (def cp+ { :cmdspec [:shell command]+ :stdin :create-pipe+ :stdout :create-pipe+ :stderr :inherit+ })+ (match (system! cp)+ {:stdin [:just 'stdin]+ :stdout [:just 'stdout]+ :stderr :nothing+ :proc 'ph+ } (do (write-handle! stdin to-write)+ (close-handle! stdin)+ (def out (read-contents-handle! stdout))+ out)+ _ (throw 'io-error "expected only stdin and stdout to be open"))))++(:test "shell-with-stdout!"+ [ (shell-with-stdout! "echo hi" "") ==> ["hi"] ]+ [ (shell-with-stdout! "cat" "there") ==> ["there"] ]+)++(def process!- "Executes `command` using 'execvp'. with 'to-write' as input. Stdout and stderr are inherit.+ "Executes `command` using 'execvp'. with 'to-write' as input. Stdout and stderr are inherited.See 'man exec' for more information on 'execvp'.Example: `(process! \"ls\" [\"-Glah\"] \"\")`. "(fn [command args to-write]@@ -61,3 +106,41 @@ Example: `(process! \"ls\" [\"-Glah\"] \"\")`. "} (do (write-handle! stdin to-write)(wait-for-process! ph))_ (throw 'io-error "expected only stdin to be open"))))++(:test "process!"+ [ (process! "true" [] "") ==> :ok ]+ [ (process! "false" [] "") ==> [:error 1] ]+)++(def process-with-stdout!+ "Like `process!`, but captures stdout."+ (fn [command args to-write]+ (def cp+ { :cmdspec [:raw command args]+ :stdin :create-pipe+ :stdout :create-pipe+ :stderr :inherit+ })+ (match (system! cp)+ {:stdin [:just 'stdin]+ :stdout [:just 'stdout]+ :stderr :nothing+ :proc 'ph+ } (do (write-handle! stdin to-write)+ (close-handle! stdin)+ (def out (read-contents-handle! stdout))+ (print! out)+ out)+ _ (throw 'io-error "expected only stdin and stdout to be open"))))++(:test "process-with-stdout!"+ [ (process-with-stdout! "echo" ["hi"] "") ==> ["hi"] ]+ [ (process-with-stdout! "cat" [] "there") ==> ["there"] ]+)++;; General utilities+(def ls!+ "List the contents of the current working directory"+ (fn []+ ;; Some systems support the -1 option, but this is more portable+ (shell-with-stdout! "ls -a | cat" "")))diff --git a/reference-doc.yaml b/reference-doc.yamlindex 6fd8de0..95320c3 100644--- a/reference-doc.yaml+++ b/reference-doc.yaml@@ -105,6 +105,7 @@ primFns:- load!- read-file!- read-line-handle!+- close-handle!- now!- system!- wait-for-process!diff --git a/src/Radicle/Internal/Core.hs b/src/Radicle/Internal/Core.hsindex 53a6421..0664eb5 100644--- a/src/Radicle/Internal/Core.hs+++ b/src/Radicle/Internal/Core.hs@@ -514,7 +514,8 @@ envToRadicle = Dict . Map.mapKeys Atom . Map.map toRad . fromEnv-- | The environment in which expressions are evaluated.newtype LangT r m a = LangT{ fromLangT :: ExceptT (LangError Value) (StateT r m) a }- deriving (Functor, Applicative, Monad, MonadError (LangError Value), MonadIO, MonadState r)+ deriving (Functor, Applicative, Monad, MonadError (LangError Value)+ , MonadIO, MonadState r)mapError :: (Functor m) => (LangError Value -> LangError Value) -> LangT r m a -> LangT r m amapError f = LangT . withExceptT f . fromLangT@@ -810,8 +811,10 @@ instance CPA t => FromRad t CmdSpec wherefromRad x = case x ofVec (Keyword (Ident "shell") Seq.:<| arg Seq.:<| Seq.Empty) ->ShellCommand <$> fromRad arg- Vec (Keyword (Ident "raw") Seq.:<| comm Seq.:<| args Seq.:<| Seq.Empty) ->- RawCommand <$> fromRad comm <*> fromRad args+ Vec (Keyword (Ident "raw") Seq.:<| comm Seq.:<| Vec args Seq.:<| Seq.Empty) -> do+ args' <- traverse fromRad $ toList args+ comm' <- fromRad comm+ pure $ RawCommand comm' args'Vec (Keyword (Ident s) Seq.:<| _) ->throwError $ "Expecting either :raw or :shell, got: " <> s_ ->diff --git a/src/Radicle/Internal/Effects.hs b/src/Radicle/Internal/Effects.hsindex e3cd6eb..3540423 100644--- a/src/Radicle/Internal/Effects.hs+++ b/src/Radicle/Internal/Effects.hs@@ -253,11 +253,14 @@ replPrimFns = fromList $ allDocs $(v, _) -> throwErrorHere $ TypeError "write-handle!" 0 THandle v), ( "read-line-handle!"- , "Read a single line from a handle."+ , "Read a single line from a handle. Returns the string read, or the\+ \ keyword `:eof` if an EOF is encountered.", oneArg "read-line-handle!" $ \caseHandle h -> doh' <- lookupHandle h- String <$> hGetLineS h'+ hGetLineS h' >>= \case+ Nothing -> pure . Keyword $ Ident "eof"+ Just v -> pure $ String vv -> throwErrorHere $ TypeError "read-line-handle!" 0 THandle v), ( "wait-for-process!"@@ -268,6 +271,14 @@ replPrimFns = fromList $ allDocs $toRad <$> waitForProcessS h'v -> throwErrorHere $ TypeError "wait-for-process!" 0 TProcHandle v)+ , ( "close-handle!"+ , "Close a handle"+ , oneArg "close-handle!" $ \case+ Handle h -> do+ h' <- lookupHandle h+ toRad <$> hCloseS h'+ v -> throwErrorHere $ TypeError "wait-for-process!" 0 TProcHandle v+ ), ( "exit!", "Exit the interpreter immediately.", \casediff --git a/src/Radicle/Internal/Effects/Capabilities.hs b/src/Radicle/Internal/Effects/Capabilities.hsindex 4b9c2e6..9e479d8 100644--- a/src/Radicle/Internal/Effects/Capabilities.hs+++ b/src/Radicle/Internal/Effects/Capabilities.hs@@ -12,7 +12,15 @@ import Data.Timeimport System.Console.ANSI (hSupportsANSI)import System.Console.Haskeline hiding (catch)import System.Exit (ExitCode)-import System.IO (hGetLine, isEOF)+import System.IO+ ( BufferMode(LineBuffering)+ , hClose+ , hFlush+ , hGetLine+ , hIsEOF+ , hSetBuffering+ , isEOF+ )import System.Process(CreateProcess, ProcessHandle, createProcess, waitForProcess)#ifdef ghcjs_HOST_OS@@ -57,23 +65,34 @@ class (Monad m) => System m where-> m (Maybe Handle, Maybe Handle, Maybe Handle, ProcessHandle)waitForProcessS :: ProcessHandle -> m ExitCodehPutStrS :: Handle -> Text -> m ()- hGetLineS :: Handle -> m Text+ -- | hGetLine should return Nothing on EOF.+ hGetLineS :: Handle -> m (Maybe Text)+ hCloseS :: Handle -> m ()instance System m => System (Lang m) wheresystemS proc = lift $ systemS procwaitForProcessS = lift . waitForProcessShPutStrS a b = lift $ hPutStrS a bhGetLineS = lift . hGetLineS+ hCloseS = lift . hCloseSinstance System IO wheresystemS = createProcesswaitForProcessS = waitForProcess- hPutStrS = hPutStr- hGetLineS x = toS <$> hGetLine x+ hPutStrS h t = hSetBuffering h LineBuffering >> hPutStr h t >> hFlush h+ hGetLineS h = do+ eof <- hIsEOF h+ if eof+ then pure Nothing+ else do+ hSetBuffering h LineBuffering+ Just . toS <$> hGetLine h+ hCloseS = hCloseinstance System m => System (InputT m) wheresystemS proc = lift $ systemS procwaitForProcessS = lift . waitForProcessShPutStrS a b = lift $ hPutStrS a bhGetLineS = lift . hGetLineS+ hCloseS = lift . hCloseSclass (Monad m) => Exit m whereexitS :: m ()diff --git a/test/spec/Radicle/Internal/TestCapabilities.hs b/test/spec/Radicle/Internal/TestCapabilities.hsindex 7c1f417..58444a1 100644--- a/test/spec/Radicle/Internal/TestCapabilities.hs+++ b/test/spec/Radicle/Internal/TestCapabilities.hs@@ -179,3 +179,4 @@ instance System (StateT WorldState IO) wherewaitForProcessS = lift . waitForProcessShPutStrS a b = lift $ hPutStrS a bhGetLineS = lift . hGetLineS+ hCloseS = lift . hCloseSdiff --git a/utils/list-issues b/utils/list-issuesindex f9a79fd..27e95b4 100755--- a/utils/list-issues+++ b/utils/list-issues@@ -2,13 +2,15 @@FILE="$(mktemp)"cat << SRC > $FILE+(load! "rad/prelude.rad")+(load! "rad/prelude/io-utils.rad")(load! "rad/monadic/issues.rad")(def mk-key (fn [v](def key (nth 0 v))(def val (nth 1 v))[(string-append (show key) " - " (lookup :title val)) val]))-(def iss (dict-from-list (map mk-key (seq (list-issues)))))+(def iss (dict-from-seq (map mk-key (seq (list-issues)))))(def selected (fzf-select-by-key! iss))(def pretty-comment (fn [c](string-append@@ -21,9 +23,13 @@ cat << SRC > $FILE"\nDescription: " (lookup :body i)"\nState: " (if (eq? (lookup :state i) :open) "open" "closed")"\nLabels: " (show (lookup :labels i))- "\nComments:\n\n\n" (lines (map pretty-comment (lookup :comments i)))+ "\nComments:\n\n\n" (unlines (map pretty-comment (lookup :comments i))))))(put-str! (pretty-issue selected))SRC-radicle -- $FILE | less+if [ "$IS_NIX_SHELL" = "true" ]; then+ stack exec --silent radicle --nix-packages fzf -- $FILE+else+ stack exec --silent radicle -- $FILE+fi