Skip to content

A peer-to-peer stack for code collaboration

Project RSM and app (#389)

Julian Arniba9eff49e7bf
diff --git a/bin/rad-diff b/bin/rad-diff
index 9fa852f..fab98d0 100755
--- a/bin/rad-diff
+++ b/bin/rad-diff
@@ -1,27 +1,18 @@
#!/usr/bin/env radicle
;; TODO:
-;; - don't use make-chain-ref when we don't need loading
+;; - don't use chain/make-chain-ref! when we don't need loading
;; - handle parsing numbers in cmd-parsing/validation logic
(load! (find-module-file! "prelude.rad"))
(load! (find-module-file! "monadic/diff.rad"))
(load! (find-module-file! "prelude/io-utils.rad"))
+(load! (find-module-file! "monadic/project.rad"))
(load! (find-module-file! "prelude/cmd-parsing.rad"))
(import prelude/validation :as 'validation)
-(def base-name "http://localhost:8000/chains/")
-
-(def make-name
- (fn [chain]
- (if (eq? (take 7 chain) "http://")
- chain
- (string-append base-name chain))))
-
-(def make-chain-ref
- (fn [chain]
- (ref (chain/load-chain! (make-name chain)))))
+(def chain-name (fn [] (get-rsm-of-type! :rad-diff)))
(def valid-list-options
["--new" "--pending" "--retracted" "--accepted" "--rejected" "--fancy"])
@@ -34,11 +25,11 @@
"rad-diff - Radicle Diff CLI
Usage:
- rad-diff list <chain-name>" list-opts-help "
+ rad-diff list " list-opts-help "
rad-diff create-chain <chain-name>
- rad-diff propose <commit> <chain-name>
- rad-diff [retract|accept|reject|show] <diff-no> <chain-name>
- rad-diff comment <diff-no> <comment> <chain-name>
+ rad-diff propose <commit>
+ rad-diff [retract|accept|reject|show] <diff-no>
+ rad-diff comment <diff-no> <comment>
rad-diff done
rad-diff help
@@ -52,9 +43,7 @@
reject - Reject a diff
create-chain - Create a new diffs chain
help - Print this help and exit
-
- If <chain-name> begins with 'http://', that URL will be used. Otherwise,
- " base-name " will be prepended to <chain-name>." ))
+ "))
(def cmd-parse-failure
(fn [error]
@@ -122,7 +111,7 @@
(def checkout-diff!
"Creates a new branch diff/<DIFF-ID> based on the DIFF, and switches to it."
(fn [chain diff-no]
- (def chain-ref (make-chain-ref chain))
+ (def chain-ref (chain/make-chain-ref! chain))
(def diff (verify-diff-number diff-no chain-ref))
(match (process! "git" ["checkout" "-b" (string-append "diff/" (show diff-no))] "")
:ok (apply-patch! (lookup :patch diff))
@@ -157,7 +146,7 @@
:author-name author-name
:author-email author-email
:patch patch})
- (simple-create-diff! (make-chain-ref chain) diff)
+ (simple-create-diff! (chain/make-chain-ref! chain) diff)
(put-str! (string-append "Proposing " short-hash " to " chain))))
;; showing diffs
@@ -213,7 +202,7 @@
option only recent items are shown. If `--fancy is passed, the list is opened
via fzf."
(fn [chain options]
- (def chain-ref (make-chain-ref chain))
+ (def chain-ref (chain/make-chain-ref! chain))
(def mk-key
(fn [v]
@@ -271,7 +260,7 @@
(fn [chain-name n]
(if (number? n)
(if (integral? n)
- (do (def chain-ref (make-chain-ref chain-name))
+ (do (def chain-ref (chain/make-chain-ref! chain-name))
(def diff (verify-diff-number n chain-ref))
(put-str! (pretty-diff diff)))
(cmd-parse-failure "Diff numbers must be whole numbers!"))
@@ -280,7 +269,7 @@
(def new-diff-chain!
"Create a new DIFF chain with the given URL"
(fn [chain-name]
- (create-diffs-chain! (make-name chain-name))))
+ (create-diffs-chain! chain-name)))
(def edit-diff-state!
"Edit the state of a DIFF. If the new state is `:accepted` the DIFF is then
@@ -288,7 +277,7 @@
(fn [chain-name n new-state]
(if (number? n)
(if (integral? n)
- (do (def chain-ref (make-chain-ref chain-name))
+ (do (def chain-ref (chain/make-chain-ref! chain-name))
(verify-diff-number n chain-ref)
(simple-edit-diff! chain-ref n {:state new-state})
(if (eq? new-state :accepted)
@@ -304,7 +293,7 @@
(fn [chain-name n comment]
(if (number? n)
(if (integral? n)
- (do (def chain-ref (make-chain-ref chain-name))
+ (do (def chain-ref (chain/make-chain-ref! chain-name))
(verify-diff-number n chain-ref)
(simple-add-comment! chain-ref n comment get-git-username!)
(put-str! (string-append "Added comment to Diff " (show n))))
@@ -319,20 +308,20 @@
(cmd-parse-failure (string-append "Invalid list option: " o)))) os)))
(def /list-cmd
- (fn [chain-name opts]
- (/cmd-2-opts "list" chain-name opts valid-list-options list-options help)))
+ (fn [opts]
+ (/cmd-1-opts "list" opts valid-list-options list-options help)))
(def args (get-args!))
(match args
- (/list-cmd 'chain-name 'options) (list-items chain-name options)
- (/cmd-2 "propose" 'commit 'chain-name help) (new-diff! (make-name chain-name) commit)
- (/cmd-2 "checkout" 'diff-no 'chain-name help) (checkout-diff! chain-name (read diff-no))
- (/cmd-2 "show" 'diff-no 'chain-name help) (show-diff! chain-name (read diff-no))
- (/cmd-2 "retract" 'diff-no 'chain-name help) (edit-diff-state! chain-name (read diff-no) :retracted)
- (/cmd-2 "accept" 'diff-no 'chain-name help) (edit-diff-state! chain-name (read diff-no) :accepted)
- (/cmd-2 "reject" 'diff-no 'chain-name help) (edit-diff-state! chain-name (read diff-no) :rejected)
- ["comment" 'diff-no 'comment 'chain-name] (create-comment! chain-name (read diff-no) comment)
- (/cmd-1 "create-chain" 'chain-name help) (new-diff-chain! chain-name)
+ (/list-cmd 'options) (list-items (chain-name) options)
+ (/cmd-1 "propose" 'commit help) (new-diff! (chain-name) commit)
+ (/cmd-1 "checkout" 'diff-no help) (checkout-diff! (chain-name) (read diff-no))
+ (/cmd-1 "show" 'diff-no help) (show-diff! (chain-name) (read diff-no))
+ (/cmd-1 "retract" 'diff-no help) (edit-diff-state! (chain-name) (read diff-no) :retracted)
+ (/cmd-1 "accept" 'diff-no help) (edit-diff-state! (chain-name) (read diff-no) :accepted)
+ (/cmd-1 "reject" 'diff-no help) (edit-diff-state! (chain-name) (read diff-no) :rejected)
+ ["comment" 'diff-no 'comment] (create-comment! (chain-name) (read diff-no) comment)
+ (/cmd-0 "create-chain" help) (new-diff-chain! (chain-name))
(/cmd-0 "done" help) (mark-last-seen)
["help"] (put-str! help)
["-h"] (put-str! help)
diff --git a/bin/rad-issues b/bin/rad-issues
index 94cf881..c69ce80 100755
--- a/bin/rad-issues
+++ b/bin/rad-issues
@@ -2,23 +2,24 @@
(load! (find-module-file! "prelude.rad"))
(load! (find-module-file! "monadic/issues.rad"))
+(load! (find-module-file! "monadic/project.rad"))
(load! (find-module-file! "prelude/io-utils.rad"))
(load! (find-module-file! "prelude/cmd-parsing.rad"))
(import prelude/validation :as 'validation)
+(import prelude/chain :as 'chain)
-(def base-name "http://machines.radicle.xyz/chains/")
+(def chain-name (fn [] (get-rsm-of-type! :rad-issues)))
(def name-base "http://machines.radicle.xyz/chains/names")
(def help
- (string-append
"rad-issues - Radicle issue CLI
Usage:
- rad-issues list <chain-name> [--closed] [--open] [--new]
- rad-issues [new|create-chain] <chain-name>
- rad-issues close <issue-number> <chain-name>
+ rad-issues list [--closed] [--open] [--new]
+ rad-issues [new|create-chain]
+ rad-issues close <issue-number>
rad-issues make-key <nick>
rad-issues names
rad-issues done
@@ -33,24 +34,12 @@
make-key - Create a key-pair and register the name
names - See all registered names
help - Print this help and exit
-
- If <chain-name> begins with 'http://', that URL will be used. Otherwise,
- " base-name " will be prepended to <chain-name>." ))
+ ")
(def cmd-parse-failure
(fn [error]
(parse-failure error help)))
-(def make-name
- (fn [chain]
- (if (eq? (take 7 chain) "http://")
- chain
- (string-append base-name chain))))
-
-(def make-chain-ref
- (fn [chain]
- (ref (chain/load-chain! (make-name chain)))))
-
(def mark-last-seen
(fn []
(write-file-key! ".radicle-issues" :last-mark-done (now!))))
@@ -104,9 +93,9 @@
"Lists the recent items and uses an editor to add a relevant comment."
(fn [chain options]
- (def chain-ref (make-chain-ref chain))
- (load! (find-module-file! "rad/monadic/names.rad"))
- (def names (ref (chain/load-chain! name-base)))
+ (def chain-ref (chain/make-chain-ref! chain))
+ (load! (find-module-file! "monadic/names.rad"))
+ (def names (chain/make-chain-ref! name-base))
(def add-username
(fn [d]
(def n (catch
@@ -183,14 +172,14 @@
(def n (read issue-number))
(if (number? n)
(if (integral? n)
- (do (def chain-ref (ref (chain/new-chain (make-name chain-name))))
+ (do (def chain-ref (ref (chain/new-chain chain-name)))
(simple-edit-issue! chain-ref n {:state :closed}))
(cmd-parse-failure "Issue numbers must be whole numbers!"))
(cmd-parse-failure "To close an issue, please provide the issue number."))))
(def new-issue
(fn [chain]
- (def chain-ref (ref (chain/new-chain (make-name chain))))
+ (def chain-ref (ref (chain/new-chain chain)))
(def template
";; Issue template. An empty or invalid value will abort.
{:title \"Pick a title\"
@@ -204,18 +193,18 @@
(def create-chain
(fn [chain]
- (create-issues-chain! (make-name chain))))
+ (create-issues-chain! chain)))
(def make-key
(fn [name]
(def kp (gen-key-pair! (default-ecc-curve)))
(write-file! "my-keys.rad" (show kp))
- (load! "rad/monadic/names.rad")
+ (load! (find-module-file! "monadic/names.rad"))
(add-name! name-base name (lookup :public-key kp))))
(def names
(fn []
- (load! "rad/monadic/names.rad")
+ (load! (find-module-file! "monadic/names.rad"))
(print! (list-names name-base))))
(init-file-dict! ".radicle-issues")
@@ -238,12 +227,12 @@
(def args (get-args!))
(match args
- (/list-cmd 'chain-name 'options) (list-items chain-name options)
+ ["list"] (list-items (chain-name) [])
(/cmd-0 "names" help) (names)
(/cmd-1 "make-key" 'nick help) (make-key nick)
- (/cmd-1 "new" 'chain-name help) (new-issue chain-name)
+ (/cmd-0 "new" help) (new-issue (chain-name))
(/cmd-1 "create-chain" 'chain-name help) (create-chain chain-name)
- (/cmd-2 "close" 'issue-number 'chain-name help) (close-issue issue-number chain-name)
+ (/cmd-1 "close" 'issue-number help) (close-issue issue-number (chain-name))
(/cmd-0 "done" help) (mark-last-seen)
["help"] (put-str! help)
["-h"] (put-str! help)
diff --git a/bin/rad-project b/bin/rad-project
new file mode 100755
index 0000000..10e1da1
--- /dev/null
+++ b/bin/rad-project
@@ -0,0 +1,113 @@
+#!/usr/bin/env radicle
+
+(load! (find-module-file! "prelude.rad"))
+(load! (find-module-file! "monadic/issues.rad"))
+(load! (find-module-file! "monadic/diff.rad"))
+(load! (find-module-file! "monadic/project.rad"))
+(load! (find-module-file! "prelude/io-utils.rad"))
+(load! (find-module-file! "prelude/cmd-parsing.rad"))
+
+(import prelude/validation :as 'validation)
+
+(def help
+ "rad-project - Radicle project CLI
+
+ Usage:
+ rad-project init
+ rad-project show-id
+ rad-project checkout <PROJECT-ID>
+
+ init - Initialize a new project
+ show-id - Show the project id
+ checkout - Checkout a project
+ ")
+
+(def base "http://localhost:8000/chains/")
+
+(def prompt-for-metadata!
+ (fn []
+ (def name (prompt! "? What's the name of your project: "))
+ (def desc (prompt! "? Briefly describe the project: "))
+ {:name name :description desc}))
+
+(def cid-of-empty-repo "QmUNLLsPACCz1vLxQVkXqqLX5R1X345qqfHbsf67hvA3Nn")
+
+(def init-git-ipfs-repo
+ "Creates a key for a repo. Sets the remote to that. Points the IPNS link to
+ the provided CID. Returns the remote."
+ (fn [orig-cid]
+ (def keyname (uuid!))
+ (def key
+ (unlines
+ (process-with-stdout!
+ "rad-ipfs"
+ ["key" "gen" "--type=ed25519" keyname]
+ "")))
+ (process-with-stdout!
+ "rad-ipfs"
+ ["name" "publish" "--key" key orig-cid]
+ "")
+ (def remote (string-append "ipfs://ipns/" key))
+ remote))
+
+(def checkout!
+ "Checkout a project."
+ (fn [project-url]
+ (def rsm (ref (chain/new-chain project-url)))
+ (fetch! rsm)
+ (def name (lookup :name (get-meta! rsm)))
+ (def origin (lookup :id (first-rsm-of-type! rsm :rad-repo)))
+ (put-str! name)
+ (process! "git" ["clone" origin name] "")
+ (cd! name)
+ (set-git-config! "rad.project.url" project-url)))
+
+(def new-or-forked-project!
+ "Create a new or forked project. If `maybe-upstream` is :nothing, creates a
+ new project. Otherwise, uses that as the url to fork from"
+ (fn [maybe-upstream]
+ ;; TODO: switch to IPFS
+ (def project-url (string-append base (uuid!)))
+ (def issues-url (string-append base (uuid!)))
+ (create-issues-chain! issues-url)
+ (def diff-url (string-append base (uuid!)))
+ (create-diffs-chain! diff-url)
+ (def meta (prompt-for-metadata!))
+ (process! "git" ["init"] "")
+ (def repo-url (match maybe-upstream
+ :nothing (do
+ (create-project! project-url meta)
+ (init-git-ipfs-repo cid-of-empty-repo))
+ 'upstream (do
+ ;; TODO: make ipns origin point to same as ipns upstream
+ (put-str! (<> "=> adding \"upstream\" remote: " upstream)
+ (process! "git" ["remote" "add" "upstream" upstream] ""))
+ (error "todo: get old meta"))))
+ (put-str! (string-append "=> adding \"origin\" remote: " repo-url))
+ (put-str! (string-append "=> project id: " project-url))
+ (process! "git" ["remote" "add" "origin" repo-url] "")
+ (def project-rsm (ref (chain/new-chain project-url)))
+ (add-rsm! project-rsm { :id repo-url :type :rad-repo })
+ (add-rsm! project-rsm { :id issues-url :type :rad-issues })
+ (add-rsm! project-rsm { :id diff-url :type :rad-diff })
+ (set-git-config! "rad.project.url" project-url)
+ (put-str! "=> project created!")))
+
+
+(def show-project-id
+ (fn []
+ (put-str! (string-append "=> " (get-project-url!)))
+ (put-str! "=> Share this project id for people to collaborate with you on your project.")))
+
+(def args (get-args!))
+;; TODO: use Merle's refactored cmd stuff
+(match args
+ (/cmd-0 "init" help) (new-or-forked-project! :nothing)
+ (/cmd-1 "fork" 'upstream help) (new-or-forked-project! upstream)
+ (/cmd-0 "show-id" help) (show-project-id)
+ (/cmd-1 "checkout" 'project-id help) (checkout! project-id)
+ ["help"] (put-str! help)
+ ["-h"] (put-str! help)
+ ["--help"] (put-str! help)
+ (/cons 'cmd _) (cmd-parse-failure (string-append "Unknown command: " cmd))
+ [] (put-str! help))
diff --git a/docs/source/reference.rst b/docs/source/reference.rst
index d6d6eb0..5eca6b0 100644
--- a/docs/source/reference.rst
+++ b/docs/source/reference.rst
@@ -508,6 +508,26 @@ Reads a single line of input and returns it as a string.
Evaluates the contents of a file. Each seperate radicle expression is
``eval``\ uated according to the current definition of ``eval``.
+``cd!``
+~~~~~~~
+
+Change the current working directory.
+
+``stdin!``
+~~~~~~~~~~
+
+A handle for standard in.
+
+``stdout!``
+~~~~~~~~~~~
+
+A handle for standard out.
+
+``stderr!``
+~~~~~~~~~~~
+
+A handle for standard error.
+
``read-file!``
~~~~~~~~~~~~~~
@@ -893,6 +913,11 @@ This requires the ``prelude/test/primitive-stub`` script to be loaded.
Like ``process-with-stdout!``, but returns a vec
``[stdout stderr exitcode]``.
+``(prompt! prompt)``
+~~~~~~~~~~~~~~~~~~~~
+
+Ask for user input with a prompt.
+
``prelude/bool``
----------------
@@ -1137,31 +1162,30 @@ An eval in which one can use ``(:enter-chain url)`` to make the eval
behave as that of a remote chain, and ``:send`` to send all enqueued
expressions.
-``(updatable-eval sub-eval)``
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Given an evaluation function ``f``, returns a new one which augments
-``f`` with a new command ``(update expr)`` which evaluates arbitrary
-expression using ``base-eval``.
-
``(update-chain! chain)``
~~~~~~~~~~~~~~~~~~~~~~~~~
Takes a chain, and returns a new chain updated with the new expressions
from the remote chain
-``(eval-fn-app state f arg cb)``
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Given a state, a function, an argument and a callback, returns the
-result of evaluating the function call on the arg in the given state,
-while also calling the callback on the result.
-
``(send-prelude! chain-id)``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Send the pure prelude to a chain.
+``(send-signed-command! chain chain-id cmd payload)``
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Send a command signed by the keys in ``my-keys.rad``.
+
+``(sign-entity! e chain-id)``
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Assumes a key pair is stored at ``my-keys.rad``. Using that key pair,
+will sign a dict by adding ``:author`` and ``:signature`` fields, so
+that it is valid according to ``validator/signed``, while also adding a
+``:nonce``.
+
``(send-code! chain-id filename)``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -1183,6 +1207,11 @@ last input in ``inputs``. The ``index`` argument is either ``:nothing``
in which case all inputs are fetched or ``[:just i]`` in which case all
inputs following after the index ``i`` are fetched.
+``(make-chain-ref! chain)``
+~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Makes a new ref containing the loaded chain.
+
``(install-remote-chain-fake)``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -1190,11 +1219,6 @@ Install test doubles for the ``send!`` and ``receive!`` primitives that
use a mutable dictionary to store RSMs. Requires
``rad/test/stub-primitives`` to be loaded
-``(send-signed-command! chain chain-id cmd payload)``
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Send a command signed by the keys in ``my-keys.rad``.
-
``prelude/state-machine``
-------------------------
@@ -1317,6 +1341,12 @@ author. The rest of the dict is turned into a string according to
A validator which checks if a string is an ISO 8601 formatted
Coordinated Universal Time (UTC) timestamp.
+``(string-of-max-length max-len)``
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+A validator which checks that it's argument is a string and less than
+the specified length.
+
``prelude/util``
----------------
diff --git a/nix/shell.nix b/nix/shell.nix
index 16668fc..3670f94 100644
--- a/nix/shell.nix
+++ b/nix/shell.nix
@@ -19,14 +19,16 @@ stdenv.mkDerivation {
LANG = "en_US.UTF-8";
libraryPkgconfigDepends = [ zlib ];
shellHook = ''
- export PATH=$PATH:`stack path --local-bin`
- export STACK_ARGS="--system-ghc --no-nix-pure --nix-packages 'zlib fzf moreutils'"
+ export PATH=$PATH:`stack path --local-bin`:$PWD/bin
+ export RADPATH=$PWD/rad
+ export STACK_ARGS="--silent --system-ghc --no-nix-pure --nix-packages 'zlib fzf moreutils'"
export IS_NIX_SHELL="true"
export LOCALE_ARCHIVE="${pkgs.glibcLocales}/lib/locale/locale-archive";
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 $STACK_ARGS"
+ alias se="stack exec $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"
diff --git a/rad/monadic/diff-remote.rad b/rad/monadic/diff-remote.rad
index b234f96..87953d1 100644
--- a/rad/monadic/diff-remote.rad
+++ b/rad/monadic/diff-remote.rad
@@ -3,10 +3,12 @@
(import prelude/dict :unqualified)
(import prelude/set :as 'set)
(import prelude/ref :unqualified)
+(import prelude/nonces :unqualified)
(import prelude/validation :as 'validator)
(import prelude/patterns :unqualified)
(import prelude/util :unqualified)
(import prelude/lens :unqualified)
+(import prelude/chain-remote '[make-updatable-eval] :unqualified)
(def chain-id
"The name of this chain."
@@ -20,41 +22,15 @@
"We use a stateful counter for giving diff numbers."
(make-counter))
-(def used-nonces
- "We keep track of the UUIDs which have been used as nonces in inputs."
- (ref set/empty))
-
-(def unused-nonce?
- "Check that a nonce has not been used already."
- (fn [nonce]
- (not (set/member? nonce (read-ref used-nonces)))))
-
-(def mark-used-nonce
- "Mark a UUID as used."
- (fn [nonce]
- (modify-ref used-nonces (fn [s] (set/insert nonce s)))))
+(def noncer (make-noncer))
(def set-diffs
"A helper to set stuff in the diffs ref."
(fn [l v]
(set-ref diffs l v)))
-(def validator/nonce
- "Validator for unused nonces."
- (validator/and
- [validator/uuid
- (validator/pred "Nonce not already used" unused-nonce?)]))
-
-(def validator/text
- "A validator for text."
- (fn [max-len]
- (validator/and
- [(validator/type :string)
- (validator/pred (string-append "< " (show max-len) " chars in length")
- (fn [s] (< (string-length s) max-len)))])))
-
(def input-keys
- {:nonce validator/nonce
+ {:nonce (noncer :validator)
:chain-id (validator/= chain-id)})
(def validator/time-created
@@ -86,7 +62,7 @@
(def comment-keys
"A comment's body should be text that isn't too long."
- {:body (validator/text 4000)})
+ {:body (validator/string-of-max-length 4000)})
(def validator/full-comment
(validator/keys comment-keys))
@@ -104,8 +80,8 @@
validator/diff-reference]))
(def diff-keys
- {:title (validator/text 100)
- :description (validator/text 4000)
+ {:title (validator/string-of-max-length 100)
+ :description (validator/string-of-max-length 4000)
:patch (validator/type :string)
:state (validator/member [:pending :retracted :accepted :rejected])
:comments (validator/every validator/full-comment)})
@@ -149,7 +125,7 @@
(<> i
{:number n})))
(set-diffs (@ n) i_)
- (mark-used-nonce (lookup :nonce i))))
+ (noncer [:use (lookup :nonce i)])))
(def over-diffs
"A helper to modify stuff in the diff ref."
@@ -164,7 +140,7 @@
(over-diffs
(.. (@ (lookup :diff-number c)) (@ :comments))
(fn [cs] (add-right c_ cs)))
- (mark-used-nonce (lookup :nonce c))))
+ (noncer [:use (lookup :nonce c)])))
(def merge-new
(fn [new]
@@ -184,43 +160,9 @@
(def commands
"The set of allowed chain commands."
- (ref
- {'create-diff create-diff
- 'list-diffs list-diffs
- 'edit-diff edit-diff
- 'add-comment add-comment}))
-
-(def process-command
- "Function that maps post-eval commands to existing functions"
- (fn [expr]
- (def command (first expr))
- (def args (rest expr))
- (def do-this (lookup command (read-ref commands)))
- (apply do-this args)))
-
-;; Move to eval-fn-app & updatable-eval from chain.rad to a pure file so it may
-;; be imported
-
-(def eval-fn-app
- "Given a state, a function, an argument and a callback, returns
- the result of evaluating the function call on the arg in the given
- state, while also calling the callback on the result."
- (fn [state f arg cb]
- (def exec (base-eval (list f (list 'quote arg)) state))
- (cb (first exec))
- exec))
-
-(def updatable-eval
- "Given an evaluation function `f`, returns a new one which augments `f` with a new
- command `(update expr)` which evaluates arbitrary expression using `base-eval`."
- (fn [sub-eval]
- (fn [expr state]
- (match expr
- (/cons 'cmd _) (if (eq? cmd 'update)
- (base-eval (nth 1 expr) state)
- (sub-eval expr state))
- _ (sub-eval expr state)))))
-
-(def eval (updatable-eval
- (fn [expr state]
- (eval-fn-app state 'process-command expr (fn [x] x)))))
+ {'create-diff create-diff
+ 'list-diffs list-diffs
+ 'edit-diff edit-diff
+ 'add-comment add-comment})
+
+(def eval (make-updatable-eval commands))
diff --git a/rad/monadic/issue-remote.rad b/rad/monadic/issue-remote.rad
index 60db186..129942e 100644
--- a/rad/monadic/issue-remote.rad
+++ b/rad/monadic/issue-remote.rad
@@ -10,6 +10,8 @@
(import prelude/patterns :unqualified)
(import prelude/util :unqualified)
(import prelude/lens :unqualified)
+(import prelude/nonces :unqualified)
+(import prelude/chain-remote '[make-updatable-eval] :unqualified)
(def chain-id
"The name of this chain."
@@ -23,19 +25,7 @@
"We use a stateful counter for giving issues numbers."
(make-counter))
-(def used-nonces
- "We keep track of the UUIDs which have been used as nonces in inputs."
- (ref set/empty))
-
-(def unused-nonce?
- "Check that a nonce has not been used already."
- (fn [nonce]
- (not (set/member? nonce (read-ref used-nonces)))))
-
-(def mark-used-nonce
- "Mark a UUID as used."
- (fn [nonce]
- (modify-ref used-nonces (fn [s] (set/insert nonce s)))))
+(def noncer (make-noncer))
(def set-issues
"A helper to set stuff in the issues ref."
@@ -47,22 +37,8 @@
(fn [l f]
(over-ref issues l f)))
-(def validator/nonce
- "Validator for unused nonces."
- (validator/and
- [validator/uuid
- (validator/pred "Nonce not already used" unused-nonce?)]))
-
-(def validator/text
- "A validator for text."
- (fn [max-len]
- (validator/and
- [(validator/type :string)
- (validator/pred (string-append "< " (show max-len) " chars in length")
- (fn [s] (< (length s) max-len)))])))
-
(def input-keys
- {:nonce validator/nonce
+ {:nonce (noncer :validator)
:chain-id (validator/= chain-id)})
(def validator/time-created
@@ -94,7 +70,7 @@
(def comment-keys
"A comment's body should be text that isn't too long."
- {:body (validator/text 4000)})
+ {:body (validator/string-of-max-length 4000)})
(def validator/sub-comment
(validator/optional-keys comment-keys))
@@ -115,9 +91,9 @@
validator/issue-reference]))
(def issue-keys
- {:title (validator/text 100)
- :body (validator/text 4000)
- :labels (validator/every (validator/text 80))
+ {:title (validator/string-of-max-length 100)
+ :body (validator/string-of-max-length 4000)
+ :labels (validator/every (validator/string-of-max-length 80))
:state (validator/member [:open :closed])
:comments (validator/every (validator/and [validator/full-comment
validator/time-created]))})
@@ -207,7 +183,7 @@
{:number n
:comments (map strip-input (lookup :comments fixed))})))
(set-issues (@ n) i_)
- (mark-used-nonce (lookup :nonce i))))
+ (noncer [:use (lookup :nonce i)])))
(def add-comment
"Add a comment to an issue."
@@ -217,7 +193,7 @@
(over-issues
(.. (@ (lookup :issue-number c)) (@ :comments))
(fn [cs] (add-right c_ cs)))
- (mark-used-nonce (lookup :nonce c))))
+ (noncer [:use (lookup :nonce c)])))
(def merge-new
(fn [new]
@@ -251,44 +227,11 @@
(def commands
"The set of allowed chain commands."
- (ref
- {'create-issue create-issue
- 'edit-issue edit-issue
- 'add-comment add-comment
- 'edit-comment edit-comment
- 'list-issues list-issues}))
-
-(def process-command
- "Function that maps post-eval commands to existing functions"
- (fn [expr]
- (def command (first expr))
- (def args (rest expr))
- (def do-this (lookup command (read-ref commands)))
- (apply do-this args)))
-
-;; Move to eval-fn-app & updatable-eval from chain.rad to a pure file so it may
-;; be imported
-
-(def eval-fn-app
- "Given a state, a function, an argument and a callback, returns
- the result of evaluating the function call on the arg in the given
- state, while also calling the callback on the result."
- (fn [state f arg cb]
- (def exec (base-eval (list f (list 'quote arg)) state))
- (cb (first exec))
- exec))
-
-(def updatable-eval
- "Given an evaluation function `f`, returns a new one which augments `f` with a new
- command `(update expr)` which evaluates arbitrary expression using `base-eval`."
- (fn [sub-eval]
- (fn [expr state]
- (match expr
- (/cons 'cmd _) (if (eq? cmd 'update)
- (base-eval (nth 1 expr) state)
- (sub-eval expr state))
- _ (sub-eval expr state)))))
-
-(def eval (updatable-eval
- (fn [expr state]
- (eval-fn-app state 'process-command expr (fn [x] x)))))
+ {'create-issue create-issue
+ 'edit-issue edit-issue
+ 'add-comment add-comment
+ 'edit-comment edit-comment
+ 'list-issues list-issues})
+
+(def eval (make-updatable-eval commands))
+
diff --git a/rad/monadic/issues.rad b/rad/monadic/issues.rad
index 3536d28..21457c6 100644
--- a/rad/monadic/issues.rad
+++ b/rad/monadic/issues.rad
@@ -8,7 +8,7 @@
:exports '[create-issues-chain!]}
(import prelude/lens :unqualified)
-(import prelude/chain '[send-code!] :unqualified)
+(import prelude/chain '[send-code! send-signed-command!] :unqualified)
(import prelude/time '[install-fake-clock] :unqualified)
(import prelude/io :as 'io)
diff --git a/rad/monadic/project-remote.rad b/rad/monadic/project-remote.rad
new file mode 100644
index 0000000..261d104
--- /dev/null
+++ b/rad/monadic/project-remote.rad
@@ -0,0 +1,78 @@
+;; Project RSM
+;; Meant to be sent to a chain with send-code!
+
+(import prelude/basic :unqualified)
+(import prelude/bool :unqualified)
+(import prelude/dict :unqualified)
+(import prelude/set :as 'set)
+(import prelude/ref :unqualified)
+(import prelude/validation :as 'validator)
+(import prelude/patterns :unqualified)
+(import prelude/util :unqualified)
+(import prelude/lens :unqualified)
+(import prelude/nonces :unqualified)
+(import prelude/set :as 'set)
+(import prelude/chain-remote '[make-updatable-eval] :unqualified)
+
+(def rsms
+ "A url-based dict of RSMs."
+ (ref set/empty))
+
+(def rsm-id
+ "The name of this RSM."
+ "monadic/radicle/project")
+
+(def meta
+ (ref {:name ""
+ :description "" }))
+
+(def noncer (make-noncer))
+
+(def validator/rsm
+ (validator/keys
+ {:type (validator/type :keyword)
+ :id (validator/string-of-max-length 80)}))
+
+(def validator/meta
+ (validator/keys
+ {:name (validator/string-of-max-length 80)
+ :description (validator/string-of-max-length 800)}))
+
+(def validator/input
+ (validator/and
+ [ (validator/keys {:nonce (noncer :validator)
+ :chain-id (validator/= rsm-id)})
+ validator/signed] ))
+
+(def add-rsm
+ (fn [r]
+ (validator/input r)
+ (validator/rsm r)
+ (noncer [:use (lookup :nonce r)])
+ (modify-ref rsms (fn [rs] (set/insert r rs)))))
+
+(def set-meta
+ (fn [r]
+ (validator/input r)
+ (validator/meta r)
+ (noncer [:use (lookup :nonce r)])
+ (write-ref meta {:name (lookup :name r) :description (lookup :description r)})))
+
+(def list-rsms
+ (fn []
+ (set/to-vec (read-ref rsms))))
+
+(def get-meta
+ (fn []
+ (read-ref meta)))
+
+;; General logic
+
+(def commands
+ "The set of allowed commands."
+ {'add-rsm add-rsm
+ 'set-meta set-meta
+ 'get-meta get-meta
+ 'list-rsms list-rsms })
+
+(def eval (make-updatable-eval commands))
diff --git a/rad/monadic/project.rad b/rad/monadic/project.rad
new file mode 100644
index 0000000..790557f
--- /dev/null
+++ b/rad/monadic/project.rad
@@ -0,0 +1,91 @@
+;; Helpers for setting up and interacting with project RSMs
+
+(import prelude/lens :unqualified)
+(import prelude/chain '[send-code! send-signed-command! make-chain-ref!] :unqualified)
+(import prelude/time '[install-fake-clock] :unqualified)
+(import prelude/io :as 'io)
+
+(def get-project-url!
+ (fn []
+ (def proj (get-git-config! "rad.project.url"))
+ (if (eq? proj "")
+ (do
+ (put-str! "Not in a radicle project")
+ (exit! 1))
+ proj)))
+
+(def rsm-id
+ "The name of this RSM."
+ "monadic/radicle/project")
+
+(def set-meta!
+ "Set the metadata for a project"
+ (fn [chain i]
+ (send-signed-command! chain rsm-id 'set-meta i)))
+
+(def get-meta!
+ "Get the metadata for a project"
+ (fn [chain]
+ (lookup :result (chain/eval-in-chain '(get-meta) (read-ref chain)))))
+
+(def create-project!
+ "Create a remote project RSM with the given url."
+ (fn [url meta]
+ (chain/send-prelude! url)
+ (send-code! url (find-module-file! "monadic/project-remote.rad"))
+ (set-meta! (ref {:url url}) meta)))
+
+(def add-rsm!
+ "Add a new RSM to the project."
+ (fn [chain i]
+ (send-signed-command! chain rsm-id 'add-rsm i)))
+
+(def list-rsms!
+ "List RMSs of the project."
+ (fn [chain]
+ (lookup :result (chain/eval-in-chain '(list-rsms) (read-ref chain)))))
+
+(def add-issues-rsm!
+ (fn [chain id]
+ (add-rsm! chain { :id id :type :rad-issues })))
+
+(def add-diff-rsm!
+ (fn [chain id]
+ (add-rsm! chain { :id id :type :rad-diff })))
+
+(def add-repo-rsm!
+ (fn [chain id]
+ (add-rsm! chain { :id id :type :rad-repo })))
+
+(def first-rsm-of-type!
+ (fn [chain typ]
+ (first (filter (fn [x] (eq? (lookup :type x) typ)) (list-rsms! chain)))))
+
+(def get-rsm-of-type!
+ "Gets the project via get-project-url, and looks in the project for an RSM
+ of the specified type. The `:id` of the first matching RSM is returned."
+ (fn [rsm-type]
+ (lookup :id (first-rsm-of-type! (make-chain-ref! (get-project-url!)) rsm-type))))
+
+(:test "The monadic project chain works."
+
+ [:setup
+ (do (chain/install-remote-chain-fake)
+ (install-fake-clock)
+ (io/install-fake-filesystem!
+ { "../my-keys.rad" (show (gen-key-pair! (default-ecc-curve)))
+ })
+ (def chain-name "http://bar")
+ (def chain (ref (chain/new-chain chain-name)))
+ (create-project! chain-name { :name "test" :description "test project"})
+ (add-issues-rsm! chain "a")
+ (add-diff-rsm! chain "b")
+ (add-repo-rsm! chain "c")
+ (fetch! chain))
+ ]
+
+ [ (get-meta! chain) ==> { :name "test" :description "test project" }]
+ [ (lookup :id (first-rsm-of-type! chain :rad-issues)) ==> "a" ]
+ [ (lookup :id (first-rsm-of-type! chain :rad-diff)) ==> "b" ]
+ [ (lookup :id (first-rsm-of-type! chain :rad-repo)) ==> "c" ]
+)
diff --git a/rad/prelude.rad b/rad/prelude.rad
index 64774b8..ca56137 100644
--- a/rad/prelude.rad
+++ b/rad/prelude.rad
@@ -15,9 +15,12 @@
(file-module! "prelude/ref.rad")
(file-module! "prelude/lens.rad")
(file-module! "prelude/chain.rad")
+(file-module! "prelude/chain-remote.rad")
(file-module! "prelude/state-machine.rad")
(file-module! "prelude/validation.rad")
+(file-module! "prelude/nonces.rad")
(file-module! "prelude/util.rad")
+(file-module! "prelude/io-utils.rad")
(file-module! "prelude/time.rad")
(file-module! "prelude/test.rad")
@@ -32,5 +35,8 @@
(import prelude/list :unqualified)
(import prelude/ref :unqualified)
(import prelude/validation :as 'validator)
+(import prelude/nonces :unqualified)
(import prelude/util :unqualified)
+(import prelude/io-utils :unqualified)
(import prelude/chain :as 'chain)
+(import prelude/chain-remote :unqualified)
diff --git a/rad/prelude/chain-remote.rad b/rad/prelude/chain-remote.rad
new file mode 100644
index 0000000..8b71e44
--- /dev/null
+++ b/rad/prelude/chain-remote.rad
@@ -0,0 +1,56 @@
+{:module 'prelude/chain-remote
+ :doc "Functions for writing remote RSMs"
+ :exports '[make-updatable-eval]}
+
+(import prelude/ref '[modify-ref] :unqualified)
+(import prelude/patterns :unqualified)
+
+(def eval-fn-app
+ "Given a state, a function, an argument and a callback, returns
+ the result of evaluating the function call on the arg in the given
+ state, while also calling the callback on the result."
+ (fn [state f arg cb]
+ (def exec (base-eval (list f (list 'quote arg)) state))
+ (cb (first exec))
+ exec))
+
+(def updatable-eval
+ "Given an evaluation function `f`, returns a new one which augments `f` with a new
+ command `(update expr)` which evaluates arbitrary expression using `base-eval`."
+ (fn [sub-eval]
+ (fn [expr state]
+ (match expr
+ (/cons 'cmd _) (if (eq? cmd 'update)
+ (base-eval (nth 1 expr) state)
+ (sub-eval expr state))
+ _ (sub-eval expr state)))))
+
+(def make-updatable-eval
+ "Make an updatable eval from a list of command mappings."
+ (fn [initial-commands]
+ (def commands (ref initial-commands))
+ (def process-command
+ "Function that maps post-eval commands to existing functions"
+ (fn [expr]
+ (def command (first expr))
+ (def args (rest expr))
+ (def do-this (lookup command (read-ref commands)))
+ (apply do-this args)))
+ (updatable-eval
+ (fn [expr state]
+ (eval-fn-app state process-command expr (fn [x] x))))))
+
+(:test "make-updatable-eval"
+ [:setup
+ (do
+ (def counter (ref 0))
+ (def commands
+ {'inc (fn [] (modify-ref counter (fn [x] (+ x 1))))
+ 'get (fn [] (read-ref counter))})
+ (def ev (make-updatable-eval commands))
+ (def res (ev '(inc) (get-current-state)))
+ (def st (nth 1 res))
+ )
+ ]
+ [ (nth 0 (ev '(get) st)) ==> 1 ]
+)
diff --git a/rad/prelude/chain.rad b/rad/prelude/chain.rad
index e29dd17..c7345d7 100644
--- a/rad/prelude/chain.rad
+++ b/rad/prelude/chain.rad
@@ -1,8 +1,8 @@
{:module 'prelude/chain
:doc "Functions for simulating remote chains."
:exports '[new-chain load-chain! eval-in-chain update-chain-ref! eval
- updatable-eval update-chain! eval-fn-app send-prelude!
- send-code! send! receive! install-remote-chain-fake send-signed-command!]}
+ update-chain! send-prelude! send-signed-command! sign-entity!
+ send-code! send! receive! make-chain-ref! install-remote-chain-fake]}
(import prelude/io '[read-file-value! read-file-values!] :as 'io)
(import prelude/ref '[modify-ref] :unqualified)
@@ -223,25 +223,6 @@
:else (eval__ expr env))
(eval__ expr env))))
-(def eval-fn-app
- "Given a state, a function, an argument and a callback, returns
- the result of evaluating the function call on the arg in the given
- state, while also calling the callback on the result."
- (fn [state f arg cb]
- (def exec (base-eval (list f (list 'quote arg)) state))
- (cb (first exec))
- exec))
-
-(def updatable-eval
- "Given an evaluation function `f`, returns a new one which augments `f` with a new
- command `(update expr)` which evaluates arbitrary expression using `base-eval`."
- (fn [sub-eval]
- (fn [expr state]
- (match expr
- (/cons 'cmd _) (if (eq? cmd 'update)
- (base-eval (nth 1 expr) state)
- (sub-eval expr state))
- _ (sub-eval expr state)))))
(def pure-prelude-files
"List of files which together define the pure prelude."
@@ -258,6 +239,8 @@
"prelude/lens.rad"
"prelude/state-machine.rad"
"prelude/validation.rad"
+ "prelude/nonces.rad"
+ "prelude/chain-remote.rad"
"prelude/util.rad"]))
(def file-to-module
@@ -302,3 +285,8 @@
(fn [chain chain-id cmd payload]
(send! (lookup :url (read-ref chain))
[(list cmd (sign-entity! payload chain-id))])))
+
+(def make-chain-ref!
+ "Makes a new ref containing the loaded chain."
+ (fn [chain]
+ (ref (load-chain! chain))))
diff --git a/rad/prelude/cmd-parsing.rad b/rad/prelude/cmd-parsing.rad
index d81a01b..be15e70 100644
--- a/rad/prelude/cmd-parsing.rad
+++ b/rad/prelude/cmd-parsing.rad
@@ -20,6 +20,18 @@
(fn [cmd]
(string-append "Too many arguments for command \"" cmd "\"")))
+(def /cmd-1-opts
+ "Matches a command `cmd` with one argument and an optional
+ combination of options from `valid-opts`."
+ (fn [cmd opts valid-opts opts-map help]
+ (fn [v]
+ (match v
+ [cmd] [:just {opts []}]
+ (/cons cmd (/cons 'c-n 'os)) (if (member? c-n valid-opts)
+ (parse-failure (missing-arg-error arg-1 cmd) help)
+ [:just {opts (opts-map os)}])
+ _ :nothing))))
+
(def /cmd-2-opts
"Matches a command `cmd` with one argument and an optional
combination of options from `valid-opts`."
diff --git a/rad/prelude/io-utils.rad b/rad/prelude/io-utils.rad
index 58cbe13..d263f33 100644
--- a/rad/prelude/io-utils.rad
+++ b/rad/prelude/io-utils.rad
@@ -1,8 +1,8 @@
{:module 'prelude/io-utils
:doc "IO-related utilities"
- :exports '[fzf-select! edit-in-editor!]}
+ :exports '[fzf-select! edit-in-editor! get-git-config! set-git-config!]}
-(import prelude/io '[shell-with-stdout! write-file!] :unqualified)
+(import prelude/io '[shell-with-stdout! write-file! process-with-stdout!] :unqualified)
(import prelude/strings '[unlines] :unqualified)
(def fzf-select!
@@ -40,3 +40,13 @@
(write-file! file orig)
(shell-no-stdin! (string-append "${EDITOR:-nano} " file) "")
(read-file! file)))
+
+(def get-git-config!
+ "Get the value associated with a key in git config."
+ (fn [key]
+ (unlines (process-with-stdout! "git" ["config" "--get" key] ""))))
+
+(def set-git-config!
+ "Set the value associated with a key in git config."
+ (fn [key value]
+ (process-with-stdout! "git" ["config" key value] "")))
diff --git a/rad/prelude/io.rad b/rad/prelude/io.rad
index 63072ca..54d4963 100644
--- a/rad/prelude/io.rad
+++ b/rad/prelude/io.rad
@@ -3,7 +3,7 @@
:exports '[print! shell! process! read-line! read-file-value! read-file-values!
shell-with-stdout! shell-no-stdin! process-with-stdout! write-file!
init-file-dict! read-file-key! write-file-key! ls! modify-file!
- install-fake-filesystem! process-with-stdout-stderr-exitcode!
+ install-fake-filesystem! process-with-stdout-stderr-exitcode! prompt!
]}
(import prelude/patterns :unqualified)
@@ -218,6 +218,12 @@ Example: `(process! \"ls\" [\"-Glah\"] \"\")`. "
(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.
diff --git a/rad/prelude/nonces.rad b/rad/prelude/nonces.rad
new file mode 100644
index 0000000..f86ffaf
--- /dev/null
+++ b/rad/prelude/nonces.rad
@@ -0,0 +1,59 @@
+{:module 'prelude/nonces
+ :doc "Functions for using nonces."
+ :exports '[make-noncer]}
+
+(import prelude/basic :unqualified)
+(import prelude/bool :unqualified)
+(import prelude/patterns :unqualified)
+(import prelude/ref :unqualified)
+(import prelude/validation :as 'validator)
+(import prelude/set :as 'set)
+
+(def make-noncer
+ "Create a new noncer, which stores used nonces and allows validating that
+ inputs are nonced, thus preventing replay attacks.
+
+ Use it like so:
+
+ ```
+ (def noncer (make-noncer))
+ (def uuid1 (uuid!))
+ (def uuid2 (uuid!))
+ (noncer [:use uuid1])
+ ((noncer :validator) uuid1) ;; validation fails, nonce already used
+ ((noncer :validator) uuid2) ;; validation succeeds
+ ```
+ "
+ (fn []
+ (def used-nonces (ref set/empty))
+ (def unused? (fn [nonce] (not (set/member? nonce (read-ref used-nonces)))))
+ (def use-nonce (fn [nonce] (modify-ref used-nonces (fn [s] (set/insert nonce s)))))
+ (fn [expr]
+ (match expr
+ :validator (validator/and [validator/uuid (validator/pred "Nonce already used" unused?)])
+ [:use 'nonce] (use-nonce nonce)
+ _ (throw 'match-failure "expecting [:use <nonce>] or :validate")))))
+
+(:test "make-noncer"
+ [:setup
+ (do
+ (def noncer (make-noncer))
+ (def n1 (uuid!))
+ (def n2 (uuid!))
+ (noncer [:use n1]))
+ ]
+
+ [ (catch
+ 'validation-failure
+ ((noncer :validator) n1)
+ (fn [x] x)) ==> {:info "Did not satisfy predicate." :name "Nonce already used"}
+ ]
+
+ [ (eq? ((noncer :validator) n2) n2) ==> #t ]
+
+ [ (catch
+ 'validation-failure
+ ((noncer :validator) "not a UUID")
+ (fn [x] x)) ==> {:info "Did not satisfy predicate." :name "valid UUID"}
+ ]
+)
diff --git a/rad/prelude/validation.rad b/rad/prelude/validation.rad
index 4ca89c3..ecc6024 100644
--- a/rad/prelude/validation.rad
+++ b/rad/prelude/validation.rad
@@ -4,7 +4,8 @@
used for checking data before accepting it onto a chain."
:exports
'[= member and or type pred integral optional-key contains contains-all
- contains-only key optional-keys keys every uuid signed timestamp]}
+ contains-only key optional-keys keys every uuid signed timestamp
+ string-of-max-length]}
(import prelude/dict :unqualified)
(import prelude/dict :as 'dict)
@@ -270,3 +271,12 @@
[ (catch 'validation-failure
(timestamp "12-12-2018T14:10:21Z")
(fn [_] :ok)) ==> :ok ])
+
+(def string-of-max-length
+ "A validator which checks that it's argument is a string and less than the
+ specified length."
+ (fn [max-len]
+ (and
+ [(type :string)
+ (pred (string-append "< " (show max-len) " chars in length")
+ (fn [s] (< (length s) max-len)))])))
diff --git a/reference-doc.yaml b/reference-doc.yaml
index 91d6c4a..80801a6 100644
--- a/reference-doc.yaml
+++ b/reference-doc.yaml
@@ -112,6 +112,10 @@ primFns:
- put-str!
- get-line!
- load!
+- cd!
+- stdin!
+- stdout!
+- stderr!
- read-file!
- read-line-handle!
- open-file!
diff --git a/src/Radicle/Internal/Core.hs b/src/Radicle/Internal/Core.hs
index 55cc06f..727e6f2 100644
--- a/src/Radicle/Internal/Core.hs
+++ b/src/Radicle/Internal/Core.hs
@@ -72,7 +72,7 @@ data LangErrorData r =
-- | Takes the function name, expected number of args, and actual number of
-- args
| WrongNumberOfArgs Text Int Int
- | NonHashableKey
+ | NonHashableKey Value
| ModuleError ModuleError
| OtherError Text
| ParseError (Par.ParseErrorBundle Text Void)
@@ -135,7 +135,7 @@ errorDataToValue e = case e of
expected)
, ("actual", Number $ fromIntegral actual)]
)
- NonHashableKey -> makeVal ( "non-hashable-key", [])
+ NonHashableKey k -> makeVal ("non-hashable-key", [("key", k)])
ModuleError me -> case me of
MissingDeclaration -> makeVal ( "missing-module-declaration", [])
InvalidDeclaration t v -> makeVal ( "invalid-module-declaration", [("info", String t), ("declaration", v)])
@@ -182,8 +182,14 @@ readRef (Reference r) = do
-- | As with References and ProcHdls, we keep a counter for each handle, and in
-- the environment map those to actual handles.
-newtype Hdl = Hdl { getHandle :: Int }
- deriving (Show, Read, Ord, Eq, Generic, Serialise)
+data Hdl
+ = Hdl Int
+ | StdIn
+ | StdOut
+ | StdErr
+ deriving (Show, Read, Ord, Eq, Generic)
+
+instance Serialise Hdl
-- | Create a new handle.
newHandle :: Monad m => Handle.Handle -> Lang m Value
@@ -202,6 +208,9 @@ lookupHandle (Hdl h) = do
case IntMap.lookup h hdls of
Nothing -> throwErrorHere $ Impossible "no such handle"
Just v -> pure v
+lookupHandle StdIn = pure stdin
+lookupHandle StdOut = pure stdout
+lookupHandle StdErr = pure stderr
-- | As with References and Hdls, we keep a counter for each handle, and in the
-- environment map those to actual handles.
@@ -300,10 +309,9 @@ hashable = \case
-- | Smart constructor for dicts which checks that all the keys are hashable.
dict :: (Monad m) => Map Value Value -> Lang m Value
-dict kvs =
- if all hashable (Map.keys kvs)
- then pure $ Dict kvs
- else throwErrorHere NonHashableKey
+dict kvs = case filter (not . hashable) (Map.keys kvs) of
+ [] -> pure $ Dict kvs
+ k : _ -> throwErrorHere $ NonHashableKey k
{-# COMPLETE Atom, Keyword, String, Number, Boolean, List, Vec, PrimFn, Dict
, Ref, Handle, ProcHandle, Lambda, LambdaRec, VEnv, VState #-}
diff --git a/src/Radicle/Internal/Effects.hs b/src/Radicle/Internal/Effects.hs
index 5600c8d..6b61c37 100644
--- a/src/Radicle/Internal/Effects.hs
+++ b/src/Radicle/Internal/Effects.hs
@@ -113,13 +113,11 @@ replPrimFns sysArgs = fromList $ allDocs $
, ( "apropos!"
, "Prints documentation for all documented variables in scope."
- , \case
- [] -> do
+ , noArg "apropos!" $ do
env <- gets bindingsEnv
let docs = [ i <> "\n" <> doc | (Ident i, Just doc, _) <- toList env ]
putStrS (T.intercalate "\n\n" docs)
pure nil
- xs -> throwErrorHere $ WrongNumberOfArgs "apropos!" 0 (length xs)
)
, ( "get-line!"
@@ -266,6 +264,18 @@ replPrimFns sysArgs = fromList $ allDocs $
, ("proc", toRad ph')
]
)
+ , ( "stdin!"
+ , "A handle for standard in."
+ , noArg "stdin!" $ pure $ Handle StdIn
+ )
+ , ( "stdout!"
+ , "A handle for standard out."
+ , noArg "stdout!" $ pure $ Handle StdIn
+ )
+ , ( "stderr!"
+ , "A handle for standard error."
+ , noArg "stderr!" $ pure $ Handle StdErr
+ )
, ( "write-handle!"
, "Write a string to the provided handle."
, twoArg "write-handle!" $ \case
@@ -346,6 +356,14 @@ replPrimFns sysArgs = fromList $ allDocs $
Just t -> pure $ String t
v -> throwErrorHere $ TypeError "find-module-file!" 0 TString v
)
+ , ( "cd!"
+ , "Change the current working directory."
+ , oneArg "cd!" $ \case
+ String filename -> do
+ setCurrentDirS $ toS filename
+ pure $ Keyword $ Ident "ok"
+ v -> throwErrorHere $ TypeError "cd!" 0 TString v
+ )
]
-- | Since `#` is not a comment in radicle, we need to explictly remove shebang
diff --git a/src/Radicle/Internal/Effects/Capabilities.hs b/src/Radicle/Internal/Effects/Capabilities.hs
index 5cc90c4..a6b9139 100644
--- a/src/Radicle/Internal/Effects/Capabilities.hs
+++ b/src/Radicle/Internal/Effects/Capabilities.hs
@@ -12,7 +12,7 @@ import Data.Time
import Paths_radicle
import System.Console.ANSI (hSupportsANSI)
import System.Console.Haskeline hiding (catch)
-import System.Directory (doesFileExist)
+import System.Directory (doesFileExist, setCurrentDirectory)
import System.Environment (lookupEnv)
import System.Exit (ExitCode)
import System.FilePath (splitSearchPath, (</>))
@@ -69,6 +69,7 @@ class (Monad m) => System m where
hGetLineS :: Handle -> m (Maybe Text)
hCloseS :: Handle -> m ()
openFileS :: Text -> IOMode -> m (Either Text Handle)
+ setCurrentDirS :: FilePath -> m ()
instance System m => System (Lang m) where
systemS proc = lift $ systemS proc
@@ -77,6 +78,7 @@ instance System m => System (Lang m) where
hGetLineS = lift . hGetLineS
hCloseS = lift . hCloseS
openFileS f mode = lift $ openFileS f mode
+ setCurrentDirS = lift . setCurrentDirS
instance System IO where
systemS = createProcess
@@ -92,6 +94,8 @@ instance System IO where
hCloseS = hClose
openFileS f mode = catch (Right <$> openFile (toS f) mode)
(\e -> pure . Left $ show (e :: IOException))
+ setCurrentDirS = setCurrentDirectory
+
instance System m => System (InputT m) where
systemS proc = lift $ systemS proc
@@ -100,6 +104,7 @@ instance System m => System (InputT m) where
hGetLineS = lift . hGetLineS
hCloseS = lift . hCloseS
openFileS f mode = lift $ openFileS f mode
+ setCurrentDirS = lift . setCurrentDirS
class Monad m => CurrentTime m where
currentTime :: m UTCTime
diff --git a/src/Radicle/Internal/Pretty.hs b/src/Radicle/Internal/Pretty.hs
index 5c32303..6e3cb3b 100644
--- a/src/Radicle/Internal/Pretty.hs
+++ b/src/Radicle/Internal/Pretty.hs
@@ -105,7 +105,7 @@ instance PrettyV r => PrettyV (LangErrorData r) where
WrongNumberOfArgs t x y -> "Wrong number of args in" <+> pretty t
<+> "Expected:" <+> pretty x
<+> "Got:" <+> pretty y
- NonHashableKey -> "Non-hashable key in dict."
+ NonHashableKey k -> "Non-hashable key in dict:" <+> prettyV k
ModuleError me -> case me of
MissingDeclaration -> "Modules must start with a metadata declaration"
InvalidDeclaration t decl -> vsep
diff --git a/src/Radicle/Internal/PrimFns.hs b/src/Radicle/Internal/PrimFns.hs
index d4e21c5..b6a6c1b 100644
--- a/src/Radicle/Internal/PrimFns.hs
+++ b/src/Radicle/Internal/PrimFns.hs
@@ -374,7 +374,7 @@ purePrimFns = fromList $ allDocs $
(k, v, Dict m) ->
if hashable k
then pure . Dict $ Map.insert k v m
- else throwErrorHere NonHashableKey
+ else throwErrorHere $ NonHashableKey k
(_, _, v) -> throwErrorHere $ TypeError "insert" 2 TDict v
)
, ( "delete"
@@ -719,7 +719,11 @@ data ImportQual = Unqualified | FullyQualified | Qualified Ident
-- * Helpers
--- Many primFns have a single argument.
+noArg :: Monad m => Text -> Lang m Value -> [Value] -> Lang m Value
+noArg fname f = \case
+ [] -> f
+ xs -> throwErrorHere $ WrongNumberOfArgs fname 0 (length xs)
+
oneArg :: Monad m => Text -> (Value -> Lang m Value) -> [Value] -> Lang m Value
oneArg fname f = \case
[x] -> f x
diff --git a/test/all.rad b/test/all.rad
index 7c70611..d69f93e 100755
--- a/test/all.rad
+++ b/test/all.rad
@@ -8,6 +8,7 @@
(load! (find-module-file! "monadic/diff.rad"))
(load! (find-module-file! "monadic/issues.rad"))
(load! (find-module-file! "monadic/names.rad"))
+(load! (find-module-file! "monadic/project.rad"))
(import prelude/test)
diff --git a/test/spec/Radicle/Internal/TestCapabilities.hs b/test/spec/Radicle/Internal/TestCapabilities.hs
index 14592dd..d88159b 100644
--- a/test/spec/Radicle/Internal/TestCapabilities.hs
+++ b/test/spec/Radicle/Internal/TestCapabilities.hs
@@ -177,3 +177,4 @@ instance System (StateT WorldState IO) where
hGetLineS = lift . hGetLineS
hCloseS = lift . hCloseS
openFileS a b = lift $ openFileS a b
+ setCurrentDirS = lift . setCurrentDirS
diff --git a/test/spec/Radicle/Tests.hs b/test/spec/Radicle/Tests.hs
index c8dd87b..78d10e2 100644
--- a/test/spec/Radicle/Tests.hs
+++ b/test/spec/Radicle/Tests.hs
@@ -149,7 +149,9 @@ test_eval =
prog3 `succeedsWith` String "b"
, testCase "dict keys should be hashable" $ do
- let f x = x `failsWith` NonHashableKey
+ let f x = case noStack (runPureCode x) of
+ Left (NonHashableKey _) -> True @?= True
+ _ -> assertFailure "Expected NonHashableKey"
f "(insert (ref 0) 1 {})"
f "{(ref 0) 1}"
"(lookup :k {'(fn [x] y) 1 :k :v})" `succeedsWith` Keyword [ident|v|]