Compare commits

..
2 Commits
Author SHA1 Message Date
tristan 4cce5cc45c 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.
2026-08-30 22:13:39 -05:00
tristan f2d5c84f2b Made changes:
- Updated .gitignore to include specs
- Re-licensed to MPL-2.0 as I want any modifications to be pushed back
  to the main codebase so that the ecosystem can benefit from developer
  adoption
- Updated LICENSE & shard.yml with new license
- Changed author to personal email as this is not being done for my
  company
2026-08-30 12:52:16 -05:00
42 changed files with 2144 additions and 561 deletions
+9 -1
View File
@@ -6,8 +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.
+198 -17
View File
@@ -1,21 +1,202 @@
MIT License
Copyright (c) 2026 Tristan Ancelet <[email protected]>
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
1. Definitions.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"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: [email protected]
: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
+2 -2
View File
@@ -2,8 +2,8 @@ name: cligen
version: 0.1.0
authors:
- Tristan Ancelet <tristan.ancelet@acumera.com>
- Tristan Ancelet <tristanancelet@yahoo.com>
crystal: '>= 1.19.1'
license: MIT
license: Apache-2.0
+93
View File
@@ -0,0 +1,93 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
require "../spec_helper"
def make_arg(val, index = 0) : CliGen::Arg
CliGen::Arg.new(value: val, index: index)
end
describe CliGen::Arg do
describe "#processed" do
it "will raise a ArgReprocessedError exception when re-processed" do
arg = make_arg("abc")
arg.processed
expect_raises(CliGen::ArgReprocessedError) do
arg.processed
end
end
end
describe "#flag?" do
it "will return true when value is in long flag format --[a-zA-Z0-9-_]+" do
arg = make_arg("--help")
arg.flag?.should be_true
end
it "will return true when value is in short flag format -[a-zA-Z0-9]" do
arg = make_arg("-h")
arg.flag?.should be_true
end
it "will return false when value is literally anything else" do
arg = make_arg("abc")
arg.flag?.should be_false
end
end
describe "#uint?" do
it "will return true on a value in an unigned int format ^[[:digit:]]+$" do
make_arg("3").uint?.should be_true
end
it "will return false on a value in an signed int format ^[+-][[:digit:]]+$" do
make_arg("-3").uint?.should be_false
make_arg("+3").uint?.should be_false
end
it "will return false on a value in a mixed format" do
make_arg("a2").uint?.should be_false
end
it "will return false on a value in any other format" do
make_arg("a").uint?.should be_false
end
end
describe "#int?" do
it "will return true on a value in int format ^[[:digit:]]+$" do
make_arg("3").int?.should be_true
end
it "will return true on a value in an signed int format ^[+-][[:digit:]]+$" do
make_arg("-3").int?.should be_true
make_arg("+3").int?.should be_true
end
it "will return false on a value in a mixed format" do
make_arg("a2").int?.should be_false
end
it "will return false on a value in any other format" do
make_arg("a").int?.should be_false
end
end
describe "#float?" do
it "will return true on a value in a float format ^[[:digit:]]+\.[[:digit:]]+$" do
make_arg("1.1").float?.should be_true
end
it "will return true on a value in a int format ^[[:digit:]]$" do
make_arg("1").float?.should be_true
end
it "will return false on a value in any other format" do
make_arg("a").float?.should be_false
end
it "will return false on a value that isn't fully int's" do
make_arg("a1").float?.should be_false
end
end
end
+437
View File
@@ -0,0 +1,437 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
require "../spec_helper"
module CliGen
class Flag(T)
def test_coerce(var : String)
coerce(var)
end
def process(args : Array(String))
process(make_args(args))
end
end
end
enum TestEnum
ABC
DEF
GHI
end
class MyGoodData
extend CliGen::Coercable
extend CliGen::Parsable
getter value : TestEnum
def initialize(@value)
end
def self.to_s
nil
end
def to_s
@value.to_s
end
def to_s(io : IO)
io << @value.to_s
end
def self.coerce(arg : String)
case arg
when "abc"
new(TestEnum::ABC)
when "def"
new(TestEnum::DEF)
when "ghi"
new(TestEnum::GHI)
else
raise "WTF?"
end
end
def self.parse_args(args : Array(CliGen::Arg))
raise "ERROR" if args.empty?
arg = args.first
arg.processed
coerce(arg.value)
end
end
class MyBadData < MyGoodData
def self.parse_args(args : Array(CliGen::Arg))
raise "ERROR" if args.empty?
arg = args.first
coerce(arg.value)
end
end
def make_arg(value, index : Int32 = 0) : CliGen::Arg
CliGen::Arg.new(value: value, index: index)
end
def make_args(values : Array(String)) : Array(CliGen::Arg)
output = [] of CliGen::Arg
values.each_with_index{|v, i| output << make_arg(v,i)}
output
end
macro make_flag(type, long = "--test", env_var = "TEST", var = "", description = "", short = nil, delimiter = ",", default = nil, options = nil, validate = nil, on_match = nil, format = nil)
CliGen::Flag({{type}}).new(
var: {{var}},
env_var: {{env_var}},
short: {{short}},
long: {{long}},
description: {{description}},
delimiter: {{delimiter}},
default: {{default}},
options: {{options}},
validate: {{validate}},
on_match: {{on_match}},
format: {{format}}
)
end
describe CliGen::Flag do
before_each { ENV.delete("TEST") }
describe "#check!" do
it "will throw CliGen::ReservedFlagError if -h is used as short" do
expect_raises(CliGen::ReservedFlagError) do
make_flag(type: Bool, short: "-h", long: "--not-help").check!
end
end
it "will throw CliGen::ReservedFlagError if --help is used in long" do
expect_raises(CliGen::ReservedFlagError) do
make_flag(type: Bool, short: "-b", long: "--help TOPIC").check!
end
end
it "will throw CliGen::ReservedFlagError if --help is used as long_key" do
expect_raises(CliGen::ReservedFlagError) do
make_flag(type: Bool, short: "-b", long: "--help").check!
end
end
end
describe "#value!" do
it "will throw CliGen::MissingRequiredFlagError if a flag without a default value is called with no way of determining a value" do
flg = make_flag(type: String)
expect_raises(CliGen::MissingRequiredFlagError) do
flg.value!
end
end
it "will fallback to provided default if no data is provided by the user" do
make_flag(type: String, default: "abc").value!.should eq "abc"
end
it "will resolve values from ENV VAR if not directly supplied with one" do
flg = make_flag(type: String, env_var: "MYTESTVAR")
ENV["MYTESTVAR"] = "abc"
flg.value!.should eq "abc"
end
describe "Flag(Array(String))" do
it "returns a valid array when resolving from ENV VAR" do
flg = make_flag(type: Array(String), env_var: "ABCDEF")
ENV["ABCDEF"]="a,b,c"
flg.value!.should eq %w[ a b c ]
end
end
end
describe "#coerce" do
{% for int in Int.subclasses %}
{% uint = int.stringify =~ /^UInt/ ? true : false %}
describe "Flag({{int}})" do
it "can correctly coerce {{int}}" do
make_flag(type: {{int}}).test_coerce("1").should be_a {{int}}
end
it "will raise CliGen::InvalidFlagValueError if provided a value that is not an {{int}}" do
expect_raises(CliGen::InvalidFlagValueError) do
make_flag(type: {{int}}).test_coerce("abc")
end
end
{% if uint %}
it "will raise CliGen::InvalidFlagValueError if provided a value in a signed int" do
expect_raises(CliGen::InvalidFlagValueError) do
make_flag(type: {{int}}).test_coerce("-1")
end
end
{% end %}
end
{% if uint %}
describe "Flag(Array({{int}}))" do
it "Will be correctly parsed when providing an unsigned int" do
abc = "1,2,3"
make_flag(type: Array({{int}})).test_coerce(abc).should eq([ 1, 2, 3 ] of {{int}})
end
it "will raise CliGen::InvalidFlagValueError if an signed int is provided" do
abc = "-1,2,3"
expect_raises(CliGen::InvalidFlagValueError) do
make_flag(type: Array({{int}})).test_coerce(abc)
end
end
end
{% else %}
describe "Flag(Array({{int}}))" do
it "Will be correctly parsed when providing a signed int" do
abc = "-1,2,3"
make_flag(type: Array({{int}})).test_coerce(abc).should eq([ -1, 2, 3 ] of {{int}})
end
end
{% end %}
{% end %}
{% for float in Float.subclasses %}
describe "Flag({{float}})" do
it "can correctly coerce {{float}}" do
make_flag(type: {{float}}).test_coerce("1.1").should be_a {{float}}
end
it "will raise CliGen::InvalidFlagValueError if provided value isn't a {{float}}" do
expect_raises(CliGen::InvalidFlagValueError) do
make_flag(type: {{float}}).test_coerce("why")
end
end
end
describe "Flag(Array({{float}}))" do
it "will correctly coerce data in a unsigned int format" do
abc = "1,2,3"
make_flag(type: Array({{float}})).test_coerce(abc).should eq([1,2,3] of {{float}})
end
it "will correctly coerce data in a signed int format" do
abc = "-1,2,3"
make_flag(type: Array({{float}})).test_coerce(abc).should eq([-1,2,3] of {{float}})
end
it "will correctly coerce data in a mixed int & float format" do
abc = "-1,2,3.2"
make_flag(type: Array({{float}})).test_coerce(abc).should eq([-1,2,3.2] of {{float}})
end
end
{% end %}
describe "Flag(Bool)" do
it "correctly coerces with valid data" do
%w[ t true 1 y yes ].each do |opt|
make_flag(type: Bool).test_coerce(opt).should be_true
end
%w[ f false 0 n no ].each do |opt|
make_flag(type: Bool).test_coerce(opt).should be_false
end
end
it "raises CliGen::InvalidFlagValueError if provided an invalid value" do
expect_raises(CliGen::InvalidFlagValueError) do
make_flag(type: Bool).test_coerce("why?")
end
end
end
describe "Flag(Array(CustomObj))" do
it "can correctly coerce data from the custom object" do
flg = make_flag(type: Array(MyGoodData))
flg.test_coerce("abc,def").map(&.to_s.downcase).should eq %w[ abc def ]
end
end
describe "Flag(Array(String))" do
it "correctly splits based on delimiter" do
flg = make_flag(type: Array(String), long: "--mytest", delimiter: "|")
flg.test_coerce("a|b|c").should eq %w[ a b c ]
end
it "will raise CliGen::InvalidFlagValueError if an element of the array doesn't match the format defined" do
flg = make_flag(type: Array(String), format: /^test[A-Z]$/)
expect_raises(CliGen::InvalidFlagValueError) do
flg.test_coerce("testA,testB,test1")
end
end
end
end
describe "#validate!" do
it "will raise CliGen::InvalidOptionError if the provided value isn't in the static list of options" do
flg = make_flag(type: String, long: "--test", env_var: "TESTVAR", options: %w[ a b c ])
ENV["TESTVAR"] = "d"
expect_raises(CliGen::InvalidOptionError) do
flg.validate!
end
end
it "will raise CliGen::ValidationError if the dev provided validation fails" do
flg = make_flag(type: String, long: "--test", env_var: "TESTVAR", validate: ->(v : String) : Bool { v == "abc" })
ENV["TESTVAR"] = "def"
expect_raises(CliGen::ValidationError) do
flg.validate!
end
end
describe "Flag(Array(String))" do
flg = make_flag(type: Array(String), long: "--test", env_var: "TESTVAR2", options: [%w[ a b c ]])
it "will raise CliGen::InvalidOptionError if the provided value isn't in the static list of options" do
end
end
end
describe "#process" do
describe "Flag(String)" do
it "will raise CliGen::InvalidFlagValueError if provided string doesn't match format" do
flg = make_flag(type: String, env_var: "TEST", short: "-t", long: "--test", format: /^abc$/)
expect_raises(CliGen::InvalidFlagValueError) do
flg.process(%w[ def ])
end
end
end
{% for int in Int.subclasses %}
{% uint = int.stringify =~ /^UInt/ ? true : false %}
describe "Flag({{int}})" do
it "coerces a valid {{int}} from provided arguments" do
{% if uint %}
val = 1
{% else %}
val = -1
{% end %}
flg = make_flag(type: {{int}})
flg.process(make_args([val.to_s]))
flg.value!.should eq val
end
{% if uint %}
it "will raise CliGen::InvalidFlagValueError if provided a signed int" do
expect_raises(CliGen::InvalidFlagValueError) do
make_flag(type: {{int}}).process([make_arg("-1", 0)])
end
end
{% end %}
end
describe "Flag(Array({{int}}))" do
{% if uint %}
it "will raise when a signed int is provided" do
args = make_args(%w[ 1 2 -3 ])
flg = make_flag(type: Array({{int}}))
expect_raises(CliGen::InvalidFlagValueError) do
flg.process(args)
end
end
it "will raise when a signed int is provided in a delimited string" do
args = [make_arg("1,2,-3")]
flg = make_flag(type: Array({{int}}))
expect_raises(CliGen::InvalidFlagValueError) do
flg.process(args)
end
end
{% end %}
it "can consume positive ints" do
args = make_args(%w[ 1 2 3 ])
flg = make_flag(type: Array({{int}}))
flg.process(args)
flg.value!.should eq([1, 2, 3] of {{int}})
end
it "can consume positive ints in a delimited string" do
args = [make_arg("1,2,3", 0)]
flg = make_flag(type: Array({{int}}))
flg.process(args)
flg.value!.should eq([1, 2, 3] of {{int}})
end
it "can consume positive ints in a delimited string and will strip whitespace" do
args = [make_arg("1 ,2,3", 0)]
flg = make_flag(type: Array({{int}}))
flg.process(args)
flg.value!.should eq([1, 2, 3] of {{int}})
end
it "can consume positive ints in multiple arguments" do
args = make_args(%w[ 1,2,3 4 ])
flg = make_flag(type: Array({{int}}))
flg.process(args)
flg.value!.should eq([1, 2, 3, 4] of {{int}})
end
{% unless uint %}
it "can consume signed ints" do
args = make_args(%w[ 1 2 -3 ])
flg = make_flag(type: Array({{int}}))
flg.process(args)
flg.value!.should eq([1, 2, -3] of {{int}})
end
it "can consume signed ints in a delimited string" do
args = [make_arg("1,2,-3")]
flg = make_flag(type: Array({{int}}))
flg.process(args)
flg.value!.should eq([1, 2, -3] of {{int}})
end
{% end %}
end
{% end %}
{% for float in Float.subclasses %}
describe "Flag({{float}})" do
it "coerces a valid {{float}} from provided arguments" do
val = {{float}}.new("1.1")
flg = make_flag(type: {{float}})
flg.process(make_args([val.to_s]))
flg.value!.should eq val
end
end
describe "Flag(Array({{float}}))" do
it "can handle an array of int/float formatted values" do
args = make_args(%w[ 1 2 3 1.1 -1])
flg = make_flag(type: Array({{float}}))
flg.process(args)
flg.value!.should eq([1, 2, 3, 1.1, -1] of {{float}})
end
end
{% end %}
describe "Flag(Array(String))" do
it "will throw CliGen::InvalidFlagValueError if a deserialized var/item is an invalid format" do
flg = make_flag(type: Array(String), format: /^(a|b|c)$/)
expect_raises(CliGen::InvalidFlagValueError) do
flg.process([ "a,b,c,d" ])
end
end
end
describe "Flag(CustomObj)" do
it "will throw a CliGen::ParseableInvariantError if object doesn't mark data as processed" do
flg = make_flag(type: MyBadData)
expect_raises(CliGen::ParseableInvariantError) do
flg.process(["abc"])
end
end
it "will correctly set the value if parsed" do
flg = make_flag(type: MyGoodData)
flg.process(["abc"])
flg.value!.value.should eq TestEnum::ABC
end
end
end
end
+6
View File
@@ -0,0 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
require "spec"
require "../src/cligen"
+6 -23
View File
@@ -1,3 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
require "./cligen/exceptions"
require "./cligen/coercable"
require "./cligen/parsable"
@@ -5,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"
@@ -12,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
+3
View File
@@ -1,3 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
module CliGen
annotation ProxyCommand
end
+30
View File
@@ -1,3 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
require "./arg"
require "./command_node"
require "./flag"
@@ -16,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
+3
View File
@@ -1,3 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
module CliGen
macro finished
class App
+3
View File
@@ -1,3 +1,6 @@
# 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
# arg-parsing.
+3
View File
@@ -1,3 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
module CliGen::Coercable
abstract def coerce(arg : String)
end
+3
View File
@@ -1,3 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
require "colorize"
require "time"
+15 -6
View File
@@ -1,10 +1,17 @@
# 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 %}
@@ -20,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")%}
@@ -46,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 %}
@@ -55,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}}
+3
View File
@@ -1,3 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
module CliGen
class Command
macro def_init
@@ -1,3 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
module CliGen
class Command
macro define_command_initializer
+3
View File
@@ -1,3 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
module CliGen
class Command
macro help_template(filepath)
+3
View File
@@ -1,3 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
module CliGen
class Command
macro selection(variable, description, options, short = nil, long = nil, validation = nil, on_match = nil)
+3
View File
@@ -1,3 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
module CliGen
class Command
macro subcommand(func, description, examples = nil, &block)
+23 -149
View File
@@ -1,158 +1,30 @@
# 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 %}
@@ -197,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
+16 -4
View File
@@ -1,9 +1,12 @@
# 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
@@ -18,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
@@ -29,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
@@ -42,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
@@ -69,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
+23 -171
View File
@@ -1,63 +1,12 @@
# 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?
@@ -116,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 %}
@@ -213,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}/")
@@ -256,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
@@ -278,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)
@@ -326,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 %}
@@ -386,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
+5
View File
@@ -1,6 +1,11 @@
# 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
+5 -34
View File
@@ -1,46 +1,17 @@
# 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
+3
View File
@@ -1,3 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
module CliGen
enum MatchType
FlagWithArg
+3
View File
@@ -1,3 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
module CliGen::Parsable
abstract def parse_args(args : Array(CliGen::Arg))
end
+37 -10
View File
@@ -1,18 +1,45 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Tristan Ancelet
module CliGen::Regex
FLAG_REGEX=/^(-[a-zA-Z]|--[a-zA-Z-_0-9]+)$/
FLAG_WITH_ARG=/^(?<flag>(-[a-zA-Z]|--[a-zA-Z-_]+))="?(?<arg>\S+?)"?$/
FLAG_MULTIPLE_SHORT=/^-[a-zA-Z0-9]+$/
INPUT_TIMEZONE = /(?<timezone>[-+][0-9]{4})/
INPUT_TIME = /(?<time>(?<hour>[0-9]{2}):(?<minute>[0-9]{2}):(?<second>[0-9]{2}))/
INPUT_DATE_SIMPLE = /(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2})/
INPUT_DATE_SIMPLE_WITH_TIMEZONE = /^#{INPUT_DATE_SIMPLE}\s+#{INPUT_TIMEZONE}$/
INPUT_DATE_FULL = /^(?<date>#{INPUT_DATE_SIMPLE})\s+#{INPUT_TIME}\s+#{INPUT_TIMEZONE}$/
INPUT_DATE_PARTIAL = /^(?<date>#{INPUT_DATE_SIMPLE})\s+#{INPUT_TIME}$/
INPUT_DATE_RELATIVE = /(?<sign>[+-])?(?<quantity>[0-9]+)\s+(?<unit>seconds?|days?|hours?|minutes?|years?)/
INPUT_DATE_RELATIVE_WITH_TIMEZONE = /#{INPUT_DATE_RELATIVE}\s+#{INPUT_TIMEZONE}/
INPUT_DATE_EPOCH = /@(?<epoch>[0-9]+)/
INPUT_DATE_EPOCH_WITH_TIMEZONE = /#{INPUT_DATE_EPOCH}\s+#{INPUT_TIMEZONE}/
# ---------------------------------------------------------------------------
# Date/time components.
#
# These are building blocks ONLY — they are interpolated into the anchored
# matchers below and must stay unanchored. Interpolating a Regex renders it
# as `(?-imsx:...)`, so an anchor here would end up buried mid-pattern in the
# composites (`^(?-imsx:^...$)\s+...$`) and could never match.
#
# Never match user input against these directly — use the INPUT_DATE_*
# matchers, which are anchored.
# ---------------------------------------------------------------------------
# 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 = /[+-][0-9]+\s+(seconds?|minutes?|hours?|days?|weeks?|months?|years?)/
# ---------------------------------------------------------------------------
# Relative Operation matcher - For use with CliGen::Timeparse::RelativeOperation
# ---------------------------------------------------------------------------
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 ]