pax_global_header 0000666 0000000 0000000 00000000064 12712503773 0014521 g ustar 00root root 0000000 0000000 52 comment=38c398fbff33351550fab7b7910e822495e472ba
tools.cli-tools.cli-0.3.5/ 0000775 0000000 0000000 00000000000 12712503773 0015340 5 ustar 00root root 0000000 0000000 tools.cli-tools.cli-0.3.5/.gitignore 0000664 0000000 0000000 00000000116 12712503773 0017326 0 ustar 00root root 0000000 0000000 target
.lein-failures
/src/test/clojure/cljs
/.lein-repl-history
/.nrepl-port
tools.cli-tools.cli-0.3.5/CONTRIBUTING.md 0000664 0000000 0000000 00000001220 12712503773 0017564 0 ustar 00root root 0000000 0000000 This is a [Clojure contrib] project.
Under the Clojure contrib [guidelines], this project cannot accept
pull requests. All patches must be submitted via [JIRA].
See [Contributing] and the [FAQ] on the Clojure development [wiki] for
more information on how to contribute.
[Clojure contrib]: http://dev.clojure.org/display/doc/Clojure+Contrib
[Contributing]: http://dev.clojure.org/display/community/Contributing
[FAQ]: http://dev.clojure.org/display/community/Contributing+FAQ
[JIRA]: http://dev.clojure.org/jira/browse/TCLI
[guidelines]: http://dev.clojure.org/display/community/Guidelines+for+Clojure+Contrib+committers
[wiki]: http://dev.clojure.org/
tools.cli-tools.cli-0.3.5/README.md 0000664 0000000 0000000 00000031246 12712503773 0016625 0 ustar 00root root 0000000 0000000 # tools.cli
Tools for working with command line arguments.
## Stable Releases and Dependency Information
Latest stable release: 0.3.5
* [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22tools.cli%22)
* [Development Snapshot Versions](https://oss.sonatype.org/index.html#nexus-search;gav~org.clojure~tools.cli~~~)
[Leiningen](https://github.com/technomancy/leiningen) dependency information:
```clojure
[org.clojure/tools.cli "0.3.5"]
```
[Maven](http://maven.apache.org/) dependency information:
```xml
org.clojure
tools.cli
0.3.5
```
The 0.3.x series of tools.cli features a new flexible API, better adherence
to GNU option parsing conventions, and ClojureScript support.
The function `clojure.tools.cli/cli` has been superseded by
`clojure.tools.cli/parse-opts`, and should not be used in new programs.
The previous function will remain for the forseeable future. It has also been
adapted to use the new tokenizer, so upgrading is still worthwhile even if you
are not ready to migrate to `parse-opts`.
## Quick Start
```clojure
(ns my.program
(:require [clojure.tools.cli :refer [parse-opts]])
(:gen-class))
(def cli-options
;; An option with a required argument
[["-p" "--port PORT" "Port number"
:default 80
:parse-fn #(Integer/parseInt %)
:validate [#(< 0 % 0x10000) "Must be a number between 0 and 65536"]]
;; A non-idempotent option
["-v" nil "Verbosity level"
:id :verbosity
:default 0
:assoc-fn (fn [m k _] (update-in m [k] inc))]
;; A boolean option defaulting to nil
["-h" "--help"]])
(defn -main [& args]
(parse-opts args cli-options))
```
Execute the command line:
my-program -vvvp8080 foo --help --invalid-opt
to produce the map:
```clojure
{:options {:port 8080
:verbosity 3
:help true}
:arguments ["foo"]
:summary " -p, --port PORT 80 Port number
-v Verbosity level
-h, --help"
:errors ["Unknown option: \"--invalid-opt\""]}
```
**Note** that exceptions are _not_ thrown on parse errors, so errors must be
handled explicitly after checking the `:errors` entry for a truthy value.
Please see the [example program](#example-usage) for a more detailed example
and refer to the docstring of `parse-opts` for comprehensive documentation:
http://clojure.github.io/tools.cli/index.html#clojure.tools.cli/parse-opts
## New Features in 0.3.x
### Better Option Tokenization
In accordance with the [GNU Program Argument Syntax Conventions][GNU], two
features have been added to the options tokenizer:
* Short options may be grouped together.
For instance, `-abc` is equivalent to `-a -b -c`. If the `-b` option
requires an argument, the same `-abc` is interpreted as `-a -b "c"`.
* Long option arguments may be specified with an equals sign.
`--long-opt=ARG` is equivalent to `--long-opt "ARG"`.
If the argument is omitted, it is interpreted as the empty string.
e.g. `--long-opt=` is equivalent to `--long-opt ""`
[GNU]: https://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html
### In-order Processing for Subcommands
Large programs are often divided into subcommands with their own sets of
options. To aid in designing such programs, `clojure.tools.cli/parse-opts`
accepts an `:in-order` option that directs it to stop processing arguments at
the first unrecognized token.
For instance, the `git` program has a set of top-level options that are
unrecognized by subcommands and vice-versa:
git --git-dir=/other/proj/.git log --oneline --graph
By default, `clojure.tools.cli/parse-opts` interprets this command line as:
options: [[--git-dir /other/proj/.git]
[--oneline]
[--graph]]
arguments: [log]
When :in-order is true however, the arguments are interpreted as:
options: [[--git-dir /other/proj/.git]]
arguments: [log --oneline --graph]
Note that the options to `log` are not parsed, but remain in the unprocessed
arguments vector. These options could be handled by another call to
`parse-opts` from within the function that handles the `log` subcommand.
### Options Summary
`parse-opts` returns a minimal options summary string:
-p, --port NUMBER 8080 Required option with default
--host HOST localhost Short and long options may be omitted
-d, --detach Boolean option
-h, --help
This may be inserted into a larger usage summary, but it is up to the caller.
If the default formatting of the summary is unsatisfactory, a `:summary-fn`
may be supplied to `parse-opts`. This function will be passed the sequence
of compiled option specification maps and is expected to return an options
summary.
The default summary function `clojure.tools.cli/summarize` is public and may
be useful within your own `:summary-fn` for generating the default summary.
### Option Argument Validation
There is a new option entry `:validate`, which takes a tuple of
`[validation-fn validation-msg]`. The validation-fn receives an option's
argument *after* being parsed by `:parse-fn` if it exists.
["-p" "--port PORT" "A port number"
:parse-fn #(Integer/parseInt %)
:validate [#(< 0 % 0x10000) "Must be a number between 0 and 65536"]]
If the validation-fn returns a falsy value, the validation-msg is added to the
errors vector.
### Error Handling and Return Values
Instead of throwing errors, `parse-opts` collects error messages into a vector
and returns them to the caller. Unknown options, missing required arguments,
validation errors, and exceptions thrown during `:parse-fn` are all added to
the errors vector.
Correspondingly, `parse-opts` returns the following map of values:
{:options A map of default options merged with parsed values from the command line
:arguments A vector of unprocessed arguments
:summary An options summary string
:errors A vector of error messages, or nil if no errors}
During development, parse-opts asserts the uniqueness of option `:id`,
`:short-opt`, and `:long-opt` values and throws an error on failure.
### ClojureScript Support
The `cljs.tools.cli` namespace is available for use in ClojureScript programs!
Both `parse-opts` and `summarize` have been ported, and have complete feature
parity with their Clojure counterparts.
ClojureScript Versions `0.0-2080` and above are supported, but earlier
versions are likely to work as well.
## Example Usage
```clojure
(ns cli-example.core
(:require [cli-example.server :as server]
[clojure.string :as string]
[clojure.tools.cli :refer [parse-opts]])
(:import (java.net InetAddress))
(:gen-class))
(def cli-options
[;; First three strings describe a short-option, long-option with optional
;; example argument description, and a description. All three are optional
;; and positional.
["-p" "--port PORT" "Port number"
:default 80
:parse-fn #(Integer/parseInt %)
:validate [#(< 0 % 0x10000) "Must be a number between 0 and 65536"]]
["-H" "--hostname HOST" "Remote host"
:default (InetAddress/getByName "localhost")
;; Specify a string to output in the default column in the options summary
;; if the default value's string representation is very ugly
:default-desc "localhost"
:parse-fn #(InetAddress/getByName %)]
;; If no required argument description is given, the option is assumed to
;; be a boolean option defaulting to nil
[nil "--detach" "Detach from controlling process"]
["-v" nil "Verbosity level; may be specified multiple times to increase value"
;; If no long-option is specified, an option :id must be given
:id :verbosity
:default 0
;; Use assoc-fn to create non-idempotent options
:assoc-fn (fn [m k _] (update-in m [k] inc))]
["-h" "--help"]])
(defn usage [options-summary]
(->> ["This is my program. There are many like it, but this one is mine."
""
"Usage: program-name [options] action"
""
"Options:"
options-summary
""
"Actions:"
" start Start a new server"
" stop Stop an existing server"
" status Print a server's status"
""
"Please refer to the manual page for more information."]
(string/join \newline)))
(defn error-msg [errors]
(str "The following errors occurred while parsing your command:\n\n"
(string/join \newline errors)))
(defn exit [status msg]
(println msg)
(System/exit status))
(defn -main [& args]
(let [{:keys [options arguments errors summary]} (parse-opts args cli-options)]
;; Handle help and error conditions
(cond
(:help options) (exit 0 (usage summary))
(not= (count arguments) 1) (exit 1 (usage summary))
errors (exit 1 (error-msg errors)))
;; Execute program with options
(case (first arguments)
"start" (server/start! options)
"stop" (server/stop! options)
"status" (server/status! options)
(exit 1 (usage summary)))))
```
## Developer Information
* [GitHub project](https://github.com/clojure/tools.cli)
* [Bug Tracker](http://dev.clojure.org/jira/browse/TCLI)
* [Continuous Integration](http://build.clojure.org/job/tools.cli/)
* [Compatibility Test Matrix](http://build.clojure.org/job/tools.cli-test-matrix/)
## Change Log
* Release 0.3.5 on 2016-05-04
* Fix `summarize` in cljs after renaming during TCLI-36 below
[TCLI-85](http://dev.clojure.org/jira/browse/TCLI-85).
* Release 0.3.4 on 2016-05-01
* Clarify use of `summarize` via expanded docstring and make both of the
functions it calls public so it is easier to build your own `:summary-fn`.
[TCLI-36](http://dev.clojure.org/jira/browse/TCLI-36).
* Release 0.3.3 on 2015-08-21
* Add `:missing` to option specification to produce the given error message
if the option is not provided (and has no default value).
[TCLI-12](http://dev.clojure.org/jira/browse/TCLI-12)
* Add `:strict` to `parse-opts`:
If true, treats required option arguments that match other options as a
parse error (missing required argument).
[TCLI-10](http://dev.clojure.org/jira/browse/TCLI-10)
* Release 0.3.2 on 2015-07-28
* Add `:no-defaults` to `parse-opts`:
Returns sequence of options that excludes defaulted ones. This helps
support constructing options from multiple sources (command line, config file).
* Add `get-default-options`:
Returns sequence of options that have defaults specified.
* Support multiple validations [TCLI-9](http://dev.clojure.org/jira/browse/TCLI-9)
* Support in-order arguments [TCLI-5](http://dev.clojure.org/jira/browse/TCLI-5):
`:in-order` processes arguments up to the first unknown option;
A warning is displayed when unknown options are encountered.
* Release 0.3.1 on 2014-01-02
* Apply patch for [TCLI-8](http://dev.clojure.org/jira/browse/TCLI-8):
Correct test that trivially always passes
* Apply patch for [TCLI-7](http://dev.clojure.org/jira/browse/TCLI-7):
summarize throws when called with an empty sequence of options
* Release 0.3.0 on 2013-12-15
* Add public functions `parse-opts` and `summarize` to supersede `cli`,
addressing [TCLI-3](http://dev.clojure.org/jira/browse/TCLI-3),
[TCLI-4](http://dev.clojure.org/jira/browse/TCLI-4), and
[TCLI-6](http://dev.clojure.org/jira/browse/TCLI-6)
* Add ClojureScript port of `parse-opts` and `summarize`, available in
`cljs.tools.cli`.
* Move extra documentation of `cli` function to
https://github.com/clojure/tools.cli/wiki/Documentation-for-0.2.4
* Release 0.2.4 on 2013-08-06
* Applying patch for [TCLI-2](http://dev.clojure.org/jira/browse/TCLI-2)
(support an assoc-fn option)
* Release 0.2.3 on 2013-08-06
* Add optional description string to prefix the returned banner
* Release 0.2.2 on 2012-08-09
* Applying patch for [TCLI-1](http://dev.clojure.org/jira/browse/TCLI-1)
(do not include keys when no value provided by :default)
* Release 0.2.1 on 2011-11-03
* Removing the :required option. Hangover from when -h and --help were
implemented by default, causes problems if you want help and dont
provide a :required argument.
* Release 0.2.0 on 2011-10-31
* Remove calls to System/exit
* Remove built-in help options
* Release 0.1.0
* Initial import of Clargon codebase
## License
Copyright (c) Rich Hickey and contributors. All rights reserved.
The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
which can be found in the file epl.html at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software.
tools.cli-tools.cli-0.3.5/dalap_rules.clj 0000664 0000000 0000000 00000000563 12712503773 0020331 0 ustar 00root root 0000000 0000000 ;; This file directs the generation of the CLJS test namespace. The main CLJ
;; and CLJS clojure.tools.cli files are hand-crafted.
;;
;; http://birdseyesoftware.github.io/lein-dalap.docs/articles/getting_started.html#specifying_which_files_you_want_to_transform_to_cljs
{["src/test/clojure/clojure/tools/cli_test.clj"
"src/test/clojure/cljs/tools/cli_test.cljs"]
[]}
tools.cli-tools.cli-0.3.5/epl.html 0000664 0000000 0000000 00000030536 12712503773 0017015 0 ustar 00root root 0000000 0000000
Eclipse Public License - Version 1.0
Eclipse Public License - v 1.0
THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE
PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR
DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS
AGREEMENT.
1. DEFINITIONS
"Contribution" means:
a) in the case of the initial Contributor, the initial
code and documentation distributed under this Agreement, and
b) in the case of each subsequent Contributor:
i) changes to the Program, and
ii) additions to the Program;
where such changes and/or additions to the Program
originate from and are distributed by that particular Contributor. A
Contribution 'originates' from a Contributor if it was added to the
Program by such Contributor itself or anyone acting on such
Contributor's behalf. Contributions do not include additions to the
Program which: (i) are separate modules of software distributed in
conjunction with the Program under their own license agreement, and (ii)
are not derivative works of the Program.
"Contributor" means any person or entity that distributes
the Program.
"Licensed Patents" mean patent claims licensable by a
Contributor which are necessarily infringed by the use or sale of its
Contribution alone or when combined with the Program.
"Program" means the Contributions distributed in accordance
with this Agreement.
"Recipient" means anyone who receives the Program under
this Agreement, including all Contributors.
2. GRANT OF RIGHTS
a) Subject to the terms of this Agreement, each
Contributor hereby grants Recipient a non-exclusive, worldwide,
royalty-free copyright license to reproduce, prepare derivative works
of, publicly display, publicly perform, distribute and sublicense the
Contribution of such Contributor, if any, and such derivative works, in
source code and object code form.
b) Subject to the terms of this Agreement, each
Contributor hereby grants Recipient a non-exclusive, worldwide,
royalty-free patent license under Licensed Patents to make, use, sell,
offer to sell, import and otherwise transfer the Contribution of such
Contributor, if any, in source code and object code form. This patent
license shall apply to the combination of the Contribution and the
Program if, at the time the Contribution is added by the Contributor,
such addition of the Contribution causes such combination to be covered
by the Licensed Patents. The patent license shall not apply to any other
combinations which include the Contribution. No hardware per se is
licensed hereunder.
c) Recipient understands that although each Contributor
grants the licenses to its Contributions set forth herein, no assurances
are provided by any Contributor that the Program does not infringe the
patent or other intellectual property rights of any other entity. Each
Contributor disclaims any liability to Recipient for claims brought by
any other entity based on infringement of intellectual property rights
or otherwise. As a condition to exercising the rights and licenses
granted hereunder, each Recipient hereby assumes sole responsibility to
secure any other intellectual property rights needed, if any. For
example, if a third party patent license is required to allow Recipient
to distribute the Program, it is Recipient's responsibility to acquire
that license before distributing the Program.
d) Each Contributor represents that to its knowledge it
has sufficient copyright rights in its Contribution, if any, to grant
the copyright license set forth in this Agreement.
3. REQUIREMENTS
A Contributor may choose to distribute the Program in object code
form under its own license agreement, provided that:
a) it complies with the terms and conditions of this
Agreement; and
b) its license agreement:
i) effectively disclaims on behalf of all Contributors
all warranties and conditions, express and implied, including warranties
or conditions of title and non-infringement, and implied warranties or
conditions of merchantability and fitness for a particular purpose;
ii) effectively excludes on behalf of all Contributors
all liability for damages, including direct, indirect, special,
incidental and consequential damages, such as lost profits;
iii) states that any provisions which differ from this
Agreement are offered by that Contributor alone and not by any other
party; and
iv) states that source code for the Program is available
from such Contributor, and informs licensees how to obtain it in a
reasonable manner on or through a medium customarily used for software
exchange.
When the Program is made available in source code form:
a) it must be made available under this Agreement; and
b) a copy of this Agreement must be included with each
copy of the Program.
Contributors may not remove or alter any copyright notices contained
within the Program.
Each Contributor must identify itself as the originator of its
Contribution, if any, in a manner that reasonably allows subsequent
Recipients to identify the originator of the Contribution.
4. COMMERCIAL DISTRIBUTION
Commercial distributors of software may accept certain
responsibilities with respect to end users, business partners and the
like. While this license is intended to facilitate the commercial use of
the Program, the Contributor who includes the Program in a commercial
product offering should do so in a manner which does not create
potential liability for other Contributors. Therefore, if a Contributor
includes the Program in a commercial product offering, such Contributor
("Commercial Contributor") hereby agrees to defend and
indemnify every other Contributor ("Indemnified Contributor")
against any losses, damages and costs (collectively "Losses")
arising from claims, lawsuits and other legal actions brought by a third
party against the Indemnified Contributor to the extent caused by the
acts or omissions of such Commercial Contributor in connection with its
distribution of the Program in a commercial product offering. The
obligations in this section do not apply to any claims or Losses
relating to any actual or alleged intellectual property infringement. In
order to qualify, an Indemnified Contributor must: a) promptly notify
the Commercial Contributor in writing of such claim, and b) allow the
Commercial Contributor to control, and cooperate with the Commercial
Contributor in, the defense and any related settlement negotiations. The
Indemnified Contributor may participate in any such claim at its own
expense.
For example, a Contributor might include the Program in a commercial
product offering, Product X. That Contributor is then a Commercial
Contributor. If that Commercial Contributor then makes performance
claims, or offers warranties related to Product X, those performance
claims and warranties are such Commercial Contributor's responsibility
alone. Under this section, the Commercial Contributor would have to
defend claims against the other Contributors related to those
performance claims and warranties, and if a court requires any other
Contributor to pay any damages as a result, the Commercial Contributor
must pay those damages.
5. NO WARRANTY
EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS
PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION,
ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY
OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely
responsible for determining the appropriateness of using and
distributing the Program and assumes all risks associated with its
exercise of rights under this Agreement , including but not limited to
the risks and costs of program errors, compliance with applicable laws,
damage to or loss of data, programs or equipment, and unavailability or
interruption of operations.
6. DISCLAIMER OF LIABILITY
EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT
NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING
WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR
DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED
HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
7. GENERAL
If any provision of this Agreement is invalid or unenforceable under
applicable law, it shall not affect the validity or enforceability of
the remainder of the terms of this Agreement, and without further action
by the parties hereto, such provision shall be reformed to the minimum
extent necessary to make such provision valid and enforceable.
If Recipient institutes patent litigation against any entity
(including a cross-claim or counterclaim in a lawsuit) alleging that the
Program itself (excluding combinations of the Program with other
software or hardware) infringes such Recipient's patent(s), then such
Recipient's rights granted under Section 2(b) shall terminate as of the
date such litigation is filed.
All Recipient's rights under this Agreement shall terminate if it
fails to comply with any of the material terms or conditions of this
Agreement and does not cure such failure in a reasonable period of time
after becoming aware of such noncompliance. If all Recipient's rights
under this Agreement terminate, Recipient agrees to cease use and
distribution of the Program as soon as reasonably practicable. However,
Recipient's obligations under this Agreement and any licenses granted by
Recipient relating to the Program shall continue and survive.
Everyone is permitted to copy and distribute copies of this
Agreement, but in order to avoid inconsistency the Agreement is
copyrighted and may only be modified in the following manner. The
Agreement Steward reserves the right to publish new versions (including
revisions) of this Agreement from time to time. No one other than the
Agreement Steward has the right to modify this Agreement. The Eclipse
Foundation is the initial Agreement Steward. The Eclipse Foundation may
assign the responsibility to serve as the Agreement Steward to a
suitable separate entity. Each new version of the Agreement will be
given a distinguishing version number. The Program (including
Contributions) may always be distributed subject to the version of the
Agreement under which it was received. In addition, after a new version
of the Agreement is published, Contributor may elect to distribute the
Program (including its Contributions) under the new version. Except as
expressly stated in Sections 2(a) and 2(b) above, Recipient receives no
rights or licenses to the intellectual property of any Contributor under
this Agreement, whether expressly, by implication, estoppel or
otherwise. All rights in the Program not expressly granted under this
Agreement are reserved.
This Agreement is governed by the laws of the State of New York and
the intellectual property laws of the United States of America. No party
to this Agreement will bring a legal action under this Agreement more
than one year after the cause of action arose. Each party waives its
rights to a jury trial in any resulting litigation.
tools.cli-tools.cli-0.3.5/pom.xml 0000664 0000000 0000000 00000001554 12712503773 0016662 0 ustar 00root root 0000000 0000000
4.0.0
tools.cli
0.3.5
${artifactId}
org.clojure
pom.contrib
0.1.2
Gareth Jones
Sung Pae
scm:git:git@github.com:clojure/tools.cli.git
scm:git:git@github.com:clojure/tools.cli.git
git@github.com:clojure/tools.cli.git
tools.cli-0.3.5
tools.cli-tools.cli-0.3.5/project.clj 0000664 0000000 0000000 00000004342 12712503773 0017503 0 ustar 00root root 0000000 0000000 (defproject org.clojure/tools.cli "0.3.6-SNAPSHOT"
:description "Command line arguments library."
:parent [org.clojure/pom.contrib "0.1.2"]
:url "https://github.com/clojure/tools.cli"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:source-paths ["src/main/clojure"]
:test-paths ["src/test/clojure"]
:repositories {"sonatype-oss-public" "https://oss.sonatype.org/content/groups/public/"}
:dependencies [[org.clojure/clojure "1.6.0"]]
:profiles {:1.2 {:dependencies [[org.clojure/clojure "1.2.1"]]}
:1.3 {:dependencies [[org.clojure/clojure "1.3.0"]]}
:1.4 {:dependencies [[org.clojure/clojure "1.4.0"]]}
:1.5 {:dependencies [[org.clojure/clojure "1.5.1"]]}
:1.6 {:dependencies [[org.clojure/clojure "1.6.0"]]}
:1.7 {:dependencies [[org.clojure/clojure "1.7.0"]]}
:1.8 {:dependencies [[org.clojure/clojure "1.8.0"]]}
:1.9 {:dependencies [[org.clojure/clojure "1.9.0-master-SNAPSHOT"]]}
;; Local CLJS development; not in pom.xml
:dev {:dependencies [[org.clojure/clojurescript "0.0-2080"]]
:plugins [[lein-cljsbuild "1.0.0"]
[com.birdseye-sw/lein-dalap "0.1.1"]
[com.cemerick/clojurescript.test "0.2.1"]]
:hooks [leiningen.dalap]
:cljsbuild {:builds [{:source-paths ["src/main/clojure/cljs"
"src/test/clojure/cljs"]
:compiler {:output-to "target/cli_test.js"
:optimizations :whitespace
:pretty-print true}}]
:test-commands {"phantomjs" ["phantomjs"
:runner
"target/cli_test.js"]}}}}
:aliases {"test-all" ["with-profile" "test,1.2:test,1.3:test,1.4:test,1.5:test,1.6:test,1.7:test,1.8:test,1.9" "test"]
"check-all" ["with-profile" "1.2:1.3:1.4:1.5:1.6:1.7:1.8:1.9" "check"]}
:min-lein-version "2.0.0")
tools.cli-tools.cli-0.3.5/src/ 0000775 0000000 0000000 00000000000 12712503773 0016127 5 ustar 00root root 0000000 0000000 tools.cli-tools.cli-0.3.5/src/main/ 0000775 0000000 0000000 00000000000 12712503773 0017053 5 ustar 00root root 0000000 0000000 tools.cli-tools.cli-0.3.5/src/main/clojure/ 0000775 0000000 0000000 00000000000 12712503773 0020516 5 ustar 00root root 0000000 0000000 tools.cli-tools.cli-0.3.5/src/main/clojure/cljs/ 0000775 0000000 0000000 00000000000 12712503773 0021451 5 ustar 00root root 0000000 0000000 tools.cli-tools.cli-0.3.5/src/main/clojure/cljs/tools/ 0000775 0000000 0000000 00000000000 12712503773 0022611 5 ustar 00root root 0000000 0000000 tools.cli-tools.cli-0.3.5/src/main/clojure/cljs/tools/cli.cljs 0000664 0000000 0000000 00000044644 12712503773 0024251 0 ustar 00root root 0000000 0000000 (ns cljs.tools.cli
"Tools for working with command line arguments."
{:author "Sung Pae"}
(:require [clojure.string :as s]
goog.string.format
[goog.string :as gs]))
(defn- tokenize-args
"Reduce arguments sequence into [opt-type opt ?optarg?] vectors and a vector
of remaining arguments. Returns as [option-tokens remaining-args].
Expands clumped short options like \"-abc\" into:
[[:short-opt \"-a\"] [:short-opt \"-b\"] [:short-opt \"-c\"]]
If \"-b\" were in the set of options that require arguments, \"-abc\" would
then be interpreted as: [[:short-opt \"-a\"] [:short-opt \"-b\" \"c\"]]
Long options with `=` are always parsed as option + optarg, even if nothing
follows the `=` sign.
If the :in-order flag is true, the first non-option, non-optarg argument
stops options processing. This is useful for handling subcommand options."
[required-set args & options]
(let [{:keys [in-order]} (apply hash-map options)]
(loop [opts [] argv [] [car & cdr] args]
(if car
(condp re-seq car
;; Double dash always ends options processing
#"^--$" (recur opts (into argv cdr) [])
;; Long options with assignment always passes optarg, required or not
#"^--\S+=" (recur (conj opts (into [:long-opt] (s/split car #"=" 2)))
argv cdr)
;; Long options, consumes cdr head if needed
#"^--" (let [[optarg cdr] (if (contains? required-set car)
[(first cdr) (rest cdr)]
[nil cdr])]
(recur (conj opts (into [:long-opt car] (if optarg [optarg] [])))
argv cdr))
;; Short options, expands clumped opts until an optarg is required
#"^-." (let [[os cdr] (loop [os [] [c & cs] (rest car)]
(let [o (str \- c)]
(if (contains? required-set o)
(if (seq cs)
;; Get optarg from rest of car
[(conj os [:short-opt o (s/join cs)]) cdr]
;; Get optarg from head of cdr
[(conj os [:short-opt o (first cdr)]) (rest cdr)])
(if (seq cs)
(recur (conj os [:short-opt o]) cs)
[(conj os [:short-opt o]) cdr]))))]
(recur (into opts os) argv cdr))
(if in-order
(recur opts (into argv (cons car cdr)) [])
(recur opts (conj argv car) cdr)))
[opts argv]))))
(def ^{:private true} spec-keys
[:id :short-opt :long-opt :required :desc :default :default-desc :parse-fn
:assoc-fn :validate-fn :validate-msg :missing])
(defn- select-spec-keys
"Select only known spec entries from map and warn the user about unknown
entries at development time."
[map]
;; The following is formatted strangely for better manual diffing
(let [unknown-keys (keys (apply dissoc map spec-keys))]
(when (seq unknown-keys)
(println (str "Warning: The following options to parse-opts are unrecognized: "
(s/join ", " unknown-keys)))))
(select-keys map spec-keys))
(defn- compile-spec [spec]
(let [sopt-lopt-desc (take-while #(or (string? %) (nil? %)) spec)
spec-map (apply hash-map (drop (count sopt-lopt-desc) spec))
[short-opt long-opt desc] sopt-lopt-desc
long-opt (or long-opt (:long-opt spec-map))
[long-opt req] (when long-opt
(rest (re-find #"^(--[^ =]+)(?:[ =](.*))?" long-opt)))
id (when long-opt
(keyword (subs long-opt 2)))
validate (:validate spec-map)
[validate-fn validate-msg] (when (seq validate)
(->> (partition 2 2 (repeat nil) validate)
(apply map vector)))]
(merge {:id id
:short-opt short-opt
:long-opt long-opt
:required req
:desc desc
:validate-fn validate-fn
:validate-msg validate-msg}
(select-spec-keys (dissoc spec-map :validate)))))
(defn- distinct?* [coll]
(if (seq coll)
(apply distinct? coll)
true))
(defn- wrap-val [map key]
(if (contains? map key)
(update-in map [key] #(cond (nil? %) nil
(coll? %) %
:else [%]))
map))
(defn- compile-option-specs
"Map a sequence of option specification vectors to a sequence of:
{:id Keyword ; :server
:short-opt String ; \"-s\"
:long-opt String ; \"--server\"
:required String ; \"HOSTNAME\"
:desc String ; \"Remote server\"
:default Object ; #
:default-desc String ; \"example.com\"
:parse-fn IFn ; #(InetAddress/getByName %)
:assoc-fn IFn ; assoc
:validate-fn [IFn] ; [#(instance? Inet4Address %)
; #(not (.isMulticastAddress %)]
:validate-msg [String] ; [\"Must be an IPv4 host\"
; \"Must not be a multicast address\"]
:missing String ; \"server must be specified\"
}
:id defaults to the keywordized name of long-opt without leading dashes, but
may be overridden in the option spec.
The option spec entry `:validate [fn msg ...]` desugars into the two vector
entries :validate-fn and :validate-msg. Multiple pairs of validation
functions and error messages may be provided.
A :default entry will not be included in the compiled spec unless specified.
An option spec may also be passed as a map containing the entries above,
in which case that subset of the map is transferred directly to the result
vector.
An assertion error is thrown if any :id values are unset, or if there exist
any duplicate :id, :short-opt, or :long-opt values."
[option-specs]
{:post [(every? (comp identity :id) %)
(distinct?* (map :id (filter :default %)))
(distinct?* (remove nil? (map :short-opt %)))
(distinct?* (remove nil? (map :long-opt %)))]}
(map (fn [spec]
(-> (if (map? spec)
(select-spec-keys spec)
(compile-spec spec))
(wrap-val :validate-fn)
(wrap-val :validate-msg)))
option-specs))
(defn- default-option-map [specs]
(reduce (fn [m s]
(if (contains? s :default)
(assoc m (:id s) (:default s))
m))
{} specs))
(defn- missing-errors
"Given specs, returns a map of spec id to error message if missing."
[specs]
(reduce (fn [m s]
(if (:missing s)
(assoc m (:id s) (:missing s))
m))
{} specs))
(defn- find-spec [specs opt-type opt]
(first (filter #(= opt (opt-type %)) specs)))
(defn- pr-join [& xs]
(pr-str (s/join \space xs)))
(defn- missing-required-error [opt example-required]
(str "Missing required argument for " (pr-join opt example-required)))
(defn- parse-error [opt optarg msg]
(str "Error while parsing option " (pr-join opt optarg) ": " msg))
(defn- validation-error [opt optarg msg]
(str "Failed to validate " (pr-join opt optarg)
(if msg (str ": " msg) "")))
(defn- validate [value spec opt optarg]
(let [{:keys [validate-fn validate-msg]} spec]
(or (loop [[vfn & vfns] validate-fn [msg & msgs] validate-msg]
(when vfn
(if (try (vfn value) (catch js/Error e))
(recur vfns msgs)
[::error (validation-error opt optarg msg)])))
[value nil])))
(defn- parse-value [value spec opt optarg]
(let [{:keys [parse-fn]} spec
[value error] (if parse-fn
(try
[(parse-fn value) nil]
(catch js/Error e
[nil (parse-error opt optarg (str e))]))
[value nil])]
(if error
[::error error]
(validate value spec opt optarg))))
(defn- parse-optarg [spec opt optarg]
(let [{:keys [required]} spec]
(if (and required (nil? optarg))
[::error (missing-required-error opt required)]
(parse-value (if required optarg true) spec opt optarg))))
(defn- parse-option-tokens
"Reduce sequence of [opt-type opt ?optarg?] tokens into a map of
{option-id value} merged over the default values in the option
specifications.
If the :no-defaults flag is true, only options specified in the tokens are
included in the option-map.
Unknown options, missing options, missing required arguments, option
argument parsing exceptions, and validation failures are collected into
a vector of error message strings.
If the :strict flag is true, required arguments that match other options
are treated as missing, instead of a literal value beginning with - or --.
Returns [option-map error-messages-vector]."
[specs tokens & options]
(let [{:keys [no-defaults strict]} (apply hash-map options)
defaults (default-option-map specs)
requireds (missing-errors specs)]
(-> (reduce
(fn [[m ids errors] [opt-type opt optarg]]
(if-let [spec (find-spec specs opt-type opt)]
(let [[value error] (parse-optarg spec opt optarg)
id (:id spec)]
(if-not (= value ::error)
(if-let [matched-spec (and strict
(or (find-spec specs :short-opt optarg)
(find-spec specs :long-opt optarg)))]
[m ids (conj errors (missing-required-error opt (:required spec)))]
[((:assoc-fn spec assoc) m id value) (conj ids id) errors])
[m ids (conj errors error)]))
[m ids (conj errors (str "Unknown option: " (pr-str opt)))]))
[defaults [] []] tokens)
(#(reduce
(fn [[m ids errors] [id error]]
(if (contains? m id)
[m ids errors]
[m ids (conj errors error)]))
% requireds))
(#(let [[m ids errors] %]
(if no-defaults
[(select-keys m ids) errors]
[m errors]))))))
(defn ^{:added "0.3.0"} make-summary-part
"Given a single compiled option spec, turn it into a formatted string,
optionally with its default values if requested."
[show-defaults? spec]
(let [{:keys [short-opt long-opt required default default-desc desc]} spec
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 (str default))]
[opt ""])]
(if show-defaults?
[opt dd (or desc "")]
[opt (or desc "")])))
(defn ^{:added "0.3.0"} format-lines
"Format a sequence of summary parts into columns. lens is a sequence of
lengths to use for parts. There are two sequences of lengths if we are
not displaying defaults. There are three sequences of lengths if we
are showing defaults."
[lens parts]
(let [fmt (case (count lens)
2 " %%-%ds %%-%ds"
3 " %%-%ds %%-%ds %%-%ds")
fmt (apply gs/format fmt lens)]
(map #(s/trimr (apply gs/format fmt %)) parts)))
(defn- required-arguments [specs]
(reduce
(fn [s {:keys [required short-opt long-opt]}]
(if required
(into s (remove nil? [short-opt long-opt]))
s))
#{} specs))
(defn ^{:added "0.3.0"} summarize
"Reduce options specs into a options summary for printing at a terminal.
Note that the specs argument should be the compiled version. That effectively
means that you shouldn't call summarize directly. When you call parse-opts
you get back a :summary key which is the result of calling summarize (or
your user-supplied :summary-fn option) on the compiled option specs."
[specs]
(if (seq specs)
(let [show-defaults? (some #(and (:required %) (contains? % :default)) specs)
parts (map (partial make-summary-part show-defaults?) specs)
lens (apply map (fn [& cols] (apply max (map count cols))) parts)
lines (format-lines lens parts)]
(s/join \newline lines))
""))
(defn ^{:added "0.3.2"} get-default-options
"Extract the map of default options from a sequence of option vectors."
[option-specs]
(default-option-map (compile-option-specs option-specs)))
(defn ^{:added "0.3.0"} parse-opts
"Parse arguments sequence according to given option specifications and the
GNU Program Argument Syntax Conventions:
https://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html
Option specifications are a sequence of vectors with the following format:
[short-opt long-opt-with-required-description description
:property value]
The first three string parameters in an option spec are positional and
optional, and may be nil in order to specify a later parameter.
By default, options are toggles that default to nil, but the second string
parameter may be used to specify that an option requires an argument.
e.g. [\"-p\" \"--port PORT\"] specifies that --port requires an argument,
of which PORT is a short description.
The :property value pairs are optional and take precedence over the
positional string arguments. The valid properties are:
:id The key for this option in the resulting option map. This
is normally set to the keywordized name of the long option
without the leading dashes.
Multiple option entries can share the same :id in order to
transform a value in different ways, but only one of these
option entries may contain a :default entry.
This option is mandatory.
:short-opt The short format for this option, normally set by the first
positional string parameter: e.g. \"-p\". Must be unique.
:long-opt The long format for this option, normally set by the second
positional string parameter; e.g. \"--port\". Must be unique.
:required A description of the required argument for this option if
one is required; normally set in the second positional
string parameter after the long option: \"--port PORT\".
The absence of this entry indicates that the option is a
boolean toggle that is set to true when specified on the
command line.
:desc A optional short description of this option.
:default The default value of this option. If none is specified, the
resulting option map will not contain an entry for this
option unless set on the command line.
:default-desc An optional description of the default value. This should be
used when the string representation of the default value is
too ugly to be printed on the command line.
:parse-fn A function that receives the required option argument and
returns the option value.
If this is a boolean option, parse-fn will receive the value
true. This may be used to invert the logic of this option:
[\"-q\" \"--quiet\"
:id :verbose
:default true
:parse-fn not]
:assoc-fn A function that receives the current option map, the current
option :id, and the current parsed option value, and returns
a new option map.
This may be used to create non-idempotent options, like
setting a verbosity level by specifying an option multiple
times. (\"-vvv\" -> 3)
[\"-v\" \"--verbose\"
:default 0
:assoc-fn (fn [m k _] (update-in m [k] inc))]
:validate A vector of [validate-fn validate-msg ...]. Multiple pairs
of validation functions and error messages may be provided.
:validate-fn A vector of functions that receives the parsed option value
and returns a falsy value or throws an exception when the
value is invalid. The validations are tried in the given
order.
:validate-msg A vector of error messages corresponding to :validate-fn
that will be added to the :errors vector on validation
failure.
parse-opts returns a map with four entries:
{:options The options map, keyed by :id, mapped to the parsed value
:arguments A vector of unprocessed arguments
:summary A string containing a minimal options summary
:errors A possible vector of error message strings generated during
parsing; nil when no errors exist}
A few function options may be specified to influence the behavior of
parse-opts:
:in-order Stop option processing at the first unknown argument. Useful
for building programs with subcommands that have their own
option specs.
:no-defaults Only include option values specified in arguments and do not
include any default values in the resulting options map.
Useful for parsing options from multiple sources; i.e. from a
config file and from the command line.
:strict Parse required arguments strictly: if a required argument value
matches any other option, it is considered to be missing (and
you have a parse error).
:summary-fn A function that receives the sequence of compiled option specs
(documented at #'clojure.tools.cli/compile-option-specs), and
returns a custom option summary string.
"
[args option-specs & options]
(let [{:keys [in-order no-defaults strict summary-fn]} (apply hash-map options)
specs (compile-option-specs option-specs)
req (required-arguments specs)
[tokens rest-args] (tokenize-args req args :in-order in-order)
[opts errors] (parse-option-tokens specs tokens
:no-defaults no-defaults :strict strict)]
{:options opts
:arguments rest-args
:summary ((or summary-fn summarize) specs)
:errors (when (seq errors) errors)}))
tools.cli-tools.cli-0.3.5/src/main/clojure/clojure/ 0000775 0000000 0000000 00000000000 12712503773 0022161 5 ustar 00root root 0000000 0000000 tools.cli-tools.cli-0.3.5/src/main/clojure/clojure/tools/ 0000775 0000000 0000000 00000000000 12712503773 0023321 5 ustar 00root root 0000000 0000000 tools.cli-tools.cli-0.3.5/src/main/clojure/clojure/tools/cli.clj 0000664 0000000 0000000 00000056512 12712503773 0024573 0 ustar 00root root 0000000 0000000 (ns ^{:author "Gareth Jones, Sung Pae"
:doc "Tools for working with command line arguments."}
clojure.tools.cli
(:require [clojure.pprint :as pp]
[clojure.string :as s]))
(defn- tokenize-args
"Reduce arguments sequence into [opt-type opt ?optarg?] vectors and a vector
of remaining arguments. Returns as [option-tokens remaining-args].
Expands clumped short options like \"-abc\" into:
[[:short-opt \"-a\"] [:short-opt \"-b\"] [:short-opt \"-c\"]]
If \"-b\" were in the set of options that require arguments, \"-abc\" would
then be interpreted as: [[:short-opt \"-a\"] [:short-opt \"-b\" \"c\"]]
Long options with `=` are always parsed as option + optarg, even if nothing
follows the `=` sign.
If the :in-order flag is true, the first non-option, non-optarg argument
stops options processing. This is useful for handling subcommand options."
[required-set args & options]
(let [{:keys [in-order]} (apply hash-map options)]
(loop [opts [] argv [] [car & cdr] args]
(if car
(condp re-seq car
;; Double dash always ends options processing
#"^--$" (recur opts (into argv cdr) [])
;; Long options with assignment always passes optarg, required or not
#"^--\S+=" (recur (conj opts (into [:long-opt] (s/split car #"=" 2)))
argv cdr)
;; Long options, consumes cdr head if needed
#"^--" (let [[optarg cdr] (if (contains? required-set car)
[(first cdr) (rest cdr)]
[nil cdr])]
(recur (conj opts (into [:long-opt car] (if optarg [optarg] [])))
argv cdr))
;; Short options, expands clumped opts until an optarg is required
#"^-." (let [[os cdr] (loop [os [] [c & cs] (rest car)]
(let [o (str \- c)]
(if (contains? required-set o)
(if (seq cs)
;; Get optarg from rest of car
[(conj os [:short-opt o (s/join cs)]) cdr]
;; Get optarg from head of cdr
[(conj os [:short-opt o (first cdr)]) (rest cdr)])
(if (seq cs)
(recur (conj os [:short-opt o]) cs)
[(conj os [:short-opt o]) cdr]))))]
(recur (into opts os) argv cdr))
(if in-order
(recur opts (into argv (cons car cdr)) [])
(recur opts (conj argv car) cdr)))
[opts argv]))))
;;
;; Legacy API
;;
(defn- build-doc [{:keys [switches docs default]}]
[(apply str (interpose ", " switches))
(or (str default) "")
(or docs "")])
(defn- banner-for [desc specs]
(when desc
(println desc)
(println))
(let [docs (into (map build-doc specs)
[["--------" "-------" "----"]
["Switches" "Default" "Desc"]])
max-cols (->> (for [d docs] (map count d))
(apply map (fn [& c] (apply vector c)))
(map #(apply max %)))
vs (for [d docs]
(mapcat (fn [& x] (apply vector x)) max-cols d))]
(doseq [v vs]
(pp/cl-format true "~{ ~vA ~vA ~vA ~}" v)
(prn))))
(defn- name-for [k]
(s/replace k #"^--no-|^--\[no-\]|^--|^-" ""))
(defn- flag-for [^String v]
(not (.startsWith v "--no-")))
(defn- opt? [^String x]
(.startsWith x "-"))
(defn- flag? [^String x]
(.startsWith x "--[no-]"))
(defn- end-of-args? [x]
(= "--" x))
(defn- spec-for
[arg specs]
(->> specs
(filter (fn [s]
(let [switches (set (s :switches))]
(contains? switches arg))))
first))
(defn- default-values-for
[specs]
(reduce (fn [m s]
(if (contains? s :default)
((:assoc-fn s) m (:name s) (:default s))
m))
{} specs))
(defn- apply-specs
[specs args]
(loop [options (default-values-for specs)
extra-args []
args args]
(if-not (seq args)
[options extra-args]
(let [opt (first args)
spec (spec-for opt specs)]
(cond
(end-of-args? opt)
(recur options (into extra-args (vec (rest args))) nil)
(and (opt? opt) (nil? spec))
(throw (Exception. (str "'" opt "' is not a valid argument")))
(and (opt? opt) (spec :flag))
(recur ((spec :assoc-fn) options (spec :name) (flag-for opt))
extra-args
(rest args))
(opt? opt)
(recur ((spec :assoc-fn) options (spec :name) ((spec :parse-fn) (second args)))
extra-args
(drop 2 args))
:default
(recur options (conj extra-args (first args)) (rest args)))))))
(defn- switches-for
[switches flag]
(-> (for [^String s switches]
(cond
(and flag (flag? s)) [(s/replace s #"\[no-\]" "no-") (s/replace s #"\[no-\]" "")]
(and flag (.startsWith s "--")) [(s/replace s #"--" "--no-") s]
:default [s]))
flatten))
(defn- generate-spec
[raw-spec]
(let [[switches raw-spec] (split-with #(and (string? %) (opt? %)) raw-spec)
[docs raw-spec] (split-with string? raw-spec)
options (apply hash-map raw-spec)
aliases (map name-for switches)
flag (or (flag? (last switches)) (options :flag))]
(merge {:switches (switches-for switches flag)
:docs (first docs)
:aliases (set aliases)
:name (keyword (last aliases))
:parse-fn identity
:assoc-fn assoc
:flag flag}
(when flag {:default false})
options)))
(defn- normalize-args
"Rewrite arguments sequence into a normalized form that is parsable by cli."
[specs args]
(let [required-opts (->> specs
(filter (complement :flag))
(mapcat :switches)
(into #{}))
;; Preserve double-dash since this is a pre-processing step
largs (take-while (partial not= "--") args)
rargs (drop (count largs) args)
[opts largs] (tokenize-args required-opts largs)]
(concat (mapcat rest opts) largs rargs)))
(defn cli
"THIS IS A LEGACY FUNCTION and may be deprecated in the future. Please use
clojure.tools.cli/parse-opts in new applications.
Parse the provided args using the given specs. Specs are vectors
describing a command line argument. For example:
[\"-p\" \"--port\" \"Port to listen on\" :default 3000 :parse-fn #(Integer/parseInt %)]
First provide the switches (from least to most specific), then a doc
string, and pairs of options.
Valid options are :default, :parse-fn, and :flag. See
https://github.com/clojure/tools.cli/wiki/Documentation-for-0.2.4 for more
detailed examples.
Returns a vector containing a map of the parsed arguments, a vector
of extra arguments that did not match known switches, and a
documentation banner to provide usage instructions."
[args & specs]
(let [[desc specs] (if (string? (first specs))
[(first specs) (rest specs)]
[nil specs])
specs (map generate-spec specs)
args (normalize-args specs args)]
(let [[options extra-args] (apply-specs specs args)
banner (with-out-str (banner-for desc specs))]
[options extra-args banner])))
;;
;; New API
;;
(def ^{:private true} spec-keys
[:id :short-opt :long-opt :required :desc :default :default-desc :parse-fn
:assoc-fn :validate-fn :validate-msg :missing])
(defn- select-spec-keys
"Select only known spec entries from map and warn the user about unknown
entries at development time."
[map]
;; The following is formatted strangely for better manual diffing
(when *assert*
(let [unknown-keys (keys (apply dissoc map spec-keys))]
(when (seq unknown-keys)
(binding [*out* *err*]
(println (str "Warning: The following options to parse-opts are unrecognized: "
(s/join ", " unknown-keys)))))
))
(select-keys map spec-keys))
(defn- compile-spec [spec]
(let [sopt-lopt-desc (take-while #(or (string? %) (nil? %)) spec)
spec-map (apply hash-map (drop (count sopt-lopt-desc) spec))
[short-opt long-opt desc] sopt-lopt-desc
long-opt (or long-opt (:long-opt spec-map))
[long-opt req] (when long-opt
(rest (re-find #"^(--[^ =]+)(?:[ =](.*))?" long-opt)))
id (when long-opt
(keyword (subs long-opt 2)))
validate (:validate spec-map)
[validate-fn validate-msg] (when (seq validate)
(->> (partition 2 2 (repeat nil) validate)
(apply map vector)))]
(merge {:id id
:short-opt short-opt
:long-opt long-opt
:required req
:desc desc
:validate-fn validate-fn
:validate-msg validate-msg}
(select-spec-keys (dissoc spec-map :validate)))))
(defn- distinct?* [coll]
(if (seq coll)
(apply distinct? coll)
true))
(defn- wrap-val [map key]
(if (contains? map key)
(update-in map [key] #(cond (nil? %) nil
(coll? %) %
:else [%]))
map))
(defn- compile-option-specs
"Map a sequence of option specification vectors to a sequence of:
{:id Keyword ; :server
:short-opt String ; \"-s\"
:long-opt String ; \"--server\"
:required String ; \"HOSTNAME\"
:desc String ; \"Remote server\"
:default Object ; #
:default-desc String ; \"example.com\"
:parse-fn IFn ; #(InetAddress/getByName %)
:assoc-fn IFn ; assoc
:validate-fn [IFn] ; [#(instance? Inet4Address %)
; #(not (.isMulticastAddress %)]
:validate-msg [String] ; [\"Must be an IPv4 host\"
; \"Must not be a multicast address\"]
:missing String ; \"server must be specified\"
}
:id defaults to the keywordized name of long-opt without leading dashes, but
may be overridden in the option spec.
The option spec entry `:validate [fn msg ...]` desugars into the two vector
entries :validate-fn and :validate-msg. Multiple pairs of validation
functions and error messages may be provided.
A :default entry will not be included in the compiled spec unless specified.
An option spec may also be passed as a map containing the entries above,
in which case that subset of the map is transferred directly to the result
vector.
An assertion error is thrown if any :id values are unset, or if there exist
any duplicate :id, :short-opt, or :long-opt values."
[option-specs]
{:post [(every? (comp identity :id) %)
(distinct?* (map :id (filter :default %)))
(distinct?* (remove nil? (map :short-opt %)))
(distinct?* (remove nil? (map :long-opt %)))]}
(map (fn [spec]
(-> (if (map? spec)
(select-spec-keys spec)
(compile-spec spec))
(wrap-val :validate-fn)
(wrap-val :validate-msg)))
option-specs))
(defn- default-option-map [specs]
(reduce (fn [m s]
(if (contains? s :default)
(assoc m (:id s) (:default s))
m))
{} specs))
(defn- missing-errors
"Given specs, returns a map of spec id to error message if missing."
[specs]
(reduce (fn [m s]
(if (:missing s)
(assoc m (:id s) (:missing s))
m))
{} specs))
(defn- find-spec [specs opt-type opt]
(first (filter #(= opt (opt-type %)) specs)))
(defn- pr-join [& xs]
(pr-str (s/join \space xs)))
(defn- missing-required-error [opt example-required]
(str "Missing required argument for " (pr-join opt example-required)))
(defn- parse-error [opt optarg msg]
(str "Error while parsing option " (pr-join opt optarg) ": " msg))
(defn- validation-error [opt optarg msg]
(str "Failed to validate " (pr-join opt optarg)
(if msg (str ": " msg) "")))
(defn- validate [value spec opt optarg]
(let [{:keys [validate-fn validate-msg]} spec]
(or (loop [[vfn & vfns] validate-fn [msg & msgs] validate-msg]
(when vfn
(if (try (vfn value) (catch Throwable e))
(recur vfns msgs)
[::error (validation-error opt optarg msg)])))
[value nil])))
(defn- parse-value [value spec opt optarg]
(let [{:keys [parse-fn]} spec
[value error] (if parse-fn
(try
[(parse-fn value) nil]
(catch Throwable e
[nil (parse-error opt optarg (str e))]))
[value nil])]
(if error
[::error error]
(validate value spec opt optarg))))
(defn- parse-optarg [spec opt optarg]
(let [{:keys [required]} spec]
(if (and required (nil? optarg))
[::error (missing-required-error opt required)]
(parse-value (if required optarg true) spec opt optarg))))
(defn- parse-option-tokens
"Reduce sequence of [opt-type opt ?optarg?] tokens into a map of
{option-id value} merged over the default values in the option
specifications.
If the :no-defaults flag is true, only options specified in the tokens are
included in the option-map.
Unknown options, missing options, missing required arguments, option
argument parsing exceptions, and validation failures are collected into
a vector of error message strings.
If the :strict flag is true, required arguments that match other options
are treated as missing, instead of a literal value beginning with - or --.
Returns [option-map error-messages-vector]."
[specs tokens & options]
(let [{:keys [no-defaults strict]} (apply hash-map options)
defaults (default-option-map specs)
requireds (missing-errors specs)]
(-> (reduce
(fn [[m ids errors] [opt-type opt optarg]]
(if-let [spec (find-spec specs opt-type opt)]
(let [[value error] (parse-optarg spec opt optarg)
id (:id spec)]
(if-not (= value ::error)
(if-let [matched-spec (and strict
(or (find-spec specs :short-opt optarg)
(find-spec specs :long-opt optarg)))]
[m ids (conj errors (missing-required-error opt (:required spec)))]
[((:assoc-fn spec assoc) m id value) (conj ids id) errors])
[m ids (conj errors error)]))
[m ids (conj errors (str "Unknown option: " (pr-str opt)))]))
[defaults [] []] tokens)
(#(reduce
(fn [[m ids errors] [id error]]
(if (contains? m id)
[m ids errors]
[m ids (conj errors error)]))
% requireds))
(#(let [[m ids errors] %]
(if no-defaults
[(select-keys m ids) errors]
[m errors]))))))
(defn ^{:added "0.3.0"} make-summary-part
"Given a single compiled option spec, turn it into a formatted string,
optionally with its default values if requested."
[show-defaults? spec]
(let [{:keys [short-opt long-opt required default default-desc desc]} spec
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 (str default))]
[opt ""])]
(if show-defaults?
[opt dd (or desc "")]
[opt (or desc "")])))
(defn ^{:added "0.3.0"} format-lines
"Format a sequence of summary parts into columns. lens is a sequence of
lengths to use for parts. There are two sequences of lengths if we are
not displaying defaults. There are three sequences of lengths if we
are showing defaults."
[lens parts]
(let [fmt (case (count lens)
2 "~{ ~vA ~vA~}"
3 "~{ ~vA ~vA ~vA~}")]
(map #(s/trimr (pp/cl-format nil fmt (interleave lens %))) parts)))
(defn- required-arguments [specs]
(reduce
(fn [s {:keys [required short-opt long-opt]}]
(if required
(into s (remove nil? [short-opt long-opt]))
s))
#{} specs))
(defn ^{:added "0.3.0"} summarize
"Reduce options specs into a options summary for printing at a terminal.
Note that the specs argument should be the compiled version. That effectively
means that you shouldn't call summarize directly. When you call parse-opts
you get back a :summary key which is the result of calling summarize (or
your user-supplied :summary-fn option) on the compiled option specs."
[specs]
(if (seq specs)
(let [show-defaults? (some #(and (:required %) (contains? % :default)) specs)
parts (map (partial make-summary-part show-defaults?) specs)
lens (apply map (fn [& cols] (apply max (map count cols))) parts)
lines (format-lines lens parts)]
(s/join \newline lines))
""))
(defn ^{:added "0.3.2"} get-default-options
"Extract the map of default options from a sequence of option vectors."
[option-specs]
(default-option-map (compile-option-specs option-specs)))
(defn ^{:added "0.3.0"} parse-opts
"Parse arguments sequence according to given option specifications and the
GNU Program Argument Syntax Conventions:
https://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html
Option specifications are a sequence of vectors with the following format:
[short-opt long-opt-with-required-description description
:property value]
The first three string parameters in an option spec are positional and
optional, and may be nil in order to specify a later parameter.
By default, options are toggles that default to nil, but the second string
parameter may be used to specify that an option requires an argument.
e.g. [\"-p\" \"--port PORT\"] specifies that --port requires an argument,
of which PORT is a short description.
The :property value pairs are optional and take precedence over the
positional string arguments. The valid properties are:
:id The key for this option in the resulting option map. This
is normally set to the keywordized name of the long option
without the leading dashes.
Multiple option entries can share the same :id in order to
transform a value in different ways, but only one of these
option entries may contain a :default entry.
This option is mandatory.
:short-opt The short format for this option, normally set by the first
positional string parameter: e.g. \"-p\". Must be unique.
:long-opt The long format for this option, normally set by the second
positional string parameter; e.g. \"--port\". Must be unique.
:required A description of the required argument for this option if
one is required; normally set in the second positional
string parameter after the long option: \"--port PORT\".
The absence of this entry indicates that the option is a
boolean toggle that is set to true when specified on the
command line.
:desc A optional short description of this option.
:default The default value of this option. If none is specified, the
resulting option map will not contain an entry for this
option unless set on the command line.
:default-desc An optional description of the default value. This should be
used when the string representation of the default value is
too ugly to be printed on the command line.
:parse-fn A function that receives the required option argument and
returns the option value.
If this is a boolean option, parse-fn will receive the value
true. This may be used to invert the logic of this option:
[\"-q\" \"--quiet\"
:id :verbose
:default true
:parse-fn not]
:assoc-fn A function that receives the current option map, the current
option :id, and the current parsed option value, and returns
a new option map.
This may be used to create non-idempotent options, like
setting a verbosity level by specifying an option multiple
times. (\"-vvv\" -> 3)
[\"-v\" \"--verbose\"
:default 0
:assoc-fn (fn [m k _] (update-in m [k] inc))]
:validate A vector of [validate-fn validate-msg ...]. Multiple pairs
of validation functions and error messages may be provided.
:validate-fn A vector of functions that receives the parsed option value
and returns a falsy value or throws an exception when the
value is invalid. The validations are tried in the given
order.
:validate-msg A vector of error messages corresponding to :validate-fn
that will be added to the :errors vector on validation
failure.
parse-opts returns a map with four entries:
{:options The options map, keyed by :id, mapped to the parsed value
:arguments A vector of unprocessed arguments
:summary A string containing a minimal options summary
:errors A possible vector of error message strings generated during
parsing; nil when no errors exist}
A few function options may be specified to influence the behavior of
parse-opts:
:in-order Stop option processing at the first unknown argument. Useful
for building programs with subcommands that have their own
option specs.
:no-defaults Only include option values specified in arguments and do not
include any default values in the resulting options map.
Useful for parsing options from multiple sources; i.e. from a
config file and from the command line.
:strict Parse required arguments strictly: if a required argument value
matches any other option, it is considered to be missing (and
you have a parse error).
:summary-fn A function that receives the sequence of compiled option specs
(documented at #'clojure.tools.cli/compile-option-specs), and
returns a custom option summary string.
"
[args option-specs & options]
(let [{:keys [in-order no-defaults strict summary-fn]} (apply hash-map options)
specs (compile-option-specs option-specs)
req (required-arguments specs)
[tokens rest-args] (tokenize-args req args :in-order in-order)
[opts errors] (parse-option-tokens specs tokens
:no-defaults no-defaults :strict strict)]
{:options opts
:arguments rest-args
:summary ((or summary-fn summarize) specs)
:errors (when (seq errors) errors)}))
tools.cli-tools.cli-0.3.5/src/test/ 0000775 0000000 0000000 00000000000 12712503773 0017106 5 ustar 00root root 0000000 0000000 tools.cli-tools.cli-0.3.5/src/test/clojure/ 0000775 0000000 0000000 00000000000 12712503773 0020551 5 ustar 00root root 0000000 0000000 tools.cli-tools.cli-0.3.5/src/test/clojure/clojure/ 0000775 0000000 0000000 00000000000 12712503773 0022214 5 ustar 00root root 0000000 0000000 tools.cli-tools.cli-0.3.5/src/test/clojure/clojure/tools/ 0000775 0000000 0000000 00000000000 12712503773 0023354 5 ustar 00root root 0000000 0000000 tools.cli-tools.cli-0.3.5/src/test/clojure/clojure/tools/cli_legacy_test.clj 0000664 0000000 0000000 00000014742 12712503773 0027210 0 ustar 00root root 0000000 0000000 (ns clojure.tools.cli-legacy-test
(:use [clojure.string :only [split]]
[clojure.test :only [deftest is testing]]
[clojure.tools.cli :as cli :only [cli]]))
(testing "syntax"
(deftest should-handle-simple-strings
(is (= {:host "localhost"}
(first (cli ["--host" "localhost"]
["--host"])))))
(testing "booleans"
(deftest should-handle-trues
(is (= {:verbose true}
(first (cli ["--verbose"]
["--[no-]verbose"])))))
(deftest should-handle-falses
(is (= {:verbose false}
(first (cli ["--no-verbose"]
["--[no-]verbose"])))))
(testing "explicit syntax"
(is (= {:verbose true}
(first (cli ["--verbose"]
["--verbose" :flag true]))))
(is (= {:verbose false}
(first (cli ["--no-verbose"]
["--verbose" :flag true]))))))
(testing "default values"
(deftest should-default-when-no-value
(is (= {:server "10.0.1.10"}
(first (cli []
["--server" :default "10.0.1.10"])))))
(deftest should-override-when-supplied
(is (= {:server "127.0.0.1"}
(first (cli ["--server" "127.0.0.1"]
["--server" :default "10.0.1.10"])))))
(deftest should-omit-key-when-no-default
(is (= false
(contains? (cli ["--server" "127.0.0.1"]
["--server" :default "10.0.1.10"]
["--names"])
:server)))))
(deftest should-apply-parse-fn
(is (= {:names ["john" "jeff" "steve"]}
(first (cli ["--names" "john,jeff,steve"]
["--names" :parse-fn #(vec (split % #","))])))))
(testing "aliases"
(deftest should-support-multiple-aliases
(is (= {:server "localhost"}
(first (cli ["-s" "localhost"]
["-s" "--server"])))))
(deftest should-use-last-alias-provided-as-name-in-map
(is (= {:server "localhost"}
(first (cli ["-s" "localhost"]
["-s" "--server"]))))))
(testing "merging args"
(deftest should-merge-identical-arguments
(let [assoc-fn (fn [previous key val]
(assoc previous key
(if-let [oldval (get previous key)]
(merge oldval val)
(hash-set val))))
[options args _] (cli ["-p" "1" "--port" "2"]
["-p" "--port" "description"
:assoc-fn assoc-fn
:parse-fn #(Integer/parseInt %)])]
(is (= {:port #{1 2}} options)))))
(testing "extra arguments"
(deftest should-provide-access-to-trailing-args
(let [[options args _] (cli ["--foo" "bar" "a" "b" "c"]
["-f" "--foo"])]
(is (= {:foo "bar"} options))
(is (= ["a" "b" "c"] args))))
(deftest should-work-with-trailing-boolean-args
(let [[options args _] (cli ["--no-verbose" "some-file"]
["--[no-]verbose"])]
(is (= {:verbose false} options))
(is (= ["some-file"] args))))
(deftest should-accept-double-hyphen-as-end-of-args
(let [[options args _] (cli ["--foo" "bar" "--verbose" "--" "file" "-x" "other"]
["--foo"]
["--[no-]verbose"])]
(is (= {:foo "bar" :verbose true} options))
(is (= ["file" "-x" "other"] args)))))
(testing "description"
(deftest should-be-able-to-supply-description
(let [[options args banner]
(cli ["-s" "localhost"]
"This program does something awesome."
["-s" "--server" :description "Server name"])]
(is (= {:server "localhost"} options))
(is (empty? args))
(is (re-find #"This program does something awesome" banner)))))
(testing "handles GNU option parsing conventions"
(deftest should-handle-gnu-option-parsing-conventions
(is (= (take 2 (cli ["foo" "-abcp80" "bar" "--host=example.com"]
["-a" "--alpha" :flag true]
["-b" "--bravo" :flag true]
["-c" "--charlie" :flag true]
["-h" "--host" :flag false]
["-p" "--port" "Port number"
:flag false :parse-fn #(Integer/parseInt %)]))
[{:alpha true :bravo true :charlie true :port 80 :host "example.com"}
["foo" "bar"]])))))
(def normalize-args
#'cli/normalize-args)
(deftest test-normalize-args
(testing "expands clumped short options"
(is (= (normalize-args [] ["-abc" "foo"])
["-a" "-b" "-c" "foo"]))
(is (= (normalize-args [{:switches ["-p"] :flag false}] ["-abcp80" "foo"])
["-a" "-b" "-c" "-p" "80" "foo"])))
(testing "expands long options with assignment"
(is (= (normalize-args [{:switches ["--port"] :flag false}] ["--port=80" "--noopt=" "foo"])
["--port" "80" "--noopt" "" "foo"])))
(testing "preserves double dash"
(is (= (normalize-args [] ["-ab" "--" "foo" "-c"])
["-a" "-b" "--" "foo" "-c"])))
(testing "hoists all options and optargs to the front"
(is (= (normalize-args
[{:switches ["-x"] :flag false}
{:switches ["-y"] :flag false}
{:switches ["--zulu"] :flag false}]
["foo" "-axray" "bar" "-by" "yankee" "-c" "baz" "--zulu" "zebra"
"--" "--full" "stop"])
["-a" "-x" "ray" "-b" "-y" "yankee" "-c" "--zulu" "zebra"
"foo" "bar" "baz" "--" "--full" "stop"]))))
(deftest all-together-now
(let [[options args _] (cli ["-p" "8080"
"--no-verbose"
"--log-directory" "/tmp"
"--server" "localhost"
"filename"]
["-p" "--port" :parse-fn #(Integer/parseInt %)]
["--host" :default "localhost"]
["--[no-]verbose" :default true]
["--log-directory" :default "/some/path"]
["--server"])]
(is (= {:port 8080
:host "localhost"
:verbose false
:log-directory "/tmp"
:server "localhost"} options))
(is (= ["filename"] args))))
tools.cli-tools.cli-0.3.5/src/test/clojure/clojure/tools/cli_test.clj 0000664 0000000 0000000 00000034073 12712503773 0025663 0 ustar 00root root 0000000 0000000 (ns ^{:cljs 'cljs.tools.cli-test} clojure.tools.cli-test
^{:cljs
'(:require [cljs.tools.cli :as cli :refer [get-default-options parse-opts summarize]]
[clojure.string :refer [join]]
cemerick.cljs.test)}
(:use [clojure.tools.cli :as cli :only [get-default-options parse-opts summarize]]
[clojure.string :only [join]]
[clojure.test :only [deftest is testing]])
#_(:cljs (:require-macros [cemerick.cljs.test :refer [deftest is testing]])))
;; Refer private vars
(def tokenize-args (^{:cljs 'do} var cli/tokenize-args))
(def compile-option-specs (^{:cljs 'do} var cli/compile-option-specs))
(def parse-option-tokens (^{:cljs 'do} var cli/parse-option-tokens))
(deftest test-tokenize-args
(testing "expands clumped short options"
(is (= (tokenize-args #{"-p"} ["-abcp80"])
[[[:short-opt "-a"] [:short-opt "-b"] [:short-opt "-c"] [:short-opt "-p" "80"]] []])))
(testing "detects arguments to long options"
(is (= (tokenize-args #{"--port" "--host"} ["--port=80" "--host" "example.com"])
[[[:long-opt "--port" "80"] [:long-opt "--host" "example.com"]] []]))
(is (= (tokenize-args #{} ["--foo=bar" "--noarg=" "--bad =opt"])
[[[:long-opt "--foo" "bar"] [:long-opt "--noarg" ""] [:long-opt "--bad =opt"]] []])))
(testing "stops option processing on double dash"
(is (= (tokenize-args #{} ["-a" "--" "-b"])
[[[:short-opt "-a"]] ["-b"]])))
(testing "finds trailing options unless :in-order is true"
(is (= (tokenize-args #{} ["-a" "foo" "-b"])
[[[:short-opt "-a"] [:short-opt "-b"]] ["foo"]]))
(is (= (tokenize-args #{} ["-a" "foo" "-b"] :in-order true)
[[[:short-opt "-a"]] ["foo" "-b"]])))
(testing "does not interpret single dash as an option"
(is (= (tokenize-args #{} ["-"]) [[] ["-"]]))))
(deftest test-compile-option-specs
(testing "does not set values for :default unless specified"
(is (= (map #(contains? % :default) (compile-option-specs
[["-f" "--foo"]
["-b" "--bar=ARG" :default 0]]))
[false true])))
(testing "interprets first three string arguments as short-opt, long-opt=required, and desc"
(is (= (map (juxt :short-opt :long-opt :required :desc)
(compile-option-specs [["-a" :id :alpha]
["-b" "--beta"]
[nil nil "DESC" :id :gamma]
["-f" "--foo=FOO" "desc"]]))
[["-a" nil nil nil]
["-b" "--beta" nil nil]
[nil nil nil "DESC"]
["-f" "--foo" "FOO" "desc"]])))
(testing "throws AssertionError on unset :id, duplicate :short-opt or :long-opt,
or multiple :default entries per :id"
(is (thrown? ^{:cljs js/Error} AssertionError
(compile-option-specs [["-a" :id nil]])))
(is (thrown? ^{:cljs js/Error} AssertionError
(compile-option-specs [{:id :a :short-opt "-a"} {:id :b :short-opt "-a"}])))
(is (thrown? ^{:cljs js/Error} AssertionError
(compile-option-specs [{:id :alpha :long-opt "--alpha"} {:id :beta :long-opt "--alpha"}])))
(is (thrown? ^{:cljs js/Error} AssertionError
(compile-option-specs [{:id :alpha :default 0} {:id :alpha :default 1}]))))
(testing "desugars `--long-opt=value`"
(is (= (map (juxt :id :long-opt :required)
(compile-option-specs [[nil "--foo FOO"] [nil "--bar=BAR"]]))
[[:foo "--foo" "FOO"]
[:bar "--bar" "BAR"]])))
(testing "desugars :validate [fn msg]"
(let [port? #(< 0 % 0x10000)]
(is (= (map (juxt :validate-fn :validate-msg)
(compile-option-specs
[[nil "--name NAME" :validate [seq "Must be present"]]
[nil "--port PORT" :validate [integer? "Must be an integer"
port? "Must be between 0 and 65536"]]
[:id :back-compat
:validate-fn identity
:validate-msg "Should be backwards compatible"]]))
[[[seq] ["Must be present"]]
[[integer? port?] ["Must be an integer" "Must be between 0 and 65536"]]
[[identity] ["Should be backwards compatible"]]]))))
(testing "accepts maps as option specs without munging values"
(is (= (compile-option-specs [{:id ::foo :short-opt "-f" :long-opt "--foo"}])
[{:id ::foo :short-opt "-f" :long-opt "--foo"}])))
(testing "warns about unknown keys"
(^{:cljs 'do} when ^{:clj true} *assert*
(is (re-find #"Warning:.* :flag"
(with-out-str
(binding ^{:cljs []} [*err* *out*]
(compile-option-specs [[nil "--alpha" :validate nil :flag true]])))))
(is (re-find #"Warning:.* :validate"
(with-out-str
(binding ^{:cljs []} [*err* *out*]
(compile-option-specs [{:id :alpha :validate nil}]))))))))
(defn has-error? [re coll]
(seq (filter (partial re-seq re) coll)))
(defn parse-int [x]
^{:cljs (do (assert (re-seq #"^\d" x))
(js/parseInt x))}
(Integer/parseInt x))
(deftest test-parse-option-tokens
(testing "parses and validates option arguments"
(let [specs (compile-option-specs
[["-p" "--port NUMBER"
:parse-fn parse-int
:validate [#(< 0 % 0x10000) "Must be between 0 and 65536"]]
["-f" "--file PATH"
:missing "--file is required"
:validate [#(not= \/ (first %)) "Must be a relative path"
;; N.B. This is a poor way to prevent path traversal
#(not (re-find #"\.\." %)) "No path traversal allowed"]]
["-q" "--quiet"
:id :verbose
:default true
:parse-fn not]])]
(is (= (parse-option-tokens specs [[:long-opt "--port" "80"] [:short-opt "-q"] [:short-opt "-f" "FILE"]])
[{:port (int 80) :verbose false :file "FILE"} []]))
(is (= (parse-option-tokens specs [[:short-opt "-f" "-p"]])
[{:file "-p" :verbose true} []]))
(is (has-error? #"Unknown option"
(peek (parse-option-tokens specs [[:long-opt "--unrecognized"]]))))
(is (has-error? #"Missing required"
(peek (parse-option-tokens specs [[:long-opt "--port"]]))))
(is (has-error? #"Missing required"
(peek (parse-option-tokens specs [[:short-opt "-f" "-p"]] :strict true))))
(is (has-error? #"--file is required"
(peek (parse-option-tokens specs []))))
(is (has-error? #"Must be between"
(peek (parse-option-tokens specs [[:long-opt "--port" "0"]]))))
(is (has-error? #"Error while parsing"
(peek (parse-option-tokens specs [[:long-opt "--port" "FOO"]]))))
(is (has-error? #"Must be a relative path"
(peek (parse-option-tokens specs [[:long-opt "--file" "/foo"]]))))
(is (has-error? #"No path traversal allowed"
(peek (parse-option-tokens specs [[:long-opt "--file" "../../../etc/passwd"]]))))))
(testing "merges values over default option map"
(let [specs (compile-option-specs
[["-a" "--alpha"]
["-b" "--beta" :default false]
["-g" "--gamma=ARG"]
["-d" "--delta=ARG" :default "DELTA"]])]
(is (= (parse-option-tokens specs [])
[{:beta false :delta "DELTA"} []]))
(is (= (parse-option-tokens specs [[:short-opt "-a"]
[:short-opt "-b"]
[:short-opt "-g" "GAMMA"]
[:short-opt "-d" "delta"]])
[{:alpha true :beta true :gamma "GAMMA" :delta "delta"} []]))))
(testing "associates :id and value with :assoc-fn"
(let [specs (compile-option-specs
[["-a" "--alpha"
:default true
:assoc-fn (fn [m k v] (assoc m k (not v)))]
["-v" "--verbose"
:default 0
:assoc-fn (fn [m k _] (assoc m k (inc (m k))))]])]
(is (= (parse-option-tokens specs [])
[{:alpha true :verbose 0} []]))
(is (= (parse-option-tokens specs [[:short-opt "-a"]])
[{:alpha false :verbose 0} []]))
(is (= (parse-option-tokens specs [[:short-opt "-v"]
[:short-opt "-v"]
[:long-opt "--verbose"]])
[{:alpha true :verbose 3} []]))
(is (= (parse-option-tokens specs [[:short-opt "-v"]] :no-defaults true)
[{:verbose 1} []])))))
(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 "--ternary t|f|?" "A ternary option defaulting to false"
:default false
:parse-fn #(case %
"t" true
"f" false
"?" :maybe)]
[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"
" --ternary t|f|? false A ternary option defaulting to false"
" --help"]))))
(testing "does not print :default column when no defaults will be shown"
(is (= (summarize (compile-option-specs [["-b" "--boolean" "A boolean option with a hidden default"
:default true]
["-o" "--option ARG" "An option without a default"]]))
(join \newline [" -b, --boolean A boolean option with a hidden default"
" -o, --option ARG An option without a default"]))))
(testing "works with no options"
(is (= (summarize (compile-option-specs []))
""))))
(deftest test-get-default-options
(testing "Extracts map of default options from a sequence of option vectors."
(is (= (get-default-options [[:id :a :default "a"]
[:id :b :default 98]
[:id :c]])
{:a "a" :b 98}))))
(deftest test-parse-opts
(testing "parses options to :options"
(is (= (:options (parse-opts ["-abp80"] [["-a" "--alpha"]
["-b" "--beta"]
["-p" "--port PORT"
:parse-fn parse-int]]))
{:alpha true :beta true :port (int 80)})))
(testing "collects error messages into :errors"
(let [specs [["-f" "--file PATH"
:validate [#(not= \/ (first %)) "Must be a relative path"]]
["-p" "--port PORT"
:parse-fn parse-int
:validate [#(< 0 % 0x10000) "Must be between 0 and 65536"]]]
errors (:errors (parse-opts ["-f" "/foo/bar" "-p0"] specs))]
(is (has-error? #"Must be a relative path" errors))
(is (has-error? #"Must be between 0 and 65536" errors))))
(testing "collects unprocessed arguments into :arguments"
(is (= (:arguments (parse-opts ["foo" "-a" "bar" "--" "-b" "baz"]
[["-a" "--alpha"] ["-b" "--beta"]]))
["foo" "bar" "-b" "baz"])))
(testing "provides an option summary at :summary"
(is (re-seq #"-a\W+--alpha" (:summary (parse-opts [] [["-a" "--alpha"]])))))
(testing "processes arguments in order when :in-order is true"
(is (= (:arguments (parse-opts ["-a" "foo" "-b"]
[["-a" "--alpha"] ["-b" "--beta"]]
:in-order true))
["foo" "-b"])))
(testing "does not merge over default values when :no-defaults is true"
(let [option-specs [["-p" "--port PORT" :default 80]
["-H" "--host HOST" :default "example.com"]
["-q" "--quiet" :default true]
["-n" "--noop"]]]
(is (= (:options (parse-opts ["-n"] option-specs))
{:port 80 :host "example.com" :quiet true :noop true}))
(is (= (:options (parse-opts ["-n"] option-specs :no-defaults true))
{:noop true}))))
(testing "accepts optional summary-fn for generating options summary"
(is (= (:summary (parse-opts [] [["-a" "--alpha"] ["-b" "--beta"]]
:summary-fn (fn [specs]
(str "Usage: myprog ["
(join \| (map :long-opt specs))
"] arg1 arg2"))))
"Usage: myprog [--alpha|--beta] arg1 arg2"))))
(comment
;; Chas Emerick's PhantomJS test runner
(spit "target/runner.js"
(slurp (clojure.java.io/resource "cemerick/cljs/test/runner.js")))
;; CLJS test runner; same as `lein cljsbuild test`
(defn run-cljs-tests []
(println
(clojure.java.shell/sh
"phantomjs"
"target/runner.js"
"target/cli_test.js")))
)