Modified a few things:

- Finished implementing relative date parsing and migrated date parsing
  from Flag(T) to it's own dedicated module. Additionally added a
  the ability to do "recursive" relative operations for time searching.
- Additionally made a Struct & Enum for containing relative operations
  around dates.
- Added additional checks in App & CommandNode(T) around checking
  env_vars of flags & checking for duplicate commands
- Added a CommandMeta record to contain the classname of the
  CommandNode(T)
- Seperated out all of the monolitic files (command_node.cr & file.cr).
  Moved the base classes and records into their own files in the dir
  with the same name of their generic counterparts.
- Fixed a number of macro related bugs around Command.argument &
  CliGen.add_global_flag
- My ass hurts from sitting here for hours and doing these changes and
  arguing with claude over what needs to be done. Fun tho.
This commit is contained in:
2026-08-30 22:13:39 -05:00
parent f2d5c84f2b
commit 4cce5cc45c
42 changed files with 1576 additions and 988 deletions
+7 -1
View File
@@ -6,10 +6,16 @@
!src/**
!shard.yml
!README.md
!design.adoc
!DESIGN.md
!docs/
!docs/**
!Makefile
!LICENSE
!NOTICE
!spec/
!spec/**
!utils/
!utils/**
# ...but not the binary utils/flag_matrix.sh builds (later rules win).
utils/flag_matrix
+501
View File
@@ -0,0 +1,501 @@
# Crystal Cli Generator
**Author:** Tristan Ancelet
**Email:** tristanancelet@yahoo.com
## Overview
This document outlines the overall design of the CliGen shard & it's underlying classes/objects & their usecases.
## How it works/High-Level overview
Using crystal macros, you define the shape (arguments/flags, selections, work functions/subcommands, etc) and later on in `src/cligen/app/generate.cr` will use macros to (at compile time) generate `CommandNode(T)` objects & `Flag(T)` objects to contain your command/subcommand/arg parsing code from the data you provided in your `CliGen::Command` subclass.
## Architecture
The desire for this project is to provide a framework for generating commandline arg-parses & command dispatch built into a class/object.
The idea is to (much like `JSON::Serializable` & `YAML::Serializable`) is to use macros to help defining a Command object and abstract the command-line away from the codebase needing input from the user at init time.
### Command Objects
The core of this codebase is the `CliGen::Command` object.
This is the object that is meant to provide you the hook into being able to utilize the codebase. It is where you are able to define all of your expecetd arguments/flags & any selectables (aka, instance variable that you want the user to choose one value for. `ex: -f|--format json|yaml|ecr`).
To make this all possible we load the base class with macros that help define your variables & inform the framework how it needs to handle arguments being presented to your command object setters.
```crystal
require "cligen"
module MyModule
@[CliGen::CommandInfo(description: "My command that does cool things")]
class MyCommand < CliGen::Command
argument(myvar : Int32 = 23,
long: "--myvar VAR",
short: "-m",
description: "This tells the utility how many times to do thing",
validate: ->(v : Int32) : Bool { (1..23).includes?(v) }
)
argument(output_format : String = "ecr",
long: "--format FORMAT",
short: "-f",
description: "Inform the utility what output you want the data in",
options: %w[ json yaml ecr ]
)
DO_THING_EXAMPLES = [
"myutil mycommand do_thing --myvar 5"
]
subcommand do_thing, description: "Do the THING", examples: MyModule::MyCommand::DO_THING_EXAMPLES do
output = 0
@myvar.times do |i|
puts "thing done %i times" % [ i + 1 ]
output += i
end
puts "Total : %i" % output
end
end
CliGen::App.process
end
```
The examples like above provide a "DSL-esk" way of defining:
- Instance Variables,
- Short/Long flags
- Description of the flags (used in the help output as well)
- A verification proc/lambda for doing ad-hoc checks of the value provided by the user (essentially allowing you to implement your own option: key like in selection)
- Selections (currently compile-time and will open it up to runtime collecting of options later on based on defined annotations in the class)
- define subcommands of this current command
#### CliGen::CommandNode(T)
This is the "CliGen" representation of your command. Using crystal macros & generics when the CommandNode is created it will generate the internal Generic methods based on the defined command object and whether it has subcommands & main method, etc.
This is where all of the actual argument processing gets done in the `CliGen::CommandNode(T)#process(args : Array(CliGen::Arg))` method.
A main-loop of scoped parsing happens in it's `#process` method and if a child-command is detected `CliGen::Command -> MyModule::MyCommand -> MyModule::MyOtherCommand` it will gather all unprocessed arguments and will call that `CommandNode(T)`'s `#process` method.
This was done because it effectively keeps arguments scoped in their own contexts without causing something like OptionParser implementation having flag/argument bleed between commands and subcommands if multiple parsers are defined (aka OptionParser does not `#shift` arguments off as they are processed, which end up causing arguments to bleed into child instances).
Alongside it's main duty of handling CLI parsing of arguments it also serves to handle any framework related raises from `Flag(T)` (invalid values, incorrect custom data class behavior, internal errors, etc).
#### CliGen::App
This object is the root application that handles all initial execution from bare CLI arguments. It's just a subclass of `CommandNode(Nil)` (Subclassed with `Nil` for simplicity and to not deal with code duplication between macro generated `CommandNode(T)` and a custom `App` object (with them needing almost exactly the same methods).
For the majority of the process, this object just serves as the inital entrypoint to the CLI parsing and handles raises of any Framework related error classes (help output, exceptions related directly with the `CommandNode(T)` objects)
#### CliGen::Flag(T)
This is the object that handles option/argument parsing. It's a Generic Container who's internal layout changes depending on the type it's initalized with.
The only (currently as of writing this doc) types that are supported are:
- All Int permutations (Int8, UInt8, etc)
- All Float permutations (Float32, etc)
- String
- Bool
- Enum (*planned, but not implemented yet*)
- Time (strict formatting allowed)
- Array(T)
##### Time Limitations
The framework has some strict formatting for time arguments
It only accepts data in the following static formats:
- `%Y-%m-%d %H:%M:%S %z` (ex: `2026-08-30 19:00:00 +0000`)
* This specifies the date, time & timezone/offset (allowing you to customize the time)
- `%Y-%m-%d %H:%M:%S` (ex: `2026-08-30 19:00:00`)
* This specifies the date & time and will default to the local timezone of the device it's being run on (via `::Time.parse_local`) (would need much more conditionals but it gets the point accross)
- `%Y-%m-%d %z` (ex: `2026-08-30 +0000`)
* This specifies the date & timezone/offset, and will default to 00:00:00 for the time value
- `%Y-%m-%d` (ex: `2026-08-30`)
* This specifies the date, and will default to 00:00:00 for the time value and to the local timezone of the host (via `::Time.parse_local`)
- `@%s %z` (ex: `@1788122911 +0900`)
* This specifies the epoch time and the timezone you want the final `Time` object to be in (this gets the provided epoch time as UTC via `::Time.unix` and then setting the timezone to the provided offset)
- `@%s`
* This specifies the epoch time and via `::Time.unix` will default to `::Time::Location::UTC` for the timzone
However, minimal support for relative time has been added. Valid formats for this are:
- `[-+][0-9]+ (years|months|weeks|days|hours|minutes|seconds) %z` (ex: `+2 hours -0900`)
* This provides a relative time to look for and what timezone offset to convert to after the relative time is calculated via `::Time#in`
- `[-+][0-9]+ (years|months|weeks|days|hours|minutes|seconds)` (ex: `-2 hours`)
* This provides a relative time to look for and will default to the local timezone via `::Time.local`
- `[-+]%H:[-+]?%M:[-+]?%S %z` (ex: `-2:3:3 -0900`) (*planned but not currently implemented*)
* This provides a hour, minute and second to decrease/increase by (depending on each field's sign) and a timezone to convert to afterwards with `::Time#in`
- `[-+]%H:[-+]?%M %z` (ex: `-2:3 -0900`) (*planned but not currently implemented*)
* This provides a hour and minute to decrease/increase by (depending on each field's sign) and a timezone to convert to afterwards with `::Time#in`
- `[-+]%H:[-+]?%M:[-+]?%S` (ex: `-2:3:3`) (*planned but not currently implemented*)
* This provides a hour, minute and second to decrease/increase by (depending on each field's sign)
**Note:** Multiple human-readable operations
The relative operations for getting time relatively to the current time on the running system `+1 days` can be chained and the specific operation order is important when providing your ops.
So when doing multiple you can provide them like so
```
mycli mycmd --time '+2 weeks -1 month +30 days -0900`
```
This essentially grabs the local time (via `::Time.local`), setting it's timezone to the `-0900` offset, and then adding 2 weeks/14 days, jumping back a full month (dependant on the actual month) and then going forward 30 days.
**Note:** Relative operations short format (*planned but not implemented yet*)
For the `[-+]%H:[-+]?%M:[-+]?%S` formats if the sign's (`+-`) aren't provided for the `%M` or `%S` fields it will default to the sign provided to the `%H` field
##### Array(T) limitations
However, with Array(T) types there are a few limitations. The only supported in-place T-types are the core classes (Int*, Float*, String). However, provided you do the below extentions to your custom data class you can also use it as a data class with Arrays.
The framework (deliberately) limits the `:options` key to an array of individual choices that the user can provide instead of permutations of valid `Array(T)` values. So when providing an `Array(T)`
```crystal
require "cligen"
module MyModule
@[CliGen::CommandInfo(description: "Test Command")]
class MyCommand < CliGen::Command
argument(sources : Array(String),
description: "The source of all your pain",
options: %w[ tacos golang coffee ]
)
def main
@sources.each_with_index do |source, index|
puts "%d : %s" % [index + 1, source]
end
end
end
end
CliGen::App.process
```
Providing it in the array format will have the framework collapse it into just the Array(T) values so that they can be value-checked (`Array(T)#includes?(val)`)
Of which when an invalid value is provided the framework will abort directly if an invalid value is provided
```
(ins) tristan@arcanetome $: crystal run test4.cr -- mycommand --sources golang coffee pain
crystal-run-test4.tmp: 'pain' is not a valid value for --sources (valid: ["tacos", "golang", "coffee"])
```
However when run with valid values it has no issues
```
(ins) tristan@arcanetome $: crystal run test4.cr -- mycommand --sources golang coffee
1 : golang
2 : coffee
```
##### Custom Data Types
However, there is an API defined via the `CliGen::Parsable` and `CliGen::Coercable` modules that will allow you to customize parsing of a Custom DataType.
This is limited to parsing raw strings (of any format) into whatever your data is supposed to represent
```crystal
module MyModule
class MyData
extend CliGen::Parsable
extend CliGen::Coercable
@value : Int32
def initialize(value : String)
@value = value.to_i32
end
def self.parse_args(args : Array(CliGen::Arg))
arg = args.first
# Mark the argument as processed
arg.processed
new(arg.value)
end
def self.coerce(arg : String)
new(arg)
end
end
end
```
##### Override #to_s for CLI help readablility
If you do plan to use your custom data-type with the you will need to override the `#to_s(io : IO)` method to ensure that the help output can render it correctly
Example of a Custom DataType use in a `CliGen::Command` subclass argument/flag:
```crystal
require "cligen"
module MyModule
class MyData
extend CliGen::Coercable
extend CliGen::Parsable
@@instances = {} of String => MyData
getter name : String
getter work : Proc(Nil)
def initialize(@name, &@work)
unless @@instances.has_key?(@name)
@@instances[@name] = self
else
raise "HUH?"
end
end
def to_s(io : IO)
io << @name
end
def self.get(name : String)
@@instances[name]
end
def self.parse_args(args : Array(CliGen::Arg))
arg = args.first
arg.processed
get(arg.value)
end
def self.coerce(arg : String)
get(arg)
end
def self.all
@@instances.values
end
end
MyData.new("test") do
puts "Did a test"
end
MyData.new("really") do
puts "Yes really"
end
MyData.new("why") do
puts "Just because"
end
@[CliGen::CommandInfo(description: "Test Command")]
class MyCommand < CliGen::Command
argument(source : MyModule::MyData,
description: "The source of all your pain",
options: MyModule::MyData.all
)
def main
@source.work.call()
end
end
end
CliGen::App.process
```
Providing the overridden `#to_s` method makes the help output render your objects in a readable way
```
(ins) tristan@arcanetome $: crystal run test2.cr -- mycommand -h
Command: mycommand
Description: Test Command
Flags:
---------------------------------------------------------------
--source The source of all your pain (valid: test, really, why)
Global Flags
---------------------------------------------------------------
-v,--verbose Enable verbose output from program & help output (default: false)
Note: When wanting help output of any command you can provide the -h/--help flags or help command
(ins) tristan@arcanetome $: crystal run test2.cr -- mycommand --source why
Just because
```
Without the `#to_s` method overridden you'll get the crystal representation of your object instead (like below)
```
(ins) tristan@arcanetome $: crystal run test2.cr -- mycommand -h
Command: mycommand
Description: Test Command
Flags:
---------------------------------------------------------------
--source The source of all your pain (valid: #<MyModule::MyData:0x7f683ad0cc90>, #<MyModule::MyData:0x7f683ad0cc60>, #<MyModule::MyData:0x7f683ad0cc30>)
Global Flags
---------------------------------------------------------------
-v,--verbose Enable verbose output from program & help output (default: false)
Note: When wanting help output of any command you can provide the -h/--help flags or help command
```
Sill valid, but if you plan to make a registry based command/work/strategy selector you might want to override the `#to_s` method
##### CliGen::Coercable
```crystal
def self.coerce(arg : String)
new(arg)
end
```
The coerce method provides you the ability to parse a single string value into your class/datatype. This is generally only used when parsing from ENV VAR and when being used by parsing from an `Array(T)` type.
This should only be used in the case you need a simple datatype that can be learned from a single string.
##### CliGen::Parsable
```crystal
def self.parse_args(args : Array(CliGen::Arg))
arg = args.first
# Mark the argument as processed (required)
arg.processed
new(arg.value)
end
```
This method is used the most and is used for when using the bare class as the generic type in the `Flag(T)`. With this the `Flag(T)` will collect all provided arguments (cli arguments that weren't determined to be flags or subcommands) and pass them to your parse_args method so that you can parse them how you see fit and determine if the args provided by the user are enough and to be able to raise if data is not provided correctly/in the right format.
This gives the framework a way to allow you to extend the parser in your own custom way to allow for a "custom" format to be processed. However, it's very strict and you MUST properly mark the arguments as processed so that the mainloop won't double-process arguments passed to your custom parser. However, this won't happen as in the Flag(T) I am doing a check to ensure that args were processed after passing it to your code.
#### CliGen::Arg
This object serves as a wrapper around ARGV objects/strings/items and is used to keep track of argument processing to ensure that no argument is double-processed/re-processed and enforces this by the internal raise if the `Arg#processed` is called multiple times (mostly did it for MY sanity as doing offset math of ARGV was causing me anxiety so this was the only acceptible method in my opinion on a possibly MASSIVE set of args that could be provided via the CLI).
## Planned Features
### Markdown Documentation Generation
Since all command metadata is present in annotations at compile time (`@[CliGen::CommandInfo]`, `@[CliGen::SubCommand]`, `@[CliGen::Argument]`, `@[CliGen::Selection]`), the framework can walk the same structures that `generate.cr` already walks and render them into a Markdown document instead of a `CommandNode` tree.
The generation would be driven by a `macro finished` block (similar to `generate.cr`) that emits a `self.generate_docs` class method on `App`. This method walks every `Command` subclass and its annotations to produce a structured document.
Proposed output structure:
```
# <AppName>
## Commands
### mycommand
<CommandInfo description>
#### Help
<CommandNode help output>
#### Flags
| Flag | Type | Default | Description |
|----------------|-------|---------|-------------|
| -m,--myvar VAR | Int32 | 23 | ... |
#### Subcommands
- `do_thing` — <description>
- Examples: ...
```
Implementation notes:
* Driven by a `--generate-docs` global flag or a dedicated class method (if the utility was compiled with the INCLUDE_DOC=true ENV VAR set)
* ECR templates (already pulled in) are the natural rendering mechanism
* The same annotation data powers both runtime help output and the doc generator, keeping them in sync automatically
### Bash Autocompletion Generation
Since all command names and flag names are known at compile time, a complete bash completion script can be generated statically — no runtime `--completions` endpoint needed.
The approach is a hidden `--generate-completion bash` flag (potentially extended to `zsh`/`fish` later) that prints a ready-to-install completion script to stdout.
Proposed completion script shape:
```bash
_myapp() {
local cur="${COMP_WORDS[COMP_CWORD]}"
local prev="${COMP_WORDS[COMP_CWORD-1]}"
case "${COMP_WORDS[1]}" in
mycommand)
COMPREPLY=($(compgen -W "--myvar -m --format -f" -- "$cur"))
;;
*)
COMPREPLY=($(compgen -W "mycommand myothercommand" -- "$cur"))
;;
esac
}
complete -F _myapp myapp
```
Implementation notes:
* Script body generated at compile time via a `macro finished` walk of `Command.subclasses`
* `@[CliGen::Selection]` options (`%w[json yaml ecr]`) can be included as valid completions for their flag
* Install path: `myapp --generate-completion bash > ~/.bash_completion.d/myapp` or printed with instructions
* Same annotation data used by the doc generator, so both stay in sync with the command definition
### JSON-RPC like execution
This is a LATE (post v1.0) feature. It takes the same format and instead of a CLI argument
```json
{
"method": "myclass.mysubcommand",
"params": {
"myvar": 3,
"format": "json"
}
}
```
Essentially, this would (instead of tying directly into a command execution module would essentially wrap around App.process and provide them as Array(String) args to App.process(args : Array(String)) to allow the entire app execution to happen.
The json snippet above would essentially be the same as
```crystal
App.process(["--myvar", "3", "--format" , "json", "myclass", "mysubcommand"])
```
However, the design is bound to change as the complexity alone to make the command execution be "similar but different" as any responses would like need to be returned back in JSON-RPC style back to the calling process.
Alongside to generating the JSON-RPC style documenatation for a calling process to know what methods are defined and what type of params are accessible and what types they accept.
This is a LONG TERM goal as it would be pretty neat to implement.
+201 -372
View File
@@ -1,373 +1,202 @@
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at https://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) 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. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+5
View File
@@ -0,0 +1,5 @@
cligen
Copyright 2026 Tristan Ancelet
This product includes software developed by Tristan Ancelet
(https://git.arcanium.tech/tristan/cligen).
+92 -3
View File
@@ -28,8 +28,25 @@ class Greet < CliGen::Command
@[CliGen::Argument(short: "-n", long: "--name VALUE", description: "Name to greet")]
@name : String = "world"
argument(otherval : String = "abc",
long: "--other",
short: "-o",
options: %w[ abc def ghi ],
description: "This provides a way of setting the second string taht is printed"
)
argument(myvars : Array(String) = [ "a" ],
short: "-m",
options: %w[ a b c ],
description: "Provide multiple things to be printed out in the main function"
)
def main
puts "Hello, #{@name}!"
puts "1) Hello, #{@name}!"
puts "2) #{@otherval}"
@myvars.each_with_index do |var, index|
puts "%d) %s" % [ 3 + index, var ]
end
end
end
@@ -37,12 +54,84 @@ CliGen::App.process
```
```
$ myapp --name Alice
Hello, Alice!
$ myapp greet --name Alice -m a a -m a,a,b
1) Hello, Alice!
2) abc
3) a
4) a
5) a
6) a
7) b
```
Full API documentation and design notes are in [`design.adoc`](design.adoc).
## Architecture
As a short overview, this projects makes HEAVY use of Crystal macros to learn the shape of your project & command subclasses.
Subclassing to `CliGen::Command` injects macros into your class that provides you user friendly DSLs/Macros for defining arguments/flags & subcommands. This is later used in the library `src/cligen/app/generate.cr` to generate a object graph of your commands and all annotated "arguments/flags" and stores them in a tree from the App object itself.
This allows the project to "learn" your project & generate a command tree from the defined data.
The MAJORITY of stdlib types (Int*, Float*, String, Bool & Time) are all supported in-place (as these are the primary data-types you might try to comsume from the CLI. However, custom data types are supported provided you extend the class's metaclass with `CliGen::Coercable` && `CliGen::Parsable` modules and define the `self.parse_args(args : Array(CliGen::Arg)` and `self.coerce(arg : String)` class methods.
EX:
```crystal
module MyModule
class MyData
extend CliGen::Parsable
extend CliGen::Coercable
@value : Int32
def initialize(value : String)
@value = value.to_i32
end
def self.parse_args(args : Array(CliGen::Arg))
arg = args.first
# Mark the argument as processed
arg.processed
new(arg.value)
end
def self.coerce(arg : String)
new(arg)
end
end
end
```
Coercable Method:
-----------------
```crystal
def self.coerce(arg : String)
new(arg)
end
```
The coerce method provides you the ability to parse a single string value into your class/datatype. This is generally only used when parsing from ENV VAR and when being used by parsing from an Array(T) type.
This should only be used in the case you need a simple datatype that can be learned from a single string.
Parsable Method:
----------------
```crystal
def self.parse_args(args : Array(CliGen::Arg))
arg = args.first
# Mark the argument as processed (required)
arg.processed
new(arg.value)
end
```
This method is used the most and is used for when using the bare class as the generic type in the Flag(T). With this the Flag(T) will collect all provided arguments (cli arguments that weren't determined to be flags or subcommands) and pass them to your parse_args method so that you can parse them how you see fit and determine if the args provided by the user are enough and to be able to raise if data is not provided correctly/in the right format.
This gives the framework a way to allow you to extend the parser in your own custom way to allow for a "custom" format to be procesed. However, it's very strict and you MUST properly mark the arguments as processed so that the mainloop won't double-process arguments passed to your custom parser. However, this won't happen as in the Flag(T) I am doing a check to ensure that args were processed after passing it to your code.
## Development
```bash
-141
View File
@@ -1,141 +0,0 @@
= Crytal Cli Generator
:author: Tristan Anclelet
:email: tristanancelet@yahoo.com
:toc:
This document outlines the overall design of the CliGen shard & it's underlying classes/objects & their usecases.
== Architecture
The desire for this project is to provide a framework for generating commandline arg-parses & command dispatch built into a class/object.
The idea is to (much like `JSON::Serializable` & `YAML::Serializable`) is to use macros to help defining a Command object and abstract the command-line away from the codebase needing input from the user at init time.
=== Command Objects
The core of this codebase is the `CliGen::Command` object.
This is the object that is meant to provide you the hook into being able to utilize the codebase. It is where you are able to define all of your expecetd arguments/flags & any selectables (aka, instance variable that you want the user to choose one value for. `ex: -f|--format json|yaml|ecr`).
To make this all possible we load the base class with macros that help define your variables & inform the framework how it needs to handle arguments being presented to your command object setters.
[source,crystal]
----
require "cligen"
module MyModule
class MyCommand < CliGen::Command
argument(myvar : Int32 = 23,
long: "--myvar VAR",
short: "-m",
description: "This tells the utility how many times to do thing",
validate: ->(v : Int32) : Bool { (1..23).includes?(v) }
)
selection(output_format : String = "ecr",
long: "--format FORMAT",
short: "-f",
description: "Inform the utility what output you want the data in",
options: %w[ json yaml ecr ]
)
DO_THING_EXAMPLES = [
"myutil mycommand do_thing --myvar 5"
]
subcommand do_thing, description: "Do the THING", examples: MyModule::MyCommand::DO_THING_EXAMPLES do
output = 0
@myvar.times do |i|
puts "thing done %i times" % [ i + 1 ]
output += i
end
puts "Total : %i" % output
end
end
CliGen::App.process
end
----
The examples like above provide a "DSL-esk" way of defining:
- Instance Variables,
- Short/Long flags
- Description of the flags (used in the help output as well)
- A verification proc/lambda for doing ad-hoc checks of the value provided by the user (essentially allowing you to implement your own option: key like in selection)
- Selections (currently compile-time and will open it up to runtime collecting of options later on based on defined annotations in the class)
- define subcommands of this current command
==== How it works
Using crystal macros, you define the shape (arguments/flags, selections, work functions/subcommands, etc
== Planned Features
=== Markdown Documentation Generation
Since all command metadata is present in annotations at compile time (`@[CliGen::CommandInfo]`, `@[CliGen::SubCommand]`, `@[CliGen::Argument]`, `@[CliGen::Selection]`), the framework can walk the same structures that `generate.cr` already walks and render them into a Markdown document instead of a `CommandNode` tree.
The generation would be driven by a `macro finished` block (similar to `generate.cr`) that emits a `self.generate_docs` class method on `App`. This method walks every `Command` subclass and its annotations to produce a structured document.
Proposed output structure:
----
# <AppName>
## Commands
### mycommand
<CommandInfo description>
#### Flags
| Flag | Short | Type | Default | Description |
|------|-------|------|---------|-------------|
| --myvar VAR | -m | Int32 | 23 | ... |
#### Subcommands
- `do_thing` — <description>
- Examples: ...
----
Implementation notes:
* Driven by a `--generate-docs` global flag or a dedicated class method
* ECR templates (already pulled in) are the natural rendering mechanism
* The same annotation data powers both runtime help output and the doc generator, keeping them in sync automatically
=== Bash Autocompletion Generation
Since all command names and flag names are known at compile time, a complete bash completion script can be generated statically — no runtime `--completions` endpoint needed.
The approach is a hidden `--generate-completion bash` flag (potentially extended to `zsh`/`fish` later) that prints a ready-to-install completion script to stdout.
Proposed completion script shape:
[source,bash]
----
_myapp() {
local cur="${COMP_WORDS[COMP_CWORD]}"
local prev="${COMP_WORDS[COMP_CWORD-1]}"
case "${COMP_WORDS[1]}" in
mycommand)
COMPREPLY=($(compgen -W "--myvar -m --format -f" -- "$cur"))
;;
*)
COMPREPLY=($(compgen -W "mycommand myothercommand" -- "$cur"))
;;
esac
}
complete -F _myapp myapp
----
Implementation notes:
* Script body generated at compile time via a `macro finished` walk of `Command.subclasses`
* `@[CliGen::Selection]` options (`%w[json yaml ecr]`) can be included as valid completions for their flag
* Install path: `myapp --generate-completion bash > ~/.bash_completion.d/myapp` or printed with instructions
* Same annotation data used by the doc generator, so both stay in sync with the command definition
+1 -1
View File
@@ -6,4 +6,4 @@ authors:
crystal: '>= 1.19.1'
license: MPL-2.0
license: Apache-2.0
+2 -3
View File
@@ -1,6 +1,5 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
require "../spec_helper"
+2 -3
View File
@@ -1,6 +1,5 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
require "../spec_helper"
+2 -3
View File
@@ -1,6 +1,5 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
require "spec"
require "../src/cligen"
+5 -26
View File
@@ -1,6 +1,5 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
require "./cligen/exceptions"
require "./cligen/coercable"
@@ -9,6 +8,7 @@ require "./cligen/annotations"
require "./cligen/format"
require "./cligen/regex"
require "./cligen/flag"
require "./cligen/timeparse"
require "./cligen/command"
require "./cligen/command_node"
require "./cligen/app"
@@ -16,32 +16,11 @@ require "./cligen/app"
module CliGen
VERSION = "0.1.0"
APPNAME = File.basename(PROGRAM_NAME)
macro override_help_template(filepath)
{% raise "ERROR : CliGen.override_help_template : File(#{filepath}) doesn't exist" unless file_exists?(filepath) %}
CliGen::HELP_OVERRIDE_TEMPLATE = {{`readlink -f #{filepath}`.strip.stringify}}
end
APPNAME = File.basename(PROGRAM_NAME)
record AdditionalDefaultFlag,
short : String,
long : String,
description : String,
work : String ->
ADDITIONAL_DEFAULT_FLAGS = [] of AdditionalDefaultFlag
def self.add_default_flag(short : String = "", long : String = "", description : String = "", &work : String -> )
raise "ERROR : add_default_flag : You must provide a description" if description.empty?
ADDITIONAL_DEFAULT_FLAGS << AdditionalDefaultFlag.new(
short: short,
long: long,
description: description,
work: work
)
end
annotation DefaultFlag
end
end
+2 -3
View File
@@ -1,6 +1,5 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
module CliGen
annotation ProxyCommand
+29 -3
View File
@@ -1,6 +1,5 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
require "./arg"
require "./command_node"
@@ -20,6 +19,33 @@ module CliGen
def check!
super
check_for_env_duplicates(all_flags + CliGen::GLOBAL_FLAGS)
end
def check_for_env_duplicates(flags : Array(BaseFlag))
flgs = flags.reject(&.env_var.empty?)
env_vars = flgs.group_by(&.env_var)
failures = [] of Tuple(String, Array(BaseFlag))
env_vars.each do |env_var, flg_group|
if flg_group.size > 1
failures << Tuple.new(env_var, flg_group)
end
end
unless failures.empty?
error_buffer = "ERROR : App(%s)#check! : Found ENV VAR Duplicates \n%s"
format = "\n%s:\n%s\n\n"
buffer = ""
failures.each do |env_var, flgs|
buffer += format % [env_var, flgs.map{|f| "- #{f.long_key}"}.join("\n")]
end
raise CliGen::DuplicateFlagError.new(error_buffer % [@name, buffer])
end
end
def self.handle_command_raises(&) : Nil
+2 -3
View File
@@ -1,6 +1,5 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
module CliGen
macro finished
+2 -3
View File
@@ -1,6 +1,5 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
module CliGen
# This class serves as a "argument wrapper" to force a fail-fast approach to
+2 -3
View File
@@ -1,6 +1,5 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
module CliGen::Coercable
abstract def coerce(arg : String)
+2 -3
View File
@@ -1,6 +1,5 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
require "colorize"
require "time"
+14 -9
View File
@@ -1,14 +1,17 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
module CliGen
class Command
macro argument(variable, description, long = nil, short = nil, validation = nil, on_match = nil, def_setter = false, def_getter = false, options = nil, delimiter = ",", format = nil, allow_no_verification = false)
macro argument(variable, description, long = nil, short = nil, validation = nil, on_match = nil, def_setter = false, def_getter = false, options = nil, delimiter = ",", format = nil, allow_no_verification = false, env_var = nil)
{% raise "ERROR : CliGen::Command.argument : def_setter must be a Bool" unless def_setter.is_a? BoolLiteral %}
{% raise "ERROR : CliGen::Command.argument : First argument (#{variable}) must be a TypeDeclaration (ex: '<var> : <type> [= val]')" unless variable.is_a? TypeDeclaration %}
{% name = variable.var %}
{% type = variable.type %}
{% if env_var %}
{% raise "ERROR : CliGen::Command.argument(#{name}) : Provided env_var must be a string" unless env_var.is_a? StringLiteral %}
{% raise "ERROR : CliGen::Command.argument(#{name}) : Provided env_var cannot contain a \"-\". Please fix and re-run" if env_var.includes?("-") %}
{% end %}
{% raise "ERROR : CliGen::Command.argument(#{name}) : Provided delimiter must be a string" unless delimiter.is_a? StringLiteral %}
{% if short %}
{% raise "ERROR : CliGen::Command.argument(#{name}) : Provided short must be a string" unless short.is_a? StringLiteral %}
@@ -24,7 +27,9 @@ module CliGen
{% unless on_match.nil? %}
{% puts "DEBUG : #{@type.name}.argument(#{name}) : OnMatch:\n\tid: #{on_match}\n\treturn_type: #{on_match.return_type}\n\tinput_vars: #{on_match.args}" if env("DEBUG")%}
{% raise "ERROR : CliGen::Command.argument(#{name}) : Provided on_match must be a Proc" unless on_match.is_a? ProcLiteral %}
{% raise "ERROR : CliGen::Command.argument(#{name}) : Provided on_match return type must be Nil" unless on_match.return_type.resolve == Nil %}
{% raise "ERROR : CliGen::Command.argument(#{name}) : You must have arguments for on_match" if on_match.args.empty? %}
{% raise "ERROR : CliGen::Command.argument(#{name}) : Your input argument must have a type" unless on_match.args.first.restriction %}
{% raise "ERROR : CliGen::Command.argument(#{name}) : Your input argument must be the same type as your argument (#{type})" unless on_match.args.first.restriction == type %}
{% end %}
{% unless validation.nil? %}
{% puts "DEBUG : #{@type.name}.argument(#{name}) : Validation:\n\tid: #{validation}\n\treturn_type: #{validation.return_type}\n\tinput_vars: #{validation.args}" if env("DEBUG")%}
@@ -50,8 +55,8 @@ module CliGen
{% raise "ERROR : CliGen::Command.argument(#{name}) : Provided format must be a RegexLiteral" unless format.is_a? RegexLiteral %}
{% end %}
{% if type.resolve <= Array && ! allow_no_verification %}
{% elem = type.type_vars.first %}
{% unless elem == Int32 %}
{% elem = type.resolve.type_vars.first %}
{% unless elem < Int || elem < Float %}
{% if format.nil? && options.nil? %}
{% raise "ERROR : CliGen::Command.argument(#{name}) : When providing custom data types for Array(T) or using Array(String) you must provide a format or options for argument filtering so that parsing can be done deterministically" %}
{% end %}
@@ -59,9 +64,9 @@ module CliGen
{% end %}
{% if type.resolve < Array && ! options.nil? %}
@[CliGen::Argument(short: {{short}}, long: {{long}}, description: {{description}}, validation: {{validation}}, on_match: {{on_match}}, options: [{{options}}], delimiter: {{delimiter}}, format: {{format}})]
@[CliGen::Argument(short: {{short}}, long: {{long}}, description: {{description}}, validation: {{validation}}, on_match: {{on_match}}, options: [{{options}}], delimiter: {{delimiter}}, format: {{format}}, env_var: {{env_var}})]
{% else %}
@[CliGen::Argument(short: {{short}}, long: {{long}}, description: {{description}}, validation: {{validation}}, on_match: {{on_match}}, options: {{options}}, delimiter: {{delimiter}}, format: {{format}})]
@[CliGen::Argument(short: {{short}}, long: {{long}}, description: {{description}}, validation: {{validation}}, on_match: {{on_match}}, options: {{options}}, delimiter: {{delimiter}}, format: {{format}}, env_var: {{env_var}})]
{% end %}
@{{variable}}
+2 -3
View File
@@ -1,6 +1,5 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
module CliGen
class Command
@@ -1,6 +1,5 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
module CliGen
class Command
+2 -3
View File
@@ -1,6 +1,5 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
module CliGen
class Command
+2 -3
View File
@@ -1,6 +1,5 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
module CliGen
class Command
+2 -3
View File
@@ -1,6 +1,5 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
module CliGen
class Command
+22 -152
View File
@@ -1,162 +1,30 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
require "log"
require "ecr"
require "./command_node/base"
require "./global_flag"
require "./match_type"
require "./flag"
require "./arg"
require "log"
require "ecr"
module CliGen
record SubCommandInfo,
name : String,
description : String,
examples : Array(String)?
alias RunCommand = Proc(Nil)
# Non-generic base that lets the tree hold heterogeneous CommandNode(T) children.
# Everything that doesn't depend on T lives here.
abstract class BaseCommandNode
getter name : String
getter flags : Array(BaseFlag)
getter commands : Array(BaseCommandNode)
getter description : String?
@pre_run_commands : Array(RunCommand)
@post_run_commands : Array(RunCommand)
Log = ::Log.for(CliGen::CommandInfo)
def initialize(
@name : String,
@flags : Array(BaseFlag),
@commands : Array(BaseCommandNode),
@pre_run_commands : Array(RunCommand),
@post_run_commands : Array(RunCommand),
@description : String? = nil
)
end
def check_for_duplicates!(flags : Array(BaseFlag)) : Nil
Log.trace { "CommandNode(#{@name})#check_for_duplicates! : entered with #{flags.map(&.long_key)}" }
shorts = flags.compact_map(&.short)
short_duplicates = [] of String
longs = flags.compact_map { |f| f.long_key unless f.long_key.empty? }
long_duplicates = [] of String
last_short : String = ""
shorts.sort.each do |short|
short_duplicates << short if last_short == short
last_short = short
end
last_long : String = ""
longs.sort.each do |long|
long_duplicates << long if last_long == long
last_long = long
end
unless long_duplicates.empty? && short_duplicates.empty?
error_buffer = "ERROR : CommandNode(%s)#check! : Found Duplicates : %s"
message = ""
unless long_duplicates.empty?
message += "\nLong:\n%s\n" % long_duplicates.map { |f| "- #{f}" }.join("\n")
end
unless short_duplicates.empty?
message += "\nShort:\n%s" % short_duplicates.map { |f| "- #{f}" }.join("\n")
end
raise CliGen::DuplicateFlagError.new(error_buffer % [@name, message])
end
end
def get(*, long : String) : BaseFlag?
Log.trace { "CommandNode(#{@name})#get(long: #{long}) : entered" }
@flags.find{|f| f.long_key == long} || @commands.find(&.flag?(long)).try(&.get(long: long)) || CliGen::GLOBAL_FLAGS.find(&.long_key.==(long))
end
def get(*, short : String) : BaseFlag?
Log.trace { "CommandNode(#{@name})#get(short: #{short}) : entered" }
@flags.find{|f| f.short == short} || @commands.find(&.flag?(short)).try(&.get(short: short)) || CliGen::GLOBAL_FLAGS.find(&.short.==(short))
end
def handle_flag_raises(&) : Nil
begin
yield
rescue e : CliGen::RuntimeError
abort e.message
end
end
def find_match(arg : String)
Log.trace { "CommandNode(#{@name})#find_match(#{arg}) : Entered" }
if subcommand?(arg)
Log.debug { "CommandNode(#{@name})#find_match(#{arg}) : arg found to be subcommand" }
return CliGen::MatchType::SubCommand
end
case arg
when "-h", "--help"
Log.debug { "CommandNode(#{@name})#find_match(#{arg}) : was found to be a help flag" }
CliGen::MatchType::Help
when CliGen::Regex::FLAG_REGEX
Log.debug { "CommandNode(#{@name})#find_match(#{arg}) : arg found to match the format of a flag" }
if flg = flag?(arg)
Log.debug { "CommandNode(#{@name})#find_match(#{arg}) : arg found to be a Flag(long: #{flg.long_key})" }
flg
else
Log.debug { "CommandNode(#{@name})#find_match(#{arg}) : arg found not to have a flag associated with it" }
CliGen::MatchType::NoMatch
end
when CliGen::Regex::FLAG_WITH_ARG
Log.debug { "CommandNode(#{@name})#find_match(#{arg}) : arg found to match the format of a flag with an arg <flag>=<arg>" }
CliGen::MatchType::FlagWithArg
when CliGen::Regex::FLAG_MULTIPLE_SHORT
Log.debug { "CommandNode(#{@name})#find_match(#{arg}) : arg found to match the clumped flag format" }
CliGen::MatchType::FlagMultipleShort
else
Log.debug { "CommandNode(#{@name})#find_match(#{arg}) : Found no obvious match format wise. Checking if arg is a command" }
if cmd = @commands.find(&.name.== arg)
Log.debug { "CommandNode(#{@name})#find_match(#{arg}) : Looks like the arg matched a defined command" }
cmd
else
Log.debug { "CommandNode(#{@name})#find_match(#{arg}) : No match found for arg" }
CliGen::MatchType::NoMatch
end
end
end
def subcommands? : Bool
subcommands.size > 0
end
def subcommand?(arg : String) : Bool
Log.trace { "CommandNode(#{@name})#subcommand?(#{arg}) : Entered" }
subcommands.any?(&.name.== arg)
end
def flag?(arg : String) : BaseFlag?
Log.trace { "CommandNode(#{@name})#flag?(#{arg}) : Entered" }
get(short: arg) || get(long: arg)
end
# Converts String array to Arg array and hands off to the typed process method
def process(args : Array(String)) : Nil
Log.trace { "CommandNode(#{@name})#process(#{args}) : Entered" }
new_args = args.each_with_index.map { |arg, i| CliGen::Arg.new(value: arg, index: i) }.to_a
process(new_args)
end
abstract def subcommands : Array(SubCommandInfo)
abstract def check! : Nil
abstract def process(args : Array(CliGen::Arg)) : Nil
end
class CommandNode(T) < BaseCommandNode
def initialize(
name : String,
flags : Array(BaseFlag),
commands : Array(BaseCommandNode),
pre_run_commands : Array(RunCommand),
post_run_commands : Array(RunCommand),
description : String? = nil
)
meta = CommandMeta.new(
cls: {{T.name.stringify}}
)
super(name, flags, commands, pre_run_commands, post_run_commands, meta, description)
end
def subcommands : Array(SubCommandInfo)
{% begin %}
@@ -201,8 +69,10 @@ module CliGen
def check! : Nil
@flags.each(&.check!)
check_for_duplicates!(@flags + CliGen::GLOBAL_FLAGS)
check_for_duplicate_flags!(@flags + CliGen::GLOBAL_FLAGS)
@commands.each(&.check!)
check_for_duplicate_subcommands!
{% unless T == Nil %}
raise CliGen::MissingDispatchError.new("CommandNode(#{@name})#check! : {{T}} has no subcommands and no #main defined") \
if subcommands.empty? && !{{T.has_method?(:main)}}
+177
View File
@@ -0,0 +1,177 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
require "../flag"
require "./command_meta"
require "./subcommand_meta"
module CliGen
alias RunCommand = Proc(Nil)
# Non-generic base that lets the tree hold heterogeneous CommandNode(T) children.
# Everything that doesn't depend on T lives here.
abstract class BaseCommandNode
getter name : String
getter flags : Array(BaseFlag)
getter commands : Array(BaseCommandNode)
getter description : String?
getter meta : CommandMeta
@pre_run_commands : Array(RunCommand)
@post_run_commands : Array(RunCommand)
Log = ::Log.for(CliGen::CommandNode)
def initialize(
@name : String,
@flags : Array(BaseFlag),
@commands : Array(BaseCommandNode),
@pre_run_commands : Array(RunCommand),
@post_run_commands : Array(RunCommand),
@meta : CommandMeta,
@description : String? = nil
)
end
def all_flags : Array(BaseFlag)
@flags + @commands.flat_map(&.all_flags)
end
def check_for_duplicate_subcommands!
failures = [] of Tuple(String, Array(BaseCommandNode))
@commands.group_by(&.name).each do |command, cmd_group|
if cmd_group.size > 1
failures << Tuple.new(command, cmd_group)
end
end
unless failures.empty?
error_buffer = "ERROR : #{self.class}(%s)#check! : Found Command Name Duplicates \n%s"
format = "\n%s:\n%s\n\n"
buffer = ""
failures.each do |name, cmds|
buffer += format % [name, cmds.map{|c| "- #{c.meta.cls} (#{c.description})"}.join("\n") ]
end
raise CliGen::DuplicateCommandError.new(error_buffer % [@name, buffer])
end
end
def check_for_duplicate_flags!(flags : Array(BaseFlag)) : Nil
Log.trace { "CommandNode(#{@name})#check_for_duplicate_flags! : entered with #{flags.map(&.long_key)}" }
shorts = flags.compact_map(&.short)
short_duplicates = [] of String
longs = flags.compact_map { |f| f.long_key unless f.long_key.empty? }
long_duplicates = [] of String
last_short : String = ""
shorts.sort.each do |short|
short_duplicates << short if last_short == short
last_short = short
end
last_long : String = ""
longs.sort.each do |long|
long_duplicates << long if last_long == long
last_long = long
end
unless long_duplicates.empty? && short_duplicates.empty?
error_buffer = "ERROR : CommandNode(%s)#check! : Found Duplicates : %s"
message = ""
unless long_duplicates.empty?
message += "\nLong:\n%s\n" % long_duplicates.map { |f| "- #{f}" }.join("\n")
end
unless short_duplicates.empty?
message += "\nShort:\n%s" % short_duplicates.map { |f| "- #{f}" }.join("\n")
end
raise CliGen::DuplicateFlagError.new(error_buffer % [@name, message])
end
end
def get(*, long : String) : BaseFlag?
Log.trace { "CommandNode(#{@name})#get(long: #{long}) : entered" }
@flags.find{|f| f.long_key == long} || @commands.find(&.flag?(long)).try(&.get(long: long)) || CliGen::GLOBAL_FLAGS.find(&.long_key.==(long))
end
def get(*, short : String) : BaseFlag?
Log.trace { "CommandNode(#{@name})#get(short: #{short}) : entered" }
@flags.find{|f| f.short == short} || @commands.find(&.flag?(short)).try(&.get(short: short)) || CliGen::GLOBAL_FLAGS.find(&.short.==(short))
end
def handle_flag_raises(&) : Nil
begin
yield
rescue e : CliGen::RuntimeError
abort e.message
end
end
def find_match(arg : String)
Log.trace { "CommandNode(#{@name})#find_match(#{arg}) : Entered" }
if subcommand?(arg)
Log.debug { "CommandNode(#{@name})#find_match(#{arg}) : arg found to be subcommand" }
return CliGen::MatchType::SubCommand
end
case arg
when "-h", "--help"
Log.debug { "CommandNode(#{@name})#find_match(#{arg}) : was found to be a help flag" }
CliGen::MatchType::Help
when CliGen::Regex::FLAG_REGEX
Log.debug { "CommandNode(#{@name})#find_match(#{arg}) : arg found to match the format of a flag" }
if flg = flag?(arg)
Log.debug { "CommandNode(#{@name})#find_match(#{arg}) : arg found to be a Flag(long: #{flg.long_key})" }
flg
else
Log.debug { "CommandNode(#{@name})#find_match(#{arg}) : arg found not to have a flag associated with it" }
CliGen::MatchType::NoMatch
end
when CliGen::Regex::FLAG_WITH_ARG
Log.debug { "CommandNode(#{@name})#find_match(#{arg}) : arg found to match the format of a flag with an arg <flag>=<arg>" }
CliGen::MatchType::FlagWithArg
when CliGen::Regex::FLAG_MULTIPLE_SHORT
Log.debug { "CommandNode(#{@name})#find_match(#{arg}) : arg found to match the clumped flag format" }
CliGen::MatchType::FlagMultipleShort
else
Log.debug { "CommandNode(#{@name})#find_match(#{arg}) : Found no obvious match format wise. Checking if arg is a command" }
if cmd = @commands.find(&.name.== arg)
Log.debug { "CommandNode(#{@name})#find_match(#{arg}) : Looks like the arg matched a defined command" }
cmd
else
Log.debug { "CommandNode(#{@name})#find_match(#{arg}) : No match found for arg" }
CliGen::MatchType::NoMatch
end
end
end
def subcommands? : Bool
subcommands.size > 0
end
def subcommand?(arg : String) : Bool
Log.trace { "CommandNode(#{@name})#subcommand?(#{arg}) : Entered" }
subcommands.any?(&.name.== arg)
end
def flag?(arg : String) : BaseFlag?
Log.trace { "CommandNode(#{@name})#flag?(#{arg}) : Entered" }
get(short: arg) || get(long: arg)
end
# Converts String array to Arg array and hands off to the typed process method
def process(args : Array(String)) : Nil
Log.trace { "CommandNode(#{@name})#process(#{args}) : Entered" }
new_args = args.each_with_index.map { |arg, i| CliGen::Arg.new(value: arg, index: i) }.to_a
process(new_args)
end
abstract def subcommands : Array(SubCommandInfo)
abstract def check! : Nil
abstract def process(args : Array(CliGen::Arg)) : Nil
end
end
+7
View File
@@ -0,0 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
module CliGen
record CommandMeta,
cls : String
end
@@ -0,0 +1,10 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
module CliGen
record SubCommandInfo,
name : String,
description : String,
examples : Array(String)?
end
+15 -7
View File
@@ -1,13 +1,12 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
module CliGen
# Base for all CliGen exceptions
class Error < Exception; end
# -------------------------------------------------------------------------
# Internal errors framework invariant violations, should never reach users
# Internal errors - framework invariant violations, should never reach users
# -------------------------------------------------------------------------
class InternalError < Error; end
@@ -22,7 +21,7 @@ module CliGen
class UnknownCommandNodeError < InternalError; end
# -------------------------------------------------------------------------
# Configuration errors shard consumer wired something up incorrectly
# Configuration errors - shard consumer wired something up incorrectly
# -------------------------------------------------------------------------
class ConfigurationError < Error; end
@@ -33,6 +32,9 @@ module CliGen
# Duplicate short or long flags detected during check!
class DuplicateFlagError < ConfigurationError; end
# Duplicate command names detected during check!
class DuplicateCommandError < ConfigurationError; end
# A CommandNode(T) has no subcommands and no #main defined
class MissingDispatchError < ConfigurationError; end
@@ -46,7 +48,7 @@ module CliGen
class ParseableInvariantError < ConfigurationError; end
# -------------------------------------------------------------------------
# Runtime errors bad user input at the CLI level
# Runtime errors - bad user input at the CLI level
# -------------------------------------------------------------------------
class RuntimeError < Error; end
@@ -73,9 +75,15 @@ module CliGen
class FlagBundleError < RuntimeError; end
# -------------------------------------------------------------------------
# Help signal not an error; exit 0 after printing
# Help signal - not an error; exit 0 after printing
# -------------------------------------------------------------------------
# Raised when -h/--help is matched; carries the rendered help string
class HelpRequestedError < Error; end
# -------------------------------------------------------------------------
# CliGen::Timeparse Errors
# -------------------------------------------------------------------------
class TimeParseError < RuntimeError; end
end
+22 -174
View File
@@ -1,67 +1,12 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
require "./flag/base"
require "./timeparse"
require "./exceptions"
require "./arg"
module CliGen
# To be able to store metadata for use in the help output
record FlagMeta,
type : String,
array : Bool,
format : String?,
default : String,
options : Array(String)?
abstract class BaseFlag
getter var : String
getter short : String?
getter long : String
getter long_key : String
getter env_var : String
getter description : String
getter delimiter : String
getter meta : FlagMeta
Log = ::Log.for(CliGen::Flag)
def initialize(
@var : String,
@short : String?,
@long : String,
@env_var : String,
@description : String,
@delimiter : String,
@meta : FlagMeta
)
Log.trace {
"Flag was initialized:\n" \
"\t@var : #{@var}\n" \
"\t@short : #{@short}\n" \
"\t@long : #{@long}\n" \
"\t@env_var : #{@env_var}\n" \
"\t@description : #{@description}\n" \
"\t@delimiter : #{@delimiter}\n"
}
# if the user provides just a "--long" I want the @long_key to match it
if @long =~ /\s|=/
@long_key = @long.split(/\s|=/).first
else
@long_key = @long
end
end
def matches?(token : String) : Bool
Log.trace { "Flag(#{@long})#matches?(#{token}) : entered" }
token == @short || (!@long_key.empty? && token == @long_key)
end
abstract def satisfied? : Bool
abstract def validate! : Nil
abstract def raw_value : String?
abstract def check! : Nil
end
class Flag(T) < BaseFlag
@value : T?
@default : T?
@@ -120,7 +65,6 @@ module CliGen
raise CliGen::FlagArgumentError.new("Flag(#{T}, long: #{@long_key}) : a flag token was provided where a value was expected (got: #{argv.first.value})") if argv.first.flag?
end
{% if T == Bool %}
@value = true
{% elsif T < Array %}
@@ -217,8 +161,12 @@ module CliGen
@value = T.new(argv.first.value)
argv.first.processed
{% elsif T == Time %}
@value = parse_time(argv.first.value)
argv.first.processed
begin
@value = ::CliGen::Timeparse.parse(argv.first.value)
argv.first.processed
rescue e : ::CliGen::TimeParseError
raise CliGen::InvalidFlagValueError.new("Flag(#{T}, long: #{@long_key}) : #{e.message}")
end
{% elsif T == String %} # String
if ! @format.nil? && argv.first.value !~ @format
raise CliGen::InvalidFlagValueError.new("Flag(#{T}, long: #{@long_key}) : '#{argv.first.value}' does not match required format /#{@format.not_nil!.source}/")
@@ -260,6 +208,9 @@ module CliGen
v ||= @default
raise CliGen::MissingRequiredFlagError.new("#{CliGen::APPNAME}: required flag #{@long_key} was not provided") if v.nil?
validate!(v)
v.not_nil!
end
@@ -282,14 +233,14 @@ module CliGen
false
end
def validate! : Nil
def validate!(v : T? = nil) : Nil
Log.trace { "Flag(long: #{@long}, type: #{@meta.type})#validate! : called" }
v = value!
v = value! if v.nil?
if opts = @options
{% if T < Array %}
v.each do |v2|
raise CliGen::InvalidOptionError.new("#{CliGen::APPNAME}: '#{v2}' is not a valid value for #{@long_key} (valid: #{opts.join(", ")})") unless opts.first.includes?(v2)
raise CliGen::InvalidOptionError.new("#{CliGen::APPNAME}: '#{v2}' is not a valid value for #{@long_key} (valid: #{opts.first.join(", ")})") unless opts.first.includes?(v2)
end
{% else %}
raise CliGen::InvalidOptionError.new("#{CliGen::APPNAME}: '#{v}' is not a valid value for #{@long_key} (valid: #{opts.join(", ")})") unless opts.includes?(v)
@@ -330,7 +281,11 @@ module CliGen
end
T.new(raw)
{% elsif T == Time %}
parse_time(raw)
begin
::CliGen::Timeparse.parse(raw)
rescue e : ::CliGen::TimeParseError
raise CliGen::InvalidFlagValueError.new("Flag(#{T}, long: #{@long_key}) : #{e.message}")
end
{% elsif T < Array %}
if raw.includes?(@delimiter)
{% elem = T.type_vars.first %}
@@ -390,112 +345,5 @@ module CliGen
{% raise "ERROR : Flag(#{T}) : #{T} is not a coercable type. If you wish to coerce it from a bare string extend CliGen::Coercable & implement the class method" %}
{% end %}
end
private def parse_time(raw : String) : Time
get_location = -> (tz : String) {
sign = tz.starts_with?("-") ? -1 : 1
hour = tz[1..2].to_i
min = tz[3..4].to_i
Time::Location.fixed(tz, sign * ((hour * 3600) + (min * 60)))
}
get_time = ->(sign : String, quantity : Int32, unit : String) {
time = Time.local
diff = case unit
when /year/
quantity.year
when /month/
quantity.month
when /day/
quantity.day
when /hour/
quantity.hour
when /minute/
quantity.minute
when /second/
quantity.second
else
raise CliGen::InvalidFlagValueError.new("Flag({{T}}, long: #{@long_key}) : #{unit} is not a valid unit (valid: year, month, day, hour, minute, second)")
end
case sign
when "+"
time + diff
when "-"
time - diff
else
raise CliGen::InvalidFlagValueError.new("Flag({{T}}, long: #{@long_key}) : #{sign} is not a valid modifier (valid: - or +)")
end
}
case raw
when CliGen::Regex::INPUT_DATE_EPOCH_WITH_TIMEZONE
epoch = $1
tz = $2
::Time.unix(epoch.to_i).in(get_location.call(tz))
when CliGen::Regex::INPUT_DATE_EPOCH
::Time.unix($1.to_i)
when CliGen::Regex::INPUT_DATE_FULL
::Time.parse!(raw, CliGen::Format::INPUT_DATE_FULL)
when CliGen::Regex::INPUT_DATE_PARTIAL
::Time.parse_local(raw, CliGen::Format::INPUT_DATE_PARTIAL)
when CliGen::Regex::INPUT_DATE_SIMPLE_WITH_TIMEZONE
::Time.parse!(raw, CliGen::Format::INPUT_DATE_SIMPLE_WITH_TIMEZONE)
when CliGen::Regex::INPUT_DATE_SIMPLE
::Time.parse_local(raw, CliGen::Format::INPUT_DATE_SIMPLE)
when CliGen::Regex::INPUT_DATE_RELATIVE_WITH_TIMEZONE
if match = raw.match(CliGen::Regex::INPUT_DATE_RELATIVE_WITH_TIMEZONE)
sign = match["sign"]
quantity = match["quantity"].to_i32
unit = match["unit"]
tz = match["timezone"]
get_time.call(sign, quantity, unit).in(get_location.call(tz))
else
raise CliGen::InvalidFlagValueError.new("#{CliGen::APPNAME}: How did regex break?")
end
when CliGen::Regex::INPUT_DATE_RELATIVE
if match = raw.match(CliGen::Regex::INPUT_DATE_RELATIVE)
sign = match["sign"]
quantity = match["quantity"].to_i32
unit = match["unit"]
get_time.call(sign, quantity, unit)
else
raise CliGen::InvalidFlagValueError.new("#{CliGen::APPNAME}: How did regex break?")
end
else
raise CliGen::InvalidFlagValueError.new(<<-EOF
#{CliGen::APPNAME}: Flag(type: #{@meta.type}, long: #{@long_key}) : invalid date/time format "#{raw}".
Valid are:
1) %Y-%m-%d %H:%M:%S %z
2) %Y-%m-%d %H:%M:%S
3) %Y-%m-%d %z
4) %Y-%m-%d
5) %s %z
6) %s
7) [+-][0-9]+ [years|months|days|hours|minutes|seconds] %z
8) [+-][0-9]+ [years|months|days|hours|minutes|seconds]
Note on format:
# Timezone Offset (ex: -0500 == CST)
%z == [-+][0-9]{4}
# Year (ex: 2026)
%Y == [0-9]{4}
# month
%m == [0-9]{2}
# day
%d == [0-9]{2}
# hour
%H == [0-9]{2}
# minute
%S == [0-9]{2}
# epoch time
%s == @[0-9]+
EOF
)
end
end
end
end
+57
View File
@@ -0,0 +1,57 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
require "log"
require "./meta"
module CliGen
abstract class BaseFlag
getter var : String
getter short : String?
getter long : String
getter long_key : String
getter env_var : String
getter description : String
getter delimiter : String
getter meta : FlagMeta
Log = ::Log.for(CliGen::Flag)
def initialize(
@var : String,
@short : String?,
@long : String,
@env_var : String,
@description : String,
@delimiter : String,
@meta : FlagMeta
)
Log.trace {
"Flag was initialized:\n" \
"\t@var : #{@var}\n" \
"\t@short : #{@short}\n" \
"\t@long : #{@long}\n" \
"\t@env_var : #{@env_var}\n" \
"\t@description : #{@description}\n" \
"\t@delimiter : #{@delimiter}\n"
}
# if the user provides just a "--long" I want the @long_key to match it
if @long =~ /\s|=/
@long_key = @long.split(/\s|=/).first
else
@long_key = @long
end
end
def matches?(token : String) : Bool
Log.trace { "Flag(#{@long})#matches?(#{token}) : entered" }
token == @short || (!@long_key.empty? && token == @long_key)
end
abstract def satisfied? : Bool
abstract def validate! : Nil
abstract def raw_value : String?
abstract def check! : Nil
end
end
+12
View File
@@ -0,0 +1,12 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
module CliGen
# To be able to store metadata for use in the help output
record FlagMeta,
type : String,
array : Bool,
format : String?,
default : String,
options : Array(String)?
end
+4 -3
View File
@@ -1,10 +1,11 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
# This module just holds time formats to be used with ::Time.parse!/.parse/.parse_local
module CliGen::Format
INPUT_DATE_PARTIAL = "%Y-%m-%d %H:%M:%S"
INPUT_DATE_FULL = "%Y-%m-%d %H:%M:%S %z"
INPUT_DATE_SIMPLE_WITH_TIMEZONE = "%Y-%m-%d %z"
INPUT_DATE_SIMPLE = "%Y-%m-%d"
INPUT_EPOCH = "@%s"
end
+4 -37
View File
@@ -1,50 +1,17 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
require "./flag"
require "./global_flag/add_global_flag"
module CliGen
GLOBAL_FLAGS = [] of BaseFlag
GLOBAL_FLAGS << Flag(Bool).new(
var: "",
add_global_flag(Bool,
short: "-v",
long: "--verbose",
env_var: "VERBOSE",
default: false,
description: "Enable verbose output from program & help output"
)
macro add_global_flag(type, long, description, env_var = nil, short = nil, validation = nil, &on_match)
{% raise "ERROR : CliGen.add_global_flag : type must be a TypeNode" unless type.is_a? TypeNode %}
{% raise "ERROR : CliGen.add_global_flag : long must begin a StringLiteral" unless long.is_a? StringLiteral %}
{% raise "ERROR : CliGen.add_global_flag : long must begin with --" unless long =~ /^--/ %}
{% if short %}
{% raise "ERROR : CliGen.add_global_flag : Short must be a StringLiteral" unless short.is_a? StringLiteral %}
{% raise "ERROR : CliGen.add_global_flag : Short must be a - with single char (ex: -a)" unless short =~ /^-[a-zA-Z]/ %}
{% end %}
{% if validation %}
{% raise "ERROR : CliGen.add_global_flag : validation must be a Proc" unless validation.is_a? ProcLiteral %}
{% raise "ERROR : CliGen.add_global_flag : validation proc return type must be nil \"->(...) : Nil {...}\"" unless validation.is_a? ProcLiteral %}
{% raise "ERROR : CliGen.add_global_flag : validation proc must have a single input variable" unless validation.args.size == 1%}
{% arg = validation.args.first %}
{% raise "ERROR : CliGen.add_global_flag : validation proc input variable MUST be typed to match the flag type \"->(#{arg.name} : #{type}) : Nil { ... }\"" unless arg.restriction == type %}
{% end %}
{% raise "ERROR : CliGen.add_global_flag : decription must be a StringLiteral" unless description.is_a? StringLiteral %}
{% if env_var %}
{% raise "ERROR : CliGen.add_global_flag : env_var must be a StringLiteral" unless env_var.is_a? StringLiteral %}
{% else %}
{% env_var = long.gsub(/--/, "").upcase %}
{% end %}
::CliGen::GLOBAL_FLAGS << CliGen::Flag({{type}}).new(
var: "",
short: {{short}},
long: {{long}},
description: {{description}},
env_var: {{env_var}},
on_match: {% if on_match %} ->() : Nil { {{on_match.body}} } {% else %} nil {% end %},
validation: {% if validation %} {{validation}} {% else %} nil {% end %}
)
end
end
+44
View File
@@ -0,0 +1,44 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
module CliGen
macro add_global_flag(type, *, long, description, env_var = nil, short = nil, validation = nil, default = nil, on_match = nil)
{% raise "ERROR : CliGen.add_global_flag(#{long}) : type must be a TypeNode" unless type.resolve.is_a? TypeNode %}
{% raise "ERROR : CliGen.add_global_flag(#{long}) : long must begin a StringLiteral" unless long.is_a? StringLiteral %}
{% raise "ERROR : CliGen.add_global_flag(#{long}) : long must begin with --" unless long =~ /^--/ %}
{% if short %}
{% raise "ERROR : CliGen.add_global_flag(#{long}) : Short must be a StringLiteral" unless short.is_a? StringLiteral %}
{% raise "ERROR : CliGen.add_global_flag(#{long}) : Short must be a - with single char (ex: -a)" unless short =~ /^-[a-zA-Z]/ %}
{% end %}
{% unless validation.nil? %}
{% raise "ERROR : CliGen.add_global_flag(#{long}) : validation must be a Proc" unless validation.is_a? ProcLiteral %}
{% raise "ERROR : CliGen.add_global_flag(#{long}) : validation proc return type must be Bool \"->(...) : Bool {...}\"" unless validation.return_type.resolve == Bool %}
{% raise "ERROR : CliGen.add_global_flag(#{long}) : validation proc must have a single input variable" unless validation.args.size == 1%}
{% arg = validation.args.first %}
{% raise "ERROR : CliGen.add_global_flag(#{long}) : validation proc input variable MUST be typed to match the flag type \"->(#{arg.name} : #{type}) : Bool { ... }\"" unless arg.restriction == type %}
{% end %}
{% unless on_match.nil? %}
{% raise "ERROR : CliGen.add_global_flag(#{long}) : Provided on_match must be a Proc" unless on_match.is_a? ProcLiteral %}
{% raise "ERROR : CliGen.add_global_flag(#{long}) : You must have arguments for on_match" if on_match.args.empty? %}
{% raise "ERROR : CliGen.add_global_flag(#{long}) : Your input argument must have a type" unless on_match.args.first.restriction %}
{% raise "ERROR : CliGen.add_global_flag(#{long}) : Your input argument must be the same type as your argument (#{type})" unless on_match.args.first.restriction == type %}
{% end %}
{% raise "ERROR : CliGen.add_global_flag(#{long}) : decription must be a StringLiteral" unless description.is_a? StringLiteral %}
{% if env_var %}
{% raise "ERROR : CliGen.add_global_flag(#{long}) : env_var must be a StringLiteral" unless env_var.is_a? StringLiteral %}
{% raise "ERROR : CliGen.add_global_flag(#{long}) : env_var cannot contain \"-\"'s please fix this" if env_var.includes?("-") %}
{% else %}
{% env_var = long.gsub(/--/, "").gsub(/-/,"_").upcase %}
{% end %}
::CliGen::GLOBAL_FLAGS << ::CliGen::Flag({{type}}).new(
var: "",
short: {{short}},
long: {{long}},
description: {{description}},
env_var: {{env_var}},
default: {{default}},
on_match: {% if on_match %} {{on_match}} {% else %} nil {% end %},
validate: {% if validation %} {{validation}} {% else %} nil {% end %}
)
end
end
+2 -3
View File
@@ -1,6 +1,5 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
module CliGen
enum MatchType
+2 -3
View File
@@ -1,6 +1,5 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
module CliGen::Parsable
abstract def parse_args(args : Array(CliGen::Arg))
+19 -14
View File
@@ -1,6 +1,5 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
module CliGen::Regex
FLAG_REGEX=/^(-[a-zA-Z]|--[a-zA-Z-_0-9]+)$/
@@ -18,23 +17,29 @@ module CliGen::Regex
# Never match user input against these directly — use the INPUT_DATE_*
# matchers, which are anchored.
# ---------------------------------------------------------------------------
TIMEZONE = /(?<timezone>[-+][0-9]{4})/
# Hour is bounded 00-23 and minute 00-59 so the largest representable offset
# is 23:59 (86340s), which stays inside Time::Location.fixed's +/-24h limit.
# Without these bounds an offset like -9999 passes the match and then raises
# Time::Location::InvalidTimezoneOffsetError - a non-CliGen exception that
# escapes App#handle_command_raises and reaches the user as a stack trace.
TIMEZONE = /(?<timezone>(?<offset_sign>[-+])(?<offset_hour>[01][0-9]|2[0-3])(?<offset_minute>[0-5][0-9]))/
TIME = /(?<time>(?<hour>[0-9]{2}):(?<minute>[0-9]{2}):(?<second>[0-9]{2}))/
DATE = /(?<date>(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2}))/
EPOCH = /@(?<epoch>[0-9]+)/
RELATIVE = /(?<sign>[+-])(?<quantity>[0-9]+)\s+(?<unit>seconds?|minutes?|hours?|days?|months?|years?)/
RELATIVE = /[+-][0-9]+\s+(seconds?|minutes?|hours?|days?|weeks?|months?|years?)/
# ---------------------------------------------------------------------------
# Date/time matchers — fully anchored so a partial match can't slip through.
# Relative Operation matcher - For use with CliGen::Timeparse::RelativeOperation
# ---------------------------------------------------------------------------
INPUT_DATE_FULL = /^#{DATE}\s+#{TIME}\s+#{TIMEZONE}$/
INPUT_DATE_PARTIAL = /^#{DATE}\s+#{TIME}$/
INPUT_DATE_SIMPLE_WITH_TIMEZONE = /^#{DATE}\s+#{TIMEZONE}$/
INPUT_DATE_SIMPLE = /^#{DATE}$/
INPUT_DATE_EPOCH_WITH_TIMEZONE = /^#{EPOCH}\s+#{TIMEZONE}$/
INPUT_DATE_EPOCH = /^#{EPOCH}$/
INPUT_DATE_RELATIVE_WITH_TIMEZONE = /^#{RELATIVE}\s+#{TIMEZONE}$/
INPUT_DATE_RELATIVE = /^#{RELATIVE}$/
RELATIVE_OPERATION = /(?<sign>[+-])(?<quantity>[0-9]+)\s+(?<unit>seconds?|minutes?|hours?|days?|weeks?|months?|years?)/
# ---------------------------------------------------------------------------
# Date/time matchers - fully anchored so a partial match can't slip through.
# ---------------------------------------------------------------------------
INPUT_DATE_FULL = /^#{DATE}\s+#{TIME}(\s+#{TIMEZONE})?$/
INPUT_DATE_SIMPLE = /^#{DATE}(\s+#{TIMEZONE})?$/
INPUT_DATE_EPOCH = /^#{EPOCH}(\s+#{TIMEZONE})?$/
INPUT_RELATIVE_OPERATIONS = /^(?<operations>(#{RELATIVE}\s*)+)(\s+#{TIMEZONE})?$/
FLOAT = /^[-+]?[[:digit:]]+(\.[[:digit:]]+)?$/
UINT = /^[[:digit:]]+$/
+94
View File
@@ -0,0 +1,94 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
require "time"
require "./timeparse/relative_operation"
module CliGen::Timeparse
private def self.get_location(raw : String) : Time::Location
match = raw.match!(CliGen::Regex::TIMEZONE)
sign = match["offset_sign"] == "-" ? -1 : 1
hour = match["offset_hour"].to_i
min = match["offset_minute"].to_i
Time::Location.fixed(raw, sign * ((hour * 3600) + (min * 60)))
end
def self.parse(raw : String) : Time
raw = raw.strip
case raw
when CliGen::Regex::INPUT_DATE_EPOCH
match = raw.match!(CliGen::Regex::INPUT_DATE_EPOCH)
if match["timezone"]?
::Time.unix(match["epoch"].to_i).in(get_location(match["timezone"]))
else
::Time.parse!(raw, CliGen::Format::INPUT_EPOCH)
end
when CliGen::Regex::INPUT_DATE_FULL
match = raw.match!(CliGen::Regex::INPUT_DATE_FULL)
if match["timezone"]?
::Time.parse!(raw, CliGen::Format::INPUT_DATE_FULL)
else
::Time.parse_local(raw, CliGen::Format::INPUT_DATE_PARTIAL)
end
when CliGen::Regex::INPUT_DATE_SIMPLE
match = raw.match!(CliGen::Regex::INPUT_DATE_SIMPLE)
if match["timezone"]?
::Time.parse!(raw, CliGen::Format::INPUT_DATE_SIMPLE_WITH_TIMEZONE)
else
::Time.parse_local(raw, CliGen::Format::INPUT_DATE_SIMPLE)
end
when CliGen::Regex::INPUT_RELATIVE_OPERATIONS
match = raw.match!(CliGen::Regex::INPUT_RELATIVE_OPERATIONS)
ops = RelativeOperation.get_operations(match["operations"])
time = ::Time.local
if match["timezone"]?
time = time.in(get_location(match["timezone"]))
end
ops.each do |op|
time = op.apply(time)
end
time
else
raise CliGen::TimeParseError.new(<<-EOF
ERROR : invalid date/time format "#{raw}".
Valid are:
1) %Y-%m-%d %H:%M:%S %z
2) %Y-%m-%d %H:%M:%S
3) %Y-%m-%d %z
4) %Y-%m-%d
5) %s %z
6) %s
7) ([+-][0-9]+ (years|months|weeks|days|hours|minutes|seconds))+ %z
8) ([+-][0-9]+ [years|months|weeks|days|hours|minutes|seconds])+
Note on format:
# Timezone Offset (ex: -0500 == CST)
%z == [-+]([0-1][0-9]|2[0-3])[0-5][0-9]
# Year (ex: 2026)
%Y == [0-9]{4}
# month
%m == [0-9]{2}
# day
%d == [0-9]{2}
# hour
%H == [0-9]{2}
# minute
%S == [0-9]{2}
# epoch time
%s == @[0-9]+
EOF
)
end
end
end
+14
View File
@@ -0,0 +1,14 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
module CliGen::Timeparse
enum OperationUnit
YEAR
MONTH
WEEK
DAY
HOUR
MINUTE
SECOND
end
end
@@ -0,0 +1,47 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
require "time"
require "./operation_unit"
require "../regex"
module CliGen::Timeparse
struct RelativeOperation
getter sign : Int32
getter quantity : Int32
getter unit : CliGen::Timeparse::OperationUnit
def initialize(@sign, @quantity, @unit)
end
def apply(time : Time) : Time
{% begin %}
case @unit
{% for unit in CliGen::Timeparse::OperationUnit.constants %}
in OperationUnit::{{unit.id}}
time + (@sign * @quantity).{{unit.id.downcase}}
{% end %}
end
{% end %}
end
# Just handles retrieving the operations from a bare string and returning
# an array of them for use in applying them in a row
def self.get_operations(raw : String) : Array(RelativeOperation)
raw.scan(CliGen::Regex::RELATIVE_OPERATION).map{|match| from_regex(match)}
end
# Just an initializer from a regex match. Only callable internally
# so any operations must come from get_operations as that will handle
# parsing it for the user
private def self.from_regex(match : ::Regex::MatchData)
new(
sign: match["sign"] == "-" ? -1 : 1,
quantity: match["quantity"].to_i32,
# just in case the user provides the "s" (ex: "days", "hours", etc)
unit: OperationUnit.parse(match["unit"].chomp("s"))
)
end
end
end
+56
View File
@@ -0,0 +1,56 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
#
# Manual harness for flag resolution + validation across every source a value
# can arrive from. Driven by ./utils/flag_matrix.sh; see that script for the expected
# results. Kept out of spec/ because each case needs its own process (env vars
# must be set before startup).
#
# ENV VAR NAMING - the two kinds of flag derive their names differently:
#
# global flag add_global_flag(..., long: "--retries") -> RETRIES
# derived from the long flag, minus the leading dashes
#
# command arg class Greet; argument(level : Int32 ...) -> GREET_LEVEL
# derived as <COMMAND>_<VAR>, see app/generate.cr
#
# The asymmetry is easy to trip over: exporting LEVEL=9 does nothing at all,
# because the command argument is bound to GREET_LEVEL.
require "cligen"
CliGen.add_global_flag(Int32,
long: "--retries",
short: "-r",
description: "retry count (global, validated 0..10, env: RETRIES)",
default: 3,
validation: ->(v : Int32) : Bool { v >= 0 && v <= 10 }
)
@[CliGen::CommandInfo(description: "flag resolution matrix")]
class Greet < CliGen::Command
argument(name : String = "world",
long: "--name",
description: "plain string, no validation (env: GREET_NAME)"
)
argument(level : Int32 = 1,
long: "--level",
description: "validated < 5 (env: GREET_LEVEL)",
validation: ->(v : Int32) : Bool { v < 5 }
)
private def retries : Int32
CliGen::GLOBAL_FLAGS
.find { |f| f.long_key == "--retries" }
.not_nil!
.as(CliGen::Flag(Int32))
.value!
end
def main
puts "retries=#{retries} level=#{@level} name=#{@name}"
end
end
CliGen::App.process
+87
View File
@@ -0,0 +1,87 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
#
# Runs flag_matrix.cr across every value source (default / env / CLI) for both
# a global flag and a command argument, and checks each result.
#
# Each case needs its own process because env vars must be set before startup,
# which is why this lives here rather than in spec/.
#
# ./utils/flag_matrix.sh (runnable from anywhere)
#
# Exits non-zero if any case does not match.
set -u
# Build from the PROJECT ROOT, not utils/. Two things depend on the CWD:
# - `require "cligen"` resolves via ./lib/cligen (the self-symlink)
# - command_node.cr renders ECR from the hardcoded relative path
# "lib/cligen/src/cligen/template/cmd_help.ecr"
# Building inside utils/ breaks both.
cd "$(dirname "$0")/.."
SRC=utils/flag_matrix.cr
BIN=utils/flag_matrix
pass=0
fail=0
echo "building..."
if ! crystal build "$SRC" -o "$BIN" 2>&1 | grep -v sframe; then :; fi
[ -x "$BIN" ] || { echo "build failed"; exit 1; }
echo
# check <label> <expected-substring> <env-assignments> <args...>
#
# Matches against the FULL output, not just the last line - multi-line output
# such as help text would otherwise only ever be compared against its footer.
# Only the last line is echoed back, to keep the report readable.
check() {
local label="$1" want="$2" envs="$3"; shift 3
local got shown
got=$(env $envs "$BIN" "$@" 2>&1)
shown=$(printf '%s' "$got" | tail -1)
if [[ "$got" == *"$want"* ]]; then
printf ' ok %-44s %s\n' "$label" "$shown"
pass=$((pass + 1))
else
printf ' FAIL %-44s %s\n' "$label" "$shown"
printf ' %-44s want substring: %s\n' "" "$want"
fail=$((fail + 1))
fi
}
echo "== defaults =="
check "no env, no flags" "retries=3 level=1 name=world" "" greet
echo
echo "== global flag: --retries (env RETRIES, valid 0..10) =="
check "env valid" "retries=7" "RETRIES=7" greet
check "env invalid -> rejected" "validation failed for --retries" "RETRIES=99" greet
check "cli valid" "retries=5" "" greet -r 5
check "cli invalid -> rejected" "validation failed for --retries" "" greet -r 99
check "cli overrides env" "retries=2" "RETRIES=8" greet -r 2
echo
echo "== command arg: --level (env GREET_LEVEL, valid < 5) =="
check "env valid" "level=3" "GREET_LEVEL=3" greet
check "env invalid -> rejected" "validation failed for --level" "GREET_LEVEL=9" greet
check "cli valid" "level=4" "" greet --level 4
check "cli invalid -> rejected" "validation failed for --level" "" greet --level 9
check "cli overrides env" "level=2" "GREET_LEVEL=4" greet --level 2
check "un-namespaced LEVEL ignored" "level=1" "LEVEL=9" greet
echo
echo "== command arg: --name (no validation) =="
check "env" "name=Bob" "GREET_NAME=Bob" greet
check "cli" "name=Alice" "" greet --name Alice
echo
echo "== help output =="
check "root help lists globals" "--retries" "" --help
check "command help lists args" "--level" "" greet --help
echo
echo "$pass passed, $fail failed"
rm -f "$BIN"
[ "$fail" -eq 0 ]