verctl-core 0.9.0

Core configuration, manifest, fragment, changelog, and version domain logic for verctl
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
//! The members a virtual cargo workspace publishes, in publish order.
//!
//! A package whose manifest is a virtual workspace publishes one member at a
//! time. A rerun after a partial release then uploads only what is missing,
//! because `cargo publish --workspace` refuses to run when any selected
//! version exists. Cargo resolves member globs and workspace inheritance, so
//! verctl reads only [`cargo metadata`].
//!
//! [`cargo metadata`]: https://doc.rust-lang.org/cargo/commands/cargo-metadata.html

use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::path::{Path, PathBuf};
use std::time::Duration;

use anyhow::{Context, Result};
use serde::Deserialize;
use toml_edit::DocumentMut;

use crate::process;

/// How long `cargo metadata --no-deps` may run. It reads only manifests.
const METADATA_TIMEOUT: Duration = Duration::from_mins(2);

/// A workspace member that publishes.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Member {
    /// The crate name.
    pub name: String,
    /// The version Cargo resolves for it.
    pub version: String,
    /// Its `Cargo.toml`.
    pub manifest: PathBuf,
    /// The registries its `publish` names. `None` when it names none, which
    /// lets it publish anywhere.
    pub publish: Option<Vec<String>>,
    /// Other published members of the same workspace that this member depends
    /// on through a publish-ordering dependency, sorted and without repeats.
    pub workspace_deps: Vec<String>,
}

/// Whether `manifest` is a virtual workspace manifest: a `[workspace]` table
/// and no `[package]` table.
///
/// # Errors
///
/// Returns an error when the manifest cannot be read or is not TOML.
pub fn is_virtual(manifest: &Path) -> Result<bool> {
    let raw = fs::read_to_string(manifest).with_context(|| manifest.display().to_string())?;
    let document = raw
        .parse::<DocumentMut>()
        .with_context(|| manifest.display().to_string())?;
    Ok(document.contains_key("workspace") && !document.contains_key("package"))
}

/// The members of the workspace at `manifest` that publish, each after the
/// published members it depends on.
///
/// A member with `publish = false` is left out. A normal or build dependency
/// orders publishes. So does a development dependency that declares a
/// version, because `cargo publish` keeps it. A path-only development
/// dependency does not, since `cargo publish` strips it. Members with no such
/// dependency between them keep the order of `workspace_members`. `--offline`
/// with `--no-deps` reads only manifests, so it never reaches a registry.
///
/// # Errors
///
/// Returns an error when `cargo metadata` fails or prints something other than
/// its JSON. It also returns an error when the dependencies that order
/// publishes form a cycle, which cargo cannot publish ([cargo issue 4242]).
///
/// [cargo issue 4242]: https://github.com/rust-lang/cargo/issues/4242
pub fn members(manifest: &Path) -> Result<Vec<Member>> {
    let path = manifest.display().to_string();
    let argv = process::argv(&[
        "cargo",
        "metadata",
        "--format-version",
        "1",
        "--no-deps",
        "--offline",
        "--manifest-path",
        &path,
    ]);
    let raw = process::run_limited(&argv, &[], METADATA_TIMEOUT)?;
    let metadata: Metadata = serde_json::from_str(&raw).context("cargo metadata output")?;
    in_publish_order(&metadata)
}

/// The version of every member of the workspace that contains `manifest`, by
/// crate name, published or not.
///
/// Cargo resolves member globs and `version.workspace = true`, so the Version
/// PR check reads each member's version here. `--offline` with `--no-deps`
/// reads only manifests, so the check never reaches a registry.
///
/// # Errors
///
/// Returns an error when `cargo metadata` fails or prints something other than
/// its JSON.
pub fn versions(manifest: &Path) -> Result<BTreeMap<String, String>> {
    let path = manifest.display().to_string();
    let argv = process::argv(&[
        "cargo",
        "metadata",
        "--format-version",
        "1",
        "--no-deps",
        "--offline",
        "--manifest-path",
        &path,
    ]);
    let raw = process::run_limited(&argv, &[], METADATA_TIMEOUT)?;
    let metadata: Metadata = serde_json::from_str(&raw).context("cargo metadata output")?;
    Ok(metadata
        .packages
        .into_iter()
        .filter(|package| metadata.workspace_members.contains(&package.id))
        .map(|package| (package.name, package.version))
        .collect())
}

/// The parts of `cargo metadata --format-version 1` this module reads.
#[derive(Deserialize)]
struct Metadata {
    packages: Vec<Package>,
    workspace_members: Vec<String>,
}

#[derive(Deserialize)]
struct Package {
    id: String,
    name: String,
    version: String,
    manifest_path: PathBuf,
    publish: Option<Vec<String>>,
    dependencies: Vec<Dependency>,
}

