1use serde::Serialize;
2use std::collections::HashMap;
3use std::collections::HashSet;
4
5use crate::ArgType;
6use crate::ExecCall;
7use crate::arg_matcher::ArgMatcher;
8use crate::arg_resolver::PositionalArg;
9use crate::arg_resolver::resolve_observed_args_with_patterns;
10use crate::error::Error;
11use crate::error::Result;
12use crate::opt::Opt;
13use crate::opt::OptMeta;
14use crate::valid_exec::MatchedFlag;
15use crate::valid_exec::MatchedOpt;
16use crate::valid_exec::ValidExec;
17
18#[derive(Debug)]
19pub struct ProgramSpec {
20 pub program: String,
21 pub system_path: Vec<String>,
22 pub option_bundling: bool,
23 pub combined_format: bool,
24 pub allowed_options: HashMap<String, Opt>,
25 pub arg_patterns: Vec<ArgMatcher>,
26 forbidden: Option<String>,
27 required_options: HashSet<String>,
28 should_match: Vec<Vec<String>>,
29 should_not_match: Vec<Vec<String>>,
30}
31
32impl ProgramSpec {
33 pub fn new(
34 program: String,
35 system_path: Vec<String>,
36 option_bundling: bool,
37 combined_format: bool,
38 allowed_options: HashMap<String, Opt>,
39 arg_patterns: Vec<ArgMatcher>,
40 forbidden: Option<String>,
41 should_match: Vec<Vec<String>>,
42 should_not_match: Vec<Vec<String>>,
43 ) -> Self {
44 let required_options = allowed_options
45 .iter()
46 .filter_map(|(name, opt)| {
47 if opt.required {
48 Some(name.clone())
49 } else {
50 None
51 }
52 })
53 .collect();
54 Self {
55 program,
56 system_path,
57 option_bundling,
58 combined_format,
59 allowed_options,
60 arg_patterns,
61 forbidden,
62 required_options,
63 should_match,
64 should_not_match,
65 }
66 }
67}
68
69#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
70pub enum MatchedExec {
71 Match { exec: ValidExec },
72 Forbidden { cause: Forbidden, reason: String },
73}
74
75#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
76pub enum Forbidden {
77 Program {
78 program: String,
79 exec_call: ExecCall,
80 },
81 Arg {
82 arg: String,
83 exec_call: ExecCall,
84 },
85 Exec {
86 exec: ValidExec,
87 },
88}
89
90impl ProgramSpec {
91 pub fn check(&self, exec_call: &ExecCall) -> Result<MatchedExec> {
95 let mut expecting_option_value: Option<(String, ArgType)> = None;
96 let mut args = Vec::<PositionalArg>::new();
97 let mut matched_flags = Vec::<MatchedFlag>::new();
98 let mut matched_opts = Vec::<MatchedOpt>::new();
99
100 for (index, arg) in exec_call.args.iter().enumerate() {
101 if let Some(expected) = expecting_option_value {
102 let (name, arg_type) = expected;
106 if arg.starts_with("-") {
107 return Err(Error::OptionFollowedByOptionInsteadOfValue {
108 program: self.program.clone(),
109 option: name,
110 value: arg.clone(),
111 });
112 }
113
114 matched_opts.push(MatchedOpt::new(&name, arg, arg_type)?);
115 expecting_option_value = None;
116 } else if arg == "--" {
117 return Err(Error::DoubleDashNotSupportedYet {
118 program: self.program.clone(),
119 });
120 } else if arg.starts_with("-") {
121 match self.allowed_options.get(arg) {
122 Some(opt) => {
123 match &opt.meta {
124 OptMeta::Flag => {
125 matched_flags.push(MatchedFlag { name: arg.clone() });
126 continue;
128 }
129 OptMeta::Value(arg_type) => {
130 expecting_option_value = Some((arg.clone(), arg_type.clone()));
131 continue;
132 }
133 }
134 }
135 None => {
136 }
138 }
139
140 return Err(Error::UnknownOption {
141 program: self.program.clone(),
142 option: arg.clone(),
143 });
144 } else {
145 args.push(PositionalArg {
146 index,
147 value: arg.clone(),
148 });
149 }
150 }
151
152 if let Some(expected) = expecting_option_value {
153 let (name, _arg_type) = expected;
154 return Err(Error::OptionMissingValue {
155 program: self.program.clone(),
156 option: name,
157 });
158 }
159
160 let matched_args =
161 resolve_observed_args_with_patterns(&self.program, args, &self.arg_patterns)?;
162
163 let matched_opt_names: HashSet<String> = matched_opts
165 .iter()
166 .map(|opt| opt.name().to_string())
167 .collect();
168 if !matched_opt_names.is_superset(&self.required_options) {
169 let mut options = self
170 .required_options
171 .difference(&matched_opt_names)
172 .map(|s| s.to_string())
173 .collect::<Vec<_>>();
174 options.sort();
175 return Err(Error::MissingRequiredOptions {
176 program: self.program.clone(),
177 options,
178 });
179 }
180
181 let exec = ValidExec {
182 program: self.program.clone(),
183 flags: matched_flags,
184 opts: matched_opts,
185 args: matched_args,
186 system_path: self.system_path.clone(),
187 };
188 match &self.forbidden {
189 Some(reason) => Ok(MatchedExec::Forbidden {
190 cause: Forbidden::Exec { exec },
191 reason: reason.clone(),
192 }),
193 None => Ok(MatchedExec::Match { exec }),
194 }
195 }
196
197 pub fn verify_should_match_list(&self) -> Vec<PositiveExampleFailedCheck> {
198 let mut violations = Vec::new();
199 for good in &self.should_match {
200 let exec_call = ExecCall {
201 program: self.program.clone(),
202 args: good.clone(),
203 };
204 match self.check(&exec_call) {
205 Ok(_) => {}
206 Err(error) => {
207 violations.push(PositiveExampleFailedCheck {
208 program: self.program.clone(),
209 args: good.clone(),
210 error,
211 });
212 }
213 }
214 }
215 violations
216 }
217
218 pub fn verify_should_not_match_list(&self) -> Vec<NegativeExamplePassedCheck> {
219 let mut violations = Vec::new();
220 for bad in &self.should_not_match {
221 let exec_call = ExecCall {
222 program: self.program.clone(),
223 args: bad.clone(),
224 };
225 if self.check(&exec_call).is_ok() {
226 violations.push(NegativeExamplePassedCheck {
227 program: self.program.clone(),
228 args: bad.clone(),
229 });
230 }
231 }
232 violations
233 }
234}
235
236#[derive(Debug, Eq, PartialEq)]
237pub struct PositiveExampleFailedCheck {
238 pub program: String,
239 pub args: Vec<String>,
240 pub error: Error,
241}
242
243#[derive(Debug, Eq, PartialEq)]
244pub struct NegativeExamplePassedCheck {
245 pub program: String,
246 pub args: Vec<String>,
247}