Skip to main content

codeint_config/
coupling.rs

1use std::fmt;
2use std::str::FromStr;
3
4use crate::ChurnWindow;
5
6pub const DEFAULT_MAX_COMMIT_FILES: usize = 50;
7pub const DEFAULT_MIN_CO_CHANGES: usize = 3;
8pub const DEFAULT_MIN_COUPLING_RATIO: f64 = 0.3;
9
10#[derive(Debug, Clone, Copy)]
11pub struct CouplingRatio(f64);
12
13impl CouplingRatio {
14    pub fn new(value: f64) -> Result<CouplingRatio, CouplingRatioError> {
15        if value.is_finite() && (0.0..=1.0).contains(&value) {
16            let normalized = if value == 0.0 { 0.0 } else { value };
17            Ok(CouplingRatio(normalized))
18        } else {
19            Err(CouplingRatioError {
20                text: value.to_string(),
21            })
22        }
23    }
24
25    pub fn value(self) -> f64 {
26        self.0
27    }
28}
29
30impl Default for CouplingRatio {
31    fn default() -> CouplingRatio {
32        CouplingRatio(DEFAULT_MIN_COUPLING_RATIO)
33    }
34}
35
36impl PartialEq for CouplingRatio {
37    fn eq(&self, other: &Self) -> bool {
38        self.0.to_bits() == other.0.to_bits()
39    }
40}
41
42impl Eq for CouplingRatio {}
43
44impl fmt::Display for CouplingRatio {
45    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
46        write!(formatter, "{}", self.0)
47    }
48}
49
50#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
51#[error("{text:?} is not a coupling ratio between 0 and 1, such as 0.3")]
52pub struct CouplingRatioError {
53    text: String,
54}
55
56impl FromStr for CouplingRatio {
57    type Err = CouplingRatioError;
58
59    fn from_str(text: &str) -> Result<CouplingRatio, CouplingRatioError> {
60        let value = text.parse::<f64>().map_err(|_| CouplingRatioError {
61            text: text.to_owned(),
62        })?;
63        CouplingRatio::new(value).map_err(|_| CouplingRatioError {
64            text: text.to_owned(),
65        })
66    }
67}
68
69#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub struct CouplingSettings {
71    pub window: ChurnWindow,
72    pub max_commit_files: usize,
73    pub min_co_changes: usize,
74    pub min_ratio: CouplingRatio,
75    pub include_tests: bool,
76}
77
78impl Default for CouplingSettings {
79    fn default() -> CouplingSettings {
80        CouplingSettings {
81            window: ChurnWindow::default(),
82            max_commit_files: DEFAULT_MAX_COMMIT_FILES,
83            min_co_changes: DEFAULT_MIN_CO_CHANGES,
84            min_ratio: CouplingRatio::default(),
85            include_tests: false,
86        }
87    }
88}