简体   繁体   中英

How to accept additional arguments for an option in tools.cli?

I'm a Clojure newbie.

I need multiple arguments for option -a of my cli app, like:

java -jar app.jar -a 12 abc xyz

First one is a number, and other two have to be strings.

My code is:

["-a" "--add LINE TYPE ENTRY" "Add entry to specified line number of the menu"
:parse-fn #(split % #" ")
:validate [#(number? (Integer/parseInt (first %))) "ERROR: Invalid position"]

But I observed the % passed to :parse-fn function to be a vector containing only the first argument, ie, [12]

the other arguments are listed as value of the key :arguments of the map returned by parse-opts

Now,
(1) Is there a way to validate those unprocessed arguments?
(2) How will I retrieve and use those arguments?

I think you cannot parse white-space separated values for one option at a time. Normally you would do it like this: -a opt1 -a opt2 -a opt3 , but since you have a different type for opt1 this will not work.

What about separating them by comma?

(require '[clojure.tools.cli :refer [parse-opts]])

(def cli-opts
  [["-a" "--add LINE TYPE ENTRY" "Add entry to specified line number of the menu"
    :parse-fn (fn [a-args]
                (-> a-args
                    (str/split #",")
                    (update 0 #(Integer/parseInt %))))
    :validate [(fn [[num s1 s2]]
                 (and (number? num)
                      (string? s1)
                      (string? s2)))]]])

(parse-opts ["-a" "12,abc,xyz"] cli-opts)

;;=> {:options {:add [12 "abc" "xyz"]}, :arguments [], :summary "  -a, --add LINE TYPE ENTRY  Add entry to specified line number of the menu", :errors nil}

Another option would be to introduce two or three different options for a : --line , --type and --entry .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM