cargo-resolvediff 1.0.2

A tool for diffing `cargo` dependency resolutions between updates
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
// Copyright (C) 2026 by GiGa infosystems

//! Handle major updates & related tasks

use crate::{
    indexed::IndexedMetadata,
    toml_edit::{MutableTomlFile, TomlPathLookup},
};
use color_eyre::{Result, eyre::eyre};
use crates_io_api::SyncClient;
use itertools::Itertools;
use semver::{Version, VersionReq};
use std::{borrow::Borrow, collections::BTreeMap, fs, iter, path::PathBuf};
use tinyvec::{ArrayVec, array_vec};

/// Check whether a [`Version`] is considered a major update for a given [`VersionReq`].
///
/// Major updates are defined as:
/// * Versions that don't match the requirement,
/// * which are not pre-releases,
/// * happening on requirements that don't pin a dependency to earlier versions explicitly (`<`,
///   `<=` or `=`),
/// * for which no equal or later version is mentioned in any semver operation
pub fn is_major_update_for(requirement: &VersionReq, version: &Version) -> bool {
    if requirement.matches(version) {
        return false;
    }

    // NOTE: Don't automatically update pre-releases
    if !version.pre.is_empty() {
        return false;
    }

    let stripped_version = Version {
        build: semver::BuildMetadata::EMPTY,
        pre: semver::Prerelease::EMPTY,
        ..*version
    };

    for i in &requirement.comparators {
        let i_version = Version {
            major: i.major,
            minor: i.minor.unwrap_or(version.minor),
            patch: i.patch.unwrap_or(version.patch),
            pre: semver::Prerelease::EMPTY,
            build: semver::BuildMetadata::EMPTY,
        };

        match i.op {
            semver::Op::Exact | semver::Op::Less | semver::Op::LessEq => {
                // This version was explicitly not matched against
                return false;
            }
            semver::Op::Greater | semver::Op::GreaterEq | semver::Op::Tilde | semver::Op::Caret => {
                if i_version >= stripped_version {
                    return false;
                }
            }
            semver::Op::Wildcard => unreachable!("Should've matched this version already"),
            op => panic!("Unknown semver operation: {op:?}"),
        }
    }

    true
}

/// Fetch all versions for a crate that have not been yanked.
pub fn fetch_versions_for(
    client: &SyncClient,
    package: &str,
) -> Result<Option<impl Iterator<Item = Version>>> {
    let info = match client.get_crate(package) {
        Ok(info) => info,
        Err(crates_io_api::Error::NotFound(_)) => return Ok(None),
        Err(err) => return Err(err.into()),
    };
    let versions = info
        .versions
        .into_iter()
        .filter(|version| !version.yanked)
        .map(|version| {
            version
                .num
                .parse::<Version>()
                .expect("Published crate version should be a valid `semver` version")
        });
    Ok(Some(versions))
}

/// Fetch all versions of a crate that are considered major updates for _any_ of the given
/// [`VersionReq`]s and have not been yanked
pub fn fetch_major_updates_for(
    client: &SyncClient,
    package: &str,
    reqs: impl Iterator<Item: Borrow<VersionReq>> + Clone,
) -> Result<Option<impl Iterator<Item = Version>>> {
    let Some(versions) = fetch_versions_for(client, package)? else {
        return Ok(None);
    };
    let versions = versions.filter(move |version| {
        reqs.clone()
            .any(|version_req| is_major_update_for(version_req.borrow(), version))
    });
    Ok(Some(versions))
}

/// The result of [`fetch_latest_major_update_for`]
pub enum LatestVersion {
    CrateNotFound,
    NoMajorUpdates,
    NewestUpdate(Version),
}

/// Fetch the latest versions of a crate that is considered a major update for _any_ of the given
/// [`VersionReq`]s and has not been yanked
pub fn fetch_latest_major_update_for(
    client: &SyncClient,
    package: &str,
    reqs: impl Iterator<Item: Borrow<VersionReq>> + Clone,
) -> Result<LatestVersion> {
    let Some(versions) = fetch_major_updates_for(client, package, reqs)? else {
        return Ok(LatestVersion::CrateNotFound);
    };
    let newest = versions.max();
    Ok(newest.map_or(LatestVersion::NoMajorUpdates, LatestVersion::NewestUpdate))
}

