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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
use std::path::PathBuf;
use std::{borrow::Cow, collections::BTreeSet, path::Path};

use anyhow::Context;
use sha2::Digest as _;
use trustfall_rustdoc::{LoadingError, VersionedStorage};

use crate::manifest::Manifest;
use crate::util::{atomic_write, slugify};

use super::error::{IntoTerminalResult, TerminalError};
use super::generate::{GenerationSettings, RustdocBuildEnvironment};
use super::progress::{CallbackHandler, ProgressCallbacks};

#[derive(Debug, Clone)]
pub(crate) struct RegistryRequest<'a> {
    index_entry: &'a tame_index::IndexVersion,
}

#[derive(Debug, Clone)]
pub(crate) struct ProjectRequest<'a> {
    pub(super) manifest: &'a Manifest,
}

#[derive(Debug, Clone)]
pub(crate) enum RequestKind<'a> {
    Registry(RegistryRequest<'a>),
    LocalProject(ProjectRequest<'a>),
}

impl RequestKind<'_> {
    pub(super) fn name(&self) -> anyhow::Result<&str> {
        Ok(match self {
            Self::Registry(RegistryRequest { index_entry }) => &index_entry.name,
            Self::LocalProject(ProjectRequest { manifest }) => {
                crate::manifest::get_package_name(manifest)?
            }
        })
    }

    pub(super) fn version(&self) -> anyhow::Result<&str> {
        Ok(match self {
            Self::Registry(RegistryRequest { index_entry }) => index_entry.version.as_str(),
            Self::LocalProject(ProjectRequest { manifest }) => {
                crate::manifest::get_package_version(manifest)?
            }
        })
    }
}

#[allow(dead_code)]
#[derive(Debug, Clone)]
pub(crate) enum CacheSettings<T> {
    /// No caching at all.
    None,

    /// A read-only cache. We do *not* populate it on cache miss.
    ReadOnly(T),

    /// A read-write cache, populated on cache miss.
    ReadWrite(T),

    /// A cache that will ignore present data (because maybe it's invalid or stale!),
    /// but will write newly generated items, overwriting anything present at that path.
    WriteOnly(T),
}

impl CacheSettings<()> {
    pub(crate) fn with_path<'a>(&self, path: &'a Path) -> CacheSettings<&'a Path> {
        match self {
            CacheSettings::None => CacheSettings::None,
            CacheSettings::ReadOnly(_) => CacheSettings::ReadOnly(path),
            CacheSettings::ReadWrite(_) => CacheSettings::ReadWrite(path),
            CacheSettings::WriteOnly(_) => CacheSettings::WriteOnly(path),
        }
    }
}

#[derive(Debug, Clone)]
pub(crate) struct CacheUse<'a> {
    /// Invariant: always `None` if the cache settings are [`CacheSettings::None`],
    /// and always `Some` otherwise.
    json_cache_location: Option<PathBuf>,

    /// Invariant: always `None` if the cache settings are [`CacheSettings::None`],
    /// and always `Some` otherwise.
    metadata_cache_location: Option<PathBuf>,

    settings: CacheSettings<&'a Path>,
}

#[derive(Debug, Clone)]
struct CacheEntry<'a> {
    json: &'a Path,
    metadata: &'a Path,
}

impl<'a> CacheUse<'a> {
    fn new(
        request: &CrateDataRequest<'a>,
        build_environment: &RustdocBuildEnvironment,
        settings: CacheSettings<&'a Path>,
    ) -> anyhow::Result<Self> {
        // We can only cache registry crates. For local crates, we have no idea of the state
        // of the local filesystem: it can point to an arbitrary git commit, have dirty repo state,
        // or might not be part of a git repository at all. We cannot guarantee consistency,
        // so we don't offer caching.
        let settings = if matches!(request.kind, RequestKind::LocalProject(..)) {
            CacheSettings::None
        } else {
            settings
        };

        let key = request.artifact_slug(build_environment)?;

        let (json_cache_location, metadata_cache_location) = {
            match settings {
                CacheSettings::None => (None, None),
                CacheSettings::ReadOnly(path)
                | CacheSettings::ReadWrite(path)
                | CacheSettings::WriteOnly(path) => (
                    Some(path.join(format!("{key}.json"))),
                    Some(path.join(format!("{key}.metadata.json"))),
                ),
            }
        };

        Ok(Self {
            json_cache_location,
            metadata_cache_location,
            settings,
        })
    }

