Liking cljdoc? Tell your friends :D

babashka.cli


*exit-fn*clj/s

(*exit-fn* {:keys [exit]})

Terminates the process after dispatch's :help option prints an error (unknown/missing subcommand, flag error). --help/-h is not an error - it prints help and returns, so it does not call this. Called with a map:

  • :exit - exit code (always non-zero, 1)
  • :cause - the dispatch error cause: :no-match (unknown subcommand), :input-exhausted (group with no subcommand), or the flag cause (:restrict / :require / :validate / :coerce)
  • :dispatch - the command path
  • :data - the original dispatch error data

Rebind to use your own exit codes (switch on :cause), or to not exit at all (tests, REPL):

(binding [babashka.cli/*exit-fn* (fn [m] (throw (ex-info "exit" m)))]
  ...)

Must exit or throw.

Default: System/exit (JVM), js/process.exit (Node), throw (browser).

Terminates the process after `dispatch`'s `:help` option prints an *error*
(unknown/missing subcommand, flag error). `--help`/`-h` is not an error - it
prints help and returns, so it does not call this. Called with a map:

* `:exit` - exit code (always non-zero, `1`)
* `:cause` - the dispatch error cause: `:no-match` (unknown subcommand),
  `:input-exhausted` (group with no subcommand), or the flag cause
  (`:restrict` / `:require` / `:validate` / `:coerce`)
* `:dispatch` - the command path
* `:data` - the original `dispatch` error data

Rebind to use your own exit codes (switch on `:cause`), or to not exit at all
(tests, REPL):

```clojure
(binding [babashka.cli/*exit-fn* (fn [m] (throw (ex-info "exit" m)))]
  ...)
```

Must exit or throw.

Default: `System/exit` (JVM), `js/process.exit` (Node), `throw` (browser).
sourceraw docstring

apply-defaultsclj/s

(apply-defaults m)
(apply-defaults m opts)

Fills missing keys in m from defaults. Existing keys in m win. Preserves metadata of m.

Supported options:

  • :exec-args - map of defaults. Not subject to :restrict.
  • :spec - spec; :default entries become defaults via spec->opts.
Fills missing keys in `m` from defaults. Existing keys in `m` win.
Preserves metadata of `m`.

Supported options:
* `:exec-args` - map of defaults. Not subject to `:restrict`.
* `:spec` - spec; `:default` entries become defaults via `spec->opts`.
sourceraw docstring

auto-coerceclj/s

(auto-coerce s)

Auto-coerces s to data. Does not coerce when s is not a string. If s:

  • is true or false, it is coerced as boolean
  • starts with number, it is coerced as a number (through Clojure's edn/read-string)
  • starts with :, it is coerced as a keyword (through parse-keyword)
Auto-coerces `s` to data. Does not coerce when `s` is not a string.
If `s`:
* is `true` or `false`, it is coerced as boolean
* starts with number, it is coerced as a number (through Clojure's `edn/read-string`)
* starts with `:`, it is coerced as a keyword (through [[parse-keyword]])
sourceraw docstring

coerceclj/s

(coerce s f)

Coerce string s using f. Does not coerce when s is not a string. f may be a keyword (:boolean, :int, :double, :symbol, :keyword) or a function. When f return nil, this is interpreted as a parse failure and throws.

Coerce string `s` using `f`. Does not coerce when `s` is not a string.
`f` may be a keyword (`:boolean`, `:int`, `:double`, `:symbol`,
`:keyword`) or a function. When `f` return `nil`, this is
interpreted as a parse failure and throws.
sourceraw docstring

coerce-optsclj/s

(coerce-opts m)
(coerce-opts m opts)

Coerces values in the map m using the provided configuration. Does not coerce values that are not strings. Returns a new map with coerced values.

Supported options:

  • :coerce - a map of option (keyword) names to type keywords (optionally wrapped in a collection).
  • :spec - a spec of options. See spec.
  • :error-fn - error handler, called with a map containing :cause (:coerce), :msg, :option, :value, :opts, and :flag (when the option was typed).

:flag is the literal option token as it appeared on the command line (e.g. "--foo", "-f", or ":foo"), as opposed to :option, the normalized keyword (:foo). It lets a handler echo what the user actually typed rather than reconstruct it. It is omitted when no originating token is known.

Coerces values in the map `m` using the provided configuration.
Does not coerce values that are not strings.
Returns a new map with coerced values.

Supported options:
* `:coerce` - a map of option (keyword) names to type keywords (optionally wrapped in a collection).
* `:spec` - a spec of options. See [spec](https://github.com/babashka/cli#spec).
* `:error-fn` - error handler, called with a map containing `:cause` (`:coerce`), `:msg`, `:option`, `:value`, `:opts`, and `:flag` (when the option was typed).

`:flag` is the literal option token as it appeared on the command line (e.g.
`"--foo"`, `"-f"`, or `":foo"`), as opposed to `:option`, the normalized
keyword (`:foo`). It lets a handler echo what the user actually typed rather
than reconstruct it. It is omitted when no originating token is known.
sourceraw docstring

default-width-fnclj/s

(default-width-fn _cfg)

The default :max-width-fn for format-table/format-opts. Receives the table cfg map (currently unused, reserved for extension) and returns the terminal width or nil: node process.stdout.columns, else $COLUMNS, else a JLine provider probe (clj, when JLine is on the classpath, e.g. babashka), else nil (the caller then falls back to 80).

The default `:max-width-fn` for [[format-table]]/[[format-opts]]. Receives the
table cfg map (currently unused, reserved for extension) and returns the terminal
width or nil: node `process.stdout.columns`, else `$COLUMNS`, else a JLine
provider probe (clj, when JLine is on the classpath, e.g. babashka), else nil
(the caller then falls back to 80).
sourceraw docstring

dispatchclj/s

(dispatch table args)
(dispatch table args opts)

Subcommand dispatcher.

Dispatches on longest matching command entry in table by matching subcommands to the :cmds vector and invoking the correspondig :fn.

Table is in the form:

[{:cmds ["sub_1" .. "sub_n"] :fn f :args->opts [:lib]}
 ...
 {:cmds [] :fn f}]

When a match is found, :fn called with the return value of parse-args applied to args enhanced with:

  • :dispatch - the matching commands
  • :args - concatenation of unparsed commands and args
  • :rest-cmds: DEPRECATED, this will be removed in a future version

Use an empty :cmds vector to always match or to provide global options.

For a single-command CLI (no subcommands), use a one-entry table whose :cmds is []:

(dispatch [{:cmds [] :fn f :spec spec}] args {:prog "tool" :help true})

Provide an :error-fn to deal with non-matches.

Set :prog to the program name shown in help. Provide :help true to wire up help without :restrict:

  • --help/-h print help for the command they precede and return (no error, so the process ends with status 0). This goes through a :help-fn.
  • an unknown/missing subcommand or a flag error prints a terse message and exits non-zero (via *exit-fn*). This goes through the :error-fn.

Both default handlers can be overridden: pass your own :help-fn (called with {:tree :dispatch :prog :inherit}) and/or :error-fn. dispatch threads :prog, :inherit and the command tree into the data either receives, so they can render without being handed them separately.

Each entry in the table may have additional parse-args options.

For more information and examples, see README.md.

Subcommand dispatcher.

Dispatches on longest matching command entry in `table` by matching
subcommands to the `:cmds` vector and invoking the correspondig `:fn`.

Table is in the form:

```clojure
[{:cmds ["sub_1" .. "sub_n"] :fn f :args->opts [:lib]}
 ...
 {:cmds [] :fn f}]
```

When a match is found, `:fn` called with the return value of
[[parse-args]] applied to `args` enhanced with:

* `:dispatch` - the matching commands
* `:args` - concatenation of unparsed commands and args
* `:rest-cmds`: DEPRECATED, this will be removed in a future version

Use an empty `:cmds` vector to always match or to provide global options.

For a single-command CLI (no subcommands), use a one-entry table whose `:cmds`
is `[]`:

```clojure
(dispatch [{:cmds [] :fn f :spec spec}] args {:prog "tool" :help true})
```

Provide an `:error-fn` to deal with non-matches.

Set `:prog` to the program name shown in help. Provide `:help true` to wire up
help without `:restrict`:

* `--help`/`-h` print help for the command they precede and return (no error,
  so the process ends with status 0). This goes through a `:help-fn`.
* an unknown/missing subcommand or a flag error prints a terse message and
  exits non-zero (via [[*exit-fn*]]). This goes through the `:error-fn`.

Both default handlers can be overridden: pass your own `:help-fn` (called with
`{:tree :dispatch :prog :inherit}`) and/or `:error-fn`. `dispatch` threads
`:prog`, `:inherit` and the command tree into the data either receives, so
they can render without being handed them separately.

Each entry in the table may have additional [[parse-args]] options.

For more information and examples, see [README.md](README.md#subcommands).
sourceraw docstring

format-command-errorclj/s

(format-command-error {:keys [cause dispatch wrong-input msg prog inherit
                              tree]})

Render a terse, helpful message (a string) for a dispatch error, given the data dispatch passes to its :error-fn:

  • :no-match (unknown subcommand) -> message + commands + hint
  • :input-exhausted (group, no subcommand) -> message + commands + hint
  • flag error (:restrict / :require / :validate / :coerce) -> message
    • usage + hint

Reads the command tree, :prog, :inherit, :dispatch (the path), and for flag errors :msg (and for :no-match, :wrong-input) from the data. Messages name the flag as typed (--foo/-x), not :foo.

This is the renderer the :help option's default :error-fn uses (it prints this, then calls *exit-fn*). Call it from a custom :error-fn to keep the standard message and add your own output. --help/-h is not an error - it goes to the :help-fn, rendered by format-command-help.

Render a terse, helpful message (a string) for a dispatch error, given the
data `dispatch` passes to its `:error-fn`:

* `:no-match` (unknown subcommand) -> message + commands + hint
* `:input-exhausted` (group, no subcommand) -> message + commands + hint
* flag error (`:restrict` / `:require` / `:validate` / `:coerce`) -> message
  + usage + hint

Reads the command tree, `:prog`, `:inherit`, `:dispatch` (the path), and for
flag errors `:msg` (and for `:no-match`, `:wrong-input`) from the data.
Messages name the flag as typed (`--foo`/`-x`), not `:foo`.

This is the renderer the `:help` option's default `:error-fn` uses (it prints
this, then calls [[*exit-fn*]]). Call it from a custom `:error-fn` to keep the
standard message and add your own output. `--help`/`-h` is not an error - it
goes to the `:help-fn`, rendered by [[format-command-help]].
sourceraw docstring

format-command-helpclj/s

(format-command-help {:keys [table cmds prog inherit] :or {cmds []}})

Render conventional --help text (a string) for the command at path cmds in a dispatch table (or the tree from table->tree):

Usage: <prog> [options] <command>

<description>            ; the entry's :doc (first line, then the rest)

Commands:                ; child commands with their one-line :doc
  ...
Options:                 ; the command's own :spec
  ...
Inherited options:       ; ancestor options usable here (:inherit), deduped
  ...
<epilog>                 ; the entry's :epilog free-text, rendered verbatim

An entry's :epilog (a string) is rendered verbatim after the options - use it for examples, notes or links. Put it on the root entry (:cmds []) for the top-level help.

Takes a single map:

  • :table - a dispatch table, or a tree from table->tree (required)
  • :cmds - the command path, e.g. ["deps" "outdated"] (default [])
  • :prog - program name shown in the usage line (required)
  • :inherit - only needed when you pass a dispatch-level :inherit to dispatch; pass the same value so Inherited options: matches. Per-option :inherit true is detected automatically.

Options are listed in the entry's :order when it has one, else in spec order (a vec-of-pairs :spec keeps its order; a map follows key order, unreliable beyond a few keys - use a vec-of-pairs spec or :order).

This is the renderer the :help option uses; call it from a custom :help-fn to render the standard help and then add your own output. An entry may carry :no-doc true to be omitted from Commands:.

Render conventional `--help` text (a string) for the command at path `cmds`
in a `dispatch` table (or the tree from [[table->tree]]):

```
Usage: <prog> [options] <command>

<description>            ; the entry's :doc (first line, then the rest)

Commands:                ; child commands with their one-line :doc
  ...
Options:                 ; the command's own :spec
  ...
Inherited options:       ; ancestor options usable here (:inherit), deduped
  ...
<epilog>                 ; the entry's :epilog free-text, rendered verbatim
```

An entry's `:epilog` (a string) is rendered verbatim after the options - use it
for examples, notes or links. Put it on the root entry (`:cmds []`) for the
top-level help.

Takes a single map:
* `:table`   - a `dispatch` table, or a tree from [[table->tree]] (required)
* `:cmds`    - the command path, e.g. `["deps" "outdated"]` (default `[]`)
* `:prog`    - program name shown in the usage line (required)
* `:inherit` - only needed when you pass a dispatch-level `:inherit` to
               `dispatch`; pass the same value so `Inherited options:` matches.
               Per-option `:inherit true` is detected automatically.

Options are listed in the entry's `:order` when it has one, else in spec order
(a vec-of-pairs `:spec` keeps its order; a map follows key order, unreliable
beyond a few keys - use a vec-of-pairs spec or `:order`).

This is the renderer the `:help` option uses; call it from a custom `:help-fn`
to render the standard help and then add your own output. An entry may carry
`:no-doc true` to be omitted from `Commands:`.
sourceraw docstring

format-optsclj/s

(format-opts {:as cfg
              :keys [indent wrap max-width-fn]
              :or {indent 2 wrap true max-width-fn default-width-fn}})
source

format-tableclj/s

(format-table {:keys [rows indent divider wrap max-width-fn]
               :or
                 {indent 2 divider " " wrap true max-width-fn default-width-fn}
               :as cfg})
source

merge-optsclj/s

(merge-opts m & ms)

Merges babashka CLI options.

Merges babashka CLI options.
sourceraw docstring

number-char?clj/s

(number-char? c)
source

opts->tableclj/s

(opts->table {:keys [spec order columns]})
source

parse-argsclj/s

(parse-args args)
(parse-args args opts)

Same as parse-opts with return data reshaped.

Returns a map with:

  • :opts parsed opts
  • :args remaining unparsed args
Same as [[parse-opts]] with return data reshaped.

Returns a map with:
* `:opts` parsed opts
* `:args` remaining unparsed `args`
sourceraw docstring

parse-cmdsclj/s

(parse-cmds args)
(parse-cmds args {:keys [no-keyword-opts]})

Parses sub-commands (arguments not starting with an option prefix). Returns a map with:

  • :cmds - The parsed subcommands
  • :args - The remaining (unparsed) arguments
Parses sub-commands (arguments not starting with an option prefix). Returns a map with:
* `:cmds` - The parsed subcommands
* `:args` - The remaining (unparsed) arguments
sourceraw docstring

parse-keywordclj/s

(parse-keyword s)

Parse keyword from s. Ignores leading :.

Parse keyword from `s`. Ignores leading `:`.
sourceraw docstring

parse-optsclj/s

(parse-opts args)
(parse-opts args opts)

Returns a map of options parsed from command line arguments args, a seq of strings. Instead of a leading : either -- or - may be used as well.

Metadata on returned map, under :org.babashka/cli:

  • :args remaining unparsed args (not corresponding to any options)

Supported opts:

  • :coerce - a map of option (keyword) names to type keywords (optionally wrapped in a collection.)
  • :alias - a map of short names to long names.
  • :spec - a spec of options. See spec.
  • :restrict - true or coll of keys. Throw on first parsed option not in set of keys or keys of :spec and :coerce combined.
  • :require - a coll of options that are required. See require.
  • :validate - a map of validator functions. See validate.
  • :exec-args - a map of default args. Will be overridden by args specified in args. Values from :exec-args are NOT coerced or auto-coerced; provide them in their final form. Not subject to :restrict.
  • :no-keyword-opts - true. Support only --foo-style opts (i.e. :foo will not work).
  • :repeated-opts - true. Forces writing the option name for every value, e.g. --foo a --foo b, rather than --foo a b
  • :args->opts - consume unparsed commands and args as options
  • :collect - a map of collection fns. See custom collection handling.

Examples:

(parse-opts ["foo" ":bar" "1"])
;; => ^{:org.babashka/cli {:args ["foo"]}} {:bar 1}
(parse-opts [":b" "1"] {:aliases {:b :bar} :coerce {:bar parse-long}})
;; => {:bar 1}
(parse-opts ["--baz" "--qux"] {:spec {:baz {:desc "Baz"}} :restrict true})
;; => throws 'Unknown option --qux' exception b/c there is no :qux key in the spec

See also: parse-args

Returns a map of options parsed from command line arguments `args`, a seq of strings.
Instead of a leading `:` either `--` or `-` may be used as well.

Metadata on returned map, under `:org.babashka/cli`:
* `:args` remaining unparsed `args` (not corresponding to any options)

Supported `opts`:
* `:coerce` - a map of option (keyword) names to type keywords (optionally wrapped in a collection.)
* `:alias` - a map of short names to long names.
* `:spec` - a spec of options. See [spec](https://github.com/babashka/cli#spec).
* `:restrict` - `true` or coll of keys. Throw on first parsed option not in set of keys or keys of `:spec` and `:coerce` combined.
* `:require` - a coll of options that are required. See [require](https://github.com/babashka/cli#restrict).
* `:validate` - a map of validator functions. See [validate](https://github.com/babashka/cli#validate).
* `:exec-args` - a map of default args. Will be overridden by args specified in `args`. Values from `:exec-args` are NOT coerced or auto-coerced; provide them in their final form. Not subject to `:restrict`.
* `:no-keyword-opts` - `true`. Support only `--foo`-style opts (i.e. `:foo` will not work).
* `:repeated-opts` - `true`. Forces writing the option name for every value, e.g. `--foo a --foo b`, rather than `--foo a b`
* `:args->opts` - consume unparsed commands and args as options
* `:collect` - a map of collection fns. See [custom collection handling](https://github.com/babashka/cli#custom-collection-handling).

Examples:

```clojure
(parse-opts ["foo" ":bar" "1"])
;; => ^{:org.babashka/cli {:args ["foo"]}} {:bar 1}
(parse-opts [":b" "1"] {:aliases {:b :bar} :coerce {:bar parse-long}})
;; => {:bar 1}
(parse-opts ["--baz" "--qux"] {:spec {:baz {:desc "Baz"}} :restrict true})
;; => throws 'Unknown option --qux' exception b/c there is no :qux key in the spec
```
See also: [[parse-args]]
sourceraw docstring

parse-opts*clj/s

(parse-opts* args
             {:keys [coerce collect no-keyword-opts repeated-opts] :as opts})

Parses CLI args into a raw opts map. Returns string values unchanged (no coercion), does not apply :exec-args defaults, does not run :restrict/:require/:validate. Result map includes :org.babashka/cli metadata and internal ::implicit-true-keys / ::keys-order metadata used by coerce-opts.

Use this when you want to merge other sources (e.g. config files) before coerce/validate. Pipeline: parse-opts* -> merge -> apply-defaults -> coerce-opts -> validate-opts.

Supported options (subset of parse-opts): :alias/:aliases, :coerce, :collect, :no-keyword-opts, :repeated-opts, :args->opts, :spec.

Parses CLI `args` into a raw opts map. Returns string values unchanged
(no coercion), does not apply `:exec-args` defaults, does not run
`:restrict`/`:require`/`:validate`. Result map includes
`:org.babashka/cli` metadata and internal `::implicit-true-keys` /
`::keys-order` metadata used by `coerce-opts`.

Use this when you want to merge other sources (e.g. config files)
before coerce/validate. Pipeline: `parse-opts*` -> merge -> `apply-defaults`
-> `coerce-opts` -> `validate-opts`.

Supported options (subset of `parse-opts`): `:alias`/`:aliases`, `:coerce`,
`:collect`, `:no-keyword-opts`, `:repeated-opts`, `:args->opts`, `:spec`.
sourceraw docstring

spec->optsclj/s

(spec->opts spec)
(spec->opts spec {:keys [exec-args]})

Converts spec into opts format. Pass existing opts as optional second argument.

Converts spec into opts format. Pass existing opts as optional second argument.
sourceraw docstring

table->treeclj/s

(table->tree table)

Converts a dispatch table into a tree. Each :cmds becomes a path of nested :cmd maps; other entry keys are kept on the node. Empty :cmds merges onto the root.

(table->tree [{:cmds ["add"] :fn add} {:cmds [] :fn help}])
;; => {:fn help, :cmd {"add" {:fn add}}}
Converts a `dispatch` table into a tree. Each `:cmds` becomes a path of
nested `:cmd` maps; other entry keys are kept on the node. Empty `:cmds`
merges onto the root.

```clojure
(table->tree [{:cmds ["add"] :fn add} {:cmds [] :fn help}])
;; => {:fn help, :cmd {"add" {:fn add}}}
```
sourceraw docstring

validate-optsclj/s

(validate-opts m)
(validate-opts m opts)

Validates the map m using the provided configuration. Returns m.

Supported options:

  • :restrict - true or coll of keys. Error on keys in m not in the restrict set or not derivable from :spec and :coerce.
  • :require - a coll of options that are required.
  • :validate - a map of option keys to validator functions (or maps with :pred and :ex-msg).
  • :spec - a spec of options (restrict, require, validate extracted from it).
  • :coerce - used with :restrict true to derive the set of known keys.
  • :error-fn - error handler, called with a map containing :cause, :msg, :option, :opts, and :flag.

:flag is the literal option token as it appeared on the command line (e.g. "--foo", "-f", or ":foo"), as opposed to :option, the normalized keyword (:foo). It lets a handler echo what the user actually typed rather than reconstruct it. It is present for :restrict and :validate, and absent for :require (a missing required option was never typed, so it has no token).

Validates the map `m` using the provided configuration. Returns `m`.

Supported options:
* `:restrict` - `true` or coll of keys. Error on keys in `m` not in the restrict set or not derivable from `:spec` and `:coerce`.
* `:require` - a coll of options that are required.
* `:validate` - a map of option keys to validator functions (or maps with `:pred` and `:ex-msg`).
* `:spec` - a spec of options (restrict, require, validate extracted from it).
* `:coerce` - used with `:restrict true` to derive the set of known keys.
* `:error-fn` - error handler, called with a map containing `:cause`, `:msg`, `:option`, `:opts`, and `:flag`.

`:flag` is the literal option token as it appeared on the command line (e.g.
`"--foo"`, `"-f"`, or `":foo"`), as opposed to `:option`, the normalized
keyword (`:foo`). It lets a handler echo what the user actually typed rather
than reconstruct it. It is present for `:restrict` and `:validate`, and absent
for `:require` (a missing required option was never typed, so it has no token).
sourceraw docstring

cljdoc builds & hosts documentation for Clojure/Script libraries

Keyboard shortcuts
Ctrl+kJump to recent docs
Move to previous article
Move to next article
Ctrl+/Jump to the search field
× close