Skip to content

Commit

Permalink
Expose matched commands in :no-match and :input-exhausted error cases…
Browse files Browse the repository at this point in the history
… for dispatch (#93)

* Refactor

* Expose matched cmds as :dispatch in :no-match and :input-exhausted errors

* Add test
  • Loading branch information
Sohalt committed Mar 15, 2024
1 parent 05868bf commit acdde51
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 11 deletions.
20 changes: 10 additions & 10 deletions src/babashka/cli.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -644,29 +644,29 @@
{:error :no-match
:wrong-input arg
:available-commands (keys (:cmd cmd-info))
:dispatch cmds
:opts (dissoc all-opts ::opts-by-cmds)}
{:error :input-exhausted
:available-commands (keys (:cmd cmd-info))
:dispatch cmds
:opts (dissoc all-opts ::opts-by-cmds)})))))))

(defn- dispatch-tree
([tree args]
(dispatch-tree tree args nil))
([tree args opts]
(let [{:as res :keys [cmd-info error wrong-input available-commands]}
(let [{:as res :keys [cmd-info error available-commands]}
(dispatch-tree' tree args opts)
error-fn* (or (:error-fn opts)
error-fn (or (:error-fn opts)
(fn [{:keys [msg] :as data}]
(throw (ex-info msg data))))
error-fn (fn [data]
(-> {;; :tree tree
:type :org.babashka/cli
:wrong-input wrong-input :all-commands available-commands}
(merge data)
error-fn*))]
(throw (ex-info msg data))))]
(case error
(:no-match :input-exhausted)
(error-fn {:cause error :opts (:opts res)})
(error-fn (merge
{:type :org.babashka/cli
:cause error
:all-commands available-commands}
(select-keys res [:wrong-input :opts :dispatch])))
nil ((:fn cmd-info) (dissoc res :cmd-info))))))

(defn dispatch
Expand Down
7 changes: 6 additions & 1 deletion test/babashka/cli_test.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,12 @@
(is (= {:dispatch ["foo" "bar"], :opts {:version "2000"}, :args ["some-arg"]}
(-> (cli/dispatch
table
["foo" "bar" "--version" "2000" "some-arg"]))))))))
["foo" "bar" "--version" "2000" "some-arg"])))))
(testing "dispatch errors return :dispatch key"
(is (= {:type :org.babashka/cli, :dispatch ["foo" "bar"], :all-commands '("baz"), :cause :input-exhausted, :opts {}}
(cli/dispatch [{:cmds ["foo" "bar" "baz"] :fn identity}] ["foo" "bar"] {:error-fn identity})))
(is (= {:type :org.babashka/cli, :dispatch ["foo" "bar"], :wrong-input "wrong", :all-commands '("baz"), :cause :no-match, :opts {}}
(cli/dispatch [{:cmds ["foo" "bar" "baz"] :fn identity}] ["foo" "bar" "wrong"] {:error-fn identity})))))))

(deftest table->tree-test
(testing "internal represenation"
Expand Down

0 comments on commit acdde51

Please sign in to comment.