Files
cligen/utils/flag_matrix.cr
2026-09-05 13:19:55 -05:00

57 lines
1.7 KiB
Crystal

# SPDX-License-Identifier: MIT
# 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