/// A reference to a [crates.io] dependency version, part of [`ManifestDependencySet`]
pub struct DependencyMention {
    manifest_idx: usize,
    /// The TOML path to the version specification
    toml_path: Vec<String>,
    version: VersionReq,
}

impl DependencyMention {
    pub fn toml_path(&self) -> &[String] {
        &self.toml_path
    }

    pub fn version(&self) -> &VersionReq {
        &self.version
    }
}

/// A set of manifests with the associated direct dependencies from [crates.io], with all instances
/// of their version being requested
pub struct ManifestDependencySet {
    pub manifests: ManifestSet,
    /// Maps crate names to [`DependencyMention`]s
    pub dependencies: BTreeMap<String, Vec<DependencyMention>>,
}

impl ManifestDependencySet {
    /// The paths in which dependencies can be listed in a given manifest
    fn dependency_toml_paths(
        manifest: &MutableTomlFile,
    ) -> Result<impl Iterator<Item = ArrayVec<[&str; 3]>>> {
        let targets = manifest
            .document()
            .as_table()
            .get("target")
            .map(|target| {
                target.as_table_like().ok_or_else(|| {
                    eyre!("Invalid target table in {:?} at `target`", manifest.path())
                })
            })
            .transpose()?
            .into_iter()
            .flat_map(|target| target.iter().map(|(key, _)| key));

        let dep_paths = iter::once(None)
            .chain(targets.map(Some))
            .cartesian_product(["dependencies", "build-dependencies", "dev-dependencies"])
            .map(|(target, dep_kind)| {
                target.map_or(
                    array_vec!(_ => dep_kind),
                    |target| array_vec!(_ => "target", target, dep_kind),
                )
            });

        Ok(dep_paths)
    }

    /// Read a version from a given TOML path
    fn read_version(manifest: &MutableTomlFile, path: &[String]) -> Result<VersionReq> {
        let version = manifest
            .path_lookup(path)
            .expect("Version path lookup failed (maybe the `MutableTomlFile` changed?)")
            .as_str()
            .ok_or_else(|| {
                eyre!(
                    "Invalid `version`/immediate value in {path:?} at {:?}",
                    manifest.path()
                )
            })?
            .parse::<VersionReq>()?;
        Ok(version)
    }

    /// Collect all dependencies from a set of manifests
    fn collect_dependencies(
        manifest_idx: usize,
        manifest: &MutableTomlFile,
        direct_dependencies: &mut BTreeMap<String, Vec<DependencyMention>>,
    ) -> Result<()> {
        for dep_path in Self::dependency_toml_paths(manifest)? {
            let Some(dependencies) = manifest.path_lookup(dep_path) else {
                continue;
            };

            let dependencies = dependencies.as_table_like().ok_or_else(|| {
                eyre!(
                    "Invalid dependency table in {:?} at {dep_path}",
                    manifest.path()
                )
            })?;

            for (name, dependency) in dependencies.iter() {
                let (package, version_path_segment) =
                    if let Some(dependency) = dependency.as_table_like() {
                        let package = match dependency.get("package") {
                            None => name,
                            Some(package) => package.as_str().ok_or_else(|| {
                                eyre!(
                                    "Invalid `package` value in {:?} at {dep_path}.{name:?}",
                                    manifest.path()
                                )
                            })?,
                        };

                        if dependency.contains_key("registry")
                            || !dependency.contains_key("version")
                            || dependency.contains_key("git")
                            || dependency.contains_key("path")
                        {
                            continue;
                        }

                        (package, Some("version"))
                    } else {
                        (name, None)
                    };

                let version_path = dep_path
                    .into_iter()
                    .chain(iter::once(name))
                    .chain(version_path_segment)
                    .map(|s| s.to_owned())
                    .collect::<Vec<_>>();

                let version = Self::read_version(manifest, &version_path)?;

                direct_dependencies
                    .entry(package.to_owned())
                    .or_default()
                    .push(DependencyMention {
                        manifest_idx,
                        toml_path: version_path,
                        version,
                    })
            }
        }

        Ok(())
    }

