您可以利用工具-cli允許您爲每個命令行選項指定的:id
,:default
和:assoc-fn
屬性來實現此目的。
- 使用
:id
設置相同的ID爲「--enable」和「 - 禁用」選項
- 上的一個選項使用
:default
指定要如果沒有「--enable」發生什麼或「--disable」被指定
- 使用
:assoc-fn
指定該選項對選項圖有什麼影響。每次出現「--disable」時,您都希望將值設置爲false
,並且每次出現--enable
時都要true
。
全部放在一起:
(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))
測試在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}
使用相同ID拋出一個錯誤,不是嗎?我認爲每個參數的ID必須是唯一的。 – djhaskin987
情況並非如此。我包含的代碼作品。另請參閱[docstring for parse-opts](https://github.com/clojure/tools.cli/blob/master/src/main/clojure/clojure/tools/cli.clj#L498)。它特別指出,多個選項條目可以共享相同的':id' – ez121sl