    fn read(&self) -> anyhow::Result<Option<CacheEntry<'_>>> {
        match self.settings {
            CacheSettings::ReadWrite(..) | CacheSettings::ReadOnly(..) => {
                let json_path = self
                    .json_cache_location
                    .as_ref()
                    .expect("invariant violation: no cache path for readable cache");
                let metadata_path = self
                    .metadata_cache_location
                    .as_ref()
                    .expect("invariant violation: no metadata path for readable cache");

                if json_path.exists() && metadata_path.exists() {
                    return Ok(Some(CacheEntry {
                        json: json_path,
                        metadata: metadata_path,
                    }));
                }
            }
            CacheSettings::WriteOnly(..) | CacheSettings::None => {}
        }

        Ok(None)
    }

    /// If the cache policy allows writing to the cache, attempt to cache a path.
    ///
    /// If the cache policy does not allow writing, this returns `Ok(..)`.
    /// Errors are genuine failures to write to the cache, such as I/O errors.
    fn populate(
        &self,
        rustdoc_json: &Path,
        metadata: &cargo_metadata::Metadata,
    ) -> anyhow::Result<bool> {
        match self.settings {
            CacheSettings::ReadWrite(path) | CacheSettings::WriteOnly(path) => {
                let json_path = self
                    .json_cache_location
                    .as_ref()
                    .expect("invariant violation: no cache path for readable cache");
                let metadata_path = self
                    .metadata_cache_location
                    .as_ref()
                    .expect("invariant violation: no metadata path for readable cache");

                fs_err::create_dir_all(path)?;
                // Do not use `fs_err::copy` or `std::fs::copy` here. Those APIs open the
                // destination path themselves and stream bytes into it directly, so another process
                // can observe a partially copied cache file if it reads while the copy is in
                // progress or if the copy fails partway through. Routing the copy through
                // `atomic_write` publishes only a completed temp-file copy.
                atomic_write(json_path, |writer| {
                    let mut rustdoc_json_file = fs_err::File::open(rustdoc_json)?;
                    std::io::copy(&mut rustdoc_json_file, writer).with_context(|| {
                        format!(
                            "failed to copy rustdoc JSON cache file from {} to {}",
                            rustdoc_json.display(),
                            json_path.display()
                        )
                    })?;
                    Ok(())
                })?;
                atomic_write(metadata_path, |writer| {
                    serde_json::to_writer(writer, metadata)?;
                    Ok(())
                })?;
                Ok(true)
            }
            CacheSettings::None | CacheSettings::ReadOnly(..) => Ok(false),
        }
    }
}

#[derive(Debug, Clone)]
pub(crate) struct CrateDataRequest<'a> {
    pub(crate) kind: RequestKind<'a>,

    // N.B.: `--no-default-features --feature default` is not the same as using default features,
    //       since it will fail if the crate has no "default" feature definition.
    pub(super) default_features: bool,

    pub(super) extra_features: BTreeSet<Cow<'a, str>>,
    pub(super) build_target: Option<&'a str>,

    /// Purely for progress reporting purposes. Does not change behavior.
    pub(super) is_baseline: bool,
}

impl<'a> CrateDataRequest<'a> {
    pub(crate) fn from_index(
        index_entry: &'a tame_index::IndexVersion,
        default_features: bool,
        extra_features: BTreeSet<Cow<'a, str>>,
        build_target: Option<&'a str>,
        is_baseline: bool,
    ) -> Self {
        Self {
            kind: RequestKind::Registry(RegistryRequest { index_entry }),
            default_features,
            extra_features,
            build_target,
            is_baseline,
        }
    }

    pub(crate) fn from_local_project(
        manifest: &'a Manifest,
        default_features: bool,
        extra_features: BTreeSet<Cow<'a, str>>,
        build_target: Option<&'a str>,
        is_baseline: bool,
    ) -> Self {
        Self {
            kind: RequestKind::LocalProject(ProjectRequest { manifest }),
            default_features,
            extra_features,
            build_target,
            is_baseline,
        }
    }

    pub(crate) fn package_name(&self) -> anyhow::Result<&str> {
        self.kind.name()
    }

