verctl-core 0.9.6

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
427
428
429
430
431
432
433
434
use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::fs;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result, bail, ensure};
use cargo_config2::Config as CargoConfig;
use cargo_toml::{Dependency as TomlDependency, Manifest, Package as TomlPackage, Publish};
use glob::Pattern;
use toml_edit::{DocumentMut, Item};

use super::{Dependency, DependencyScope, Metadata, Package, Target};

pub(super) fn read_workspace(manifest: &Path) -> Result<Metadata> {
    let canonical_manifest = manifest
        .canonicalize()
        .with_context(|| format!("resolve {}", manifest.display()))?;
    let entry_dir = canonical_manifest
        .parent()
        .with_context(|| format!("manifest {} has no parent", canonical_manifest.display()))?
        .to_path_buf();
    let entry_manifest = load_raw_manifest(&canonical_manifest)?;

    let (workspace_root, root_manifest) =
        find_workspace_root(&entry_dir, &canonical_manifest, entry_manifest)?;
    let target_directory = target_directory_of(&workspace_root)?;

    let (packages, workspace_members) = if let Some(ws_manifest) = root_manifest {
        let (packages, workspace_members) = load_workspace_members(&workspace_root, &ws_manifest)?;
        if entry_dir != workspace_root {
            ensure!(
                packages
                    .iter()
                    .any(|pkg| pkg.manifest_path == canonical_manifest),
                "current package {} believes it is in workspace {}, which does not include it",
                canonical_manifest.display(),
                workspace_root.join("Cargo.toml").display()
            );
        }
        (packages, workspace_members)
    } else {
        let pkg = load_package(&canonical_manifest, None)?;
        let id = pkg.id.clone();
        (vec![pkg], vec![id])
    };

    Ok(Metadata {
        workspace_root,
        target_directory,
        packages,
        workspace_members,
    })
}

fn load_raw_manifest(path: &Path) -> Result<Manifest> {
    let bytes = fs::read(path).with_context(|| format!("read {}", path.display()))?;
    Manifest::from_slice(&bytes).with_context(|| format!("parse {}", path.display()))
}

fn find_workspace_root(
    entry_dir: &Path,
    entry_manifest_path: &Path,
    entry_manifest: Manifest,
) -> Result<(PathBuf, Option<Manifest>)> {
    if entry_manifest.workspace.is_some() {
        return Ok((entry_dir.to_path_buf(), Some(entry_manifest)));
    }
    if let Some(ws_rel) = entry_manifest
        .package
        .as_ref()
        .and_then(|pkg| pkg.workspace.as_deref())
    {
        let ws_dir = entry_dir
            .join(ws_rel)
            .canonicalize()
            .with_context(|| format!("resolve package.workspace {}", ws_rel.display()))?;
        let ws_manifest = load_raw_manifest(&ws_dir.join("Cargo.toml"))?;
        ensure!(
            ws_manifest.workspace.is_some(),
            "{} declared package.workspace = {}, but {} has no [workspace]",
            entry_manifest_path.display(),
            ws_rel.display(),
            ws_dir.join("Cargo.toml").display()
        );
        return Ok((ws_dir, Some(ws_manifest)));
    }
    for ancestor in entry_dir.ancestors().skip(1) {
        let candidate_path = ancestor.join("Cargo.toml");
        if !candidate_path.is_file() {
            continue;
        }
        let candidate = load_raw_manifest(&candidate_path)?;
        if let Some(ws) = &candidate.workspace {
            if is_excluded(ancestor, &ws.exclude, entry_dir) {
                return Ok((entry_dir.to_path_buf(), None));
            }
            return Ok((ancestor.to_path_buf(), Some(candidate)));
        }
    }
    Ok((entry_dir.to_path_buf(), None))
}

