### Create a Basic CLI with @main Source: https://github.com/comonicon/comonicon.jl/blob/main/docs/src/index.md Use the @main macro to quickly define a command-line interface with arguments and options. This is the simplest way to get started with Comonicon. ```julia using Comonicon @main function mycmd(arg; option="Sam", flag::Bool=false) @show arg @show option @show flag end ``` -------------------------------- ### Comonicon.toml Configuration Example Source: https://context7.com/comonicon/comonicon.jl/llms.txt This TOML snippet shows project-level build settings for Comonicon, including options for installation path, shell-completion, system image compilation, and standalone application packaging. ```toml # Comonicon.toml [sysimg] # enable = true [application] # enable = true ``` -------------------------------- ### Install CLI Command with build.jl Source: https://github.com/comonicon/comonicon.jl/blob/main/docs/src/project.md Set up a build.jl file in the deps folder to install the CLI command to ~/.julia/bin when the package is installed. This requires a single line to execute the installation. ```julia # build.jl using Demo; Demo.comonicon_install() ``` -------------------------------- ### Example Node Command Source: https://github.com/comonicon/comonicon.jl/blob/main/docs/src/conventions.md Demonstrates a node command in a CLI structure. ```sh git remote show origin ``` -------------------------------- ### Install ComoniconTestUtils Source: https://github.com/comonicon/comonicon.jl/blob/main/lib/ComoniconTestUtils/README.md To install ComoniconTestUtils, open Julia's interactive session (REPL) and type the command in package mode. ```julia pkg> add ComoniconTestUtils ``` -------------------------------- ### Comonicon Installation Script Source: https://context7.com/comonicon/comonicon.jl/llms.txt This script installs the Comonicon.jl application, reads configuration from Comonicon.toml, and optionally installs path and shell completion. ```julia using MyCLI MyCLI.comonicon_install() # reads Comonicon.toml, installs to ~/.julia/bin # To install only PATH/FPATH without rebuilding the binary: MyCLI.comonicon_install_path() # Programmatic override (e.g., CI): using Comonicon.Configs: read_options, SysImg opts = read_options(MyCLI; sysimg=SysImg(filter_stdlibs=true, incremental=false)) ``` -------------------------------- ### Install Comonicon (Main Branch) Source: https://github.com/comonicon/comonicon.jl/blob/main/README.md Use this command to install the latest development version from the main branch of Comonicon. ```julia pkg> add Comonicon#main ``` -------------------------------- ### Install Dependencies Source: https://github.com/comonicon/comonicon.jl/blob/main/AGENTS.md Installs project dependencies using Julia's Pkg manager. Ensure you are in the project directory. ```bash julia --project -e 'using Pkg; Pkg.instantiate()' ``` -------------------------------- ### Install Comonicon (Stable) Source: https://github.com/comonicon/comonicon.jl/blob/main/README.md Use this command to install the stable release of Comonicon in the Julia package manager. ```julia pkg> add Comonicon ``` -------------------------------- ### Running a Comonicon CLI from Terminal Source: https://github.com/comonicon/comonicon.jl/blob/main/README.md Example of how to execute a Julia script (e.g., main.jl) created with Comonicon from the command line, passing arguments and options. ```sh julia main.jl 123 --opt1 3 -o 2 -f ``` -------------------------------- ### Lazy Loading Dependencies with @lazyload Source: https://context7.com/comonicon/comonicon.jl/llms.txt This example shows how to use the @lazyload macro to defer loading of heavy dependencies like Plots and Statistics until specific subcommands are invoked. This improves startup performance for CLIs with optional heavy features. ```julia # file: analysis.jl using Comonicon # `using Plots` is only executed when the `plot` subcommand is called @lazyload using Plots @cast function plot(data_file) p = Plots.plot(rand(10), title="Preview") Plots.savefig(p, "output.png") println("Saved to output.png") end # `using Statistics` is only loaded for `stats` @lazyload using Statistics @cast function stats(values::Float64...) v = collect(values) println("mean=", Statistics.mean(v), " std=", Statistics.std(v)) end @cast function echo(msg) println(msg) end @main ``` -------------------------------- ### Comonicon.toml Configuration Source: https://context7.com/comonicon/comonicon.jl/llms.txt This TOML file configures the Comonicon.jl application, specifying installation paths, shell completion, system image compilation, application bundling, and download settings. ```toml name = "mycli" # name of the installed executable [install] path = "~/.julia" # base install path; executable goes to path/bin/ completion = true # generate shell completion scripts (bash + zsh) quiet = false # log progress messages compile = "yes" # Julia --compile flag: yes | no | all | min optimize = 2 # Julia -O level nthreads = 1 # threads for the CLI process [sysimg] # enables `julia --sysimage` for near-instant startup path = "deps" # where to write the .dylib/.so incremental = true filter_stdlibs = false cpu_target = "native" [sysimg.precompile] execution_file = ["deps/precompile.jl"] # record-based precompile [application] # build a fully self-contained app via PackageCompiler.create_app path = "build" incremental = false filter_stdlibs = true assets = ["assets/data", "OtherPkg: templates"] # bundled assets [application.precompile] statements_file = ["deps/statements.jl"] [download] # auto-download pre-built sysimg from GitHub Releases instead of building host = "github.com" user = "myorg" repo = "MyCLI.jl" [command] color = true # colorized help output static = true # generate help at compile time (fixed terminal width) width = 120 # terminal width for static help generation dash = true # support -- separator plugin = false # enable - plugin discovery ``` -------------------------------- ### Graceful Exit with cmd_exit Source: https://context7.com/comonicon/comonicon.jl/llms.txt This example illustrates using `cmd_exit` for clean CLI exits with specified status codes. It's preferred over `exit()` as it's catchable in tests and respects Julia's cleanup procedures. ```julia using Comonicon """ Deploy the application. # Options - `-e, --env=`: target environment (dev/staging/prod). """ @main function deploy(; env::String="dev") if env == "prod" println("Deploying to PRODUCTION — are you sure?") # ... perform deployment ... println("Done.") cmd_exit(0) # clean success exit elseif env in ("dev", "staging") println("Deploying to $env") else cmd_error("unknown environment: $env (choose dev/staging/prod)") end end ``` -------------------------------- ### Define Git and Docker Subcommands with @cast Source: https://context7.com/comonicon/comonicon.jl/llms.txt This snippet demonstrates how to define subcommands for Git and Docker using Comonicon's @cast macro. It includes examples for staging files, committing with a message, and building Docker images. ```julia using Comonicon @cast module Git using Comonicon """ Stage files. # Args - `files`: files to stage. """ @cast stage(files...) = println("Staging: ", join(files, ", ")) """ Commit staged changes. # Options - `-m, --message=`: commit message. """ @cast function commit(; message::String="update") println("Committing with message: $message") end end @cast module Docker using Comonicon """ Build a Docker image. # Args - `tag`: image tag. """ @cast build(tag) = println("Building image: $tag") end """ Developer toolchain CLI. """ @main ``` -------------------------------- ### Format Source Code Source: https://github.com/comonicon/comonicon.jl/blob/main/AGENTS.md Formats the Julia source code in the 'src' directory using JuliaFormatter. Ensure JuliaFormatter is installed. ```bash julia --project -e 'using JuliaFormatter; format("src")' ``` -------------------------------- ### Command-Line Syntax for Nested Options Source: https://github.com/comonicon/comonicon.jl/blob/main/docs/src/conventions.md Illustrates various ways to pass configurations to a Comonicon application, including direct field assignment and loading from a TOML file. ```sh command --config.c=1 --config.option.a=1 --config.option.b=1 ``` ```sh command --config=config.toml ``` ```sh command -c config.toml ``` ```sh command -c config.toml --config.option.b=2 # change a field of config.toml ``` -------------------------------- ### Docstring for Command with Arguments Source: https://github.com/comonicon/comonicon.jl/blob/main/docs/src/conventions.md Illustrates how to use docstrings to define a command's brief and detailed descriptions, along with arguments. ```julia """ command(args1, args2, args3, args4) the brief description of the command. # Intro the long description of the command, asdmwds dasklsam xasdklqm dasdm, qwdjiolkasjdsa dasklmdas weqwlkjmdas kljnsadlksad qwlkdnasd dasklmdlqwoi, dasdasklmd qw,asd. dasdjklnmldqw. """ ``` -------------------------------- ### Comonicon Configuration for Application Build Source: https://github.com/comonicon/comonicon.jl/blob/main/docs/src/project.md Configure standalone application build options in Comonicon.toml. Similar to system image configuration, this allows for optimization of application startup performance. ```toml [application] incremental=true filter_stdlibs=false [application.precompile] statements_file = ["deps/statements.jl"] ``` -------------------------------- ### Comonicon Configuration for System Image Source: https://github.com/comonicon/comonicon.jl/blob/main/docs/src/project.md Configure system image compilation options in Comonicon.toml to reduce CLI startup latency. Options like incremental, filter_stdlibs, and precompile execution/statements files can be specified. ```toml name = "demo" [install] completion = true quiet = false optimize = 2 [sysimg] ``` ```toml [sysimg] incremental=false filter_stdlibs=true ``` ```toml [sysimg.precompile] execution_file = ["deps/precompile.jl"] ``` ```toml [sysimg.precompile] statements_file = ["deps/statements.jl"] ``` -------------------------------- ### Basic CLI with @main Macro Source: https://github.com/comonicon/comonicon.jl/blob/main/README.md Demonstrates a simple command-line interface using the @main macro. The docstring defines arguments, options, and flags, which are automatically parsed. Save this code as a .jl file to run it from the terminal. ```julia ```julia """ ArgParse example implemented in Comonicon. # Arguments - `x`: an argument # Options - `--opt1 `: an option - `-o, --opt2 `: another option # Flags - `-f, --flag`: a flag """ @main function main(x; opt1=1, opt2::Int=2, flag=false) println("Parsed args:") println("flag=>", flag) println("arg=>", x) println("opt1=>", opt1) println("opt2=>", opt2) end ``` ``` -------------------------------- ### Comonicon @main for Single-Command Entry Point Source: https://context7.com/comonicon/comonicon.jl/llms.txt Use the `@main` macro to mark a function as the sole CLI entry point. Julia function arguments become positional CLI arguments, boolean keyword arguments become flags, and other keyword arguments become options. The `--version` flag is automatically populated from `Project.toml`. ```julia #!/usr/bin/env julia # file: greet.jl using Comonicon """ Greet a person from the command line. # Arguments - `name`: name of the person to greet. # Options - `-t, --times=`: how many times to repeat the greeting. # Flags - `-l, --loud`: print in uppercase. """ @main function greet(name; times::Int=1, loud::Bool=false) for _ in 1:times msg = "Hello, $name!" println(loud ? uppercase(msg) : msg) end end # Usage: # julia greet.jl Alice # # Hello, Alice! # # julia greet.jl Alice --times=3 -l # # HELLO, ALICE! # # HELLO, ALICE! # # HELLO, ALICE! # # julia greet.jl --help # # greet [options] [flags] # # # # Greet a person from the command line. # # # # Arguments # # name of the person to greet. # # Options # # -t, --times how many times to repeat the greeting. (default: 1::Int64) # # Flags # # -l, --loud print in uppercase. # # -h, --help print this help message. # # --version print version. ``` -------------------------------- ### Docstring for Command with Arguments and Args Section Source: https://github.com/comonicon/comonicon.jl/blob/main/docs/src/conventions.md Shows how to document command arguments using the #Args section in the docstring. ```julia """ command(args1, args2, args3, args4) the brief description of the command. # Intro the long description of the command, asdmwds dasklsam xasdklqm dasdm, qwdjiolkasjdsa dasklmdas weqwlkjmdas kljnsadlksad qwlkdnasd dasklmdlqwoi, dasdasklmd qw,asd. dasdjklnmldqw. # Args - `arg1`: argument 1. - `arg2`: argument 2. - `arg3`: argument 3. - `arg4`: argument 4. """ ``` -------------------------------- ### Enabling Plugin Support in Comonicon Source: https://github.com/comonicon/comonicon.jl/blob/main/docs/src/conventions.md Shows how to enable the plugin system in Comonicon by setting the 'plugin' option to 'true' in the Comonicon.toml configuration file. ```toml [command] plugin=true ``` -------------------------------- ### Docstring for Options in Comonicon Source: https://github.com/comonicon/comonicon.jl/blob/main/docs/src/conventions.md Demonstrates various ways to define options and their short forms within the #Options section of a docstring. ```md # Options - `--short, -s`: short option using default hint. - `--short-space, -s `: short option using given hint. - `--short-assign, -s=`: short option using given hint. - `--long`: long option using default hint. - `--long-space `: long option using given hint. - `--long-assign=`: long option using given hint. - `--short_underscore, -s `: short option with underscore. ``` -------------------------------- ### Run All Tests (with Test module) Source: https://github.com/comonicon/comonicon.jl/blob/main/AGENTS.md Executes all tests by including the main test file. Useful for debugging test execution flow. ```bash julia --project -e 'using Test; include("test/runtests.jl")' ``` -------------------------------- ### Interactive Yes/No Prompt with Comonicon Tools Source: https://context7.com/comonicon/comonicon.jl/llms.txt Use `Tools.prompt` for interactive yes/no questions in your CLI. The `yes` flag can auto-confirm prompts, useful for `--yes` or `--force` options. ```julia using Comonicon using Comonicon.Tools: prompt """ Delete a file with confirmation. # Args - `path`: file to delete. # Flags - `-y, --yes`: skip confirmation prompt. """ @main function delete(path; yes::Bool=false) isfile(path) || cmd_error("not found: $path") confirmed = prompt("Delete $path?"; yes) if confirmed rm(path) println("Deleted.") else println("Aborted.") end end ``` -------------------------------- ### Displaying Help Message Source: https://github.com/comonicon/comonicon.jl/blob/main/README.md Command to display the automatically generated help message for a Comonicon CLI application. ```sh julia main.jl --help ``` -------------------------------- ### Run All Tests Source: https://github.com/comonicon/comonicon.jl/blob/main/AGENTS.md Executes all tests defined in the project. This is useful for verifying code integrity. ```bash julia --project test/runtests.jl ``` -------------------------------- ### Detailed CLI Help with Docstring Sections Source: https://github.com/comonicon/comonicon.jl/blob/main/docs/src/index.md Provide detailed help messages for arguments, options, and flags by using specific sections within the Julia docstring. This improves user experience by clearly defining CLI parameters. ```julia using Comonicon """ my command line interface. # Arguments - `arg`: an argument # Options - `-o, --option`: an option that has short option. # Flags - `-f, --flag`: a flag that has short flag. """ @main function mycmd(arg; option="Sam", flag::Bool=false) @show arg @show option @show flag end ``` -------------------------------- ### Run Tests via Pkg Source: https://github.com/comonicon/comonicon.jl/blob/main/AGENTS.md Runs tests using Julia's built-in Pkg test functionality. This is an alternative to running the test script directly. ```bash julia --project -e 'using Pkg; Pkg.test()' ``` -------------------------------- ### Run Specific Test File Source: https://github.com/comonicon/comonicon.jl/blob/main/AGENTS.md Executes a single test file directly. This is helpful for focusing on specific test cases. ```bash julia --project test/options.jl ``` ```bash julia --project test/frontend/cast.jl ``` -------------------------------- ### Add Description to CLI with Docstring Source: https://github.com/comonicon/comonicon.jl/blob/main/docs/src/index.md Enhance your CLI by adding a Julia function docstring. This provides a basic description that will appear in the help message. ```julia using Comonicon """ my first Comonicon CLI. """ @main function mycmd(arg; option="Sam", flag::Bool=false) @show arg @show option @show flag end ``` -------------------------------- ### Define and Use Option Types with Comonicon Source: https://github.com/comonicon/comonicon.jl/blob/main/docs/src/conventions.md Define nested option structures using `@option` and integrate them into your main function for configuration. This allows reading configurations from files or command-line arguments. ```julia using Test using Comonicon using Configurations @option struct OptionA a::Int b::Int end @option struct OptionB option::OptionA c::Int end """ # Options - `-c, --config `: config. """ @main function run(;config::OptionB) @test config == OptionB(OptionA(1, 1), 1) end ``` -------------------------------- ### Using Dash Separator for Script Arguments Source: https://github.com/comonicon/comonicon.jl/blob/main/docs/src/conventions.md Demonstrates the use of the '--' dash separator to distinguish between arguments for the main CLI command and arguments for a script executed by the CLI. ```sh run --flag -- script.jl a b c ``` -------------------------------- ### Programmatic Comonicon Configuration Access Source: https://context7.com/comonicon/comonicon.jl/llms.txt Reads and validates a `Comonicon.toml` configuration into a typed `Configs.Comonicon` struct. Keyword arguments override TOML fields for temporary changes. ```julia using Comonicon.Configs: read_options, Comonicon, SysImg, Application, Install # Read from a module's project root (uses pkgdir) using MyCLI opts = read_options(MyCLI) println(opts.name) # "mycli" println(opts.install.path) # "/home/user/.julia" # Read from an explicit path opts2 = read_options("/path/to/MyProject") # Override specific nested options for a test build test_opts = read_options(MyCLI; install = Install(path="/tmp/test_install", quiet=true), sysimg = SysImg(incremental=false, filter_stdlibs=true), ) println(test_opts.install.path) # "/tmp/test_install" println(test_opts.sysimg.incremental) # false # Check whether Comonicon.toml exists for a module using Comonicon.Configs: has_comonicon_toml has_comonicon_toml(MyCLI) # true / false ``` -------------------------------- ### Make Script Executable with Shebang Source: https://github.com/comonicon/comonicon.jl/blob/main/docs/src/index.md To make a Comonicon script directly executable, add a shebang line pointing to the Julia executable at the top of the file. This allows running the script like a standard command-line tool. ```julia #! using Comonicon """ my first Comonicon CLI. """ @main function mycmd(arg; option="Sam", flag::Bool=false) @show arg @show option @show flag end ``` -------------------------------- ### Package Module Pattern for Comonicon CLI Source: https://context7.com/comonicon/comonicon.jl/llms.txt Define your CLI within a Julia package module for production-ready applications. This pattern supports multi-command CLIs, shell completions, and PackageCompiler integration. ```julia # src/MyCLI.jl module MyCLI using Comonicon """ Display system information. # Args - `component`: which component to inspect (cpu/mem/disk). # Flags - `-v, --verbose`: show detailed output. """ @cast function info(component; verbose::Bool=false) if component == "cpu" verbose ? run(`lscpu`) : println("CPU: $(Sys.cpu_info()[1].model)") elseif component == "mem" verbose ? run(`free -h`) : println("Mem: $(Sys.free_memory() >> 20) MB free") else cmd_error("unknown component: $component (choose cpu/mem/disk)") end end """ Run a diagnostic. # Args - `target`: target host to diagnose. # Options - `-t, --timeout=`: timeout in seconds. """ @cast function diagnose(target; timeout::Int=30) println("Diagnosing $target with timeout=$(timeout)s ...") end """ My system CLI tool. """ @main # generates command_main, julia_main, comonicon_install, comonicon_install_path end # module ``` ```julia # deps/build.jl — called by `]build MyCLI` or `julia --project deps/build.jl` using MyCLI MyCLI.comonicon_install() ``` -------------------------------- ### CLI-Compatible Error Reporting with cmd_error Source: https://context7.com/comonicon/comonicon.jl/llms.txt This snippet demonstrates using `cmd_error` for user-friendly CLI error messages. It replaces `error()` to provide clean output and exit codes instead of Julia stack traces, useful for file not found or empty file scenarios. ```julia using Comonicon """ Process a file. # Args - `path`: path to the input file. # Options - `-o, --output=`: output file path. """ @main function process(path; output::String="out.txt") isfile(path) || cmd_error("file not found: $path", 2) content = read(path, String) isempty(content) && cmd_error("file is empty: $path") open(output, "w") do io write(io, uppercase(content)) end println("Written to $output") end ``` -------------------------------- ### Comonicon Special Argument Types Source: https://context7.com/comonicon/comonicon.jl/llms.txt Use these special argument types as type annotations in `@cast`/`@main` function signatures to enable shell-generated context-sensitive tab completions for arguments like filenames, directory names, and usernames. ```julia using Comonicon using Comonicon.Arg: FileName, DirName, Path, UserName, Prefix, Suffix """ Copy a source file to a destination directory. # Args - `src`: source file. - `dst`: destination directory. """ @cast function cp(src::FileName, dst::DirName) cp(src.content, joinpath(dst.content, basename(src.content))) println("Copied $(src.content) -> $(dst.content)") end """ Process files matching a Julia-source suffix. # Args - `file`: a .jl file. """ @cast function lint(file::Suffix".jl") println("Linting: $(file.content).jl") end """ Handle data-prefixed resources. # Args - `resource`: a data-xxx resource name. """ @cast function fetch(resource::Prefix"data") println("Fetching resource: data$(resource.content)") end """ Transfer ownership. # Args - `user`: target Linux/macOS username. """ @cast function chown(user::UserName) println("Changing owner to: $(user.content)") end @main # Shell completions (after install with completion=true): # mycli cp → completes file names # mycli cp src.txt → completes directory names # mycli chown → completes system usernames ``` -------------------------------- ### Define Multiple Commands with @cast Source: https://github.com/comonicon/comonicon.jl/blob/main/docs/src/project.md Use @cast to define multiple commands within a module. Commands can be simple functions or nested modules. @main is used to declare the entry point for the CLI. ```julia module Demo using Comonicon @cast mycmd1(arg; option="Sam") = println("cmd1: arg=", arg, "option=", option) @cast mycmd2(arg; option="Sam") = println("cmd2: arg=", arg, "option=", option) """ a module """ module Cmd3 using Comonicon @cast mycmd4(arg) = println("cmd4: arg=", arg) end # module @cast Cmd3 """ my demo Comonicon CLI project. """ @main end # module ``` -------------------------------- ### Comonicon @cast for Multi-Command Leaf Registration Source: https://context7.com/comonicon/comonicon.jl/llms.txt Register Julia functions as named sub-commands using the `@cast` macro. Underscores in argument/keyword names are automatically converted to dashes for the CLI. A subsequent `@main` call collects these registered commands. ```julia # file: math_cli.jl using Comonicon """ Add two numbers. # Args - `x`: first number. - `y`: second number. # Options - `-p, --precision=`: numeric precision (default: Float64). # Flags - `-f, --fastmath`: enable fastmath optimizations. """ @cast function add(x::Float64, y::Float64; precision::String="Float64", fastmath::Bool=false) result = fastmath ? Base.FastMath.add_fast(x, y) : x + y println("Result ($precision): $result") end """ Multiply two numbers. # Args - `x`: first number. - `y`: second number. """ @cast function mul(x::Float64, y::Float64) println("Result: $(x * y)") end """ My math CLI tool. """ @main # Usage: # julia math_cli.jl add 1.5 2.5 # # Result (Float64): 4.0 # # julia math_cli.jl add 1.0 2.0 -p Float32 --fastmath # # Result (Float32): 3.0 # # julia math_cli.jl mul 3.0 4.0 # # Result: 12.0 # # julia math_cli.jl --help # # math_cli [options] [flags] # # # # My math CLI tool. # # # # Commands: # # add Add two numbers. # # mul Multiply two numbers. ``` -------------------------------- ### View Defined Commands Source: https://github.com/comonicon/comonicon.jl/blob/main/docs/src/project.md After defining commands with @cast, they are registered in a global variable CASTED_COMMANDS within the module. This allows inspection of all available commands. ```julia julia> Demo.CASTED_COMMANDS Dict{String,Any} with 4 entries: "mycmd2" => mycmd2 [options] "cmd3" => cmd3 "main" => demo v0.1.0 "mycmd1" => mycmd1 [options] ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.