### Simple babashka CLI script example Source: https://github.com/babashka/cli/blob/main/README.md This example demonstrates a basic babashka script that uses `babashka.cli` to parse command-line arguments, including required options, directory validation, and boolean flags. It also includes custom error handling. ```clojure #!/usr/bin/env bb (require '[babashka.cli :as cli] '[babashka.fs :as fs]) (defn dir-exists? [path] (fs/directory? path)) (defn show-help [spec] (cli/format-opts (merge spec {:order (vec (keys (:spec spec)))}))) (def cli-spec {:spec {:num {:coerce :long :desc "Number of some items" :alias :n ; adds -n alias for --num :validate pos? ; tests if supplied --num >0 :require true} ; --num,-n is required :dir {:desc "Directory name to do stuff" :alias :d :validate dir-exists?} ; tests if --dir exists :flag {:coerce :boolean ; defines a boolean flag :desc "I am just a flag"} :error-fn ; a function to handle errors (fn [{:keys [spec type cause msg option] :as data}] (when (= :org.babashka/cli type) (case cause :require (println (format "Missing required argument: %s\n" option)) :validate (println (format "%s does not exist!\n" msg))))) }) (defn -main [args] (let [opts (cli/parse-opts args cli-spec)] (if (or (:help opts) (:h opts)) (println (show-help cli-spec)) (println "Here are your cli args!:": opts)))) (-main *command-line-args*) ``` -------------------------------- ### Calling build functions as CLIs Source: https://github.com/babashka/cli/blob/main/README.md Example of how to invoke build functions using the configured alias. ```bash clj -M:build jar --verbose ``` -------------------------------- ### Creating a new app with lein clj-new Source: https://github.com/babashka/cli/blob/main/README.md Example of using the configured Leiningen alias to create a new Clojure application with specific options. ```bash $ lein clj-new app --name foobar/baz --verbose 3 -f ``` -------------------------------- ### Custom Table Formatting with Headers Source: https://context7.com/babashka/cli/llms.txt Combine `opts->table` and `format-table` to create custom-formatted help tables. This example includes a header row and custom indentation. ```clojure (require '[babashka.cli :as cli]) (def spec {:input {:alias :i :ref "" :desc "Input file path" :require true} :output {:alias :o :ref "" :desc "Output file path" :default "out.txt" :default-desc "out.txt"} :format {:alias :f :ref "" :desc "Output format (json, edn, csv)" :coerce :keyword :default :json} :quiet {:alias :q :desc "Suppress output"}}) ;; Custom table formatting with headers (println (cli/format-table {:rows (concat [["" "Option" "Arg" "Default" "Description"]] (cli/opts->table {:spec spec :order [:input :output :format :quiet]})) :indent 0})) ``` -------------------------------- ### Execute a function with arguments using babashka.cli Source: https://github.com/babashka/cli/blob/main/README.md Example of calling `clojure.core/prn` with arguments using the configured `:exec` alias. Arguments are passed as key-value pairs. ```bash $ clojure -M:exec clojure.core prn :a 1 :b 2 ``` -------------------------------- ### Fold positional arguments into options with :args->opts Source: https://github.com/babashka/cli/blob/main/README.md Uses the `:args->opts` option to fold positional arguments into the parsed options map. This example maps the first positional argument to `:url`. ```clojure (def cli-opts {:coerce {:force :boolean} :args->opts [:url]}) (cli/parse-opts ["--force" "ssh://foo"] cli-opts) ;;=> {:force true, :url "ssh://foo"} (cli/parse-opts ["ssh://foo" "--force"] cli-opts) ;;=> {:url "ssh://foo", :force true} ``` -------------------------------- ### babashka.cli - Parse Commands Source: https://github.com/babashka/cli/blob/main/API.md Parses sub-commands from a list of arguments, identifying arguments that do not start with an option prefix. ```APIDOC ## `parse-cmds` ### Description Parses sub-commands (arguments not starting with an option prefix). ### Method Function ### Endpoint N/A (Library function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```clojure (parse-cmds ["subcommand" "arg1" "--opt" "val"]) ;; => ["subcommand" "arg1"] ``` ### Response #### Success Response (200) A vector of sub-command arguments. #### Response Example ```clojure ["subcommand" "arg1"] ``` ``` -------------------------------- ### Dispatch Function Shared Options Example Output Source: https://github.com/babashka/cli/blob/main/README.md When using shared options, the `dispatch` function aggregates options from global and subcommand specs into a single map. ```clojure {:dispatch ["sub1" "sub2"], :opts {:foo :a, :bar :b, :baz :c}, :args ["arg"]} ``` -------------------------------- ### Using babashka.cli.exec with Clojure CLI Source: https://context7.com/babashka/cli/llms.txt Integrate babashka.cli with the Clojure CLI to call any function accepting a map from the command line. This example shows basic usage and setting up an alias in deps.edn. ```clojure ;; In deps.edn, add an alias: ;; :exec {:extra-deps {org.babashka/cli {:mvn/version "0.8.67"}} ;; :main-opts ["-m" "babashka.cli.exec"]} ;; Call any function with a map argument: ;; $ clojure -M:exec clojure.core prn :a 1 :b 2 ;;=> {:a "1", :b "2"} ``` ```clojure ;; With exec-fn predefined: ;; :prn {:extra-deps {org.babashka/cli {:mvn/version "0.8.67"}} ;; :exec-fn clojure.core/prn ;; :main-opts ["-m" "babashka.cli.exec"]} ;; $ clojure -M:prn --foo=bar --baz ;;=> {:foo "bar", :baz true} ``` -------------------------------- ### Define function with babashka.cli metadata for coercion Source: https://github.com/babashka/cli/blob/main/README.md Define a Clojure function with `:org.babashka/cli` metadata to specify argument coercions. This example coerces `:a` to a symbol and `:b` to a long. ```clojure (ns my-ns) (defn foo {:org.babashka/cli {:coerce {:a :symbol :b :long}}} ;; map argument: [m] ;; print map argument: (prn m)) ``` -------------------------------- ### Validate Option Values with Predicates Source: https://context7.com/babashka/cli/llms.txt Use the :validate option with a predicate function to ensure option values meet specific criteria. This example checks if a port number is positive. ```clojure (require '[babashka.cli :as cli]) ;; Validate option values (cli/parse-opts ["--port" "0"] {:coerce {:port :long} :validate {:port pos?}}) ;; Throws: "Invalid value for option :port: 0" ``` -------------------------------- ### Configure coercion for external functions in deps.edn Source: https://github.com/babashka/cli/blob/main/README.md Modify parsing behavior for functions you don't control by adding `:org.babashka/cli` data to the alias. This example coerces `--foo` to a long. ```clojure :prn {:deps {org.babashka/cli {:mvn/version ""}} :exec-fn clojure.core/prn :main-opts ["-m" "babashka.cli.exec"] :org.babashka/cli {:coerce {:foo :long}}} ``` -------------------------------- ### Function Metadata for CLI Coercion Source: https://context7.com/babashka/cli/llms.txt Add metadata to functions to define CLI argument coercion and aliases without external configuration. This example shows how to coerce a port to :long and paths to a vector. ```clojure (ns myapp.core) (defn run {:org.babashka/cli {:coerce {:port :long :paths []} :alias {:p :port}}} [opts] (println "Running with:" opts)) ;; $ clojure -M:exec myapp.core run -p 3000 --paths src test ;;=> Running with: {:port 3000, :paths ["src" "test"]} ``` -------------------------------- ### Complete CLI Application with Babashka CLI Source: https://context7.com/babashka/cli/llms.txt This snippet demonstrates a full CLI application with global options, subcommands (init, build, help), argument parsing, and error handling. It uses `babashka.cli`'s dispatch table for command routing and spec definitions for option validation and help generation. ```clojure #!/usr/bin/env bb (require '[babashka.cli :as cli]) (def global-spec {:verbose {:alias :v :coerce :boolean :desc "Enable verbose output"} :config {:alias :c :ref "" :desc "Config file path"}}) (def init-spec {:template {:alias :t :ref "" :desc "Project template" :default "default"} :force {:alias :f :coerce :boolean :desc "Overwrite existing files"}}) (def build-spec {:output {:alias :o :ref "" :desc "Output directory" :default "dist"} :minify {:alias :m :coerce :boolean :desc "Minify output"}}) (defn show-help [_] (println "Usage: mycli [options] [command-options]") (println "\nGlobal options:") (println (cli/format-opts {:spec global-spec})) (println "\nCommands:") (println " init Initialize a new project") (println " build Build the project")) (defn init-cmd [{:keys [opts]}] (println "Initializing project with template:" (:template opts)) (when (:verbose opts) (println "Verbose mode enabled")) (when (:force opts) (println "Force mode - overwriting files"))) (defn build-cmd [{:keys [opts]}] (println "Building to:" (:output opts)) (when (:minify opts) (println "Minification enabled"))) (def dispatch-table [{:cmds [] :spec global-spec} {:cmds ["init"] :fn init-cmd :spec init-spec} {:cmds ["build"] :fn build-cmd :spec build-spec} {:cmds ["help"] :fn show-help}]) (defn -main [args] (cli/dispatch dispatch-table args {:error-fn (fn [{:keys [cause msg]}] (println "Error:" msg) (show-help nil) (System/exit 1))})) (-main *command-line-args*) ;; Example invocations: ;; $ mycli --verbose init --template react --force ;; $ mycli build --output build --minify ;; $ mycli help ``` -------------------------------- ### babashka.cli.exec/-main Source: https://github.com/babashka/cli/blob/main/API.md Main entrypoint for command line usage of babashka.cli.exec. ```APIDOC ## -main ### Description Main entrypoint for command line usage. Expects a namespace and var name followed by zero or more key-value pair arguments that will be parsed and passed to the var. If the first argument is map-shaped, it is read as an EDN map containing parse instructions. ### Function Signature ```clojure (-main & args) ``` ### Parameters #### Path Parameters - **args** (variadic) - Arguments passed to the main function. ### Example ```clojure clojure -M:exec clojure.core prn :a 1 :b 2 ;;=> {:a "1" :b "2"} ``` ``` -------------------------------- ### Run kaocha with CLI arguments Source: https://github.com/babashka/cli/blob/main/README.md Invoke `kaocha` using the configured `:kaocha` alias, demonstrating the use of aliased options like `--watch` and `--fail-fast`, and a coerced reporter option. ```bash $ clj -M:kaocha --watch --fail-fast --kaocha/reporter kaocha.report/documentation ``` -------------------------------- ### Custom collection handling with :collect Source: https://github.com/babashka/cli/blob/main/README.md Uses the `:collect` option for custom transformation of arguments into a collection. This example splits comma-separated values into a vector. ```clojure (cli/parse-opts ["--foo" "a,b" "--foo=c,d,e" "--foo" "f"] {:collect {:foo (fn [coll arg-value] (into (or coll []) (str/split arg-value #",")))}}) ;; => {:foo ["a" "b" "c" "d" "e" "f"]} ``` -------------------------------- ### Generate Formatted Help Text Source: https://context7.com/babashka/cli/llms.txt Use `format-opts` to generate human-readable help text from a spec. It displays options, aliases, argument references, defaults, and descriptions. ```clojure (require '[babashka.cli :as cli]) (def spec {:input {:alias :i :ref "" :desc "Input file path" :require true} :output {:alias :o :ref "" :desc "Output file path" :default "out.txt" :default-desc "out.txt"} :format {:alias :f :ref "" :desc "Output format (json, edn, csv)" :coerce :keyword :default :json} :quiet {:alias :q :desc "Suppress output"}}) ;; Generate formatted help (println (cli/format-opts {:spec spec :order [:input :output :format :quiet]})) ;; Output: ;; -i, --input Input file path ;; -o, --output out.txt Output file path ;; -f, --format :json Output format (json, edn, csv) ;; -q, --quiet Suppress output ``` -------------------------------- ### babashka.cli.exec - Main Entrypoint Source: https://github.com/babashka/cli/blob/main/API.md The main entrypoint for command-line usage of the babashka.cli.exec module. ```APIDOC ## `-main` (babashka.cli.exec) ### Description Main entrypoint for command line usage. ### Method Function ### Endpoint N/A (Executable function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```clojure (babashka.cli.exec/-main "--help") ``` ### Response #### Success Response (0) Indicates successful execution. #### Response Example ```clojure 0 ``` ``` -------------------------------- ### babashka.cli.exec/main Source: https://github.com/babashka/cli/blob/main/API.md Main function for babashka.cli.exec. ```APIDOC ## main ### Description Main function for the `babashka.cli.exec` namespace. ### Function Signature ```clojure (main & args) ``` ### Parameters #### Path Parameters - **args** (variadic) - Arguments passed to the main function. ### Response Example (No specific response example provided in the source) ``` -------------------------------- ### Custom Error Handler Function Source: https://context7.com/babashka/cli/llms.txt Define a custom :error-fn to control how parsing errors are handled. This example provides specific logic for missing required options. ```clojure (require '[babashka.cli :as cli]) ;; Custom error handler (cli/parse-opts [] {:spec {:config {:require true}}} :error-fn (fn [{:keys [cause option msg]}] (case cause :require (do (println "Error: Missing required option" option) (System/exit 1)) (println "Error:" msg))) }) ;; Prints: "Error: Missing required option :config" ``` -------------------------------- ### Main Entrypoint for CLI Execution Source: https://github.com/babashka/cli/blob/main/API.md The main function for command-line execution. It expects a namespace and var name, followed by arguments to be parsed and passed to the var. Can also accept EDN maps for parse instructions. ```clojure (-main & args) ``` ```clojure clojure -M:exec clojure.core prn :a 1 :b 2 ``` -------------------------------- ### Leiningen profile for clj-new with babashka/cli Source: https://github.com/babashka/cli/blob/main/README.md Configure ~/.lein/profiles.clj to include babashka/cli and clj-new for project generation. Replace '' with the appropriate version. ```clojure {:clj-1.11 {:dependencies [[org.clojure/clojure "1.11.1"]]} :clj-new {:dependencies [[org.babashka/cli ""] [com.github.seancorfield/clj-new "1.2.381"]]} :user {:aliases {"clj-new" ["with-profiles" "+clj-1.11,+clj-new" "run" "-m" "babashka.cli.exec" {:exec-args {:env {:description "My project"}} :coerce {:verbose :long :args []} :alias {:f :force}} "clj-new"]}}} ``` -------------------------------- ### Compare antq CLI invocation with T-invocation Source: https://github.com/babashka/cli/blob/main/README.md Illustrates the difference between calling `antq outdated` via `babashka.cli.exec` and its standard `-T` invocation, highlighting argument passing styles. ```bash $ clj -Tantq outdated :upgrade true ``` -------------------------------- ### Custom Validation with Error Messages Source: https://context7.com/babashka/cli/llms.txt Provide a map to :validate for custom validation logic and specific error messages. This example ensures a port number is within the valid range (1-65535). ```clojure (require '[babashka.cli :as cli]) ;; Custom validation with error message (cli/parse-opts ["--port" "70000"] {:coerce {:port :long} :validate {:port {:pred #(< 0 % 65536) :ex-msg (fn [{:keys [value]}] (str "Port must be 1-65535, got: " value))}}}) ;; Throws: "Port must be 1-65535, got: 70000" ``` -------------------------------- ### Custom error handler for missing required argument Source: https://github.com/babashka/cli/blob/main/README.md Implement a custom `:error-fn` to handle specific errors like missing required arguments. This example prints a formatted message and exits the program. ```clojure (cli/parse-opts [] {:spec {:foo {:desc "You know what this is." :ref "" :require true}} :error-fn (fn [{:keys [spec type cause msg option] :as data}] (if (= :org.babashka/cli type) (case cause :require (println (format "Missing required argument:\n%s" (cli/format-opts {:spec (select-keys spec [option])}))) (println msg)) (throw (ex-info msg data))) (System/exit 1))}) ``` -------------------------------- ### Option Parsing with parse-opts Source: https://github.com/babashka/cli/blob/main/README.md Demonstrates various ways to parse command-line options using the `parse-opts` function, including coercion, aliases, and handling of boolean flags. ```APIDOC ## POST /api/parse-opts ### Description Parses command-line options using the `parse-opts` function. ### Method POST ### Endpoint /api/parse-opts ### Parameters #### Request Body - **args** (array[string]) - Required - The command-line arguments to parse. - **opts** (object) - Optional - Configuration options for parsing. - **coerce** (object) - Optional - Specifies type coercion for options. - **alias** (object) - Optional - Defines aliases for options. - **collect** (object) - Optional - Custom collection handling for options. ### Request Example ```json { "args": ["--port", "1339"], "opts": { "coerce": {"port": ":long"} } } ``` ### Response #### Success Response (200) - **parsed_options** (object) - The parsed options and arguments. #### Response Example ```json { "parsed_options": { "port": 1339 } } ``` ``` -------------------------------- ### Dispatch Function Help Output Source: https://github.com/babashka/cli/blob/main/README.md When the `--help` flag is provided, `dispatch` calls the designated help function, returning a map indicating the parsed options and the matched dispatch function. ```clojure {:opts {:help true}, :dispatch [], :fn :help} ``` -------------------------------- ### Format CLI Help Message Source: https://github.com/babashka/cli/blob/main/README.md Generate a formatted help message from a spec and an order definition. This is useful for displaying available options to the user. ```clojure (println (cli/format-opts {:spec spec :order [:from :to :paths :pretty]})) ``` -------------------------------- ### tools.deps.graph alias for babashka/cli Source: https://github.com/babashka/cli/blob/main/README.md Set up a deps.edn alias to integrate babashka/cli with tools.deps.graph. Replace '' with the correct version. ```clojure :graph {:deps {org.babashka/cli {:mvn/version ""} org.clojure/tools.deps.graph {:mvn/version "1.1.68"}} :exec-fn clojure.tools.deps.graph/graph :exec-args {} ;; insert default arguments here :org.babashka/cli {:coerce {:trace-omit [:symbol]}} :main-opts ["-m" "babashka.cli.exec"]} ``` -------------------------------- ### Configure codox alias with babashka.cli Source: https://github.com/babashka/cli/blob/main/README.md Alias configuration for `codox` using `babashka.cli.exec`. It includes dependencies, the execution function, default arguments, and CLI coercion rules for paths and themes. ```clojure :codox {:extra-deps {org.babashka/cli {:mvn/version ""} codox/codox {:mvn/version "0.10.8"}} :exec-fn codox.main/generate-docs ;; default arguments: :exec-args {:source-paths ["src"]} :org.babashka/cli {:coerce {:source-paths [] :doc-paths [] :themes [:keyword]}} :main-opts ["-m" "babashka.cli.exec"]} ``` -------------------------------- ### Configure babashka.cli in deps.edn Source: https://github.com/babashka/cli/blob/main/README.md Add this alias to your `deps.edn` to enable `babashka.cli` for executing functions via `clojure -M:exec`. Ensure you replace `` with the actual latest version. ```clojure :exec {:extra-deps {org.babashka/cli {:mvn/version ""}} :main-opts ["-m" "babashka.cli.exec"]} ``` -------------------------------- ### Invoking tools.deps.graph with CLI arguments Source: https://github.com/babashka/cli/blob/main/README.md Command line invocation for the tools.deps.graph alias, demonstrating CLI argument usage. ```bash clj -M:graph --size --output graph.png ``` -------------------------------- ### Add babashka.cli to deps.edn or bb.edn Source: https://github.com/babashka/cli/blob/main/README.md Include the babashka.cli library in your project's dependencies by adding it to your `deps.edn` or `bb.edn` file. ```clojure org.babashka/cli {:mvn/version ""} ``` -------------------------------- ### Run antq with skip option Source: https://github.com/babashka/cli/blob/main/README.md Execute `antq` with the `--skip` option, which is collected into a vector due to the `:org.babashka/cli {:coerce {:skip []}}` configuration. ```bash clj -M:antq --upgrade --skip github-action ``` -------------------------------- ### babashka.cli - Format Options Source: https://github.com/babashka/cli/blob/main/API.md Formats options, potentially with indentation, for display or further processing. ```APIDOC ## `format-opts` ### Description Formats options, potentially with indentation. ### Method Function ### Endpoint N/A (Library function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```clojure (format-opts {:keys [indent], :or {indent 2}}) ``` ### Response #### Success Response (200) Formatted options. #### Response Example ```clojure {:keys [:indent], :or {:indent 2}} ``` ``` -------------------------------- ### Define and Parse CLI Options with Spec Source: https://context7.com/babashka/cli/llms.txt Define CLI options with descriptions, coercion, aliases, defaults, validation, and requirement settings using a spec map. Parse arguments against this spec. ```clojure (require '[babashka.cli :as cli]) (def cli-spec {:spec {:port {:desc "Server port number" :alias :p :coerce :long :default 8080 :default-desc "8080" :validate pos?} :host {:desc "Server hostname" :alias :h :default "localhost"} :verbose {:desc "Enable verbose output" :alias :v :coerce :boolean} :config {:desc "Configuration file path" :alias :c :ref "" :require true}}}) ;; Parse with spec (cli/parse-opts ["-p" "3000" "-c" "app.edn" "--verbose"] cli-spec) ;;=> {:port 3000, :host "localhost", :config "app.edn", :verbose true} ;; Generate formatted help text (println (cli/format-opts (assoc cli-spec :order [:port :host :config :verbose]))) ;; Output: ;; -p, --port 8080 Server port number ;; -h, --host localhost Server hostname ;; -c, --config Configuration file path ;; -v, --verbose Enable verbose output ``` -------------------------------- ### Configure babashka.cli for a specific function execution Source: https://github.com/babashka/cli/blob/main/README.md Alias configuration to directly execute `clojure.core/prn` with `babashka.cli`. Replace `` with the current version. ```clojure :prn {:extra-deps {org.babashka/cli {:mvn/version ""}} :main-opts ["-m" "babashka.cli.exec" "clojure.core" "prn"]} ``` -------------------------------- ### babashka.cli - Options to Table Conversion Source: https://github.com/babashka/cli/blob/main/API.md Converts options, potentially defined by a spec, into a table format. ```APIDOC ## `opts->table` ### Description Converts spec into opts format. ### Method Function ### Endpoint N/A (Library function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```clojure (opts->table {:keys [spec order]}) ``` ### Response #### Success Response (200) Table representation of the options. #### Response Example ```clojure {:keys [:spec :order]} ``` ``` -------------------------------- ### Argument Parsing with parse-args Source: https://github.com/babashka/cli/blob/main/README.md Explains how to parse positional arguments using `parse-args` and the `:args->opts` option, including handling ambiguity and variable arguments. ```APIDOC ## POST /api/parse-args ### Description Parses positional arguments and options using the `parse-args` function. ### Method POST ### Endpoint /api/parse-args ### Parameters #### Request Body - **args** (array[string]) - Required - The command-line arguments to parse. - **opts** (object) - Optional - Configuration options for parsing. - **coerce** (object) - Optional - Specifies type coercion for options. - **args->opts** (array | object) - Optional - Maps positional arguments to options. ### Request Example ```json { "args": ["ssh://foo", "--force"], "opts": { "coerce": {"force": ":boolean"} } } ``` ### Response #### Success Response (200) - **parsed_result** (object) - The parsed arguments and options. #### Response Example ```json { "parsed_result": { "args": ["ssh://foo"], "opts": {"force": true} } } ``` ``` -------------------------------- ### Configure kaocha alias with babashka.cli Source: https://github.com/babashka/cli/blob/main/README.md Alias configuration for `kaocha` using `babashka.cli.exec`. It sets up dependencies, the execution function, and defines CLI aliases and coercions for options like `:watch`, `:fail-fast`, and `:kaocha/reporter`. ```clojure :kaocha {:extra-deps {org.babashka/cli {:mvn/version ""} lambdaisland/kaocha {:mvn/version "1.66.1034"}} :exec-fn kaocha.runner/exec-fn :exec-args {} ;; insert default arguments here :org.babashka/cli {:alias {:watch :watch? :fail-fast :fail-fast?} :coerce {:skip-meta :keyword :kaocha/reporter [:symbol]}} :main-opts ["-m" "babashka.cli.exec"]} ``` -------------------------------- ### Dispatch Function Copy Subcommand Output Source: https://github.com/babashka/cli/blob/main/README.md Executing the `copy` subcommand with arguments and options results in a map detailing the matched command, parsed options, and the invoked function. ```clojure {:cmds ["copy" "the-file"], :opts {:file "the-file" :dry-run true}, :dispatch ["copy"], :fn :copy} ``` -------------------------------- ### babashka.cli/parse-opts Source: https://github.com/babashka/cli/blob/main/API.md Parses command-line options from a sequence of strings. ```APIDOC ## parse-opts ### Description Parses options from command-line arguments (`args`), which is a sequence of strings. Options can be prefixed with `:`, `--`, or `-`. Returns a map of parsed options. Metadata on the returned map under `:org.babashka/cli` includes `:args`, the remaining unparsed arguments. ### Function Signature ```clojure (parse-opts args) (parse-opts args opts) ``` ### Parameters #### Path Parameters - **args** (seqable) - A sequence of strings representing command-line arguments. - **opts** (map, optional) - A map of supported options: * `:coerce` - Map of option names to type keywords for coercion. * `:alias` - Map of short option names to long option names. * `:spec` - Spec for options. * `:restrict` - `true` or a collection of keys to restrict parsed options. * `:require` - A collection of required options. * `:validate` - Map of validator functions for options. * `:exec-args` - Map of default arguments. * `:no-keyword-opts` - `true` to only support `--foo`-style options. * `:repeated-opts` - `true` to require option names for every value. * `:args->opts` - Consume unparsed commands and args as options. * `:collect` - Map of custom collection functions. ### Returns A map of parsed options. Metadata includes `:org.babashka/cli` with `:args`. ### Request Example ```json { "example": "(parse-opts [\"foo\" \":bar\" \"1\"])" } ``` ### Response Example ```json { "example": "^{:org.babashka/cli {:args [\"foo\"]}} {:bar 1}" } ``` ### See Also - [`parse-args`](#babashka.cli/parse-args) ``` -------------------------------- ### babashka.cli - Spec to Options Conversion Source: https://github.com/babashka/cli/blob/main/API.md Converts a specification into the babashka CLI options format. ```APIDOC ## `spec->opts` ### Description Converts spec into opts format. ### Method Function ### Endpoint N/A (Library function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```clojure (spec->opts {:keys [spec order]}) ``` ### Response #### Success Response (200) Options map derived from the spec. #### Response Example ```clojure {:keys [:spec :order]} ``` ``` -------------------------------- ### Generate Table from Spec Source: https://github.com/babashka/cli/blob/main/README.md Convert a spec into a table format using `opts->table` and then format it with `format-table`. This allows for custom table headers and formatting. ```clojure (cli/format-table {:rows (concat [["alias" "option" "ref" "default" "description"]] (cli/opts->table {:spec {:foo {:alias :f, :default "yupyupyupyup", :ref "" :desc "Thingy"} :bar {:alias :b, :default "sure", :ref "" :desc "Barbarbar" :default-desc "Mos def"}}})) :indent 2}) ``` -------------------------------- ### babashka.cli - Padding String Source: https://github.com/babashka/cli/blob/main/API.md Pads a string `s` to a specified length `len`. ```APIDOC ## `pad` ### Description Pads a string `s` to a specified length `len`. ### Method Function ### Endpoint N/A (Library function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```clojure (pad 10 "hello") ;=> "hello " ``` ### Response #### Success Response (200) Padded string. #### Response Example ```clojure "hello " ``` ``` -------------------------------- ### Alternative Spec Format for Ordering Source: https://github.com/babashka/cli/blob/main/README.md Use a vector of vectors for the spec to present options in a specific order without needing a separate `:order` key. This format is simpler for fixed option lists. ```clojure [[:pretty {:desc "Pretty-print output." :alias :p}] [:paths {:desc "Paths of files to transform." :coerce [] :default ["src" "test"] :default-desc "src test"}]] ``` -------------------------------- ### Validation with restrict, require, and validate Source: https://github.com/babashka/cli/blob/main/README.md Details how to add production-level validation using `:restrict`, `:require`, and `:validate` options to ensure input correctness. ```APIDOC ## POST /api/validate-options ### Description Validates parsed options against specified rules using `:restrict` and `:require`. ### Method POST ### Endpoint /api/validate-options ### Parameters #### Request Body - **args** (array[string]) - Required - The command-line arguments to parse. - **opts** (object) - Required - Configuration options for parsing and validation. - **restrict** (array[string]) - Optional - List of allowed options. - **require** (array[string]) - Optional - List of required options. - **validate** (object) - Optional - Custom validation functions for options. ### Request Example ```json { "args": ["--foo"], "opts": { "restrict": ["bar"] } } ``` ### Response #### Success Response (200) - **validation_status** (string) - Indicates if validation passed or failed. #### Response Example ```json { "validation_status": "failed", "error": "Unknown option: :foo" } ``` ``` -------------------------------- ### Configure antq alias with babashka.cli Source: https://github.com/babashka/cli/blob/main/README.md Alias configuration for `antq` using `babashka.cli.exec`. It specifies dependencies, main options, and CLI coercion rules, ensuring `--skip` options are collected into a vector. ```clojure :antq {:deps {org.babashka/cli {:mvn/version ""} com.github.liquidz/antq {:mvn/version "1.7.798"}} :paths [] :main-opts ["-m" "babashka.cli.exec" "antq.tool" "outdated"] :org.babashka/cli {:coerce {:skip []}}} ``` -------------------------------- ### Invoke codox with CLI arguments Source: https://github.com/babashka/cli/blob/main/README.md Command-line invocation of `codox` using the configured `:codox` alias, specifying the output path. ```bash $ clojure -M:codox --output-path /tmp/out ``` -------------------------------- ### Run antq outdated with CLI arguments Source: https://github.com/babashka/cli/blob/main/README.md Invoke the `antq outdated` function using the configured `:antq` alias. This command demonstrates passing the `--upgrade` flag. ```bash $ clj -M:antq --upgrade ``` -------------------------------- ### babashka.cli - Parse Options Source: https://github.com/babashka/cli/blob/main/API.md Parses command-line arguments into a map of options. Returns a map of options parsed from command line arguments `args`, a sequence of strings. ```APIDOC ## `parse-opts` ### Description Returns a map of options parsed from command line arguments `args`, a sequence of strings. ### Method Function ### Endpoint N/A (Library function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```clojure (parse-opts ["--name" "foo" "--age" "30"]) ;; => {:name "foo", :age "30"} ``` ### Response #### Success Response (200) A map of parsed options. #### Response Example ```clojure {:name "foo", :age "30"} ``` ``` -------------------------------- ### babashka.cli/parse-args Source: https://github.com/babashka/cli/blob/main/API.md Parses command-line arguments, returning parsed options and remaining arguments. ```APIDOC ## parse-args ### Description Parses command-line arguments, returning a map with parsed options and remaining arguments. This is a variant of `parse-opts` with reshaped return data. ### Function Signature ```clojure (parse-args args) (parse-args args opts) ``` ### Parameters #### Path Parameters - **args** (seqable) - The command-line arguments to parse. - **opts** (map, optional) - Additional options for parsing. ### Returns A map with: * `:opts` - Parsed options. * `:args` - Remaining unparsed arguments. ### Response Example (No specific response example provided in the source) ``` -------------------------------- ### Babashka CLI Exec Main Function Source: https://github.com/babashka/cli/blob/main/API.md A placeholder for the main function within the babashka.cli.exec namespace. ```clojure (main & args) ``` -------------------------------- ### babashka.cli/parse-cmds Source: https://github.com/babashka/cli/blob/main/API.md Parses sub-commands from arguments, separating them from options. ```APIDOC ## parse-cmds ### Description Parses sub-commands (arguments not starting with an option prefix) from the given arguments. Returns a map containing the parsed subcommands and the remaining arguments. ### Function Signature ```clojure (parse-cmds args) (parse-cmds args {:keys [no-keyword-opts]}) ``` ### Parameters #### Path Parameters - **args** (seqable) - The command-line arguments to parse. - **opts** (map, optional) - Options map, potentially containing `:no-keyword-opts`. ### Returns A map with: * `:cmds` - The parsed subcommands. * `:args` - The remaining (unparsed) arguments. ### Response Example (No specific response example provided in the source) ``` -------------------------------- ### Define CLI Subcommands with Dispatch Table Source: https://github.com/babashka/cli/blob/main/README.md Use `cli/dispatch` to define subcommands for your CLI. Each entry in the table maps command strings to functions and specifies argument parsing options. ```clojure (ns example (:require [babashka.cli :as cli])) (defn copy [m] (assoc m :fn :copy)) (defn delete [m] (assoc m :fn :delete)) (defn help [m] (assoc m :fn :help)) (def table [{:cmds ["copy"] :fn copy :args->opts [:file]} {:cmds ["delete"] :fn delete :args->opts [:file]} {:cmds [] :fn help}]) (defn -main [& args] (cli/dispatch table args {:coerce {:depth :long}})) ``` -------------------------------- ### tools.build alias for babashka/cli Source: https://github.com/babashka/cli/blob/main/README.md Configure a deps.edn alias to use babashka/cli for build tasks. Ensure you replace '' with the actual latest version. ```clojure :build {:deps {org.babashka/cli {:mvn/version ""} io.github.clojure/tools.build {:git/tag "v0.8.2" :git/sha "ba1a2bf"}} :paths [". ``` -------------------------------- ### parse-args Source: https://context7.com/babashka/cli/llms.txt Similar to `parse-opts` but returns a reshaped map with `:opts` for parsed options and `:args` for remaining unparsed arguments. Useful for handling both options and positional arguments. ```APIDOC ## parse-args ### Description Parses command-line arguments into a map containing both parsed options under the `:opts` key and remaining positional arguments under the `:args` key. This is useful when you need to process both flags and positional values. ### Method N/A (Function call within a Clojure environment) ### Endpoint N/A ### Parameters #### Function Arguments - **args** (vector of strings) - Required - The command-line arguments to parse. - **opts** (map) - Optional - Configuration options for parsing, including: - **:coerce** (map) - Specifies type coercion for arguments. - **:args->opts** (vector or keyword) - Defines how positional arguments should be mapped to options (e.g., `[:url]` or `(cons :file (repeat :extra-args))`). ### Request Example ```clojure (require '[babashka.cli :as cli]) (cli/parse-args ["--force" "file1.txt" "file2.txt"] {:coerce {:force :boolean}}) (cli/parse-args ["file.txt" "--verbose"] {:coerce {:verbose :boolean}}) (cli/parse-args ["--paths" "src" "test" "--" "extra-arg"] {:coerce {:paths []}}) (cli/parse-args ["--force" "ssh://repo.git"] {:coerce {:force :boolean} :args->opts [:url]}) (cli/parse-args ["main.clj" "arg1" "arg2" "arg3"] {:coerce {:extra-args []} :args->opts (cons :file (repeat :extra-args))}) ``` ### Response #### Success Response (map) - **:opts** (map) - A map containing the parsed command-line options. - **:args** (vector of strings) - A vector of remaining unparsed positional arguments. #### Response Example ```clojure ;; For (cli/parse-args ["--force" "file1.txt" "file2.txt"] {:coerce {:force :boolean}}) {:args ["file1.txt" "file2.txt"], :opts {:force true}} ;; For (cli/parse-args ["file.txt" "--verbose"] {:coerce {:verbose :boolean}}) {:args ["file.txt"], :opts {:verbose true}} ;; For (cli/parse-args ["--paths" "src" "test" "--" "extra-arg"] {:coerce {:paths []}}) {:args ["extra-arg"], :opts {:paths ["src" "test"]}} ;; For (cli/parse-args ["--force" "ssh://repo.git"] {:coerce {:force :boolean} :args->opts [:url]}) {:args [], :opts {:force true, :url "ssh://repo.git"}} ;; For (cli/parse-args ["main.clj" "arg1" "arg2" "arg3"] {:coerce {:extra-args []} :args->opts (cons :file (repeat :extra-args))}) {:args [], :opts {:file "main.clj", :extra-args ["arg1" "arg2" "arg3"]}} ``` ``` -------------------------------- ### Convert Spec to Options Format Source: https://github.com/babashka/cli/blob/main/API.md Converts a specification map into the options format used by `parse-opts`. Existing options can be passed as a second argument. ```clojure (spec->opts spec) ``` ```clojure (spec->opts spec {:keys [exec-args]}) ``` -------------------------------- ### babashka.cli.exec - Main Function Source: https://github.com/babashka/cli/blob/main/API.md A general main function within the babashka.cli.exec module. ```APIDOC ## `main` (babashka.cli.exec) ### Description Main function. ### Method Function ### Endpoint N/A (Library function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```clojure (babashka.cli.exec/main) ``` ### Response #### Success Response (200) Result of the main function execution. #### Response Example ```clojure nil ``` ```