Skip to main content

foundry_config/
coverage.rs

1//! Configuration for `forge coverage`.
2
3use clap::ValueEnum;
4use semver::{Version, VersionReq};
5use serde::{Deserialize, Deserializer, Serialize};
6use std::path::PathBuf;
7
8/// Coverage report kinds that can be generated by `forge coverage`.
9///
10/// Used both as a CLI value (`--report <kind>`) and as a TOML configuration
11/// value under `[profile.<name>.coverage] report = ["..."]`.
12#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, ValueEnum)]
13#[serde(rename_all = "lowercase")]
14pub enum CoverageReportKind {
15    #[default]
16    Summary,
17    Lcov,
18    Debug,
19    Bytecode,
20    /// JSON report mapping each test to the source items it covers.
21    Attribution,
22    /// JSON report listing uncovered source items with their location and context.
23    Gaps,
24}
25
26/// Configuration for `forge coverage`, exposed under `[coverage]` and
27/// `[profile.<name>.coverage]` in `foundry.toml`.
28///
29/// Fields here mirror the CLI flags accepted by `forge coverage`. CLI flags
30/// take precedence over configuration values when both are provided.
31#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
32pub struct CoverageConfig {
33    /// The report kinds to generate. Defaults to `["summary"]`.
34    #[serde(default = "default_report_kinds")]
35    pub report: Vec<CoverageReportKind>,
36
37    /// The version of the LCOV "tracefile" format to use.
38    ///
39    /// Defaults to `1` (parsed as `1.0.0`). See `forge coverage --help` for the
40    /// supported variants and their differences.
41    #[serde(default = "default_lcov_version", deserialize_with = "deserialize_lcov_version")]
42    pub lcov_version: Version,
43
44    /// Whether to enable `viaIR` with minimum optimization. Useful as a
45    /// workaround for "stack too deep" errors at the cost of source map
46    /// accuracy.
47    #[serde(default)]
48    pub ir_minimum: bool,
49
50    /// Whether to keep the project's optimizer and `viaIR` settings instead of disabling them.
51    /// Optimized builds can miss or merge coverage items. Cannot be combined with `ir_minimum`,
52    /// including the `--ir-minimum` flag, so enabling it here also rules out that flag.
53    #[serde(default)]
54    pub keep_optimizer: bool,
55
56    /// Path to write the coverage report to (relative to the project root). If
57    /// unset, the report is written to the project root.
58    #[serde(default)]
59    pub report_file: Option<PathBuf>,
60
61    /// Whether to include library dependencies in the coverage report.
62    #[serde(default)]
63    pub include_libs: bool,
64
65    /// Whether to exclude tests from the coverage report.
66    #[serde(default)]
67    pub exclude_tests: bool,
68
69    /// Glob patterns of source files to exclude from the coverage report.
70    ///
71    /// Patterns are matched against project-root-relative paths using the
72    /// `globset` crate's `Glob` semantics (`**`, `*`, `?`, character classes).
73    /// A file is skipped if any pattern matches.
74    ///
75    /// Example:
76    /// ```toml
77    /// [profile.default.coverage]
78    /// skip_files = ["test/**", "script/**", "src/mocks/**"]
79    /// ```
80    #[serde(default)]
81    pub skip_files: Vec<String>,
82}
83
84impl Default for CoverageConfig {
85    fn default() -> Self {
86        Self {
87            report: default_report_kinds(),
88            lcov_version: default_lcov_version(),
89            ir_minimum: false,
90            keep_optimizer: false,
91            report_file: None,
92            include_libs: false,
93            exclude_tests: false,
94            skip_files: Vec::new(),
95        }
96    }
97}
98
99fn default_report_kinds() -> Vec<CoverageReportKind> {
100    vec![CoverageReportKind::Summary]
101}
102
103const fn default_lcov_version() -> Version {
104    Version::new(1, 0, 0)
105}
106
107fn deserialize_lcov_version<'de, D>(deserializer: D) -> Result<Version, D::Error>
108where
109    D: Deserializer<'de>,
110{
111    let version = String::deserialize(deserializer)?;
112    parse_lcov_version(&version).map_err(serde::de::Error::custom)
113}
114
115pub fn parse_lcov_version(s: &str) -> Result<Version, String> {
116    let vr = VersionReq::parse(&format!("={s}")).map_err(|e| e.to_string())?;
117    let [c] = &vr.comparators[..] else {
118        return Err("invalid version".to_string());
119    };
120    if c.op != semver::Op::Exact {
121        return Err("invalid version".to_string());
122    }
123    if !c.pre.is_empty() {
124        return Err("pre-releases are not supported".to_string());
125    }
126    Ok(Version::new(c.major, c.minor.unwrap_or(0), c.patch.unwrap_or(0)))
127}
128
129#[cfg(test)]
130mod tests {
131    use super::*;
132
133    #[test]
134    fn default_matches_cli_defaults() {
135        let cfg = CoverageConfig::default();
136        assert_eq!(cfg.report, vec![CoverageReportKind::Summary]);
137        assert_eq!(cfg.lcov_version, default_lcov_version());
138        assert!(!cfg.ir_minimum);
139        assert!(!cfg.keep_optimizer);
140        assert!(cfg.report_file.is_none());
141        assert!(!cfg.include_libs);
142        assert!(!cfg.exclude_tests);
143        assert!(cfg.skip_files.is_empty());
144    }
145
146    #[test]
147    fn deserialize_from_toml() {
148        let toml = r#"
149            report = ["summary", "lcov"]
150            lcov_version = "2.2.0"
151            ir_minimum = true
152            keep_optimizer = true
153            report_file = "out/lcov.info"
154            include_libs = true
155            exclude_tests = true
156            skip_files = ["test/**", "src/mocks/**"]
157        "#;
158        let cfg: CoverageConfig = toml::from_str(toml).unwrap();
159        assert_eq!(cfg.report, vec![CoverageReportKind::Summary, CoverageReportKind::Lcov]);
160        assert_eq!(cfg.lcov_version, Version::new(2, 2, 0));
161        assert!(cfg.ir_minimum);
162        assert!(cfg.keep_optimizer);
163        assert_eq!(cfg.report_file.as_deref(), Some(std::path::Path::new("out/lcov.info")));
164        assert!(cfg.include_libs);
165        assert!(cfg.exclude_tests);
166        assert_eq!(cfg.skip_files, vec!["test/**".to_string(), "src/mocks/**".to_string()]);
167    }
168
169    #[test]
170    fn deserialize_partial_uses_defaults() {
171        let toml = r#"skip_files = ["src/mocks/**"]"#;
172        let cfg: CoverageConfig = toml::from_str(toml).unwrap();
173        // Defaulted fields keep their default values.
174        assert_eq!(cfg.report, vec![CoverageReportKind::Summary]);
175        assert_eq!(cfg.lcov_version, default_lcov_version());
176        assert!(!cfg.ir_minimum);
177        // Set field came through.
178        assert_eq!(cfg.skip_files, vec!["src/mocks/**".to_string()]);
179    }
180
181    #[test]
182    fn deserialize_lcov_version_accepts_cli_formats() {
183        for (input, expected) in [
184            ("0", Version::new(0, 0, 0)),
185            ("1", default_lcov_version()),
186            ("1.0", default_lcov_version()),
187            ("1.1", Version::new(1, 1, 0)),
188            ("2", Version::new(2, 0, 0)),
189            ("2.2", Version::new(2, 2, 0)),
190        ] {
191            let cfg: CoverageConfig =
192                toml::from_str(&format!(r#"lcov_version = "{input}""#)).unwrap();
193            assert_eq!(cfg.lcov_version, expected);
194        }
195    }
196}