mitts 0.3.19

Rust-first build and package tooling with a shared artifact cache
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
/*
 * Mitts Build — Rust-first build and package tooling with shared artifact cache
 * Copyright (c) 2026 Alexander Panasenko
 *
 * Contact: alex@prod.codes
 * Author: https://prod.codes/about/
 * Project: https://github.com/alex09x/mitts
 * SPDX-License-Identifier: MIT OR Apache-2.0
 */

use anyhow::{Context, Result};
use serde::Deserialize;
use std::collections::HashMap;
use std::fs;
use std::path::Path;

/// Strongly typed representation of a Cargo.toml manifest.
#[derive(Debug, Clone, Deserialize, Default)]
pub struct CargoToml {
    pub package: Option<TomlPackage>,
    pub workspace: Option<TomlWorkspace>,
    pub lib: Option<TomlLib>,
    #[serde(default)]
    pub bin: Vec<TomlBin>,
    #[serde(default)]
    pub dependencies: HashMap<String, TomlDependency>,
    #[serde(default, rename = "build-dependencies")]
    pub build_dependencies: HashMap<String, TomlDependency>,
    #[serde(default, rename = "dev-dependencies", alias = "dev_dependencies")]
    pub dev_dependencies: HashMap<String, TomlDependency>,
    #[serde(default)]
    pub test: Vec<TomlTest>,
    #[serde(default)]
    pub example: Vec<TomlTest>,
    #[serde(default)]
    pub bench: Vec<TomlTest>,
    #[serde(default)]
    pub features: HashMap<String, Vec<String>>,
    #[serde(default)]
    pub target: HashMap<String, TomlTargetSpec>,
    #[serde(default)]
    pub lints: Option<toml::Value>,
    /// `[patch.<source>]` tables: source (`crates-io`, a registry name or URL) → package → override.
    #[serde(default)]
    pub patch: HashMap<String, HashMap<String, TomlDependency>>,
}

pub use super::manifest_models::*;

impl CargoToml {
    /// Parses Cargo.toml content from a string.
    pub fn parse(content: &str) -> Result<Self> {
        toml::from_str(content).context("Failed to parse Cargo.toml content")
    }

    /// Reads and parses a Cargo.toml file from disk.
    pub fn from_file(path: &Path) -> Result<Self> {
        super::manifest_snapshot::parse(path)
    }

    pub fn resolve_inherited_workspace_fields(&mut self, path: &Path) {
        super::manifest_inherit::resolve_inherited_workspace_fields(self, path);
    }

    /// Returns the effective Cargo feature resolver version ("1" or "2").
    pub fn effective_resolver(&self) -> &str {
        if let Some(ref ws) = self.workspace {
            if let Some(ref r) = ws.resolver {
                return r.as_str();
            }
        }
        if let Some(ref pkg) = self.package {
            if let Some(ref r) = pkg.resolver {
                return r.as_str();
            }
            if let Some(ref ed) = pkg.edition {
                if ed == "2021" || ed == "2024" {
                    return "2";
                }
            }
        }
        "1"
    }

    /// The values Cargo declares for `--check-cfg cfg(feature, values(...))`: every
    /// `[features]` key plus the implicit feature of each optional dependency that no
    /// feature names as `dep:<name>`, in the normal and the build-dependency tables and
    /// their target-specific forms. tonic's examples package gates on an optional
    /// build-dependency (`#[cfg(feature = "protoc-gen-rust-grpc")]` in build.rs); leaving
    /// the build tables out gave an `unexpected cfg` warning Cargo does not give.
    pub fn feature_check_cfg_values(&self) -> Vec<String> {
        let explicit: std::collections::HashSet<&str> = self
            .features
            .values()
            .flatten()
            .filter_map(|v| v.strip_prefix("dep:"))
            .collect();
        let mut values: Vec<String> = self.features.keys().cloned().collect();
        let tables = [&self.dependencies, &self.build_dependencies]
            .into_iter()
            .chain(
                self.target
                    .values()
                    .flat_map(|t| [&t.dependencies, &t.build_dependencies]),
            );
        for (name, dep) in tables.flatten() {
            let optional = matches!(dep, TomlDependency::Detailed(d) if d.optional == Some(true));
            if optional && !explicit.contains(name.as_str()) {
                values.push(name.clone());
            }
        }
        values.sort();
        values.dedup();
        values
    }