fn load_workspace_members(
    ws_root: &Path,
    ws_manifest: &Manifest,
) -> Result<(Vec<Package>, Vec<String>)> {
    let ws = ws_manifest
        .workspace
        .as_ref()
        .context("expected [workspace] table")?;
    let mut member_dirs = Vec::new();
    let mut seen = BTreeSet::new();

    if ws_manifest.package.is_some() {
        let canonical = ws_root
            .canonicalize()
            .unwrap_or_else(|_| ws_root.to_path_buf());
        if seen.insert(canonical.clone()) {
            member_dirs.push(canonical);
        }
    }

    for pattern in &ws.members {
        let trimmed = pattern.trim_end_matches('/');
        if trimmed.contains(['*', '?', '[']) {
            let root_str = ws_root
                .to_str()
                .with_context(|| format!("non-UTF-8 workspace root {}", ws_root.display()))?;
            let pattern_str = format!("{}/{trimmed}", Pattern::escape(root_str));
            let mut matched = Vec::new();
            for entry in
                glob::glob(&pattern_str).with_context(|| format!("glob {pattern_str:?}"))?
            {
                let path = entry.with_context(|| format!("expand glob {pattern_str:?}"))?;
                if path.join("Cargo.toml").is_file() {
                    let canonical = path.canonicalize().unwrap_or(path);
                    matched.push(canonical);
                }
            }
            matched.sort();
            for dir in matched {
                if !is_excluded(ws_root, &ws.exclude, &dir) && seen.insert(dir.clone()) {
                    member_dirs.push(dir);
                }
            }
        } else {
            let dir = ws_root.join(trimmed);
            let manifest_path = dir.join("Cargo.toml");
            ensure!(
                manifest_path.is_file(),
                "workspace member {trimmed:?} has no Cargo.toml at {}",
                manifest_path.display()
            );
            let canonical = dir.canonicalize().unwrap_or(dir);
            if seen.insert(canonical.clone()) {
                member_dirs.push(canonical);
            }
        }
    }

    let mut packages = Vec::new();
    let mut workspace_members = Vec::new();
    let mut queue: VecDeque<PathBuf> = member_dirs.into_iter().collect();

    while let Some(dir) = queue.pop_front() {
        let manifest_path = dir.join("Cargo.toml");
        let workspace_ctx = if dir == ws_root {
            None
        } else {
            Some((ws_manifest, ws_root))
        };
        let (pkg, path_deps) = load_package_with_paths(&manifest_path, workspace_ctx)?;
        workspace_members.push(pkg.id.clone());
        packages.push(pkg);

        for dep_path in path_deps {
            let Ok(canonical) = dep_path.canonicalize() else {
                continue;
            };
            if !canonical.starts_with(ws_root)
                || is_excluded(ws_root, &ws.exclude, &canonical)
                || seen.contains(&canonical)
            {
                continue;
            }
            let dep_manifest_path = canonical.join("Cargo.toml");
            if !dep_manifest_path.is_file() {
                continue;
            }
            let dep_manifest = load_raw_manifest(&dep_manifest_path)?;
            if dep_manifest.workspace.is_some() {
                continue;
            }
            if seen.insert(canonical.clone()) {
                queue.push_back(canonical);
            }
        }
    }

    Ok((packages, workspace_members))
}

fn is_excluded(ws_root: &Path, exclude: &[String], candidate_dir: &Path) -> bool {
    let Ok(rel) = candidate_dir.strip_prefix(ws_root) else {
        return false;
    };
    let rel_str = rel.to_string_lossy().replace('\\', "/");
    exclude.iter().any(|raw| {
        let pat = raw.trim_end_matches('/');
        if rel == Path::new(pat) || rel.starts_with(Path::new(pat)) {
            return true;
        }
        Pattern::new(pat).is_ok_and(|compiled| compiled.matches(&rel_str))
    })
}

fn load_package(manifest_path: &Path, workspace: Option<(&Manifest, &Path)>) -> Result<Package> {
    let (pkg, _) = load_package_with_paths(manifest_path, workspace)?;
    Ok(pkg)
}

fn load_package_with_paths(
    manifest_path: &Path,
    workspace: Option<(&Manifest, &Path)>,
) -> Result<(Package, Vec<PathBuf>)> {
    let raw = fs::read_to_string(manifest_path)
        .with_context(|| format!("read {}", manifest_path.display()))?;
    let mut manifest = Manifest::from_slice(raw.as_bytes())
        .with_context(|| format!("parse {}", manifest_path.display()))?;
    manifest
        .complete_from_path_and_workspace(manifest_path, workspace)
        .with_context(|| format!("complete manifest {}", manifest_path.display()))?;
    let Some(package) = manifest.package.as_ref() else {
        bail!("{} has no [package] table", manifest_path.display());
    };
    let version = package
        .version
        .get()
        .with_context(|| format!("resolve version in {}", manifest_path.display()))?
        .to_string();
    let publish = resolve_publish(&raw, package, &version, manifest_path)?;
    let member_dir = manifest_path.parent().unwrap_or_else(|| Path::new("."));
    let mut dependencies = Vec::new();
    let mut path_deps = Vec::new();
    collect_deps(
        &manifest.dependencies,
        None,
        member_dir,
        &mut dependencies,
        &mut path_deps,
    );
    collect_deps(
        &manifest.build_dependencies,
        Some(DependencyScope::Build),
        member_dir,
        &mut dependencies,
        &mut path_deps,
    );
    collect_deps(
        &manifest.dev_dependencies,
        Some(DependencyScope::Dev),
        member_dir,
        &mut dependencies,
        &mut path_deps,
    );
    for target in manifest.target.values() {
        collect_deps(
            &target.dependencies,
            None,
            member_dir,
            &mut dependencies,
            &mut path_deps,
        );
        collect_deps(
            &target.build_dependencies,
            Some(DependencyScope::Build),
            member_dir,
            &mut dependencies,
            &mut path_deps,
        );
        collect_deps(
            &target.dev_dependencies,
            Some(DependencyScope::Dev),
            member_dir,
            &mut dependencies,
            &mut path_deps,
        );
    }

    let features = effective_features(&manifest);
    let targets = extract_targets(&manifest, &package.name);
    let id = format!("{}#{}", manifest_path.display(), package.name);

    Ok((
        Package {
            id,
            name: package.name.clone(),
            version,
            manifest_path: manifest_path.to_path_buf(),
            publish,
            dependencies,
            features,
            targets,
        },
        path_deps,
    ))
}

