From c6427c1373486a224998f12ce6a9e0a58813edb3 Mon Sep 17 00:00:00 2001 From: guns Date: Tue, 20 Aug 2013 19:02:25 -0500 Subject: [PATCH] Use optparse-clj for nice CLI options processing Allows GNU style options clumping: $ bin/frak -ec foo bar baz ^(ba[rz]|foo)$ And nice failure messages: $ bin/frak foo bar baz --evil Failed to parse `--evil`: Invalid option --- project.clj | 3 ++- src/cljx/frak/cli.cljx | 51 +++++++++++++----------------------------- 2 files changed, 17 insertions(+), 37 deletions(-) diff --git a/project.clj b/project.clj index 0030ec1..22fd846 100644 --- a/project.clj +++ b/project.clj @@ -4,7 +4,8 @@ :license {:name "Eclipse Public License" :url "http://www.eclipse.org/legal/epl-v10.html"} :jar-exclusions [#"(?:\.(?:cljx|sw[onp])|cli\.cljs?)"] - :dependencies [[org.clojure/clojure "1.5.1"]] + :dependencies [[org.clojure/clojure "1.5.1"] + [guns.cli/optparse "1.1.1"]] :plugins [[lein-cljsbuild "0.3.2"] [com.keminglabs/cljx "0.3.0"]] :source-paths ["src/cljx"] diff --git a/src/cljx/frak/cli.cljx b/src/cljx/frak/cli.cljx index d8cd6ff..606d66b 100644 --- a/src/cljx/frak/cli.cljx +++ b/src/cljx/frak/cli.cljx @@ -1,6 +1,7 @@ (ns frak.cli "Command line interface." (:require [clojure.string :as string] + [guns.cli.optparse :as o] [frak])) ;;;; Utilities @@ -32,45 +33,23 @@ ;;;; Main (def main-flags - [[["-e" "--exact"] "Generated pattern requires an exact match"] - [["-c" "--capture"] "Generated pattern captures"] - [["-h" "--help"] "Display this help message"]]) - -(defn flag-val [s] - (condp re-seq s - #"-(?:e|-exact)" {:exact? true} - #"-(?:c|-capture)" {:capture? true} - #"-(?:h|-help)" {:help? true} - {})) - -(defn flags->opts [flags] - (reduce - (fn [m flag] - (merge m (flag-val flag))) - {} - flags)) - -(def summary - (reduce - (fn [message [flags info]] - (format "%s\t%s\t%s\n" message (string/join ", " flags) info)) - "Usage: frak \n\n" - main-flags)) - -(defn parse-args [args] - (let [flag? (->> (mapcat first main-flags) - (frak/pattern) - (partial re-matches))] - (split-with flag? args))) + [["-e" "--exact" "Generated pattern requires an exact match" + :key :exact?] + ["-c" "--capture" "Generated pattern captures" + :key :capture?] + ["-h" "--help" "Display this help message"]]) (defn -main "Passes arguments to frak/pattern" [& args] - (let [[flags words] (parse-args args) - opts (flags->opts flags)] - (if (or (empty? args) (:help? opts)) - (log summary) - (log (frak/string-pattern words opts))) - (exit 0))) + (try + (let [[opts words summary] (o/parse args main-flags)] + (if (or (empty? words) (:help opts)) + (log (str "Usage: frak \n\nFlags:\n" summary)) + (log (frak/string-pattern words (select-keys opts [:exact? :capture?])))) + (exit 0)) + (catch #+clj AssertionError #+cljs js/Error e + (log (#+clj .getMessage #+cljs .-message e)) + (exit 1)))) #+cljs (set! *main-cli-fn* -main) -- 2.25.1