    /// Checks if this package defines or defaults to a build script.
    pub fn has_build_script(&self, pkg_dir: &Path) -> bool {
        if let Some(ref pkg) = self.package {
            if let Some(ref b) = pkg.build {
                return match b {
                    TomlBuild::Disabled(false) => false,
                    TomlBuild::Disabled(true) => pkg_dir.join("build.rs").is_file(),
                    TomlBuild::Path(ref p) => pkg_dir.join(p).is_file(),
                };
            }
        }
        pkg_dir.join("build.rs").is_file()
    }

    /// Extracts bidirectional mappings between dependency aliases and real package names.
    pub fn dependency_aliases(&self) -> DependencyAliases {
        let mut res = DependencyAliases::default();
        let mut record = |alias: &str, dep: &TomlDependency| {
            if let TomlDependency::Detailed(ref d) = dep {
                if let Some(ref real) = d.package_name {
                    res.alias_to_real.insert(alias.to_string(), real.clone());
                    res.alias_to_real
                        .insert(alias.replace('-', "_"), real.clone());
                    res.real_to_aliases
                        .entry(real.clone())
                        .or_default()
                        .push((alias.to_string(), d.version.clone()));
                    let norm = real.replace('-', "_");
                    if norm != *real {
                        res.real_to_aliases
                            .entry(norm)
                            .or_default()
                            .push((alias.to_string(), d.version.clone()));
                    }
                }
            }
        };
        for (alias, dep) in &self.dependencies {
            record(alias, dep);
        }
        for (alias, dep) in &self.build_dependencies {
            record(alias, dep);
        }
        for (alias, dep) in &self.dev_dependencies {
            record(alias, dep);
        }
        for target_spec in self.target.values() {
            for (alias, dep) in &target_spec.dependencies {
                record(alias, dep);
            }
            for (alias, dep) in &target_spec.build_dependencies {
                record(alias, dep);
            }
            for (alias, dep) in &target_spec.dev_dependencies {
                record(alias, dep);
            }
        }
        res
    }

    /// Checks if the manifest has a direct, unaliased dependency with the given package name,
    /// optionally matching a resolved version requirement.
    pub fn has_direct_dep_named(&self, pkg_name: &str, dep_version: Option<&str>) -> bool {
        let norm = pkg_name.replace('-', "_");
        let matches_dep = |alias: &str, dep: &TomlDependency| -> bool {
            let alias_norm = alias.replace('-', "_");
            if alias_norm != norm {
                return false;
            }
            match dep {
                TomlDependency::Simple(req_str) => {
                    if let Some(ver_str) = dep_version {
                        match (
                            semver::VersionReq::parse(req_str),
                            semver::Version::parse(ver_str),
                        ) {
                            (Ok(req), Ok(ver)) => req.matches(&ver),
                            _ => ver_str.starts_with(req_str) || req_str == ver_str,
                        }
                    } else {
                        true
                    }
                }
                TomlDependency::Detailed(d) => {
                    let is_unaliased = match d.package_name {
                        None => true,
                        Some(ref p) => p.replace('-', "_") == norm,
                    };
                    if !is_unaliased {
                        return false;
                    }
                    if let (Some(req_str), Some(ver_str)) = (&d.version, dep_version) {
                        match (
                            semver::VersionReq::parse(req_str),
                            semver::Version::parse(ver_str),
                        ) {
                            (Ok(req), Ok(ver)) => req.matches(&ver),
                            _ => ver_str.starts_with(req_str) || req_str == ver_str,
                        }
                    } else {
                        true
                    }
                }
            }
        };

        for (alias, dep) in &self.dependencies {
            if matches_dep(alias, dep) {
                return true;
            }
        }
        for (alias, dep) in &self.build_dependencies {
            if matches_dep(alias, dep) {
                return true;
            }
        }
        for (alias, dep) in &self.dev_dependencies {
            if matches_dep(alias, dep) {
                return true;
            }
        }
        for target_spec in self.target.values() {
            for (alias, dep) in &target_spec.dependencies {
                if matches_dep(alias, dep) {
                    return true;
                }
            }
            for (alias, dep) in &target_spec.build_dependencies {
                if matches_dep(alias, dep) {
                    return true;
                }
            }
            for (alias, dep) in &target_spec.dev_dependencies {
                if matches_dep(alias, dep) {
                    return true;
                }
            }
        }
        false
    }

