用于解析命令行开关和字符串args的惯用语

时间:2015-05-27 17:52:23

标签: clojure

我想解析命令行字符串,并将任何命令切换为其后续参数。所以,例如:

(parse "git branch -d f1 f2 -a -m message") => 
[["-d" "f1" "f2"]["-a"]["-m" "message"]]

我在切换后不会立即忽略args。

我写的代码如下:

(defn switch? [s] (re-find #"\-+" s))
(defn tokenify [s] (clojure.string/split s #" "))
(defn parse [cmd-str]
  (loop [lst (tokenify cmd-str), acc [], _acc []]
    (let [fs (first lst), rs (rest lst), new? (empty? _acc)]
      (cond (empty? lst) (if new? acc (conj acc _acc))
            (switch? fs) (if new?
                           (recur rs acc (conj _acc fs))
                           (recur rs (conj acc _acc) (conj [] fs)))
            :else (if new?
                    (recur rs acc _acc)
                    (recur rs acc (conj _acc fs)))))))

这样可行,但它的水平相当低且可怕。是否有一种简单的方法可以使用reduce或partition或group-by来使相同的功能更清晰,更具惯用性?

1 个答案:

答案 0 :(得分:2)

这是使用clojure.tools.cli

的基本概要
(def command-line-spec
  [["-m" "--mode 0|1" "description of option that takes 1 or 0"
    :parse-fn #(case (s/lower-case %)
                 ("1" "true" "create") :one
                 ("0" "false" "destroy") :zero
                 :invalid)
    :default :one
    :validate [#{:one :zero} "Unsupported mode"]]
   ["-c" "--config type1|type2|..."
    :desc "config specifies what to do"
    :default :dostuff
    :parse-fn #(if (keyword? %)
                 %
                 (-> % s/lower-case keyword))
    :validate-fn #(contains? configurations %)]
    ["-n" "--name service Name"
     :default (getenv "NAME")]
   [nil "--min number"
    :default 7 :parse-fn #(Integer/parseInt %)]
   [nil "--max number"
    :default 7 :parse-fn #(Integer/parseInt %)]
   [nil "--public true|false" "true or false"
    :default false
    :parse-fn #(Boolean/parseBoolean %)]
   ["-h" "--help"]])

(defn -main [& args]
  (let [{:keys [options arguments errors summary]}
         (parse-opts args
                     command-line-spec)
 ... )