Skip to content

Commit

Permalink
Support commands with arguments and subcommands at the same time
Browse files Browse the repository at this point in the history
  • Loading branch information
plexus committed May 24, 2024
1 parent 69ac086 commit e967e9c
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 12 deletions.
5 changes: 1 addition & 4 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,7 @@
## Added

- Added `:required` for `:flags`

## Fixed

## Changed
- Support commands with arguments and subcommands at the same time

# 0.7.33 (2024-02-27 / cb19704)

Expand Down
10 changes: 8 additions & 2 deletions repl_sessions/test_scratch.clj
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
(ns test-scratch
(:require [clojure.test :as t]))
(ns lambdaisland.cli.test-scratch
(:require
[lambdaisland.cli :as cli]))



Expand Down Expand Up @@ -226,3 +227,8 @@

;; :flags
;; ["-v,--verbose" {:description "Increase verbosity"}]})

(def s
{:commands ["foo ARG" {:commands ["baz" prn]}]})

(cli/dispatch* s ["foo" "XXX" "baz"])
21 changes: 15 additions & 6 deletions src/lambdaisland/cli.clj
Original file line number Diff line number Diff line change
Expand Up @@ -338,7 +338,7 @@
(print-help program-name doc [] flagpairs)
(binding [*opts* (-> opts
(dissoc ::middleware)
(assoc ::argv pos-args)
(update ::argv (fnil into []) pos-args)
(merge (zipmap argnames pos-args)))]
(if-let [missing (missing-flags flagmap opts)]
(parse-error! "Missing required flags:" (->> missing (map #(str/join " " %)) (str/join ", ")))
Expand All @@ -350,13 +350,22 @@
cmd (when cmd (first (str/split cmd #"[ =]")))
opts (if cmd (update opts ::command (fnil conj []) cmd) opts)
command-pairs (prepare-cmdpairs commands)
command-map (into {} command-pairs)
command-match (get command-map cmd)]

command-map (update-keys (into {} command-pairs)
#(first (str/split % #"[ =]")))
command-match (get command-map cmd)
argnames (:argnames command-match)
arg-count (count argnames)]
(cond
command-match
(dispatch* (assoc (merge (dissoc cmdspec :command :commands) command-match)
:name (str program-name " " cmd)) pos-args opts)
(dispatch*
(-> cmdspec
(dissoc :command :commands)
(merge command-match)
(assoc :name (str program-name " " cmd)))
(drop arg-count pos-args)
(-> opts
(update ::argv (fnil into []) (take arg-count pos-args))
(merge (zipmap argnames pos-args))))

(or (nil? command-match)
(nil? commands)
Expand Down

0 comments on commit e967e9c

Please sign in to comment.