Skip to main content

argenv_resolve/
lib.rs

1//! Resolve an [`argenv`] contract against a real invocation — argv and
2//! envp — with precedence, defaults, and linting.
3//!
4//! `argenv` declares what a program accepts, as data, and does not read
5//! argv or envp at all. This crate is the other half: it depends on
6//! `argenv` for [`Input`]/[`Record`] and adds exactly the runtime concern
7//! `argenv` deliberately leaves out. A program's contract never needs to
8//! know how it gets resolved; this crate never needs to know anything
9//! `argenv` doesn't already say.
10//!
11//! Re-exports everything from `argenv`, so `use argenv_resolve::*;` is the
12//! only import most consumers ever need.
13//!
14//! # The common case
15//!
16//! ```
17//! use argenv_resolve::*;
18//!
19//! contract! {
20//!     LOG_LEVEL: LogLevel = Input {
21//!         key:     "log_level",
22//!         ty:      Type::Enum,
23//!         default: Some(LogLevel::Info),
24//!         allowed: LogLevel::TOKENS,
25//!         env:     Some(Env::new("APP_LOG_LEVEL")),
26//!         arg:     Some(Arg { value_name: "LEVEL", ..Arg::pair("log-level", 'l') }),
27//!         summary: "Log verbosity.",
28//!         ..Input::EMPTY
29//!     };
30//! }
31//!
32//! // In main(): let resolved = Contract::parse_and_lint(OnProblems::FailOnError);
33//! let args = vec!["--log-level".to_string(), "warn".to_string()];
34//! let env = std::collections::BTreeMap::new();
35//! let resolved = Invocation { args: &args, env: &env }.resolve(&Contract::records());
36//!
37//! assert_eq!(Contract::LOG_LEVEL.get_from(&resolved), Some(LogLevel::Warn));
38//! assert_eq!(resolved.source("log_level"), Some(Source::Arg));
39//! ```
40//!
41//! # Reading this crate
42//!
43//! * [`contract!`] — declare a contract and get `records()`, `problems()`,
44//!   and `parse_and_lint()` generated for you. Start here.
45//! * [`parse()`] — the one-liner: read process argv+env, resolve, done.
46//! * [`Invocation`], [`Resolution`], [`Source`] — resolving argv and envp
47//!   directly, with provenance for every value. Use this in tests, to
48//!   inject specific args/env rather than mutating global process state.
49//! * [`lint()`] — what an invocation gets wrong.
50//! * [`OnProblems`], [`handle_problems()`] — named policies for what to do
51//!   about it, instead of a hand-rolled loop per project.
52//! * [`InputResolveExt`] — the trait giving [`Input`] its `get`/`get_from`/
53//!   etc. methods. Implemented for every `Input<T, C>`; you will not
54//!   usually name this trait directly, just `use argenv_resolve::*;`.
55#![forbid(unsafe_code)]
56#![warn(missing_docs)]
57
58/// Declare a program's invocation surface as a typed contract.
59///
60/// Generates a `Contract` struct with one `pub const` per input, plus
61/// `records()`, `problems()`, and `parse_and_lint()` — the three things every
62/// consumer needs and would otherwise write by hand for each project.
63///
64/// # Usage
65///
66/// ```
67/// use argenv_resolve::*;
68///
69/// contract! {
70///     /// Verbosity level — both a flag and an env var.
71///     LOG_LEVEL: LogLevel = Input {
72///         key:     "log_level",
73///         ty:      Type::Enum,
74///         default: Some(LogLevel::Info),
75///         allowed: LogLevel::TOKENS,
76///         env:     Some(Env::new("APP_LOG_LEVEL")),
77///         arg:     Some(Arg { value_name: "LEVEL", ..Arg::pair("log-level", 'l') }),
78///         summary: "Log verbosity.",
79///         ..Input::EMPTY
80///     };
81///
82///     /// HDR output switch.
83///     HDR: bool = Input {
84///         key:     "hdr",
85///         ty:      Type::Bool,
86///         default: Some(false),
87///         env:     Some(Env::new("APP_HDR")),
88///         arg:     Some(Arg { negatable: true, ..Arg::long("hdr") }),
89///         summary: "Expose HDR output to the application.",
90///         ..Input::EMPTY
91///     };
92/// }
93///
94/// let p = Contract::problems();
95/// assert!(p.is_empty(), "{p:#?}");
96///
97/// // In main(), one line resolves and enforces the policy:
98/// // let resolved = Contract::parse_and_lint(OnProblems::FailOnError);
99/// // let level = Contract::LOG_LEVEL.get_from_or_default(&resolved);
100/// ```
101///
102/// # What is generated
103///
104/// - `pub struct Contract;`
105/// - `impl Contract { pub const $ID: Input<$T, ..> = ...; ... }` — one typed
106///   constant per input, carrying both its declaration and (via
107///   [`InputResolveExt`]) its accessor.
108/// - `Contract::records() -> Vec<Record>` — every input as a portable contract record.
109/// - `Contract::problems() -> Vec<String>` — every declaration error across
110///   the contract (per-input `check()`, plus `check_unique`). Call this in a
111///   test so a bad declaration fails the build rather than a user's launch.
112/// - `Contract::parse_and_lint(policy: OnProblems) -> Resolution` — reads the
113///   process argv and env, resolves, lints, and applies the given policy.
114///   The one call that replaces manual `parse` + `lint` + error-loop wiring.
115#[macro_export]
116macro_rules! contract {
117    ( $( $(#[$m:meta])* $id:ident : $t:ty $(, $c:ty)? = $body:expr ; )+ ) => {
118        /// This program's invocation surface, declared as typed constants.
119        pub struct Contract;
120
121        impl Contract {
122            // The optional `, $c:ty` is the input's subcommand-enum
123            // parameter (see `Input::subcommands`) - omitted, it defaults to
124            // `NoCommand` exactly as writing `Input<$t>` by hand would.
125            $( $(#[$m])* pub const $id: $crate::Input<$t $(, $c)?> = $body; )+
126
127            /// Every input projected to a portable [`$crate::Record`].
128            ///
129            /// Hand this to [`$crate::lint`], [`$crate::document`], or any
130            /// tool that works from the cross-language contract.
131            pub fn records() -> Vec<$crate::Record> {
132                vec![ $( Contract::$id.to_record() ),+ ]
133            }
134
135            /// Every declaration error across the whole contract.
136            ///
137            /// Empty means valid. Call this once at startup (or in a test)
138            /// so a bad declaration fails loudly rather than silently doing
139            /// the wrong thing at runtime.
140            pub fn problems() -> Vec<String> {
141                let mut v = Vec::new();
142                $( v.extend(Contract::$id.check()); )+
143                v.extend($crate::check_unique(&Contract::records()));
144                v
145            }
146
147            /// Parse the process argv and env, lint the result, and apply
148            /// the given policy — all in one call.
149            ///
150            /// Panics on declaration errors (bugs in this program, not user
151            /// input) before touching argv/env, so they never reach production.
152            /// Applies `policy` to invocation problems (user mistakes).
153            pub fn parse_and_lint(policy: $crate::OnProblems) -> $crate::Resolution {
154                let p = Contract::problems();
155                assert!(p.is_empty(), "declaration errors: {p:#?}");
156                let resolved = $crate::parse(&Contract::records());
157                $crate::handle_problems(&$crate::lint(&Contract::records(), &resolved), policy);
158                resolved
159            }
160        }
161    };
162}
163
164mod ext;
165mod invocation;
166mod lint;
167mod problems;
168mod source;
169
170pub use argenv::*;
171pub use ext::{InputResolveDefaultExt, InputResolveExt};
172pub use invocation::{Invocation, Resolution, Resolved, Source};
173pub use lint::{lint, Finding, Severity};
174pub use problems::{handle_problems, OnProblems};
175pub use source::{EnvSource, ProcessEnv};
176
177/// Parse the current process's argument vector and environment against a
178/// declared model, returning a fully resolved [`Resolution`].
179///
180/// This is the one-liner for the common case — no manual argv slicing,
181/// no `Invocation` construction, no `ProcessEnv` import needed:
182///
183/// ```no_run
184/// # use argenv_resolve::*;
185/// # pub const HOST: Input<String> = Input {
186/// #     key: "host", ty: Type::String,
187/// #     env: Some(Env::new("APP_HOST")),
188/// #     arg: Some(Arg { value_name: "HOST", ..Arg::long("host") }),
189/// #     ..Input::EMPTY
190/// # };
191/// let model = vec![HOST.to_record()];
192/// let resolution = argenv_resolve::parse(&model);
193/// let host = HOST.get_from(&resolution);
194/// ```
195///
196/// For tests, inject specific args and env via [`Invocation`] directly
197/// rather than mutating global process state.
198pub fn parse(model: &[Record]) -> Resolution {
199    let args: Vec<String> = std::env::args().skip(1).collect();
200    Invocation {
201        args: &args,
202        env: &ProcessEnv,
203    }
204    .resolve(model)
205}