Skip to content

Commit e967e9c

Browse files
committed
Support commands with arguments and subcommands at the same time
1 parent 69ac086 commit e967e9c

3 files changed

Lines changed: 24 additions & 12 deletions

File tree

CHANGELOG.md

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,7 @@
33
## Added
44

55
- Added `:required` for `:flags`
6-
7-
## Fixed
8-
9-
## Changed
6+
- Support commands with arguments and subcommands at the same time
107

118
# 0.7.33 (2024-02-27 / cb19704)
129

repl_sessions/test_scratch.clj

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1-
(ns test-scratch
2-
(:require [clojure.test :as t]))
1+
(ns lambdaisland.cli.test-scratch
2+
(:require
3+
[lambdaisland.cli :as cli]))
34

45

56

@@ -226,3 +227,8 @@
226227

227228
;; :flags
228229
;; ["-v,--verbose" {:description "Increase verbosity"}]})
230+
231+
(def s
232+
{:commands ["foo ARG" {:commands ["baz" prn]}]})
233+
234+
(cli/dispatch* s ["foo" "XXX" "baz"])

src/lambdaisland/cli.clj

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -338,7 +338,7 @@
338338
(print-help program-name doc [] flagpairs)
339339
(binding [*opts* (-> opts
340340
(dissoc ::middleware)
341-
(assoc ::argv pos-args)
341+
(update ::argv (fnil into []) pos-args)
342342
(merge (zipmap argnames pos-args)))]
343343
(if-let [missing (missing-flags flagmap opts)]
344344
(parse-error! "Missing required flags:" (->> missing (map #(str/join " " %)) (str/join ", ")))
@@ -350,13 +350,22 @@
350350
cmd (when cmd (first (str/split cmd #"[ =]")))
351351
opts (if cmd (update opts ::command (fnil conj []) cmd) opts)
352352
command-pairs (prepare-cmdpairs commands)
353-
command-map (into {} command-pairs)
354-
command-match (get command-map cmd)]
355-
353+
command-map (update-keys (into {} command-pairs)
354+
#(first (str/split % #"[ =]")))
355+
command-match (get command-map cmd)
356+
argnames (:argnames command-match)
357+
arg-count (count argnames)]
356358
(cond
357359
command-match
358-
(dispatch* (assoc (merge (dissoc cmdspec :command :commands) command-match)
359-
:name (str program-name " " cmd)) pos-args opts)
360+
(dispatch*
361+
(-> cmdspec
362+
(dissoc :command :commands)
363+
(merge command-match)
364+
(assoc :name (str program-name " " cmd)))
365+
(drop arg-count pos-args)
366+
(-> opts
367+
(update ::argv (fnil into []) (take arg-count pos-args))
368+
(merge (zipmap argnames pos-args))))
360369

361370
(or (nil? command-match)
362371
(nil? commands)

0 commit comments

Comments
 (0)