    pub(crate) fn exact_version(&self) -> anyhow::Result<String> {
        Ok(format!("={}", self.kind.version()?))
    }

    pub(crate) fn local_project_dir(&self) -> anyhow::Result<Option<PathBuf>> {
        match &self.kind {
            RequestKind::Registry(..) => Ok(None),
            RequestKind::LocalProject(ProjectRequest { manifest }) => Ok(Some(
                crate::manifest::get_project_dir_from_manifest_path(&manifest.path)?,
            )),
        }
    }

    pub(crate) fn default_features_enabled(&self) -> bool {
        self.default_features
    }

    pub(crate) fn extra_features(&self) -> impl Iterator<Item = &str> + '_ {
        self.extra_features.iter().map(Cow::as_ref)
    }

    pub(crate) fn build_target(&self) -> Option<&str> {
        self.build_target
    }

    /// Best-effort Rust import name for this crate as it would appear in
    /// downstream code. This is intentionally not always the same as the Cargo
    /// package name: local projects may customize their library target name,
    /// while registry packages with dashes are imported with underscores.
    pub(crate) fn fallback_import_name(&self) -> anyhow::Result<String> {
        match &self.kind {
            RequestKind::Registry(..) => Ok(self.package_name()?.replace('-', "_")),
            RequestKind::LocalProject(ProjectRequest { manifest }) => {
                crate::manifest::get_library_target_name(manifest)
            }
        }
    }

    /// Load data for the requested crate, using the specified directories.
    ///
    /// `target_root` is the directory where we'll perform any necessary code generation
    /// to load the data. The specific operations performed there are not public API.
    ///
    /// `cache` specifies how we may use a cache to speed up our data requests:
    /// read-write, read-only, or not at all.
    pub(crate) fn resolve<'slf>(
        &'slf self,
        target_root: &Path,
        cache_settings: CacheSettings<&'a Path>,
        generation_settings: GenerationSettings,
        callbacks: &'slf mut dyn ProgressCallbacks<'slf>,
    ) -> Result<VersionedStorage, TerminalError> {
        let mut callbacks = CallbackHandler::new(
            self.kind
                .name()
                .context("failed to get crate name")
                .into_terminal_result()?,
            self.kind
                .version()
                .context("failed to get crate version")
                .into_terminal_result()?,
            self.is_baseline,
            callbacks,
        );

        // We treat failures to even set up a cache to use as fatal,
        // since they almost always indicate a serious bug in our mental model.
        // An example of a failure here would be "crates don't always have a name, actually"
        // which is something we want to know about ASAP.
        let build_environment =
            RustdocBuildEnvironment::from_env_and_config_for_target(self.build_target())
                .into_terminal_result()?;
        let cache =
            CacheUse::new(self, &build_environment, cache_settings).into_terminal_result()?;

        // Can we satisfy the request from cache?
        match cache.read() {
            // Cache hit!
            Ok(Some(entry)) => {
                callbacks.rustdoc_cache_hit();
                callbacks.parse_rustdoc_start(true);

                match std::fs::read_to_string(entry.metadata) {
                    Ok(text) => match serde_json::from_str(&text) {
                        Ok(metadata) => {
                            match load_rustdoc_with_optional_metadata(
                                entry.json,
                                metadata,
                                &mut callbacks,
                            ) {
                                Ok(data) => {
                                    callbacks.parse_rustdoc_success(true);
                                    return Ok(data);
                                }
                                Err(e) => {
                                    callbacks.non_fatal_error(
                                        e.context("failed to load cached rustdoc JSON"),
                                    );
                                }
                            }
                        }
                        Err(e) => {
                            callbacks.non_fatal_error(
                                anyhow::anyhow!(e).context("failed to parse cached metadata"),
                            );
                        }
                    },
                    Err(e) => callbacks.non_fatal_error(
                        anyhow::anyhow!(e).context("failed to read cached metadata file"),
                    ),
                }
            }

            // Cache miss. Move on.
            Ok(None) => {}

            // Error in the cache lookup. Record it, then move on as if cache miss.
            Err(e) => {
                callbacks.non_fatal_error(
                    e.context("failed to perform cache lookup, continuing as if cache miss"),
                );
            }
        }

        // Generate the data we need.
        let build_dir = target_root.join(
            self.build_path_slug(&build_environment)
                .into_terminal_result()?,
        );
        let (data_path, metadata) = super::generate::generate_rustdoc(
            self,
            &build_dir,
            generation_settings,
            &build_environment,
            &mut callbacks,
        )?;

        // Check if we need to populate the cache.
        // If the cache doesn't need to be populated, this returns `Ok(false)`.
        // Errors are genuine failures to populate the cache, such as I/O problems.
        let mut clean_up_build_dir = false;
        match cache.populate(data_path.as_path(), &metadata) {
            // Populated the cache.
            Ok(true) => {
                callbacks.rustdoc_cache_populated();

                // Clean up our build dir, since we don't need it anymore.
                clean_up_build_dir = true;
            }

            // Did not populate the cache.
            Ok(false) => {}

            // Encountered an error while attempting to populate the cache.
            Err(e) => {
                callbacks.non_fatal_error(e.context("failed to populate rustdoc cache"));
            }
        }

        // This time, failure to read the rustdoc is fatal.
        callbacks.parse_rustdoc_start(false);
        let data = load_rustdoc_with_optional_metadata(&data_path, metadata, &mut callbacks)
            .into_terminal_result()?;
        callbacks.parse_rustdoc_success(false);

        if clean_up_build_dir {
            let outcome = std::fs::remove_dir_all(&build_dir);
            if let Err(e) = outcome {
                callbacks.non_fatal_error(
                    anyhow::Error::from(e)
                        .context("failed to clean up build dir after populating rustdoc cache"),
                );
            }
        }

        Ok(data)
    }

    /// A path-safe unique identifier for the placeholder build directory.
    fn build_path_slug(
        &self,
        build_environment: &RustdocBuildEnvironment,
    ) -> anyhow::Result<String> {
        Ok(format!(
            "{}-{}",
            match &self.kind {
                RequestKind::Registry { .. } => "registry",
                RequestKind::LocalProject { .. } => "local",
            },
            self.artifact_slug(build_environment)?,
        ))
    }

    /// A path-safe unique identifier for the generated rustdoc artifact.
    fn artifact_slug(&self, build_environment: &RustdocBuildEnvironment) -> anyhow::Result<String> {
        Ok(format!(
            "{}-{}-{}-{}",
            slugify(self.kind.name()?),
            slugify(self.kind.version()?),
            slugify(&build_environment.target_triple),
            self.artifact_fingerprint(build_environment)?,
        ))
    }

    fn artifact_fingerprint(
        &self,
        build_environment: &RustdocBuildEnvironment,
    ) -> anyhow::Result<String> {
        // Bump this when the fields or semantics hashed into rustdoc artifact identity change, so
        // old cache entries and placeholder build directories cannot collide with the new
        // interpretation.
        const RUSTDOC_ARTIFACT_FINGERPRINT_SCHEMA: &str = "rustdoc-artifact-v1";

        let mut hasher = sha2::Sha256::new();
        update_artifact_hash(&mut hasher, "schema", RUSTDOC_ARTIFACT_FINGERPRINT_SCHEMA);
        update_artifact_hash(
            &mut hasher,
            "source",
            match &self.kind {
                RequestKind::Registry { .. } => "registry",
                RequestKind::LocalProject { .. } => "local",
            },
        );
        update_artifact_hash(&mut hasher, "name", self.kind.name()?);
        update_artifact_hash(&mut hasher, "version", self.kind.version()?);
        update_artifact_hash(
            &mut hasher,
            "default_features",
            if self.default_features {
                "true"
            } else {
                "false"
            },
        );
        for feature in &self.extra_features {
            update_artifact_hash(&mut hasher, "feature", feature);
        }
        update_artifact_hash(&mut hasher, "target", &build_environment.target_triple);
        update_artifact_hash(
            &mut hasher,
            "rustflags",
            build_environment.cargo_rustflags.as_ref(),
        );
        update_artifact_hash(
            &mut hasher,
            "rustdocflags",
            build_environment.cargo_rustdocflags.as_ref(),
        );
        update_artifact_hash(
            &mut hasher,
            "toolchain_version",
            &build_environment.toolchain_version,
        );

        // Store the hash as string with hex number (leading zeros added).
        let mut hash = format!("{:0>64x}", hasher.finalize());

        // First 16 hex characters are good enough for our use case.
        // For birthday paradox to occur, a single crate version must be run
        // with approximately 2**32 artifact configurations.
        hash.truncate(16);
        Ok(hash)
    }
}

