Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
97 changes: 80 additions & 17 deletions src/yetibot/core/commands/collections.clj
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
[yetibot.core.chat :refer [chat-data-structure]]
[yetibot.core.hooks :refer [cmd-hook]]
[yetibot.core.interpreter :refer [handle-cmd *contextual-data*]]
[yetibot.core.parser :as parser]
[yetibot.core.models.users :refer [min-user-keys]]
[yetibot.core.util
:refer
Expand Down Expand Up @@ -156,6 +157,68 @@

; xargs
; example usage: !users | xargs attack
(defn- subexpr-open-index
"Index of the first $( that is not inside a quoted literal, else nil."
[s]
(loop [i 0 in-q nil]
(cond
(>= i (count s)) nil
(and in-q (= (nth s i) in-q)) (recur (inc i) nil)
in-q (recur (inc i) in-q)
(or (= (nth s i) \") (= (nth s i) \')) (recur (inc i) (nth s i))
(and (< (inc i) (count s))
(= (subs s i (+ i 2)) "$(")) i
:else (recur (inc i) nil))))

(defn- subexpr-close-index
"Index of the ) matching the ( that opens at `open` (position of its $),
accounting for nesting and quoted literals. Nil when unbalanced."
[s open]
(loop [i (+ open 2) depth 1 in-q nil]
(if (>= i (count s))
nil
(let [c (subs s i (inc i))]
(cond
(and in-q (= c in-q)) (recur (inc i) depth nil)
in-q (recur (inc i) depth in-q)
(or (= c "\"") (= c "'")) (recur (inc i) depth c)
(= c "(") (recur (inc i) (inc depth) nil)
(= c ")") (if (= 1 depth) i (recur (inc i) (dec depth) nil))
:else (recur (inc i) depth nil))))))

(defn late-eval-sub-exprs
"Sub-expressions within an xargs stage arrive unevaluated: the interpreter
skips their normal depth-first evaluation so that xargs can evaluate them
here, once per item, with `*contextual-data*` bound to the item's data.
See https://github.com/yetibot/yetibot/issues/995

repeat 3 | xargs echo `random` ;=> three distinct values
!karma | xargs echo score of `render {{score}}`

Only the $(..) groups are evaluated and substituted; the surrounding
command text is left for xargs to dispatch per item. Returns the args
unchanged when they contain no sub-expressions (the common case), and a
sub-expression that fails to evaluate is replaced with its error message.
Literal $( inside quoted strings is respected."
[args]
(if (or (s/blank? args) (not (s/includes? args "$(")))
args
(try
(loop [remaining args out []]
(if-let [open (subexpr-open-index remaining)]
(if-let [close (subexpr-close-index remaining open)]
(let [inner (subs remaining (+ open 2) close)
{:keys [value error]} (parser/parse-and-eval inner)
replacement (str (or error value))]
(recur (subs remaining (inc close))
(conj out (subs remaining 0 open) replacement)))
;; unbalanced $( ; drop the marker and keep scanning
(recur (str (subs remaining 0 open) (subs remaining (+ open 2))) out))
(apply str (concat out [remaining]))))
(catch Exception e
(debug "xargs late sub-expression evaluation failed:" (pr-str e))
args))))

(defn xargs
"xargs <cmd> <list> # run <cmd> for every item in <list> in parallel; behavior is similar to xargs(1)'s xargs -n1"
{:yb/cat #{:util :collection}}
Expand Down Expand Up @@ -191,24 +254,24 @@
:params-with-data params-with-data})

cmd-result
;; allow the data to "leak" into sub commands of the
;; expression passed to xargs - although at this point
;; those subcommands would have been evaluated too early,
;; so this achieves nothing. perhaps it will be useful in
;; the future. see this issue for more info:
;; https://github.com/yetibot/yetibot/issues/995
;; sub-expressions in the expression passed to xargs are
;; evaluated here, once per item, with the item's data
;; available as contextual data (late evaluation).
;; Previously they were evaluated too early, before the
;; items existed. See issue #995.
(binding [*contextual-data* possible-data]
(info "inner contextual-data" *contextual-data*)
(apply
handle-cmd
;; item could be a collection, such as when xargs is
;; used on nested collections, e.g.:
;; repeat 5 jargon | xargs words | xargs head
(if (coll? item)
[args (merge params-with-data {:raw item :opts item})]
[(format/pseudo-format args
(execution/operand item execution/*value-origin*))
(merge params-with-data {:raw item :opts nil})])))
(let [late-args (late-eval-sub-exprs args)]
(info "late-evaluated xargs args" (pr-str late-args))
(apply
handle-cmd
;; item could be a collection, such as when xargs is
;; used on nested collections, e.g.:
;; repeat 5 jargon | xargs words | xargs head
(if (coll? item)
[late-args (merge params-with-data {:raw item :opts item})]
[(format/pseudo-format late-args
(execution/operand item execution/*value-origin*))
(merge params-with-data {:raw item :opts nil})]))))

_ (debug "xargs cmd-result" (pr-str cmd-result))]
(if (map? cmd-result)
Expand Down
21 changes: 20 additions & 1 deletion src/yetibot/core/interpreter.clj
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,22 @@
;; return nothing when fallbacks are disabled
(suppress {})))

(defn- deferred-xargs-stage?
"When an xargs stage contains sub-expressions, defer their evaluation until
the items are known so each item gets its own evaluation (or none at all),
instead of one early evaluation shared by every iteration.

Detected structurally from the stage's parse tree; the stage is then
dispatched with its raw text (sub-expressions intact, rendered in $(..)
form) so the xargs command receives them unevaluated and can evaluate them
per item. See https://github.com/yetibot/yetibot/issues/995"
[cmd-ast]
(when (some #(and (vector? %) (= :sub-expr (first %)))
(tree-seq vector? rest cmd-ast))
(when-let [raw (first (unparse-transformer [cmd-ast]))]
(when (re-find #"(?s)^\s*xargs(\s|$)" (str raw))
(str raw)))))

(defn pipe-cmds
"Pipe acc into cmd-with-args by either appending or sending acc as an extra
:opts"
Expand Down Expand Up @@ -96,7 +112,10 @@
execution/*value-origin* (or (execution/origin-of acc)
execution/*value-origin*)]
(debug "piping with *contextual-data*" *contextual-data*)
(let [cmd-with-args (evaluator cmd-ast)
(let [;; sub-expressions inside an xargs stage must not be evaluated
;; here; xargs re-evaluates them per item. See issue #995.
cmd-with-args (or (deferred-xargs-stage? cmd-ast)
(evaluator cmd-ast))

;; the result of a commad handler can either be:
;; - the literal value itself
Expand Down
40 changes: 40 additions & 0 deletions test/yetibot/core/test/commands/collections.clj
Original file line number Diff line number Diff line change
Expand Up @@ -390,3 +390,43 @@
(fact
"using 'repeat' collections command on 'range 5' (an odd number of elements), it should succeed and not throw No value supplied"
value => [["0" "1" "2" "3" "4"] ["0" "1" "2" "3" "4"]])))

(facts "late-eval-sub-exprs (issue #995)"
(fact "args without sub-expressions pass through unchanged"
(colls/late-eval-sub-exprs "echo hello") => "echo hello"
(colls/late-eval-sub-exprs "") => ""
(colls/late-eval-sub-exprs nil) => nil)

(fact "quoted literals containing $( are left alone"
(colls/late-eval-sub-exprs "echo \"cost is $(1)\"") => "echo \"cost is $(1)\""
(colls/late-eval-sub-exprs "echo 'literal $(foo) bar'") => "echo 'literal $(foo) bar'")

(fact "a sub-expression is evaluated once and substituted in place"
(let [calls (atom 0)
stub (fn [_] (swap! calls inc) {:value "HI"})]
(with-redefs [yetibot.core.parser/parse-and-eval stub]
(colls/late-eval-sub-exprs "echo item $(echo hi)") => "echo item HI"
@calls => 1)))

(fact "multiple sub-expressions are each evaluated once"
(let [calls (atom 0)
stub (fn [expr] (swap! calls inc) {:value expr})]
(with-redefs [yetibot.core.parser/parse-and-eval stub]
(colls/late-eval-sub-exprs "echo $(a) and $(b)") => "echo a and b"
@calls => 2)))

(fact "nested $(..) groups are handled as one unit"
(let [seens (atom [])
stub (fn [expr] (swap! seens conj expr) {:value "OK"})]
(with-redefs [yetibot.core.parser/parse-and-eval stub]
(colls/late-eval-sub-exprs "echo x $(echo $(inner))") => "echo x OK"
@seens => ["echo $(inner)"])))

(fact "evaluation errors are substituted as the error text"
(with-redefs [yetibot.core.parser/parse-and-eval (constantly {:error "boom"})]
(colls/late-eval-sub-exprs "echo $(bad)") => "echo boom"))

(fact "exceptions during evaluation fall back to the untouched args"
(with-redefs [yetibot.core.parser/parse-and-eval
(fn [_] (throw (ex-info "kaboom" {})))]
(colls/late-eval-sub-exprs "echo $(kaboom)") => "echo $(kaboom)")))