    /// Collect all direct dependencies from all workspace manifests which are part of an
    /// [`IndexedMetadata`]
    pub fn collect(metadata: &IndexedMetadata) -> Result<Self> {
        let manifests = ManifestSet::collect(metadata)?;

        let mut dependencies = BTreeMap::new();
        for (idx, manifest) in manifests.manifests.iter().enumerate() {
            Self::collect_dependencies(idx, manifest, &mut dependencies)?;
        }

        Ok(ManifestDependencySet {
            manifests,
            dependencies,
        })
    }

    /// Commit all changes made to the [`ManifestSet`] (see [`MutableTomlFile::commit`])
    pub fn commit(&mut self) -> Result<()> {
        self.manifests.write_back()?;
        self.manifests.commit_lock_contents()?;

        // NOTE: Writing all back before committing allows rolling back if any of the write backs
        // failed
        for manifest in &mut self.manifests.manifests {
            // NOTE: Should now be infallible since it's already been written back
            manifest.commit()?;
        }

        Ok(())
    }

    /// Roll back all changes made to the [`ManifestSet`] (see [`MutableTomlFile::roll_back`]), and
    /// reset the parsed dependency versions to the original values
    pub fn roll_back(&mut self) -> Result<()> {
        let mut errors = Vec::new();

        if let Err(error) = self.manifests.roll_back_lock_contents() {
            errors.push(error);
        }

        for manifest in &mut self.manifests.manifests {
            if let Err(error) = manifest.roll_back() {
                errors.push(error);
            }
        }

        for mention in self.dependencies.values_mut().flatten() {
            mention.version = Self::read_version(
                &self.manifests.manifests[mention.manifest_idx],
                &mention.toml_path,
            )?;
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(eyre!("Failed to roll back:\n{errors:?}"))
        }
    }
}

/// A set of manifests for a workspace
pub struct ManifestSet {
    manifests: Vec<MutableTomlFile>,
    lock_path: PathBuf,
    last_lock_contents: String,
}

impl ManifestSet {
    /// Collect all manifests from an [`IndexedMetadata`]
    pub fn collect(metadata: &IndexedMetadata) -> Result<Self> {
        let workspace_manifest = metadata.workspace_root.join("Cargo.toml");
        let lock_path = workspace_manifest.with_extension("lock").into();

        let mut member_manifests = metadata
            .packages
            .iter()
            .filter(|(pkg_id, _)| metadata.workspace_members.contains(pkg_id))
            .map(|(_, pkg)| &pkg.manifest_path)
            .collect::<Vec<_>>();

        let isnt_workspace = matches!(*member_manifests, [single] if *single == workspace_manifest);

        if isnt_workspace {
            member_manifests.clear();
        }

        let manifests = iter::once(&workspace_manifest)
            .chain(member_manifests)
            .map(MutableTomlFile::open)
            .collect::<Result<Vec<_>>>()?;

        let last_lock_contents = fs::read_to_string(&lock_path)?;

        Ok(ManifestSet {
            manifests,
            lock_path,
            last_lock_contents,
        })
    }

    pub fn as_slice(&self) -> &[MutableTomlFile] {
        &self.manifests
    }

    pub fn as_slice_mut(&mut self) -> &mut [MutableTomlFile] {
        &mut self.manifests
    }

    /// Write back all manifests to the underlying files (see [`MutableTomlFile::write_back`])
    pub fn write_back(&mut self) -> Result<()> {
        for manifest in &mut self.manifests {
            manifest.write_back()?;
        }

        Ok(())
    }

    /// Return a reference to  the manifest file associated with a given mention of a dependency
    /// version
    pub fn manifest_for(&self, mention: &DependencyMention) -> &MutableTomlFile {
        &self.manifests[mention.manifest_idx]
    }

    /// Return a mutable reference to the manifest file associated with a given mention of a
    /// dependency version
    pub fn manifest_mut_for(&mut self, mention: &DependencyMention) -> &mut MutableTomlFile {
        &mut self.manifests[mention.manifest_idx]
    }

    /// Write back the changes made to the manifest file associated with a given mention of a
    /// dependency version
    pub fn write_back_for(&mut self, mention: &DependencyMention) -> Result<()> {
        self.manifest_mut_for(mention).write_back()?;
        Ok(())
    }

