use argenv::*;
use std::path::PathBuf;
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)]
#[serde(into = "f32")]
pub struct RenderScale(u16);
impl RenderScale {
pub const FULL: RenderScale = RenderScale::from_permille(1000);
pub const fn from_permille(p: u16) -> RenderScale {
assert!(
p >= 100 && p <= 1000,
"render scale must be within 0.1..=1.0"
);
RenderScale(p)
}
pub fn as_f32(self) -> f32 {
self.0 as f32 / 1000.0
}
}
impl From<RenderScale> for f32 {
fn from(r: RenderScale) -> f32 {
r.as_f32()
}
}
impl FromRaw for RenderScale {
fn from_raw(s: &str) -> Option<RenderScale> {
let v: f32 = s.trim().parse().ok()?;
if !(0.1..=1.0).contains(&v) {
return None;
}
Some(RenderScale((v * 1000.0).round() as u16))
}
}
fn hud_replacement() -> &'static str {
Model::HUD.key
}
macro_rules! model {
( $( $(#[$m:meta])* $id:ident : $t:ty = $body:expr ; )+ ) => {
pub struct Model;
impl Model { $( $(#[$m])* pub const $id: Input<$t> = $body; )+ }
impl Model {
pub fn records() -> Vec<Record> { vec![ $( Model::$id.to_record() ),+ ] }
pub fn problems() -> Vec<String> {
let mut v = Vec::new();
$( v.extend(Model::$id.check()); )+
v.extend(check_unique(&Model::records()));
v
}
}
};
}
model! {
LOG_LEVEL: LogLevel = Input {
key: "log_level",
ty: Type::Enum,
default: Some(LogLevel::Info),
allowed: LogLevel::TOKENS,
env: Some(Env::new("MYAPP_LOG_LEVEL")),
arg: Some(Arg { value_name: "LEVEL", ..Arg::pair("log-level", 'l') }),
stability: Stability::Stable,
since: Since::This,
group: "logging",
example: "--log-level warn",
reviewed: Some(ReviewDate::parse("2026-07-21")),
summary: "Log verbosity",
..Input::EMPTY
};
HDR: bool = Input {
key: "hdr",
ty: Type::Bool,
default: Some(false),
env: Some(Env::new("MYAPP_HDR")),
arg: Some(Arg { negatable: true, ..Arg::long("hdr") }),
stability: Stability::Stable,
since: Since::This,
group: "display",
maps_to: Some(ConfigKeyRef::new("display.enableHDR")),
example: "--hdr",
observe: Some("hdr_enabled"),
reviewed: Some(ReviewDate::parse("2026-07-21")),
summary: "Expose HDR output to the application",
..Input::EMPTY
};
HUD: String = Input {
key: "hud",
ty: Type::List,
allowed: &["fps", "frametimes", "gpuload", "memory", "version"],
separators: &[',', ';'],
env: Some(Env::new("MYAPP_HUD")),
arg: Some(Arg { repeatable: true, value_name: "ELEMENT", ..Arg::long("hud") }),
stability: Stability::Stable,
since: Since::This,
group: "display",
example: "--hud fps --hud gpuload",
reviewed: Some(ReviewDate::parse("2026-07-21")),
summary: "Overlay elements to display",
..Input::EMPTY
};
LOG_PATH: PathBuf = Input {
key: "log_path",
ty: Type::Path,
env: Some(Env { name: "MYAPP_LOG_PATH", aliases: &["MYAPP_LOGFILE"] }),
group: "logging",
..Input::EMPTY
};
RENDER_SCALE: RenderScale = Input {
key: "render_scale",
ty: Type::Float,
default: Some(RenderScale::FULL),
arg: Some(Arg { value_name: "FACTOR", ..Arg::long("render-scale") }),
stability: Stability::Stable,
since: Since::This,
group: "display",
example: "--render-scale 0.75",
reviewed: Some(ReviewDate::parse("2026-07-21")),
summary: "Internal render scale before upscaling",
..Input::EMPTY
};
ACCEL: Tristate = Input {
key: "accel",
ty: Type::Enum,
default: Some(Tristate::Auto),
allowed: Tristate::TOKENS,
env: Some(Env::new("MYAPP_ACCEL")),
arg: Some(Arg { value_name: "MODE", ..Arg::long("accel") }),
stability: Stability::Stable,
since: Since::This,
group: "display",
example: "--accel auto",
reviewed: Some(ReviewDate::parse("2026-07-21")),
summary: "Hardware acceleration; auto enables it when available",
..Input::EMPTY
};
PROFILE: bool = Input {
key: "profile",
ty: Type::Bool,
default: Some(false),
env: Some(Env::new("MYAPP_PROFILE")),
arg: Some(Arg::long("profile")),
stability: Stability::Deprecated,
since: Since::This,
deprecation: Some(Deprecation {
since: THIS_VERSION,
replaced_by: Some(hud_replacement),
migration: "use --hud gpuload,frametimes instead",
}),
group: "display",
reviewed: Some(ReviewDate::parse("2026-07-21")),
summary: "Deprecated profiling overlay",
..Input::EMPTY
};
}
fn main() {
let model = Model::records();
let args: Vec<String> = std::env::args().skip(1).collect();
let env = ProcessEnv;
let invocation = Invocation {
args: &args,
env: &env,
};
let resolved = invocation.resolve(&model);
let level = Model::LOG_LEVEL.get_from_or_default(&resolved);
let hdr = Model::HDR.get_from_or_default(&resolved);
eprintln!(
"log_level = {level:?} (from {:?}), hdr = {hdr:?} (from {:?})",
resolved.source("log_level"),
resolved.source("hdr")
);
for finding in lint(&model, &invocation) {
eprintln!("{:?}: {finding}", finding.severity());
}
eprintln!("\nUSAGE");
for r in &model {
if !r.usage().is_empty() {
eprintln!(
" {:<28} {}",
r.usage(),
r.summary.clone().unwrap_or_default()
);
}
}
println!(
"{}",
serde_json::to_string_pretty(&document("myapp@a1b2c3d", &model)).unwrap()
);
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeMap;
#[test]
fn the_model_satisfies_every_rule() {
let problems = Model::problems();
assert!(problems.is_empty(), "{problems:#?}");
}
#[test]
fn an_argument_beats_an_environment_variable() {
let env: BTreeMap<String, String> =
[("MYAPP_LOG_LEVEL".to_string(), "error".to_string())].into();
let args = vec!["--log-level".to_string(), "warn".to_string()];
let r = Invocation {
args: &args,
env: &env,
}
.resolve(&Model::records());
assert_eq!(Model::LOG_LEVEL.get_from(&r), Some(LogLevel::Warn));
assert_eq!(r.source("log_level"), Some(Source::Arg));
}
}