简体   繁体   中英

clojure core.tools.cli: How to override boolean option?

I want a command that takes arguments which look like this:

--enable-boolean-flag --disable-boolean-flag --enable-boolean-flag

In the :options key returned by clojure.tools.cli/parse-opts , I want to have the :boolean-flag option set to true if the --enable-boolean-flag option came last on the command line and false if --disable-boolean-flag came last on the command line, if that makes any sense.

Any ideas?

EDIT: I'm using 0.3.6 of the core.tools.cli library.

You can achieve this by taking advantage of :id , :default , and :assoc-fn properties that tools-cli lets you specify for each command line option.

  • Use :id to set the same id for "--enable" and "--disable" options
  • Use :default on one of the options to specify what you want to happen if neither "--enable" or "--disable" are specified
  • Use :assoc-fn to specify what effect the option has on the options map. You want the value set to false every time "--disable" appears and to true every time --enable appears.

Putting it all together:

(ns clis.core
  (:require [clojure.tools.cli :refer [parse-opts]])
  (:gen-class))

(def cli-options
  [["-e" "--enable" "Enable"
    :default true
    :id :boolean-flag
    :assoc-fn (fn [m k _] (assoc m k true))]
   ["-d" "--disable" "Disable"
    :id :boolean-flag
    :assoc-fn (fn [m k _] (assoc m k false))]])

(defn -main [& args]
  (parse-opts args cli-options))

Testing at the REPL:

(-main)
;; {:options {:boolean-flag true}, :arguments [], :summary "  -e, --enable   Enable\n  -d, --disable  Disable", :errors nil}
(-main "-e" "-d" "-e")
;; {:options {:boolean-flag true}, :arguments [], :summary "  -e, --enable   Enable\n  -d, --disable  Disable", :errors nil}
(-main "-e" "-d" "-e" "-d")
;; {:options {:boolean-flag false}, :arguments [], :summary "  -e, --enable   Enable\n  -d, --disable  Disable", :errors nil}

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