fn resolve_publish(
    raw: &str,
    package: &TomlPackage,
    version: &str,
    manifest_path: &Path,
) -> Result<Option<Vec<String>>> {
    let resolved = package
        .publish
        .get()
        .with_context(|| format!("resolve publish in {}", manifest_path.display()))?;
    match resolved {
        Publish::Flag(true) => Ok(None),
        Publish::Registry(registries) => Ok(Some(registries.clone())),
        Publish::Flag(false) => {
            if version == "0.0.0" && explicit_version_without_publish_key(raw) {
                Ok(None)
            } else {
                Ok(Some(Vec::new()))
            }
        }
    }
}

fn explicit_version_without_publish_key(raw: &str) -> bool {
    let Ok(doc) = raw.parse::<DocumentMut>() else {
        return false;
    };
    let Some(pkg) = doc.get("package").and_then(Item::as_table_like) else {
        return false;
    };
    pkg.contains_key("version") && !pkg.contains_key("publish")
}

fn collect_deps(
    table: &BTreeMap<String, TomlDependency>,
    scope: Option<DependencyScope>,
    member_dir: &Path,
    out: &mut Vec<Dependency>,
    path_deps: &mut Vec<PathBuf>,
) {
    for (key, dep) in table {
        let name = dep.package().unwrap_or(key).to_owned();
        let req = match dep {
            TomlDependency::Simple(req) => req.to_string(),
            TomlDependency::Detailed(detail) => {
                if let Some(rel) = detail.path.as_deref() {
                    path_deps.push(member_dir.join(rel));
                }
                detail
                    .version
                    .as_ref()
                    .map_or_else(|| "*".to_owned(), ToString::to_string)
            }
            TomlDependency::Inherited(_) => "*".to_owned(),
        };
        out.push(Dependency { name, req, scope });
    }
}

fn effective_features(manifest: &Manifest) -> BTreeMap<String, Vec<String>> {
    let mut features = manifest.features.clone();
    let explicit_dep_refs: BTreeSet<&str> = manifest
        .features
        .values()
        .flatten()
        .filter_map(|entry| entry.strip_prefix("dep:"))
        .collect();
    let all_deps = manifest
        .dependencies
        .iter()
        .chain(manifest.build_dependencies.iter())
        .chain(manifest.target.values().flat_map(|target| {
            target
                .dependencies
                .iter()
                .chain(target.build_dependencies.iter())
        }));
    for (key, dep) in all_deps {
        if dep.optional()
            && !explicit_dep_refs.contains(key.as_str())
            && !features.contains_key(key)
        {
            features.insert(key.clone(), vec![format!("dep:{key}")]);
        }
    }
    features
}

fn extract_targets(manifest: &Manifest, package_name: &str) -> Vec<Target> {
    let mut targets = Vec::new();
    if let Some(lib) = &manifest.lib {
        let name = lib
            .name
            .clone()
            .unwrap_or_else(|| package_name.replace('-', "_"));
        let target_modes = if lib.proc_macro {
            vec!["proc-macro".to_owned()]
        } else if !lib.crate_type.is_empty() {
            lib.crate_type.clone()
        } else {
            vec!["lib".to_owned()]
        };
        targets.push(Target { name, target_modes });
    }
    for bin in &manifest.bin {
        let name = bin.name.clone().unwrap_or_else(|| package_name.to_owned());
        targets.push(Target {
            name,
            target_modes: vec!["bin".to_owned()],
        });
    }
    targets
}

fn target_directory_of(workspace_root: &Path) -> Result<PathBuf> {
    let cfg = CargoConfig::load_with_cwd(workspace_root)
        .with_context(|| format!("load Cargo config from {}", workspace_root.display()))?;
    let dir = cfg
        .build
        .target_dir
        .unwrap_or_else(|| workspace_root.join("target"));
    Ok(if dir.is_absolute() {
        dir
    } else {
        workspace_root.join(dir)
    })
}