cargo-semver-checks 0.48.0

Scan your Rust crate for semver violations.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
use std::collections::BTreeMap;

use anyhow::Context;
use serde::Deserialize;

use crate::{LintLevel, OverrideMap, QueryOverride, RequiredSemverUpdate};

#[derive(Debug, Clone)]
pub(crate) struct Manifest {
    pub(crate) path: std::path::PathBuf,
    pub(crate) parsed: cargo_toml::Manifest<MetadataTable>,
}

impl Manifest {
    /// Parse the manifest, applying workspace inheritance and heuristics from surrounding files.
    pub(crate) fn parse(path: std::path::PathBuf) -> anyhow::Result<Self> {
        // Parsing via `cargo_toml::Manifest::from_path()` is preferable to parsing from a string,
        // because inspection of surrounding files is sometimes necessary to determine
        // the existence of lib targets and ensure proper handling of workspace inheritance.
        let parsed = cargo_toml::Manifest::from_path_with_metadata(&path)
            .with_context(|| format!("failed when reading {}", path.display()))?;

        Ok(Self { path, parsed })
    }

    /// Parse the manifest without using the filesystem or applying workspace inheritance.
    ///
    /// This allows the caller to check which fields were set to be inherited,
    /// and which were missing or set explicitly.
    pub(crate) fn parse_standalone(path: std::path::PathBuf) -> anyhow::Result<Self> {
        let parsed = std::fs::read_to_string(&path)
            .map_err(anyhow::Error::from)
            .and_then(|data| {
                cargo_toml::Manifest::from_slice_with_metadata(data.as_bytes())
                    .map_err(anyhow::Error::from)
            })
            .with_context(|| format!("failed when reading {}", path.display()))?;

        Ok(Self { path, parsed })
    }
}

pub(crate) fn get_package_name(manifest: &Manifest) -> anyhow::Result<&str> {
    let package = manifest.parsed.package.as_ref().with_context(|| {
        format!(
            "failed to parse {}: no `package` table",
            manifest.path.display()
        )
    })?;
    Ok(&package.name)
}

pub(crate) fn get_package_version(manifest: &Manifest) -> anyhow::Result<&str> {
    let package = manifest.parsed.package.as_ref().with_context(|| {
        format!(
            "failed to parse {}: no `package` table",
            manifest.path.display()
        )
    })?;
    let version = package.version.get().with_context(|| {
        format!(
            "failed to retrieve package version from {}",
            manifest.path.display()
        )
    })?;
    Ok(version)
}

/// Returns the Rust library target name that downstream code imports.
///
/// This may differ from the Cargo package name when `[lib].name` is set. When
/// no explicit library name is present, Cargo's usual dash-to-underscore
/// normalization of the package name is applied.
pub(crate) fn get_library_target_name(manifest: &Manifest) -> anyhow::Result<String> {
    if let Some(name) = manifest
        .parsed
        .lib
        .as_ref()
        .and_then(|lib| lib.name.as_ref())
    {
        return Ok(name.clone());
    }

    Ok(get_package_name(manifest)?.replace('-', "_"))
}

pub(crate) fn get_project_dir_from_manifest_path(
    manifest_path: &std::path::Path,
) -> anyhow::Result<std::path::PathBuf> {
    assert!(
        manifest_path.ends_with("Cargo.toml"),
        "path {} isn't pointing to a manifest",
        manifest_path.display()
    );
    let dir_path = manifest_path
        .parent()
        .context("manifest path doesn't have a parent")?;
    Ok(dir_path.to_path_buf())
}

/// A [package.metadata] or [workspace.metadata] table with
/// `cargo-semver-checks` config entries stored in the `config` field below.
#[derive(Debug, Clone, Deserialize)]
pub(crate) struct MetadataTable {
    /// Holds the `cargo-semver-checks` table, if it is declared.
    #[serde(default, rename = "cargo-semver-checks")]
    pub(crate) config: Option<SemverChecksTable>,
}

/// A `[cargo-semver-checks]` config table in `[package.metadata]`
/// or `[workspace.metadata]`.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub(crate) struct SemverChecksTable {
    /// Holds the `lints` table, if it is declared.
    pub(crate) lints: Option<LintTable>,
}

