1use crate::{EnvSource, Finding, Record};
3use std::collections::BTreeMap;
4
5#[derive(Clone, Copy, PartialEq, Eq, Debug)]
10pub enum Source {
11 Arg,
13 Env,
15 Default,
17}
18
19impl std::fmt::Display for Source {
20 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
21 f.write_str(match self {
22 Source::Arg => "argument",
23 Source::Env => "environment",
24 Source::Default => "default",
25 })
26 }
27}
28
29#[derive(Clone, Debug, PartialEq)]
31pub struct Resolved {
32 pub raw: String,
34 pub source: Source,
36}
37
38pub struct Invocation<'a> {
40 pub args: &'a [String],
42 pub env: &'a dyn EnvSource,
44}
45
46impl<'a> Invocation<'a> {
47 pub fn from_env(env: &'a dyn EnvSource) -> Invocation<'a> {
49 Invocation { args: &[], env }
50 }
51
52 pub fn resolve(&self, model: &[Record]) -> Resolution {
54 let mut values: BTreeMap<String, Resolved> = BTreeMap::new();
55 let mut findings = Vec::new();
56
57 let parsed = parse_args(model, self.args, &mut findings);
58
59 resolve_positionals(model, &parsed.positionals, &mut values);
60
61 for (key, raw) in parsed.values {
62 values.insert(
63 key,
64 Resolved {
65 raw,
66 source: Source::Arg,
67 },
68 );
69 }
70
71 let active_subcommand = parsed.positionals.first();
79
80 for r in model {
81 if values.contains_key(&r.key) {
82 continue;
83 }
84 if !r.subcommands.is_empty()
85 && active_subcommand.map(|s| r.subcommands.contains(s)) != Some(true)
86 {
87 continue; }
89 if let Some(raw) = r.env_names().iter().find_map(|n| self.env.get(n)) {
90 values.insert(
91 r.key.clone(),
92 Resolved {
93 raw,
94 source: Source::Env,
95 },
96 );
97 continue;
98 }
99 if let Some(d) = &r.default {
100 values.insert(
101 r.key.clone(),
102 Resolved {
103 raw: render_default(d),
104 source: Source::Default,
105 },
106 );
107 }
108 }
109
110 Resolution {
111 values,
112 positionals: parsed.positionals,
113 findings,
114 env_names: self.env.names(),
115 }
116 }
117}
118
119#[derive(Clone, Debug, Default)]
121pub struct Resolution {
122 values: BTreeMap<String, Resolved>,
123 positionals: Vec<String>,
124 findings: Vec<Finding>,
125 pub(crate) env_names: Vec<String>,
129}
130
131impl Resolution {
132 pub fn raw(&self, key: &str) -> Option<&str> {
134 self.values.get(key).map(|r| r.raw.as_str())
135 }
136
137 pub fn source(&self, key: &str) -> Option<Source> {
139 self.values.get(key).map(|r| r.source)
140 }
141
142 pub fn values(&self) -> &BTreeMap<String, Resolved> {
144 &self.values
145 }
146
147 pub fn positionals(&self) -> &[String] {
149 &self.positionals
150 }
151
152 pub fn findings(&self) -> &[Finding] {
154 &self.findings
155 }
156}
157
158struct Parsed {
159 values: BTreeMap<String, String>,
160 positionals: Vec<String>,
161}
162
163fn resolve_positionals(
176 model: &[Record],
177 positionals: &[String],
178 values: &mut BTreeMap<String, Resolved>,
179) {
180 let active_subcommand = positionals.first();
181
182 for r in model {
183 let Some(position) = r.arg.as_ref().and_then(|a| a.position) else {
184 continue;
185 };
186 let index = if r.subcommands.is_empty() {
187 position as usize
188 } else {
189 match active_subcommand {
190 Some(s) if r.subcommands.contains(s) => 1 + position as usize,
191 _ => continue, }
193 };
194 if let Some(raw) = positionals.get(index) {
195 values.insert(
196 r.key.clone(),
197 Resolved {
198 raw: raw.clone(),
199 source: Source::Arg,
200 },
201 );
202 }
203 }
204}
205
206fn parse_args(model: &[Record], args: &[String], findings: &mut Vec<Finding>) -> Parsed {
221 let mut values: BTreeMap<String, String> = BTreeMap::new();
222 let mut positionals = Vec::new();
223 let mut i = 0usize;
224
225 while i < args.len() {
226 let a = &args[i];
227
228 if a == "--" {
229 positionals.extend(args[i + 1..].iter().cloned());
230 break;
231 }
232
233 if let Some(body) = a.strip_prefix("--") {
234 let (name, inline) = match body.split_once('=') {
235 Some((n, v)) => (n, Some(v.to_string())),
236 None => (body, None),
237 };
238
239 if let Some(base) = name.strip_prefix("no-") {
241 if let Some(r) = find_long(model, base)
242 .filter(|r| r.arg.as_ref().map(|a| a.negatable).unwrap_or(false))
243 {
244 values.insert(r.key.clone(), "false".to_string());
245 i += 1;
246 continue;
247 }
248 }
249
250 match find_long(model, name) {
251 Some(r) => {
252 let arity = r.arg.as_ref().map(|a| a.arity).unwrap_or(1);
253 if arity == 0 {
254 if inline.is_some() {
255 findings.push(Finding::UnexpectedValue {
256 arg: format!("--{name}"),
257 });
258 }
259 values.insert(r.key.clone(), "true".to_string());
260 i += 1;
261 } else {
262 match inline.or_else(|| args.get(i + 1).cloned()) {
263 Some(v) => {
264 accumulate(&mut values, r, v);
265 i += if a.contains('=') { 1 } else { 2 };
266 }
267 None => {
268 findings.push(Finding::MissingValue {
269 arg: format!("--{name}"),
270 });
271 i += 1;
272 }
273 }
274 }
275 }
276 None => {
277 findings.push(unknown_arg(model, &format!("--{name}")));
278 i += 1;
279 }
280 }
281 continue;
282 }
283
284 if a.len() > 1 && a.starts_with('-') {
285 let body = &a[1..];
286 let first = body.chars().next().expect("non-empty");
287 match find_short(model, first) {
288 Some(r) => {
289 let arity = r.arg.as_ref().map(|a| a.arity).unwrap_or(1);
290 let rest: String = body.chars().skip(1).collect();
291 if arity == 0 {
292 values.insert(r.key.clone(), "true".to_string());
293 if rest.is_empty() {
294 i += 1;
295 } else {
296 let mut rebuilt = vec![format!("-{rest}")];
298 rebuilt.extend(args[i + 1..].iter().cloned());
299 let sub = parse_args(model, &rebuilt, findings);
300 values.extend(sub.values);
301 positionals.extend(sub.positionals);
302 break;
303 }
304 } else {
305 let value = if !rest.is_empty() {
306 Some(rest.trim_start_matches('=').to_string())
307 } else {
308 args.get(i + 1).cloned()
309 };
310 match value {
311 Some(v) => {
312 accumulate(&mut values, r, v);
313 i += if rest.is_empty() { 2 } else { 1 };
314 }
315 None => {
316 findings.push(Finding::MissingValue {
317 arg: format!("-{first}"),
318 });
319 i += 1;
320 }
321 }
322 }
323 }
324 None => {
325 findings.push(unknown_arg(model, &format!("-{first}")));
326 i += 1;
327 }
328 }
329 continue;
330 }
331
332 positionals.push(a.clone());
333 i += 1;
334 }
335
336 Parsed {
337 values,
338 positionals,
339 }
340}
341
342fn accumulate(values: &mut BTreeMap<String, String>, r: &Record, v: String) {
344 let repeatable = r.arg.as_ref().map(|a| a.repeatable).unwrap_or(false);
345 match values.get(&r.key) {
346 Some(prev) if repeatable => {
347 let sep = r
348 .separators
349 .first()
350 .map(String::as_str)
351 .unwrap_or(",")
352 .to_string();
353 let joined = format!("{prev}{sep}{v}");
354 values.insert(r.key.clone(), joined);
355 }
356 _ => {
357 values.insert(r.key.clone(), v);
358 }
359 }
360}
361
362fn find_long<'a>(model: &'a [Record], name: &str) -> Option<&'a Record> {
363 model
364 .iter()
365 .find(|r| r.arg.as_ref().and_then(|a| a.long.as_deref()) == Some(name))
366}
367
368fn find_short(model: &[Record], c: char) -> Option<&Record> {
369 model.iter().find(|r| {
370 r.arg
371 .as_ref()
372 .and_then(|a| a.short.as_deref())
373 .and_then(|s| s.chars().next())
374 == Some(c)
375 })
376}
377
378fn unknown_arg(model: &[Record], label: &str) -> Finding {
379 let known: Vec<String> = model.iter().flat_map(Record::arg_labels).collect();
380 Finding::UnknownArg {
381 arg: label.to_string(),
382 did_you_mean: crate::lint::nearest(label, &known),
383 }
384}
385
386fn render_default(v: &serde_json::Value) -> String {
388 match v {
389 serde_json::Value::String(s) => s.clone(),
390 other => other.to_string(),
391 }
392}