    /// Discovers all compilation targets (lib, bin, proc-macro) in this package.
    pub fn discover_targets(&self, pkg_dir: &Path) -> Vec<DiscoveredTarget> {
        let mut targets = Vec::new();
        let pkg_name = self.package.as_ref().map(|p| p.name.as_str()).unwrap_or("");
        let edition = self.package.as_ref().and_then(|p| p.edition.clone());

        // 1. Library target
        if let Some(ref lib) = self.lib {
            let lib_name = lib
                .name
                .clone()
                .unwrap_or_else(|| pkg_name.replace('-', "_"));
            let src = match lib.path {
                Some(ref p) => pkg_dir.join(p),
                None => pkg_dir.join("src").join("lib.rs"),
            };
            let kind = if lib.proc_macro.unwrap_or(false) {
                "proc-macro".to_string()
            } else {
                "lib".to_string()
            };
            let crate_types = if !lib.crate_type.is_empty() {
                lib.crate_type.clone()
            } else {
                vec![kind.clone()]
            };
            if src.is_file() {
                targets.push(DiscoveredTarget {
                    name: lib_name,
                    kind,
                    src_path: src,
                    edition: edition.clone(),
                    crate_types,
                    required_features: None,
                    harness: self.lib.as_ref().and_then(|l| l.harness).unwrap_or(true),
                    test_role: None,
                    explicit_only: false,
                });
            }
        } else {
            let default_lib = pkg_dir.join("src").join("lib.rs");
            if default_lib.is_file() {
                targets.push(DiscoveredTarget {
                    name: pkg_name.replace('-', "_"),
                    kind: "lib".to_string(),
                    src_path: default_lib,
                    edition: edition.clone(),
                    crate_types: vec!["lib".to_string()],
                    required_features: None,
                    harness: true,
                    test_role: None,
                    explicit_only: false,
                });
            }
        }

        // 2. Binary targets
        if !self.bin.is_empty() {
            for b in &self.bin {
                let src = match b.path {
                    Some(ref p) => pkg_dir.join(p),
                    None => {
                        let candidate1 = pkg_dir
                            .join("src")
                            .join("bin")
                            .join(format!("{}.rs", b.name));
                        let candidate2 = pkg_dir
                            .join("src")
                            .join("bin")
                            .join(&b.name)
                            .join("main.rs");
                        if candidate1.is_file() {
                            candidate1
                        } else if candidate2.is_file() {
                            // Cargo's second inferred location for a named binary.
                            candidate2
                        } else {
                            pkg_dir.join("src").join("main.rs")
                        }
                    }
                };
                if src.is_file() {
                    targets.push(DiscoveredTarget {
                        name: b.name.clone(),
                        kind: "bin".to_string(),
                        src_path: src,
                        edition: edition.clone(),
                        crate_types: vec!["bin".to_string()],
                        required_features: b.required_features.clone(),
                        harness: b.harness.unwrap_or(true),
                        test_role: None,
                        explicit_only: false,
                    });
                }
            }
        } else {
            let default_main = pkg_dir.join("src").join("main.rs");
            if default_main.is_file() && !pkg_name.is_empty() {
                targets.push(DiscoveredTarget {
                    name: pkg_name.to_string(),
                    kind: "bin".to_string(),
                    src_path: default_main,
                    edition: edition.clone(),
                    crate_types: vec!["bin".to_string()],
                    required_features: None,
                    harness: true,
                    test_role: None,
                    explicit_only: false,
                });
            }

            // Check autobins
            let autobins = self
                .package
                .as_ref()
                .and_then(|p| p.autobins)
                .unwrap_or(true);
            if autobins {
                let bin_dir = pkg_dir.join("src").join("bin");
                if let Ok(entries) = fs::read_dir(&bin_dir) {
                    for entry in entries.flatten() {
                        let path = entry.path();
                        if path.is_file() && path.extension().and_then(|e| e.to_str()) == Some("rs")
                        {
                            if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
                                targets.push(DiscoveredTarget {
                                    name: stem.to_string(),
                                    kind: "bin".to_string(),
                                    src_path: path,
                                    edition: edition.clone(),
                                    crate_types: vec!["bin".to_string()],
                                    required_features: None,
                                    harness: true,
                                    test_role: None,
                                    explicit_only: false,
                                });
                            }
                        } else if path.is_dir() {
                            let main_rs = path.join("main.rs");
                            if main_rs.is_file() {
                                if let Some(dir_name) = path.file_name().and_then(|s| s.to_str()) {
                                    targets.push(DiscoveredTarget {
                                        name: dir_name.to_string(),
                                        kind: "bin".to_string(),
                                        src_path: main_rs,
                                        edition: edition.clone(),
                                        crate_types: vec!["bin".to_string()],
                                        required_features: None,
                                        harness: true,
                                        test_role: None,
                                        explicit_only: false,
                                    });
                                }
                            }
                        }
                    }
                }
            }
        }

        targets
    }
}