#[derive(Debug, Clone, Deserialize)]
pub(crate) struct LintTable {
    /// Optional key to indicate whether to opt-in to reading
    /// workspace lint configuration.  If not set in the TOML as
    /// `package.metadata.cargo-semver-checks.lints.workspace = true`,
    /// this field is set to `false`. (note that setting the key in the
    /// TOML to false explicitly is invalid behavior and will be interpreted
    /// as just a missing field)
    ///
    /// Currently, we also read `lints.workspace`, but having this key
    /// in a Cargo.toml manifest is invalid if there is no `[workspace.lints]
    /// table in the workspace manifest.  Since we are storing our lint config in
    /// `[workspace.metadata.*]` for now, this could be the case.  If either this
    /// field is true or `lints.workspace` is set, we should read the workspace
    /// lint config.
    #[serde(default, deserialize_with = "deserialize_workspace_key")]
    pub(crate) workspace: bool,
    /// individual `lint_name = ...` entries
    #[serde(flatten)]
    pub(crate) inner: BTreeMap<String, OverrideConfig>,
}

impl LintTable {
    /// Converts this into a stack of `OverrideMap`s, where entries at the top of the stack
    /// (later indices in the `Vec`) override entries lower in the stack.
    pub(crate) fn into_stack(self) -> Vec<OverrideMap> {
        // use a priority -> OverrideMap BTreeMap, which will be sorted by priority
        let mut map = BTreeMap::<_, OverrideMap>::new();
        for (id, config) in self.inner {
            let (priority, overrides) = match config {
                OverrideConfig::Shorthand(lint_level) => (
                    0,
                    QueryOverride {
                        lint_level: Some(lint_level),
                        required_update: None,
                    },
                ),
                OverrideConfig::Both {
                    level,
                    required_update,
                    priority,
                } => (
                    priority,
                    QueryOverride {
                        lint_level: Some(level),
                        required_update: Some(required_update),
                    },
                ),
                OverrideConfig::LintLevel { level, priority } => (
                    priority,
                    QueryOverride {
                        lint_level: Some(level),
                        required_update: None,
                    },
                ),
                OverrideConfig::RequiredUpdate {
                    required_update,
                    priority,
                } => (
                    priority,
                    QueryOverride {
                        lint_level: None,
                        required_update: Some(required_update),
                    },
                ),
            };

            map.entry(priority).or_default().insert(id, overrides);
        }

        // This will be sorted by key `priority` in ascending order.
        // To match the Cargo lint table semantics (more negative `priorities`
        // overrides more positive `priorities`) with the stack semantics
        // (later/greater-indexed elements at the top of the stack override
        // lower/lesser-indexed elements), we need to reverse this iterator,
        // so more negative `priority` keys come last at the top of the stack.
        map.into_values().rev().collect()
    }
}

/// Different valid representations of a [`QueryOverride`] in the Cargo.toml configuration table
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub(crate) enum OverrideConfig {
    /// Specify both lint level and required update by name, e.g.
    /// `lint_name = { level = "deny", required-update = "major" }
    #[serde(rename_all = "kebab-case")]
    Both {
        level: LintLevel,
        required_update: RequiredSemverUpdate,
        /// The priority for this configuration.  If there are multiple entries that
        /// configure a lint (e.g., a lint group containing a lint and the lint itself),
        /// the configuration entry with the **lowest** priority takes precedence.
        /// The default value, if omitted, is 0.
        #[serde(default)]
        priority: i64,
    },
    /// Specify just lint level by name, with optional priority.
    /// `lint_name = { level = "deny" }
    #[serde(rename_all = "kebab-case")]
    LintLevel {
        level: LintLevel,
        #[serde(default)]
        priority: i64,
    },
    /// Specify just required update by name, with optional priority.
    /// `lint_name = { required-update = "minor" }
    #[serde(rename_all = "kebab-case")]
    RequiredUpdate {
        required_update: RequiredSemverUpdate,
        #[serde(default)]
        priority: i64,
    },
    /// Shorthand for specifying just a lint level and leaving
    /// the other members (required_update and priority) as default: e.g.,
    /// `lint_name = "deny"`
    Shorthand(LintLevel),
}

/// Deserializes the `workspace` key as an `Option<bool>`, raising
/// a hard error if `workspace = false` is explicity set, which is
/// an invalid configuration.  Returns a `bool` whether the workspace
/// key was explicitly set (`workspace = true`, return true) or omitted (false).
fn deserialize_workspace_key<'de, D>(de: D) -> Result<bool, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let option = Option::<bool>::deserialize(de)?;

    match option {
        Some(true) => Ok(true),
        None => Ok(false),
        Some(false) => Err(serde::de::Error::custom(
            "`lints.workspace = false` is not valid configuration.\n\
            Either set `lints.workspace = true` or omit the key entirely.",
        )),
    }
}

