Skip to content
Browse files

Add cli/summarize

Default options summary generation function. More minimal than
cli/banner-for, and also does not handle any other text besides the
options summary.
  • Loading branch information...
1 parent 0caf5d4 commit 69f0451d224692631d39957dad87aa3481cad4cb @guns guns committed Dec 3, 2013
Showing with 52 additions and 1 deletion.
  1. +23 −0 src/main/clojure/clojure/tools/cli.clj
  2. +29 −1 src/test/clojure/clojure/tools/cli_test.clj
View
23 src/main/clojure/clojure/tools/cli.clj
@@ -347,3 +347,26 @@
[m (conj errors error)]))
[m (conj errors (str "Unknown option: " (pr-str opt)))]))
[(default-option-map specs) []] tokens))
+
+(defn- summarize
+ "Reduce options specs into a options summary for printing at a terminal."
+ [specs]
+ (let [all-boolean? (every? (comp not :required) specs)
+ parts (map (fn [{:keys [short-opt long-opt required default default-desc desc]}]
+ (let [opt (cond (and short-opt long-opt) (str short-opt ", " long-opt)
+ long-opt (str " " long-opt)
+ short-opt short-opt)
+ [opt dd] (if required
+ [(str opt \space required) (or default-desc (if default (str default) ""))]
+ [opt ""])]
+ (if all-boolean?
+ [opt (or desc "")]
+ [opt dd (or desc "")])))
+ specs)
+ cl-fmt (if all-boolean?
+ "~{ ~vA ~vA~}"
+ "~{ ~vA ~vA ~vA~}")
+ lens (apply map (fn [& cols] (apply max (map count cols))) parts)
+ lines (map #(s/trimr (cl-format nil cl-fmt (interleave lens %)))
+ parts)]
+ (s/join \newline lines)))
View
30 src/test/clojure/clojure/tools/cli_test.clj
@@ -1,5 +1,5 @@
(ns clojure.tools.cli-test
- (:use [clojure.string :only [split]]
+ (:use [clojure.string :only [join split]]
[clojure.test :only [deftest is testing]]
[clojure.tools.cli :as cli :only [cli]]))
@@ -273,3 +273,31 @@
[:short-opt "-v"]
[:long-opt "--verbose"]])
[{:alpha true :verbose 3} []])))))
+
+(def summarize
+ #'cli/summarize)
+
+(deftest test-summarize
+ (testing "summarizes options"
+ (is (= (summarize (compile-option-specs
+ [["-s" "--server HOST" "Upstream server"
+ :default :some-object-whose-string-representation-is-awful
+ :default-desc "example.com"]
+ ["-p" "--port=PORT" "Upstream port number"
+ :default 80]
+ ["-o" nil "Output file"
+ :id :output
+ :required "PATH"]
+ ["-v" nil "Verbosity level; may be specified more than once"
+ :id :verbose
+ :default 0]
+ [nil "--help"]]))
+ (join \newline
+ [" -s, --server HOST example.com Upstream server"
+ " -p, --port PORT 80 Upstream port number"
+ " -o PATH Output file"
+ " -v Verbosity level; may be specified more than once"
+ " --help"]))))
+ (testing "does not print :default column when all options are boolean"
+ (is (= (summarize (compile-option-specs [["-m" "--minimal" "A minimal option summary"]]))
+ " -m, --minimal A minimal option summary"))))

0 comments on commit 69f0451

Please sign in to comment.
Something went wrong with that request. Please try again.