mitts 0.3.26

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
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
/*
 * 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 super::manifest::{CargoToml, TomlBuild, TomlDependency};
use super::target_filter::is_target_cfg_incompatible_with_target;
use super::types::RustAdapterError;
use std::collections::HashMap;
use std::path::Path;

/// Per-pass memoization table for `(target_spec, for_host)` target-cfg compatibility checks.
pub type TargetCfgCache = HashMap<(String, bool), Result<bool, RustAdapterError>>;

fn eval_target_cfg_incompat(
    target_spec: &str,
    for_host: bool,
    explicit_target: Option<&str>,
    start_dir: &Path,
    cache: &mut TargetCfgCache,
) -> Result<bool, RustAdapterError> {
    let key = (target_spec.to_string(), for_host);
    if let Some(res) = cache.get(&key) {
        return res.clone();
    }
    let res =
        is_target_cfg_incompatible_with_target(target_spec, for_host, explicit_target, start_dir);
    cache.insert(key, res.clone());
    res
}

/// Parses a dependency spec string from `Cargo.lock` into `(name, version, source)`:
/// - `"foo"` -> `("foo", None, None)`
/// - `"foo 1.0.0"` -> `("foo", Some("1.0.0"), None)`
/// - `"foo 1.0.0 (registry+https://...)"` -> `("foo", Some("1.0.0"), Some("registry+https://..."))`
pub fn parse_package_spec(spec: &str) -> (&str, Option<&str>, Option<&str>) {
    let s = spec.trim();
    let Some((name, after_name)) = s.split_once(char::is_whitespace) else {
        return (s, None, None);
    };
    let after_name = after_name.trim_start();
    if after_name.is_empty() {
        return (name, None, None);
    }
    let Some((version, after_ver)) = after_name.split_once(char::is_whitespace) else {
        return (name, Some(after_name), None);
    };
    let after_ver = after_ver.trim();
    let source = after_ver
        .strip_prefix('(')
        .and_then(|inner| inner.strip_suffix(')'))
        .or(if after_ver.is_empty() {
            None
        } else {
            Some(after_ver)
        });
    (name, Some(version), source)
}

/// Resolves a `Cargo.lock` dependency spec `(req_ver, req_src)` against same-name
/// candidates using `(version, source)`. Order: exact `(ver, src)` -> unique local
/// (`source == None`) when only `req_ver` is set -> unique `parent_source` match when
/// all candidates share one version -> `Err` on ambiguity. Pass `fail_on_no_match = true`
/// ONLY when `candidates` is the full unfiltered `Cargo.lock` list for that crate name.
pub fn resolve_candidate_by_spec<'a, T, F>(
    candidates: &'a [T],
    get_ver_src: F,
    req_ver: Option<&str>,
    req_src: Option<&str>,
    parent_source: Option<&str>,
    fail_on_no_match: bool,
    dep_label: &str,
) -> Result<Option<usize>, String>
where
    F: Fn(&'a T) -> (&'a str, Option<&'a str>),
{
    // A lock dependency spec names a git source without its pinned commit
    // (`git+https://…/libc?branch=libc-0.2`) while the package entry carries it
    // (`…?branch=libc-0.2#<sha>`): Cargo writes the spec "without precise". Sources
    // compare with that fragment dropped on both sides (mio patches libc this way).
    let matches: Vec<usize> = candidates
        .iter()
        .enumerate()
        .filter_map(|(idx, cand)| {
            let (ver, src) = get_ver_src(cand);
            (req_ver.is_none_or(|v| ver == v)
                && req_src.is_none_or(|s| {
                    src.map(source_without_precise) == Some(source_without_precise(s))
                }))
            .then_some(idx)
        })
        .collect();
    match matches.len() {
        0 => {
            if fail_on_no_match && !candidates.is_empty() {
                Err(format!(
                    "Unresolved dependency specification '{}' in Cargo.lock (0 of {} candidates matched version={:?} source={:?})",
                    dep_label,
                    candidates.len(),
                    req_ver,
                    req_src
                ))
            } else {
                Ok(None)
            }
        }
        1 => Ok(Some(matches[0])),
        _ => {
            if req_ver.is_some() && req_src.is_none() {
                let local_only: Vec<usize> = matches
                    .iter()
                    .copied()
                    .filter(|&i| get_ver_src(&candidates[i]).1.is_none())
                    .collect();
                if local_only.len() == 1 {
                    return Ok(Some(local_only[0]));
                }
            } else if req_ver.is_none()
                && req_src.is_none()
                && matches.iter().all(|&i| {
                    get_ver_src(&candidates[i]).0 == get_ver_src(&candidates[matches[0]]).0
                })
            {
                if let Some(ps) = parent_source {
                    let same_src: Vec<usize> = matches
                        .iter()
                        .copied()
                        .filter(|&i| {
                            get_ver_src(&candidates[i]).1.map(source_without_precise)
                                == Some(source_without_precise(ps))
                        })
                        .collect();
                    if same_src.len() == 1 {
                        return Ok(Some(same_src[0]));
                    }
                }
            }
            Err(format!(
                "Ambiguous dependency specification '{}' in Cargo.lock ({} matching packages found; specify version and source)",
                dep_label,
                matches.len()
            ))
        }
    }
}

/// A lock source without its `#<commit>` fragment: the form Cargo writes in a dependency
/// spec, while the package entry keeps the pinned commit.
pub fn source_without_precise(source: &str) -> &str {
    source.split('#').next().unwrap_or(source)
}

pub fn semver_or_prefix_matches(req_str: &str, ver_str: &str) -> bool {
    if let (Ok(req), Ok(ver)) = (
        semver::VersionReq::parse(req_str),
        semver::Version::parse(ver_str),
    ) {
        req.matches(&ver)
    } else {
        ver_str.starts_with(req_str) || req_str == ver_str
    }
}

fn dep_name_matches<'a>(
    alias: &'a str,
    d: &'a TomlDependency,
    dep_name: &str,
    clean: &str,
) -> Option<&'a str> {
    let (real_name, has_custom_pkg) = match d {
        TomlDependency::Simple(_) => (alias, false),
        TomlDependency::Detailed(dt) => (
            dt.package_name.as_deref().unwrap_or(alias),
            dt.package_name.is_some(),
        ),
    };
    let ok = if has_custom_pkg {
        real_name == dep_name || real_name.replace('-', "_") == clean
    } else {
        alias == dep_name
            || alias.replace('-', "_") == clean
            || real_name == dep_name
            || real_name.replace('-', "_") == clean
    };
    ok.then_some(real_name)
}

fn dep_ver_req(d: &TomlDependency) -> Option<&str> {
    match d {
        TomlDependency::Simple(req) => Some(req.as_str()),
        TomlDependency::Detailed(dt) => dt.version.as_deref(),
    }
}

fn has_matching_ver_decl(pkg_toml: &CargoToml, dep_name: &str, clean: &str, ver: &str) -> bool {
    let in_map = |m: &HashMap<String, TomlDependency>| {
        m.iter().any(|(alias, d)| {
            dep_name_matches(alias, d, dep_name, clean).is_some()
                && dep_ver_req(d).is_some_and(|req| semver_or_prefix_matches(req, ver))
        })
    };
    in_map(&pkg_toml.dependencies)
        || in_map(&pkg_toml.build_dependencies)
        || in_map(&pkg_toml.dev_dependencies)
        || pkg_toml.target.values().any(|t| {
            in_map(&t.dependencies) || in_map(&t.build_dependencies) || in_map(&t.dev_dependencies)
        })
}

#[allow(clippy::too_many_arguments)]
fn any_active_manifest_dep<F>(
    pkg_toml: &CargoToml,
    dep_spec_or_name: &str,
    include_build: bool,
    is_test: bool,
    explicit_target: Option<&str>,
    start_dir: &Path,
    cfg_cache: &mut TargetCfgCache,
    extra_check: F,
) -> Result<bool, RustAdapterError>
where
    F: Fn(&str, &str, &str, &TomlDependency) -> bool,
{
    let (dep_name, dep_ver, _) = parse_package_spec(dep_spec_or_name);
    let clean = dep_name.replace('-', "_");
    let enforce_ver =
        dep_ver.is_some_and(|ver| has_matching_ver_decl(pkg_toml, dep_name, &clean, ver));
    let check_dep = |alias: &str, d: &TomlDependency| -> bool {
        let Some(real_name) = dep_name_matches(alias, d, dep_name, &clean) else {
            return false;
        };
        if enforce_ver
            && !dep_ver_req(d).is_none_or(|req| semver_or_prefix_matches(req, dep_ver.unwrap()))
        {
            return false;
        }
        extra_check(alias, real_name, &clean, d)
    };

    if pkg_toml.dependencies.iter().any(|(a, d)| check_dep(a, d)) {
        return Ok(true);
    }
    if include_build
        && pkg_toml
            .build_dependencies
            .iter()
            .any(|(a, d)| check_dep(a, d))
    {
        return Ok(true);
    }
    for (target_spec, target) in &pkg_toml.target {
        let is_target_incompat =
            eval_target_cfg_incompat(target_spec, false, explicit_target, start_dir, cfg_cache)?;
        let is_host_incompat =
            eval_target_cfg_incompat(target_spec, true, explicit_target, start_dir, cfg_cache)?;
        if !is_target_incompat && target.dependencies.iter().any(|(a, d)| check_dep(a, d)) {
            return Ok(true);
        }
        if include_build
            && !is_host_incompat
            && target
                .build_dependencies
                .iter()
                .any(|(a, d)| check_dep(a, d))
        {
            return Ok(true);
        }
        if is_test
            && !is_target_incompat
            && target.dev_dependencies.iter().any(|(a, d)| check_dep(a, d))
        {
            return Ok(true);
        }
    }
    if is_test
        && pkg_toml
            .dev_dependencies
            .iter()
            .any(|(a, d)| check_dep(a, d))
    {
        return Ok(true);
    }
    Ok(false)
}

/// Checks if a package manifest has an active dependency on `dep_name`,
/// filtering out inactive optional dependencies, foreign target cfgs, and dev-dependencies for non-test units.
pub fn has_active_dependency(
    pkg_toml: &CargoToml,
    dep_name: &str,
    unit_features: &[String],
    is_test: bool,
    has_build_script: bool,
    explicit_target: Option<&str>,
    start_dir: &Path,
) -> Result<bool, RustAdapterError> {
    let mut cache = TargetCfgCache::new();
    has_active_dependency_cached(
        pkg_toml,
        dep_name,
        unit_features,
        is_test,
        has_build_script,
        explicit_target,
        start_dir,
        &mut cache,
    )
}

/// Memoized variant of [`has_active_dependency`] reusing a [`TargetCfgCache`] across units.
#[allow(clippy::too_many_arguments)]
pub fn has_active_dependency_cached(
    pkg_toml: &CargoToml,
    dep_name: &str,
    unit_features: &[String],
    is_test: bool,
    has_build_script: bool,
    explicit_target: Option<&str>,
    start_dir: &Path,
    cfg_cache: &mut TargetCfgCache,
) -> Result<bool, RustAdapterError> {
    any_active_manifest_dep(
        pkg_toml,
        dep_name,
        has_build_script,
        is_test,
        explicit_target,
        start_dir,
        cfg_cache,
        |alias, real_name, clean, d| {
            let is_optional = match d {
                TomlDependency::Simple(_) => false,
                TomlDependency::Detailed(dt) => dt.optional.unwrap_or(false),
            };
            if !is_optional {
                return true;
            }
            if unit_features
                .iter()
                .any(|f| f == alias || f.replace('-', "_") == clean || f == real_name)
            {
                return true;
            }
            for f in unit_features {
                if let Some(sub_feats) = pkg_toml.features.get(f) {
                    for sub in sub_feats {
                        let sub_dep = sub.strip_prefix("dep:").unwrap_or(sub);
                        let sub_crate = sub_dep.split('/').next().unwrap_or(sub_dep);
                        if sub_crate.ends_with('?') {
                            continue;
                        }
                        let sub_clean = sub_crate.replace('-', "_");
                        if sub_crate == alias || sub_clean == clean || sub_crate == real_name {
                            return true;
                        }
                    }
                }
            }
            false
        },
    )
}

/// Checks if a package manifest declares `dep_name` in any dependency section:
/// `[dependencies]`, `[build-dependencies]`, or `[target.*.dependencies]`
/// (or `[dev-dependencies]` if `is_test` is true), failing closed on cfg discovery errors.
pub fn is_declared_dependency(
    pkg_toml: &CargoToml,
    dep_name: &str,
    is_test: bool,
    explicit_target: Option<&str>,
    start_dir: &Path,
) -> Result<bool, RustAdapterError> {
    let mut cache = TargetCfgCache::new();
    is_declared_dependency_cached(
        pkg_toml,
        dep_name,
        is_test,
        explicit_target,
        start_dir,
        &mut cache,
    )
}

/// Memoized variant of [`is_declared_dependency`] reusing a [`TargetCfgCache`] across packages.
pub fn is_declared_dependency_cached(
    pkg_toml: &CargoToml,
    dep_name: &str,
    is_test: bool,
    explicit_target: Option<&str>,
    start_dir: &Path,
    cfg_cache: &mut TargetCfgCache,
) -> Result<bool, RustAdapterError> {
    let build_disabled = matches!(
        pkg_toml.package.as_ref().and_then(|p| p.build.as_ref()),
        Some(TomlBuild::Disabled(false))
    );
    any_active_manifest_dep(
        pkg_toml,
        dep_name,
        !build_disabled,
        is_test,
        explicit_target,
        start_dir,
        cfg_cache,
        |_, _, _, _| true,
    )
}

#[cfg(test)]
mod candidate_tests {
    use super::resolve_candidate_by_spec;

    /// mio patches libc to a git branch: the lock lists a registry libc and a git libc, and
    /// the dependency spec names the git one without the pinned commit.
    #[test]
    fn a_git_spec_without_the_pinned_commit_matches_the_pinned_package() {
        let cands: Vec<(&str, Option<&str>)> = vec![
            (
                "0.2.190",
                Some("registry+https://github.com/rust-lang/crates.io-index"),
            ),
            (
                "0.2.191",
                Some("git+https://github.com/rust-lang/libc?branch=libc-0.2#0123456789abcdef"),
            ),
        ];
        let got = resolve_candidate_by_spec(
            &cands,
            |c| (c.0, c.1),
            Some("0.2.191"),
            Some("git+https://github.com/rust-lang/libc?branch=libc-0.2"),
            None,
            true,
            "libc 0.2.191 (git+https://github.com/rust-lang/libc?branch=libc-0.2)",
        )
        .expect("the git libc resolves");
        assert_eq!(got, Some(1));
        let registry = resolve_candidate_by_spec(
            &cands,
            |c| (c.0, c.1),
            Some("0.2.190"),
            Some("registry+https://github.com/rust-lang/crates.io-index"),
            None,
            true,
            "libc 0.2.190",
        )
        .expect("the registry libc still resolves");
        assert_eq!(registry, Some(0));
    }
}