1use std::path::PathBuf;
2
3use codeint_model::{Metric, MetricScope, SourceSet};
4use serde_json::Value;
5
6use super::schema::{DuplicationConfigFile, PluginEntry};
7use super::types::{
8 Budgets, Configuration, DuplicationConfig, MinSimilarity, PluginDeclaration, PluginSource,
9 Sha256Digest,
10};
11use crate::RegressionLimits;
12use crate::config_error::{
13 ConfigFileKind, ConfigurationFileError, KeyPath, KeySegment, contains_parent_traversal,
14 is_absolute_repo_path,
15};
16use crate::resolved::BudgetOverride;
17
18impl Configuration {
19 pub fn validate_cli_budget_metrics(
20 &self,
21 overrides: &[BudgetOverride],
22 external_metric_keys: &[&str],
23 ) -> Result<(), ConfigurationFileError> {
24 for entry in overrides {
25 if let Some(metric) = Metric::from_key(&entry.metric) {
26 if is_production_only_outside_production(metric, entry.source_set) {
27 return Err(cli_production_only_budget_error(entry.source_set, metric));
28 }
29 if metric == Metric::FileSize && self.file_size.max_source_lines.is_none() {
30 return Err(ConfigurationFileError::CliFileSizeBudgetWithoutLimit);
31 }
32 if metric.scope().applies_to_source_set(entry.source_set) {
33 continue;
34 }
35 } else if external_metric_keys.contains(&entry.metric.as_str()) {
36 continue;
37 }
38 return Err(ConfigurationFileError::UnknownCliBudgetMetric {
39 source_set: entry.source_set,
40 metric: entry.metric.clone(),
41 allowed: allowed_budget_metric_keys(entry.source_set, external_metric_keys),
42 });
43 }
44 Ok(())
45 }
46
47 pub fn validate_metrics(
48 &self,
49 external_metric_keys: &[&str],
50 ) -> Result<(), ConfigurationFileError> {
51 validate_source_set_budgets(
52 self.config_file,
53 "budgets",
54 &self.budgets,
55 external_metric_keys,
56 )?;
57 validate_source_set_budgets(
58 self.config_file,
59 "new_file_budgets",
60 &self.new_file_budgets,
61 external_metric_keys,
62 )?;
63 validate_regression_limit_keys(
64 self.config_file,
65 &self.regression_limits,
66 external_metric_keys,
67 )?;
68 self.validate_file_size_gates_have_a_limit()
69 }
70
71 fn validate_file_size_gates_have_a_limit(&self) -> Result<(), ConfigurationFileError> {
72 if self.file_size.max_source_lines.is_some() {
73 return Ok(());
74 }
75 let file_size = Metric::FileSize.key();
76 let budget_key = [
77 ("budgets", &self.budgets),
78 ("new_file_budgets", &self.new_file_budgets),
79 ]
80 .into_iter()
81 .find(|(_, budgets)| {
82 budgets
83 .budget_for_key(SourceSet::Production, file_size)
84 .is_some()
85 })
86 .map(|(section, _)| budget_key_path(section, SourceSet::Production, file_size));
87 let regression_key = || {
88 self.regression_limits
89 .metric_keys()
90 .find(|(_, metric_key)| *metric_key == file_size)
91 .map(|(source_set, _)| regression_limit_key_path(source_set, file_size))
92 };
93 match budget_key.or_else(regression_key) {
94 Some(key) => Err(ConfigurationFileError::FileSizeGateWithoutLimit {
95 file: self.config_file,
96 key,
97 }),
98 None => Ok(()),
99 }
100 }
101}
102
103fn validate_source_set_budgets(
104 config_file: ConfigFileKind,
105 section: &str,
106 budgets: &Budgets,
107 external_metric_keys: &[&str],
108) -> Result<(), ConfigurationFileError> {
109 for (source_set, metric_key, _) in &budgets.set {
110 if let Some(metric) = Metric::from_key(metric_key) {
111 if is_production_only_outside_production(metric, *source_set) {
112 return Err(production_only_budget_error(
113 config_file,
114 section,
115 *source_set,
116 metric,
117 ));
118 }
119 if metric.scope().applies_to_source_set(*source_set) {
120 continue;
121 }
122 } else if external_metric_keys.contains(&metric_key.as_str()) {
123 continue;
124 }
125 return Err(ConfigurationFileError::UnknownKey {
126 file: config_file,
127 key: budget_key_path(section, *source_set, metric_key),
128 allowed: allowed_budget_metric_keys(*source_set, external_metric_keys),
129 });
130 }
131 Ok(())
132}
133
134fn is_production_only_outside_production(metric: Metric, source_set: SourceSet) -> bool {
135 metric.scope() == MetricScope::ProductionOnly
136 && !metric.scope().applies_to_source_set(source_set)
137}
138
139fn budget_key_path(section: &str, source_set: SourceSet, metric_key: &str) -> KeyPath {
140 KeyPath::default()
141 .child(KeySegment::Key(section.to_owned()))
142 .child(KeySegment::Key(source_set.key().to_owned()))
143 .child(KeySegment::Key(metric_key.to_owned()))
144}
145
146fn regression_limit_key_path(source_set: Option<SourceSet>, metric_key: &str) -> KeyPath {
147 let mut path = KeyPath::default().child(KeySegment::Key("regression_limits".to_owned()));
148 if let Some(source_set) = source_set {
149 path = path.child(KeySegment::Key(source_set.key().to_owned()));
150 }
151 path.child(KeySegment::Key(metric_key.to_owned()))
152}
153
154fn production_only_budget_error(
155 file: ConfigFileKind,
156 section: &str,
157 source_set: SourceSet,
158 metric: Metric,
159) -> ConfigurationFileError {
160 let key = budget_key_path(section, source_set, metric.key());
161 match metric {
162 Metric::TestGap => ConfigurationFileError::TestGapBudgetOutsideProduction { file, key },
163 other => ConfigurationFileError::MetricBudgetOutsideProduction {
164 file,
165 key,
166 metric: other,
167 },
168 }
169}
170
171fn cli_production_only_budget_error(
172 source_set: SourceSet,
173 metric: Metric,
174) -> ConfigurationFileError {
175 match metric {
176 Metric::TestGap => ConfigurationFileError::CliTestGapBudgetOutsideProduction { source_set },
177 other => ConfigurationFileError::CliMetricBudgetOutsideProduction {
178 source_set,
179 metric: other,
180 },
181 }
182}
183
184fn validate_regression_limit_keys(
185 config_file: ConfigFileKind,
186 limits: &RegressionLimits,
187 external_metric_keys: &[&str],
188) -> Result<(), ConfigurationFileError> {
189 for (source_set, metric_key) in limits.metric_keys() {
190 validate_regression_limit_key(config_file, source_set, metric_key, external_metric_keys)?;
191 }
192 Ok(())
193}
194
195fn validate_regression_limit_key(
196 config_file: ConfigFileKind,
197 source_set: Option<SourceSet>,
198 metric_key: &str,
199 external_metric_keys: &[&str],
200) -> Result<(), ConfigurationFileError> {
201 if let Some(metric) = Metric::from_key(metric_key) {
202 if !metric.supports_diff_regression() {
203 return Err(ConfigurationFileError::TestGapRegressionLimit {
204 file: config_file,
205 key: regression_limit_key_path(source_set, metric_key),
206 });
207 }
208 let Some(set) = source_set else {
209 return Ok(());
210 };
211 if is_production_only_outside_production(metric, set) {
212 return Err(
213 ConfigurationFileError::MetricRegressionLimitOutsideProduction {
214 file: config_file,
215 key: regression_limit_key_path(Some(set), metric_key),
216 metric,
217 },
218 );
219 }
220 if metric.scope().applies_to_source_set(set) {
221 return Ok(());
222 }
223 } else if external_metric_keys.contains(&metric_key) {
224 return Ok(());
225 }
226 Err(ConfigurationFileError::UnknownKey {
227 file: config_file,
228 key: regression_limit_key_path(source_set, metric_key),
229 allowed: allowed_regression_limit_metric_keys(source_set, external_metric_keys),
230 })
231}
232
233pub(super) fn is_repository_wide_diff_metric(metric: Metric) -> bool {
234 metric.scope() == MetricScope::RepositoryWide && metric.supports_diff_regression()
235}
236
237fn ordered_built_in_metrics(predicate: impl Fn(Metric) -> bool) -> Vec<Metric> {
238 let mut built_in: Vec<Metric> = Metric::ALL
239 .into_iter()
240 .filter(|metric| predicate(*metric))
241 .collect();
242 move_metric_after(
243 &mut built_in,
244 Metric::CognitiveComplexity,
245 Metric::ImportCycles,
246 );
247 move_metric_after(&mut built_in, Metric::TestGap, Metric::Hazards);
248 built_in
249}
250
251fn move_metric_after(metrics: &mut Vec<Metric>, target: Metric, anchor: Metric) {
252 if let (Some(target_pos), Some(anchor_pos)) = (
253 metrics.iter().position(|metric| *metric == target),
254 metrics.iter().position(|metric| *metric == anchor),
255 ) && target_pos < anchor_pos
256 {
257 let metric = metrics.remove(target_pos);
258 metrics.insert(anchor_pos, metric);
259 }
260}
261
262fn allowed_budget_metric_keys(source_set: SourceSet, external_metric_keys: &[&str]) -> Vec<String> {
263 ordered_built_in_metrics(|metric| metric.scope().applies_to_source_set(source_set))
264 .into_iter()
265 .map(|metric| metric.key().to_owned())
266 .chain(external_metric_keys.iter().map(|key| (*key).to_owned()))
267 .collect()
268}
269
270pub(super) fn allowed_regression_limit_metric_keys(
271 source_set: Option<SourceSet>,
272 external_metric_keys: &[&str],
273) -> Vec<String> {
274 let built_in = match source_set {
275 Some(source_set) => ordered_built_in_metrics(|metric| {
276 metric.scope().applies_to_source_set(source_set) && metric.supports_diff_regression()
277 }),
278 None => ordered_built_in_metrics(|metric| {
279 metric.scope() != MetricScope::RepositoryWide && metric.supports_diff_regression()
280 }),
281 };
282 let mut allowed: Vec<String> = built_in
283 .into_iter()
284 .map(|metric| metric.key().to_owned())
285 .chain(external_metric_keys.iter().map(|key| (*key).to_owned()))
286 .collect();
287 if source_set.is_none() {
288 allowed.extend(
289 Metric::ALL
290 .into_iter()
291 .filter(|metric| is_repository_wide_diff_metric(*metric))
292 .map(|metric| metric.key().to_owned()),
293 );
294 allowed.extend(SourceSet::ALL.map(|set| set.key().to_owned()));
295 }
296 allowed
297}
298
299pub(super) fn reject_unsupported_metric_keys(root: &Value) -> Result<(), ConfigurationFileError> {
300 let Some(root) = root.as_object() else {
301 return Ok(());
302 };
303 if let Some(budgets) = root.get("budgets").and_then(Value::as_object) {
304 reject_unsupported_budget_keys("budgets", budgets)?;
305 }
306 if let Some(new_file_budgets) = root.get("new_file_budgets").and_then(Value::as_object) {
307 reject_unsupported_budget_keys("new_file_budgets", new_file_budgets)?;
308 }
309 if let Some(limits) = root.get("regression_limits").and_then(Value::as_object) {
310 reject_unsupported_regression_limit_keys(limits)?;
311 }
312 Ok(())
313}
314
315fn reject_unsupported_budget_keys(
316 section_name: &str,
317 budgets: &serde_json::Map<String, Value>,
318) -> Result<(), ConfigurationFileError> {
319 for source_set in SourceSet::ALL {
320 let Some(section) = budgets.get(source_set.key()).and_then(Value::as_object) else {
321 continue;
322 };
323 for metric in Metric::ALL {
324 if !section.contains_key(metric.key()) {
325 continue;
326 }
327 if is_production_only_outside_production(metric, source_set) {
328 return Err(production_only_budget_error(
329 ConfigFileKind::Json,
330 section_name,
331 source_set,
332 metric,
333 ));
334 }
335 if metric.scope() == MetricScope::RepositoryWide {
336 return Err(ConfigurationFileError::UnknownKey {
337 file: ConfigFileKind::Json,
338 key: budget_key_path(section_name, source_set, metric.key()),
339 allowed: allowed_budget_metric_keys(source_set, &[]),
340 });
341 }
342 }
343 }
344 Ok(())
345}
346
347fn reject_unsupported_regression_limit_keys(
348 limits: &serde_json::Map<String, Value>,
349) -> Result<(), ConfigurationFileError> {
350 for metric in Metric::ALL {
351 if !metric.supports_diff_regression() && limits.contains_key(metric.key()) {
352 return Err(ConfigurationFileError::TestGapRegressionLimit {
353 file: ConfigFileKind::Json,
354 key: regression_limit_key_path(None, metric.key()),
355 });
356 }
357 }
358 for source_set in SourceSet::ALL {
359 let Some(section) = limits.get(source_set.key()).and_then(Value::as_object) else {
360 continue;
361 };
362 reject_unsupported_source_set_regression_limit_keys(source_set, section)?;
363 }
364 Ok(())
365}
366
367fn reject_unsupported_source_set_regression_limit_keys(
368 source_set: SourceSet,
369 section: &serde_json::Map<String, Value>,
370) -> Result<(), ConfigurationFileError> {
371 for metric in Metric::ALL {
372 if !section.contains_key(metric.key()) {
373 continue;
374 }
375 if !metric.supports_diff_regression() {
376 return Err(ConfigurationFileError::TestGapRegressionLimit {
377 file: ConfigFileKind::Json,
378 key: regression_limit_key_path(Some(source_set), metric.key()),
379 });
380 }
381 if is_production_only_outside_production(metric, source_set) {
382 return Err(
383 ConfigurationFileError::MetricRegressionLimitOutsideProduction {
384 file: ConfigFileKind::Json,
385 key: regression_limit_key_path(Some(source_set), metric.key()),
386 metric,
387 },
388 );
389 }
390 }
391 Ok(())
392}
393
394pub(super) fn coverage_reports(reports: &[String]) -> Result<Vec<String>, ConfigurationFileError> {
395 let reports_key = KeyPath::default().child(KeySegment::Key("coverage_reports".to_owned()));
396 let mut validated = Vec::with_capacity(reports.len());
397 for (index, entry) in reports.iter().enumerate() {
398 let entry_key = reports_key.child(KeySegment::Index(index));
399 if entry.trim().is_empty() {
400 return Err(ConfigurationFileError::EmptyCoverageReportPath {
401 file: ConfigFileKind::Json,
402 key: entry_key,
403 });
404 }
405 if is_absolute_repo_path(entry) {
406 return Err(ConfigurationFileError::AbsoluteCoverageReportPath {
407 file: ConfigFileKind::Json,
408 key: entry_key,
409 path: entry.clone(),
410 });
411 }
412 if contains_parent_traversal(entry) {
413 return Err(ConfigurationFileError::ParentTraversalCoverageReportPath {
414 file: ConfigFileKind::Json,
415 key: entry_key,
416 path: entry.clone(),
417 });
418 }
419 validated.push(entry.clone());
420 }
421 Ok(validated)
422}
423
424pub(super) fn duplication_config(
425 file: DuplicationConfigFile,
426) -> Result<DuplicationConfig, ConfigurationFileError> {
427 let (near_clones, min_similarity) = file.into_parts();
428 let min_similarity = match min_similarity {
429 Some(value) => MinSimilarity::new(value).ok_or_else(|| {
430 ConfigurationFileError::OutOfExclusiveMinRange {
431 file: ConfigFileKind::Json,
432 key: KeyPath::default()
433 .child(KeySegment::Key("duplication".to_owned()))
434 .child(KeySegment::Key("min_similarity".to_owned())),
435 exclusive_minimum: 0.0,
436 maximum: 1.0,
437 found: value,
438 }
439 })?,
440 None => MinSimilarity::DEFAULT,
441 };
442 Ok(DuplicationConfig {
443 near_clones: near_clones.unwrap_or(false),
444 min_similarity,
445 })
446}
447
448pub(super) fn plugins(
449 entries: Vec<PluginEntry>,
450) -> Result<Vec<PluginDeclaration>, ConfigurationFileError> {
451 let plugins_key = KeyPath::default().child(KeySegment::Key("plugins".to_owned()));
452 entries
453 .into_iter()
454 .enumerate()
455 .map(|(index, entry)| {
456 let entry_key = plugins_key.child(KeySegment::Index(index));
457 let (name, kind, path, url, sha256) = entry.into_parts();
458 if name.trim().is_empty() {
459 return Err(ConfigurationFileError::EmptyPluginField {
460 file: ConfigFileKind::Json,
461 key: entry_key.child(KeySegment::Key("name".to_owned())),
462 });
463 }
464 let source = match (path, url) {
465 (Some(path), None) => {
466 if path.trim().is_empty() {
467 return Err(ConfigurationFileError::EmptyPluginField {
468 file: ConfigFileKind::Json,
469 key: entry_key.child(KeySegment::Key("path".to_owned())),
470 });
471 }
472 PluginSource::Path(PathBuf::from(path))
473 }
474 (None, Some(url)) => {
475 let url_key = entry_key.child(KeySegment::Key("url".to_owned()));
476 if url.trim().is_empty() {
477 return Err(ConfigurationFileError::EmptyPluginField {
478 file: ConfigFileKind::Json,
479 key: url_key,
480 });
481 }
482 let normalized = normalize_https_url(&url).ok_or_else(|| {
483 ConfigurationFileError::NonHttpsPluginUrl {
484 file: ConfigFileKind::Json,
485 key: url_key,
486 name: name.clone(),
487 url,
488 }
489 })?;
490 PluginSource::HttpsUrl(normalized)
491 }
492 (None, None) => {
493 return Err(ConfigurationFileError::MissingPluginSource {
494 file: ConfigFileKind::Json,
495 key: entry_key,
496 name,
497 });
498 }
499 (Some(_), Some(_)) => {
500 return Err(ConfigurationFileError::AmbiguousPluginSource {
501 file: ConfigFileKind::Json,
502 key: entry_key,
503 name,
504 });
505 }
506 };
507 let sha256 = Sha256Digest::parse_hex(&sha256).ok_or_else(|| {
508 ConfigurationFileError::InvalidSha256 {
509 file: ConfigFileKind::Json,
510 key: entry_key.child(KeySegment::Key("sha256".to_owned())),
511 found: sha256,
512 }
513 })?;
514 Ok(PluginDeclaration {
515 name,
516 kind,
517 source,
518 sha256,
519 })
520 })
521 .collect()
522}
523
524fn normalize_https_url(url: &str) -> Option<String> {
525 let prefix = url.get(..8)?;
526 if !prefix.eq_ignore_ascii_case("https://") {
527 return None;
528 }
529 let rest = &url[8..];
530 if rest.is_empty() || rest.starts_with('/') || url.chars().any(char::is_whitespace) {
531 return None;
532 }
533 Some(format!("https://{rest}"))
534}