fn load_rustdoc_with_optional_metadata(
    json_path: &Path,
    metadata: cargo_metadata::Metadata,
    callbacks: &mut CallbackHandler<'_>,
) -> anyhow::Result<VersionedStorage> {
    match trustfall_rustdoc::load_rustdoc(json_path, Some(metadata)) {
        Ok(data) => Ok(data),
        Err(e @ LoadingError::MetadataParsing(..)) => {
            // Metadata parsing is brand new and might have unforeseen issues.
            // Be resilient: report the problem but don't crash --
            // instead, drop back to not checking manifest data.
            callbacks.non_fatal_error(anyhow::Error::from(e).context("skipping package metadata due to failure to load it; package manifest checks will not discover any breakage"));

            trustfall_rustdoc::load_rustdoc(json_path, None).map_err(anyhow::Error::from)
        }
        Err(e) => Err(anyhow::Error::from(e)),
    }
}

fn update_artifact_hash(hasher: &mut sha2::Sha256, label: &str, value: &str) {
    // Length-prefix each field so adjacent records cannot collide by concatenating ambiguously.
    for entry in [label, value] {
        let bytes = entry.as_bytes();
        hasher.update(bytes.len().to_le_bytes());
        hasher.update(bytes);
    }
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeSet;
    use std::path::PathBuf;

    use super::*;

    fn test_manifest() -> Manifest {
        Manifest::parse(PathBuf::from(
            "test_crates/cfg_conditional_compilation/old/Cargo.toml",
        ))
        .expect("failed to load test manifest")
    }

    fn build_environment(
        target_triple: &str,
        rustdocflags: &'static str,
    ) -> RustdocBuildEnvironment {
        RustdocBuildEnvironment {
            target_triple: target_triple.to_owned(),
            cargo_rustflags: Cow::Borrowed("--cap-lints=allow"),
            cargo_rustdocflags: Cow::Borrowed(rustdocflags),
            toolchain_version: String::from("1.95.0"),
        }
    }

    #[test]
    fn artifact_slug_uses_canonical_target_triple() {
        let implicit_build_environment =
            RustdocBuildEnvironment::from_env_and_config_for_target(None)
                .expect("implicit build environment failed");
        let target_triple = implicit_build_environment.target_triple.clone();
        let explicit_build_environment =
            RustdocBuildEnvironment::from_env_and_config_for_target(Some(&target_triple))
                .expect("explicit build environment failed");

        let implicit_manifest = test_manifest();
        let explicit_manifest = test_manifest();
        let implicit = CrateDataRequest::from_local_project(
            &implicit_manifest,
            true,
            BTreeSet::new(),
            None,
            false,
        );
        let explicit = CrateDataRequest::from_local_project(
            &explicit_manifest,
            true,
            BTreeSet::new(),
            Some(&target_triple),
            false,
        );

        assert_eq!(
            implicit
                .artifact_slug(&implicit_build_environment)
                .expect("implicit artifact slug failed"),
            explicit
                .artifact_slug(&explicit_build_environment)
                .expect("explicit artifact slug failed"),
        );
    }

    #[test]
    fn artifact_slug_includes_effective_rustdocflags() {
        let manifest = test_manifest();
        let request =
            CrateDataRequest::from_local_project(&manifest, true, BTreeSet::new(), None, false);
        let host_environment = RustdocBuildEnvironment::from_env_and_config_for_target(None)
            .expect("build environment failed");
        let without_cfg = build_environment(
            &host_environment.target_triple,
            "-Z unstable-options --document-private-items --document-hidden-items --output-format=json --cap-lints=allow",
        );
        let with_cfg = build_environment(
            &host_environment.target_triple,
            "--cfg custom -Z unstable-options --document-private-items --document-hidden-items --output-format=json --cap-lints=allow",
        );

        assert_ne!(
            request
                .artifact_slug(&without_cfg)
                .expect("artifact slug without cfg failed"),
            request
                .artifact_slug(&with_cfg)
                .expect("artifact slug with cfg failed"),
        );
    }
}