/// Helper function to deserialize an optional lint table from a [`serde_json::Value`]
/// holding a `[package/workspace.metadata]` table holding a `cargo-semver-checks.lints` table
///
/// Returns an `Err` if the `cargo-semver-checks` table is present
/// but invalid.  Returns `Ok(None)` if the table is not present.
pub(crate) fn deserialize_lint_table(
    metadata: &serde_json::Value,
) -> anyhow::Result<Option<LintTable>> {
    let table = Option::<MetadataTable>::deserialize(metadata)?;
    Ok(table.and_then(|table| table.config.and_then(|config| config.lints)))
}

#[cfg(test)]
mod tests {

    use super::{LintTable, MetadataTable};
    use crate::{OverrideMap, QueryOverride};

    #[test]
    fn test_deserialize_config() {
        use crate::LintLevel::*;
        use crate::RequiredSemverUpdate::*;

        let manifest = r#"[package]
            name = "cargo-semver-checks"
            version = "1.2.3"
            edition = "2021"

            [package.metadata.cargo-semver-checks.lints]
            workspace = true
            two = "deny"
            three = { level = "warn", priority = 1 }
            four = { required-update = "major", priority = 0 }
            five = { required-update = "minor", level = "allow", priority = -1 }

            [workspace.metadata.cargo-semver-checks.lints]
            six = "allow"
            seven = { level = "deny", priority = 2 }
            "#;

        let parsed = cargo_toml::Manifest::from_slice_with_metadata(manifest.as_bytes())
            .expect("Cargo.toml should be valid");
        let package_metadata: MetadataTable = parsed
            .package
            .expect("Cargo.toml should contain a package")
            .metadata
            .expect("Package metadata should be present");

        let workspace_metadata = parsed
            .workspace
            .expect("Cargo.toml should contain a workspace")
            .metadata
            .expect("Workspace metadata should be present");

        let pkg_table = package_metadata
            .config
            .expect("Semver checks table should be present")
            .lints
            .expect("Lint table should be present");

        assert!(
            pkg_table.workspace,
            "Package lints table should contain `workspace = true`"
        );
        let pkg = pkg_table.into_stack();

        let wks = workspace_metadata
            .config
            .expect("Semver checks table should be present")
            .lints
            .expect("Lint table should be present")
            .into_stack();

        similar_asserts::assert_eq!(
            wks,
            vec![
                OverrideMap::from_iter([(
                    "seven".into(),
                    QueryOverride {
                        lint_level: Some(Deny),
                        required_update: None,
                    }
                ),]),
                OverrideMap::from_iter([(
                    "six".into(),
                    QueryOverride {
                        lint_level: Some(Allow),
                        required_update: None,
                    }
                ),]),
            ]
        );

        similar_asserts::assert_eq!(
            pkg,
            vec![
                OverrideMap::from_iter([(
                    "three".into(),
                    QueryOverride {
                        lint_level: Some(Warn),
                        required_update: None,
                    }
                )]),
                OverrideMap::from_iter([
                    (
                        "two".into(),
                        QueryOverride {
                            lint_level: Some(Deny),
                            required_update: None
                        }
                    ),
                    (
                        "four".into(),
                        QueryOverride {
                            lint_level: None,
                            required_update: Some(Major),
                        }
                    ),
                ]),
                OverrideMap::from_iter([(
                    "five".into(),
                    QueryOverride {
                        lint_level: Some(Allow),
                        required_update: Some(Minor),
                    }
                )])
            ]
        );
    }

    #[test]
    fn workspace_key_false_is_error() {
        serde_json::from_value::<LintTable>(serde_json::json! {{
            "workspace": false
        }})
        .expect_err("`workspace = false` should not be accepted");
    }

    #[test]
    fn workspace_key_omitted_is_false() {
        let table = serde_json::from_value::<LintTable>(serde_json::json! {{
        }})
        .expect("this should be a valid lint table");
        assert!(!table.workspace, "table.workspace should be false");
    }

    #[test]
    fn entry_with_no_fields_is_error() {
        toml::from_str::<LintTable>("one = {}").expect_err("one = {} should be invalid");

        toml::from_str::<LintTable>("one = { priority = 0 }")
            .expect_err("one = {priority = 0} should be invalid");
    }
}