Skip to content

A peer-to-peer stack for code collaboration

8.9 KB
Raw Blame
{:module 'prelude/io
 :doc "Some basic I/O functions."
 :exports '[print! shell! process! read-line! read-file-value! read-file-values!
            shell-with-stdout! shell-no-stdin! write-file!
            process-with-stdout! process-with-stdout-stderr-exitcode!
            process-with-stdout-strict!
            init-file-dict! read-file-key! write-file-key! delete-file-key! ls! modify-file!
            install-fake-filesystem! prompt!
           ]}

(import prelude/patterns :unqualified)
(import prelude/strings :as 'strings)
(import prelude/dict :unqualified)
(import prelude/error-messages :as 'error)

(def read-line!
  "Read a single line of input and interpret it as radicle data."
  (fn [] (read-annotated "[read-line!]" (get-line!))))

(def read-file-value!
  "Read a single radicle value from a file."
  (fn [file]
    (read-annotated file (read-file! file))))

(def read-file-values!
  "Read many radicle values from a file."
  (fn [file]
    (read-many-annotated file (read-file! file))))

(def print!
  "Print a value to the console or stdout."
  (fn [x]
    (put-str! (show x))))

(def write-file!
  "Write `contents` to file `filename`."
  (fn [filename contents]
    (def hdl (open-file! filename :write))
    (write-handle! hdl contents)
    (close-handle! hdl)))

(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)
        []
        (cons 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!
Example: `(shell! \"ls -Glah\" \"\")`. "
  (fn [command to-write]
    (def cp
      { :cmdspec [:shell command]
        :stdin :create-pipe
        :stdout :inherit
        :stderr :inherit
      })
    (match (system! cp)
      {:stdin [:just 'stdin]
       :stdout :nothing
       :stderr :nothing
       :proc   'ph
      } (do (write-handle! stdin to-write)
            (close-handle! stdin)
            (wait-for-process! ph))
      _ (throw 'io-error "expected only stdin to be open"))))

(:test "shell!"
  [ (shell! "true" "") ==> :ok ]
  [ (shell! "false" "") ==> [:error 1] ]
)

(def shell-no-stdin!
  "Like `shell!`, but inherits stdin.
WARNING: using `shell!` with unsanitized user input is a security hazard!
Example: `(shell-no-stdin! \"ls -Glah\")`. "
  (fn [command to-write]
    (def cp
      { :cmdspec [:shell command]
        :stdin :inherit
        :stdout :inherit
        :stderr :inherit
      })
    (match (system! cp)
      {:stdin  :nothing
       :stdout :nothing
       :stderr :nothing
       :proc   'ph
      } (wait-for-process! ph)
      _ (throw 'io-error "expected no handles to be open"))))

(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))
            (close-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 inherited.
See `man exec` for more information on `execvp`. Returns `:ok` if the
process exited normally and `[:error n]` otherwise. Example: `(process!
\"ls\" [\"-Glah\"] \"\")`. "
  (fn [command args to-write]
    (def cp
      { :cmdspec [:raw command args]
        :stdin :create-pipe
        :stdout :inherit
        :stderr :inherit
      })
    (match (system! cp)
      {:stdin [:just 'stdin]
       :stdout :nothing
       :stderr :nothing
       :proc   'ph
      } (do (write-handle! stdin to-write)
            (close-handle! stdin)
            (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))
            (close-handle! stdout)
            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"] ]
)

(def process-with-stdout-stderr-exitcode!
  "Like `process-with-stdout!`, but returns a vec `[stdout stderr exitcode]`.
  `exitcode` is either `:ok` or `[:error n]` where `n` is a number."
  (fn [command args to-write]
    (def cp
      { :cmdspec [:raw command args]
        :stdin   :create-pipe
        :stdout  :create-pipe
        :stderr  :create-pipe
      })
    (match (system! cp)
      {:stdin  [:just 'stdin]
       :stdout [:just 'stdout]
       :stderr [:just 'stderr]
       :proc   'ph
      } (do (write-handle! stdin to-write)
            (close-handle! stdin)
            (def out [(read-contents-handle! stdout) (read-contents-handle! stderr) (wait-for-process! ph)])
            (close-handle! stdout)
            (close-handle! stderr)
            out)
      _ (throw 'io-error "expected only stdin, stdout and stderr to be open"))))

(:test "process-with-stdout-stderr-exitcode!"
  [ (process-with-stdout-stderr-exitcode! "echo" ["hi"] "") ==> [["hi"] [] :ok] ]
  [ (process-with-stdout-stderr-exitcode! "false" [] "") ==> [[] [] [:error 1]] ]
)

(def process-with-stdout-strict!
  "Like `process-with-stdout!`, but prints an error message and exits if the command fails."
  (fn [command args to-write]
    (match (process-with-stdout-stderr-exitcode! command args to-write)
      ['stdout _ :ok] stdout
      ['stdout 'stderr [:error 'exit-code]]
        (do
          (put-str! (error/process-exit-error command args exit-code stderr))
          (exit! 1))
      )))

(:test "process-with-stdout-strict!"
  [ (process-with-stdout-strict! "echo" ["hi"] "") ==> ["hi"] ]
)

;; 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" "")))

(def modify-file!
  "Modified the value stored in a file according to the function `f`."
  (fn [file f]
    (write-file! file (show (f (read-file-value! file))))))

(def init-file-dict!
  "Initiate a file with an empty dict, but only if the file doesn't already
  exist."
  (fn [file]
    (catch 'any
        (read-file! file)
        (fn [_] (write-file! file "{}")))))

(def write-file-key!
  "Write a key to a file. Assumes that the file contents is a serialised dict."
  (fn [file k v]
    (modify-file! file
                  (fn [s] (insert k v s)))))

(def delete-file-key!
  "Delete a key from a file. Assumes that the file contents is a serialised dict."
  (fn [file k]
    (modify-file! file
                  (fn [s] (delete k s)))))

(def read-file-key!
  "Read a file key. Assumes that the file contents is a serialised dict."
  (fn [file k]
    (lookup-maybe k (read-file-value! file))))

(def prompt!
  "Ask for user input with a prompt."
  (fn [prompt]
    (write-handle! (stderr!) prompt)
    (read-line-handle! (stdin!))))

(def install-fake-filesystem!
  "Installs a fake for `read-file!` that simulates the presence of
  files in the `files` dictionary.

  If `(read-file! path) is called and `path` is a key in `files` then
  the value from `files` is returned. Otherwise the original
  `read-file!` is used.

  This requires the `prelude/test/primitive-stub` script to be loaded."
  (fn [files]
    (def original-read-file! (read-ref primitive-stub-ref/read-file!))
    (def read-file
      (fn [path]
        (if (member? path files)
          (lookup path files)
          (original-read-file! path))
        ))
    (write-ref primitive-stub-ref/read-file! read-file)
    (def original-find-module-file! (read-ref primitive-stub-ref/find-module-file!))
    (def find-module-file
      (fn [path]
        (if (member? path files)
          path
          (original-find-module-file! path))
        ))
    (write-ref primitive-stub-ref/find-module-file! find-module-file)
    ))