    /// Write back the changes made to all manifest file associated with any of the given mentions
    /// dependency versions
    pub fn write_back_for_all(&mut self, mentions: &[DependencyMention]) -> Result<()> {
        for mention in mentions {
            self.write_back_for(mention)?;
        }
        Ok(())
    }

    /// Change a dependency version in memory only (requires calling a `write_back` or `commit`
    /// method to actually change the underlying file)
    pub fn write_version_to_memory(
        &mut self,
        mention: &mut DependencyMention,
        version: VersionReq,
    ) {
        let Some(toml_edit::Value::String(toml_version)) = self
            .manifest_mut_for(mention)
            .path_lookup_mut(&mention.toml_path)
            .and_then(toml_edit::Item::as_value_mut)
        else {
            panic!("Version path lookup failed (maybe the `MutableTomlFile` changed?)");
        };
        let decor = toml_version.decor().clone();

        let as_string = match *version.comparators {
            [ref single] if single.op == semver::Op::Caret => {
                let mut out = version.to_string();
                if out.starts_with('^') {
                    out.remove(0); // Remove the caret
                }
                out
            }
            _ => version.to_string(),
        };

        *toml_version = toml_edit::Formatted::new(as_string);
        *toml_version.decor_mut() = decor;

        mention.version = version;
    }

    /// Change a dependency version in memory only (requires calling a `write_back` or `commit`
    /// method to actually change the underlying file) for multiple mentions
    pub fn write_versions_to_memory(
        &mut self,
        mentions: &mut [DependencyMention],
        version: &VersionReq,
    ) {
        for mention in mentions {
            self.write_version_to_memory(mention, version.clone());
        }
    }

    /// Change a dependency version
    pub fn write_version_to_file(
        &mut self,
        mention: &mut DependencyMention,
        version: VersionReq,
    ) -> Result<()> {
        self.write_version_to_memory(mention, version);
        self.write_back_for(mention)?;
        Ok(())
    }

    /// Change a dependency version for multiple mentions
    pub fn write_versions_to_file(
        &mut self,
        mentions: &mut [DependencyMention],
        version: &VersionReq,
    ) -> Result<()> {
        self.write_versions_to_memory(mentions, version);
        self.write_back_for_all(mentions)?;
        Ok(())
    }

    /// Change a dependency version in memory if it is considered a major update
    pub fn update_version_in_memory(&mut self, mention: &mut DependencyMention, version: &Version) {
        if is_major_update_for(&mention.version, version) {
            self.write_version_to_memory(
                mention,
                VersionReq {
                    comparators: vec![semver::Comparator {
                        op: semver::Op::Caret,
                        major: version.major,
                        minor: Some(version.minor),
                        patch: Some(version.patch),
                        pre: version.pre.clone(),
                    }],
                },
            );
        }
    }

    /// Change dependency versions in memory for each mention for which it is considered a major
    /// update
    pub fn update_versions_in_memory(
        &mut self,
        mentions: &mut [DependencyMention],
        version: &Version,
    ) {
        for mention in mentions {
            self.update_version_in_memory(mention, version);
        }
    }

    /// Change a dependency version if it is considered a major update
    pub fn update_version_in_file(
        &mut self,
        mention: &mut DependencyMention,
        version: &Version,
    ) -> Result<()> {
        self.update_version_in_memory(mention, version);
        self.write_back_for(mention)?;
        Ok(())
    }

    /// Change dependency versions for each mention for which it is considered a major update
    pub fn update_versions_in_file(
        &mut self,
        mentions: &mut [DependencyMention],
        version: &Version,
    ) -> Result<()> {
        self.update_versions_in_memory(mentions, version);
        self.write_back_for_all(mentions)?;
        Ok(())
    }

    pub fn commit_lock_contents(&mut self) -> Result<()> {
        self.last_lock_contents = fs::read_to_string(&self.lock_path)?;
        Ok(())
    }

    pub fn roll_back_lock_contents(&mut self) -> Result<()> {
        fs::write(&self.lock_path, &self.last_lock_contents)?;
        Ok(())
    }
}