#[derive(Deserialize)]
struct Dependency {
    name: String,
    req: String,
    kind: Option<DependencyKind>,
}

/// Cargo's dependency kinds besides normal, which `cargo metadata` writes as
/// `null`.
#[derive(Deserialize, Clone, Copy)]
#[serde(rename_all = "lowercase")]
enum DependencyKind {
    Dev,
    Build,
}

impl Dependency {
    /// Whether `cargo publish` keeps this dependency, so its crate must be on
    /// the registry first. A path-only dependency has the requirement `*`.
    fn orders_publish(&self) -> bool {
        match self.kind {
            None | Some(DependencyKind::Build) => true,
            Some(DependencyKind::Dev) => self.req != "*",
        }
    }
}

/// Where a member stands in the depth-first walk that orders publishes.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Mark {
    Visiting,
    Done,
}

fn in_publish_order(metadata: &Metadata) -> Result<Vec<Member>> {
    let by_id: BTreeMap<&str, &Package> = metadata
        .packages
        .iter()
        .map(|package| (package.id.as_str(), package))
        .collect();
    let published: Vec<&Package> = metadata
        .workspace_members
        .iter()
        .filter_map(|id| by_id.get(id.as_str()).copied())
        .filter(|package| {
            package
                .publish
                .as_ref()
                .is_none_or(|names| !names.is_empty())
        })
        .collect();
    let index: BTreeMap<&str, usize> = published
        .iter()
        .enumerate()
        .map(|(at, package)| (package.name.as_str(), at))
        .collect();
    let edges: Vec<Vec<usize>> = published
        .iter()
        .map(|package| {
            package
                .dependencies
                .iter()
                .filter(|dependency| dependency.orders_publish())
                .filter_map(|dependency| index.get(dependency.name.as_str()).copied())
                .collect()
        })
        .collect();
    let mut marks = vec![None; published.len()];
    let mut path = Vec::new();
    let mut order = Vec::with_capacity(published.len());
    for start in 0..published.len() {
        visit(start, &edges, &mut marks, &mut path, &mut order).map_err(|cycle| {
            let names: Vec<&str> = cycle
                .iter()
                .map(|&at| published[at].name.as_str())
                .collect();
            anyhow::anyhow!(
                "workspace members depend on each other in a cycle, which cargo cannot publish: {}; a path-only development dependency breaks it",
                names.join(" -> ")
            )
        })?;
    }
    Ok(order
        .into_iter()
        .map(|at| {
            let package = published[at];
            let workspace_deps: Vec<String> = edges[at]
                .iter()
                .map(|&dep| published[dep].name.clone())
                .collect::<BTreeSet<_>>()
                .into_iter()
                .collect();
            Member {
                name: package.name.clone(),
                version: package.version.clone(),
                manifest: package.manifest_path.clone(),
                publish: package.publish.clone(),
                workspace_deps,
            }
        })
        .collect())
}

/// Append `at` to `order` after everything it depends on. On a cycle, return
/// it as member indices, first and last the same.
fn visit(
    at: usize,
    edges: &[Vec<usize>],
    marks: &mut [Option<Mark>],
    path: &mut Vec<usize>,
    order: &mut Vec<usize>,
) -> Result<(), Vec<usize>> {
    match marks[at] {
        Some(Mark::Done) => return Ok(()),
        Some(Mark::Visiting) => {
            let from = path.iter().position(|&on| on == at).unwrap_or_default();
            let mut cycle = path[from..].to_vec();
            cycle.push(at);
            return Err(cycle);
        }
        None => {}
    }
    marks[at] = Some(Mark::Visiting);
    path.push(at);
    for &next in &edges[at] {
        visit(next, edges, marks, path, order)?;
    }
    path.pop();
    marks[at] = Some(Mark::Done);
    order.push(at);
    Ok(())
}

#[cfg(test)]
mod tests {
    use std::fs;

    use indoc::indoc;
    use tempfile::TempDir;

    use super::{Metadata, in_publish_order, is_virtual, members};

    fn names(json: &str) -> Vec<String> {
        let metadata: Metadata = serde_json::from_str(json).unwrap();
        in_publish_order(&metadata)
            .unwrap()
            .into_iter()
            .map(|member| member.name)
            .collect()
    }

    #[test]
    fn a_dependent_listed_first_publishes_after_its_dependency() {
        let found = names(indoc! {r#"
            {
              "workspace_members": ["app", "core"],
              "packages": [
                {"id": "app", "name": "app", "version": "0.0.2", "manifest_path": "/w/app/Cargo.toml", "publish": null,
                 "dependencies": [{"name": "core", "req": "=0.0.2", "kind": null}]},
                {"id": "core", "name": "core", "version": "0.0.2", "manifest_path": "/w/core/Cargo.toml", "publish": null,
                 "dependencies": []}
              ]
            }
        "#});
        assert_eq!(found, ["core", "app"]);
    }

    #[test]
    fn a_path_only_dev_dependency_does_not_order_publishes() {
        let found = names(indoc! {r#"
            {
              "workspace_members": ["core", "app"],
              "packages": [
                {"id": "core", "name": "core", "version": "0.0.2", "manifest_path": "/w/core/Cargo.toml", "publish": null,
                 "dependencies": [{"name": "app", "req": "*", "kind": "dev"}]},
                {"id": "app", "name": "app", "version": "0.0.2", "manifest_path": "/w/app/Cargo.toml", "publish": null,
                 "dependencies": [{"name": "core", "req": "=0.0.2", "kind": null}]}
              ]
            }
        "#});
        assert_eq!(found, ["core", "app"]);
    }

    #[test]
    fn a_member_with_publish_false_is_left_out() {
        let found = names(indoc! {r#"
            {
              "workspace_members": ["core", "xtask"],
              "packages": [
                {"id": "core", "name": "core", "version": "0.0.2", "manifest_path": "/w/core/Cargo.toml", "publish": ["crates-io"],
                 "dependencies": []},
                {"id": "xtask", "name": "xtask", "version": "0.1.0", "manifest_path": "/w/xtask/Cargo.toml", "publish": [],
                 "dependencies": [{"name": "core", "req": "*", "kind": null}]}
              ]
            }
        "#});
        assert_eq!(found, ["core"]);
    }

    #[test]
    fn versioned_dev_dependencies_both_ways_are_a_cycle() {
        let metadata: Metadata = serde_json::from_str(indoc! {r#"
            {
              "workspace_members": ["a", "b"],
              "packages": [
                {"id": "a", "name": "a", "version": "0.1.0", "manifest_path": "/w/a/Cargo.toml", "publish": null,
                 "dependencies": [{"name": "b", "req": "^0.1", "kind": "dev"}]},
                {"id": "b", "name": "b", "version": "0.1.0", "manifest_path": "/w/b/Cargo.toml", "publish": null,
                 "dependencies": [{"name": "a", "req": "^0.1", "kind": "dev"}]}
              ]
            }
        "#})
        .unwrap();
        let error = in_publish_order(&metadata).unwrap_err();
        assert!(format!("{error:#}").contains("a -> b -> a"), "{error:#}");
    }

    /// The real `cargo metadata` resolves member globs, inherited versions,
    /// and `publish = false`.
    #[test]
    fn cargo_metadata_lists_the_publishing_members() {
        let root = TempDir::new().unwrap();
        let write = |path: &str, body: &str| {
            let path = root.path().join(path);
            fs::create_dir_all(path.parent().unwrap()).unwrap();
            fs::write(path, body).unwrap();
        };
        write(
            "Cargo.toml",
            indoc! {r#"
                [workspace]
                resolver = "3"
                members = ["crates/*"]

                [workspace.package]
                version = "0.0.2"
                edition = "2024"
            "#},
        );
        write(
            "crates/app/Cargo.toml",
            indoc! {r#"
                [package]
                name = "demo-app"
                version.workspace = true
                edition.workspace = true

                [dependencies]
                demo-core = { version = "=0.0.2", path = "../core" }
            "#},
        );
        write("crates/app/src/lib.rs", "");
        write(
            "crates/core/Cargo.toml",
            indoc! {r#"
                [package]
                name = "demo-core"
                version.workspace = true
                edition.workspace = true
            "#},
        );
        write("crates/core/src/lib.rs", "");
        write(
            "crates/xtask/Cargo.toml",
            indoc! {r#"
                [package]
                name = "xtask"
                version = "0.1.0"
                edition.workspace = true
                publish = false
            "#},
        );
        write("crates/xtask/src/main.rs", "fn main() {}");
        let manifest = root.path().join("Cargo.toml");
        assert!(is_virtual(&manifest).unwrap());
        assert!(!is_virtual(&root.path().join("crates/app/Cargo.toml")).unwrap());
        let found = members(&manifest).unwrap();
        let shown: Vec<(&str, &str)> = found
            .iter()
            .map(|member| (member.name.as_str(), member.version.as_str()))
            .collect();
        assert_eq!(shown, [("demo-core", "0.0.2"), ("demo-app", "0.0.2")]);
        assert_eq!(found[0].workspace_deps, Vec::<String>::new());
        assert_eq!(found[1].workspace_deps, ["demo-core"]);
    }
}