code_passenger 0.4.3

Scans a Rust workspace with klepto and does the writing: feature gates across every crate from one features document, proven by cargo check, Cargo.toml edits, file headers from the plan, and the history of it.
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
//! `feature-map`, `feature-sites`, `feature-probe` (rules F1–F3 in
//! `GATE_RULES.md`): the 42-step lineage's review surface on klepto facts.

use crate::commands::klepto_for;
use crate::error::{PassengerError, Result};
use crate::gate::relative;
use klepto::graph::NodeKind;
use crate::cargo::enable_text;
use klepto::{CfgPredicate, DepKind, FeatureEnable, FeatureModel, FeatureSpec, GateReason, Implication, Klepto, Receipt};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FeatureRow {
    pub name: String,
    /// As Cargo spells them: `dep:beta`, `other`, `dep?/feat`.
    pub enables: Vec<String>,
    pub default: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DepRow {
    pub name: String,
    pub kind: String,
    pub optional: bool,
    /// Use sites of this dependency in the package.
    pub sites: usize,
    /// KLEP010 findings for this dependency.
    pub ungated: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PackageMap {
    pub name: String,
    pub features: Vec<FeatureRow>,
    pub deps: Vec<DepRow>,
    /// Items whose own cfg names a feature.
    pub gated_items: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FeatureMap {
    pub root: String,
    pub packages: Vec<PackageMap>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SiteRow {
    pub line: Option<u32>,
    pub kind: String,
    pub path: String,
    pub scope: String,
    pub cfg: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileSites {
    /// Relative to the root, `/`-separated.
    pub file: String,
    pub sites: Vec<SiteRow>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FeatureSites {
    pub root: String,
    pub target: String,
    /// `"dep"` or `"feature"`.
    pub kind: String,
    pub deps: Vec<String>,
    pub files: Vec<FileSites>,
    pub total: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UngatedRow {
    pub file: String,
    pub line: Option<u32>,
    pub scope: String,
    pub dep: String,
    pub site_cfg: String,
    pub required: String,
    pub verdict: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProposedGate {
    pub item: String,
    pub file: String,
    pub line: Option<u32>,
    pub attribute: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FeatureProbe {
    pub root: String,
    pub target: String,
    pub kind: String,
    pub deps: Vec<String>,
    pub spec: Option<String>,
    pub ungated: Vec<UngatedRow>,
    pub proposed: Vec<ProposedGate>,
    /// Sorted item ids the plan would gate, plus `reaches_public`.
    pub lost: Vec<String>,
    /// With the feature off (or each feature turning the dependency on), per
    /// crate, on the planned tree: the spec's plan, else the workspace
    /// features document's, else the tree as it is.
    #[serde(default)]
    pub off: Vec<crate::depth::FeatureOff>,
    /// Always false: a probe reviews, it never writes.
    pub writes: bool,
}

// ---------------------------------------------------------------------------

fn cfg_text(p: &CfgPredicate) -> String {
    if *p == CfgPredicate::True { "true".into() } else { p.render() }
}

fn dep_kind_text(k: DepKind) -> &'static str {
    match k {
        DepKind::Normal => "normal",
        DepKind::Dev => "dev",
        DepKind::Build => "build",
    }
}

fn verdict_word(i: &Implication) -> &'static str {
    match i {
        Implication::Always => "always",
        Implication::Never => "never",
        Implication::Sometimes { .. } => "sometimes",
        Implication::Unknown => "unknown",
    }
}

/// `default` and everything it enables, transitively.
fn default_closure(model: &FeatureModel) -> BTreeSet<String> {
    let mut out = BTreeSet::new();
    let mut stack = vec!["default".to_string()];
    while let Some(f) = stack.pop() {
        if !out.insert(f.clone()) {
            continue;
        }
        if let Some(info) = model.features.get(&f) {
            for e in &info.enables {
                if let FeatureEnable::Feature(g) = e {
                    stack.push(g.clone());
                }
            }
        }
    }
    out
}

fn packages_for<'k>(k: &'k Klepto, package: Option<&str>) -> Result<Vec<(&'k String, &'k FeatureModel)>> {
    match package {
        Some(p) => {
            let p = p.replace('-', "_");
            k.features
                .get_key_value(&p)
                .map(|(n, m)| vec![(n, m)])
                .ok_or_else(|| PassengerError::unsupported(format!("no feature model for package `{p}`")))
        }
        None => Ok(k.features.iter().collect()),
    }
}

/// A target is a dependency name or a feature name; returns
/// `(kind, deps, owning packages)` (rule F2).
fn classify(k: &Klepto, package: Option<&str>, target: &str) -> Result<(String, Vec<String>, Vec<String>)> {
    // crate names are spelled with `_` in klepto; feature names keep their dashes
    let t = target.trim().replace('-', "_");
    let feature = target.trim().to_string();
    let mut deps: BTreeSet<String> = BTreeSet::new();
    let mut owners: Vec<String> = Vec::new();
    let mut kind = None;
    for (name, model) in packages_for(k, package)? {
        if model.dep(&t).is_some() {
            kind.get_or_insert("dep".to_string());
            deps.insert(t.clone());
            owners.push(name.clone());
        } else if let Some(f) = [feature.as_str(), t.as_str()].into_iter().find(|f| model.features.contains_key(*f)) {
            kind.get_or_insert("feature".to_string());
            deps.extend(model.deps_enabled_by(f));
            owners.push(name.clone());
        }
    }
    if kind.is_none() {
        // a workspace feature the document declares and the manifests do not have yet
        let ws = crate::gate::workspace_root(k.root.as_deref().unwrap_or(Path::new(".")))?;
        if let Some(found) = crate::doc::find(&ws)?
            && let Some(f) = found.doc.features.get(&feature) {
                kind = Some("feature".to_string());
                for entry in &f.deps {
                    let (krate, dep) = crate::doc::split_dep(entry)?;
                    if package.is_none_or(|p| p.replace('-', "_") == krate) {
                        deps.insert(dep);
                        if !owners.contains(&krate) {
                            owners.push(krate);
                        }
                    }
                }
            }
    }
    let kind = kind.ok_or_else(|| PassengerError::unsupported(format!("`{target}` is neither a dependency nor a feature of the scanned packages, nor a feature of the workspace features document")))?;
    Ok((kind, deps.into_iter().collect(), owners))
}

fn root_text(root: &Path) -> String {
    root.display().to_string()
}

/// Rule F1.
pub fn feature_map(root: &Path, package: Option<&str>) -> Result<FeatureMap> {
    let k = klepto_for(root)?;
    let receipt = Receipt::from_klepto(&k);
    let ungated = k.ungated_dep_uses();
    let mut packages = Vec::new();
    for (name, model) in packages_for(&k, package)? {
        let defaults = default_closure(model);
        let features = model
            .features
            .iter()
            .map(|(f, info)| FeatureRow { name: f.clone(), enables: info.enables.iter().map(enable_text).collect(), default: defaults.contains(f) })
            .collect();
        let deps = model
            .dependencies
            .iter()
            .map(|d| DepRow {
                name: d.name.clone(),
                kind: dep_kind_text(d.kind).to_string(),
                optional: d.optional,
                sites: receipt.dep_uses.iter().filter(|u| &u.package == name && u.site.dep == d.name).count(),
                ungated: ungated.iter().filter(|u| &u.package == name && u.site.dep == d.name).count(),
            })
            .collect();
        let gated_items = k
            .graph
            .nodes
            .values()
            .filter(|n| n.package.as_deref() == Some(name.as_str()) && !matches!(n.kind, NodeKind::Module | NodeKind::External) && !n.cfg.features().is_empty())
            .count();
        packages.push(PackageMap { name: name.clone(), features, deps, gated_items });
    }
    Ok(FeatureMap { root: root_text(root), packages })
}

/// Rule F2.
pub fn feature_sites(root: &Path, package: Option<&str>, target: &str) -> Result<FeatureSites> {
    let k = klepto_for(root)?;
    let (kind, deps, owners) = classify(&k, package, target)?;
    let receipt = Receipt::from_klepto(&k);
    let mut by_file: BTreeMap<String, Vec<SiteRow>> = BTreeMap::new();
    for u in receipt.dep_uses.iter().filter(|u| owners.contains(&u.package) && deps.contains(&u.site.dep)) {
        by_file.entry(u.site.location.path.to_string_lossy().into_owned()).or_default().push(SiteRow {
            line: u.site.location.line,
            kind: format!("{:?}", u.site.kind).to_lowercase(),
            path: u.site.path.clone(),
            scope: u.site.scope.clone(),
            cfg: cfg_text(&u.cfg),
        });
    }
    let mut files: Vec<FileSites> = by_file
        .into_iter()
        .map(|(file, mut sites)| {
            sites.sort_by(|a, b| (a.line, &a.path).cmp(&(b.line, &b.path)));
            FileSites { file, sites }
        })
        .collect();
    files.sort_by(|a, b| a.file.cmp(&b.file));
    let total = files.iter().map(|f| f.sites.len()).sum();
    Ok(FeatureSites { root: root_text(root), target: target.to_string(), kind, deps, files, total })
}

/// Rule F3.
pub fn feature_probe(root: &Path, package: Option<&str>, target: &str, spec: Option<&Path>) -> Result<FeatureProbe> {
    let k = klepto_for(root)?;
    let (kind, deps, owners) = classify(&k, package, target)?;
    let receipt = Receipt::from_klepto(&k);
    // without a spec, the workspace features document (if there is one) is what is reviewed
    let ws = crate::gate::workspace_root(root)?;
    let doc_plan = match spec {
        Some(_) => None,
        None => match crate::doc::find(&ws)? {
            Some(found) => Some(crate::workspace::plan_static(&ws, &found.doc, Some(found.path), &k)?),
            None => None,
        },
    };
    let spec_model = match (spec, &doc_plan) {
        (Some(p), _) => Some(FeatureSpec::from_path(p).map_err(|e| PassengerError::unsupported(e.to_string()))?),
        (None, Some(w)) => Some(FeatureSpec { packages: w.packages.iter().map(|p| (p.package.clone(), p.spec.clone())).collect() }),
        (None, None) => None,
    };
    let mut ungated = Vec::new();
    let mut plans: Vec<klepto::GatePlan> = Vec::new();
    for owner in &owners {
        let Some(current) = k.feature_model(owner) else { continue };
        let desired = spec_model.as_ref().map(|s| current.apply_spec(&s.package(owner).cloned().unwrap_or_default()));
        let model = desired.as_ref().unwrap_or(current);
        for u in receipt.dep_uses.iter().filter(|u| &u.package == owner && deps.contains(&u.site.dep)) {
            let required = crate::workspace::minimize(model.dep_predicate(&u.site.dep).simplify(), model);
            let verdict = u.cfg.implies(&required, None);
            if matches!(verdict, Implication::Always) {
                continue;
            }
            ungated.push(UngatedRow {
                file: u.site.location.path.to_string_lossy().into_owned(),
                line: u.site.location.line,
                scope: u.site.scope.clone(),
                dep: u.site.dep.clone(),
                site_cfg: cfg_text(&u.cfg),
                required: cfg_text(&required),
                verdict: verdict_word(&verdict).to_string(),
            });
        }
        if let Some(desired) = &desired {
            // the document's plan carries the cross-crate gates; a spec's is klepto's per crate
            let plan = doc_plan.as_ref().and_then(|w| w.packages.iter().find(|p| &p.package == owner)).map(|p| p.plan.clone()).unwrap_or_else(|| k.plan_gates(owner, desired));
            plans.push(plan);
        }
    }
    // gates related to the target's deps, through cascades and violations, across crates
    let mut related: BTreeSet<String> = plans
        .iter()
        .flat_map(|p| p.gates.iter())
        .filter(|g| g.reasons.iter().any(|r| matches!(r, GateReason::UngatedDep { dep } if deps.contains(dep))))
        .map(|g| g.item.clone())
        .collect();
    loop {
        let before = related.len();
        for g in plans.iter().flat_map(|p| p.gates.iter()) {
            let linked = g.reasons.iter().any(|r| match r {
                GateReason::Cascade { from } => related.contains(from),
                GateReason::ExistingViolation { to } => related.contains(to),
                _ => false,
            });
            if linked {
                related.insert(g.item.clone());
            }
        }
        if related.len() == before {
            break;
        }
    }
    let mut proposed = Vec::new();
    let mut lost: BTreeSet<String> = BTreeSet::new();
    for plan in &plans {
        for g in plan.gates.iter().filter(|g| related.contains(&g.item)) {
            proposed.push(ProposedGate {
                item: g.item.clone(),
                file: relative(root, &g.location.path).map(|r| r.to_string_lossy().into_owned()).unwrap_or_else(|_| g.location.path.display().to_string()),
                line: g.location.line,
                attribute: if g.existing_cfg == CfgPredicate::True { g.attribute_text() } else { crate::gate::merged_attribute(&g.existing_cfg, &g.predicate) },
            });
        }
        lost.extend(plan.gates.iter().map(|g| g.item.clone()));
        lost.extend(plan.reaches_public.iter().cloned());
    }
    ungated.sort_by(|a, b| (&a.file, a.line, &a.scope).cmp(&(&b.file, b.line, &b.scope)));
    proposed.sort_by(|a, b| (&a.file, a.line, &a.item).cmp(&(&b.file, b.line, &b.item)));
    let all_off = match doc_plan {
        Some(w) => w.off,
        None => probe_off(root, &k, spec_model.as_ref(), &owners)?,
    };
    let off = all_off
        .into_iter()
        .filter(|o| owners.contains(&o.package) && if kind == "feature" { o.feature == target.trim() } else { deps.iter().any(|d| o.deps.contains(d)) })
        .collect();
    let spec_text = spec.map(|p| p.display().to_string()).or_else(|| crate::doc::find(&ws).ok().flatten().map(|f| f.path.display().to_string()));
    Ok(FeatureProbe {
        root: root_text(root),
        target: target.to_string(),
        kind,
        deps,
        spec: spec_text,
        ungated,
        proposed,
        lost: lost.into_iter().collect(),
        off,
        writes: false,
    })
}

/// Every feature off, on the tree the probe reviews against.
fn probe_off(root: &Path, k: &Klepto, spec: Option<&FeatureSpec>, owners: &[String]) -> Result<Vec<crate::depth::FeatureOff>> {
    let ws = crate::gate::workspace_root(root)?;
    if let Some(spec) = spec {
        let mut desired = k.features.clone();
        let mut plans = Vec::new();
        for owner in owners {
            let Some(current) = k.feature_model(owner) else { continue };
            let d = current.apply_spec(&spec.package(owner).cloned().unwrap_or_default());
            let plan = k.plan_gates(owner, &d);
            plans.push(crate::workspace::PackagePlan {
                package: owner.clone(),
                manifest_path: k.packages.get(owner).map(|p| p.manifest_path.clone()).unwrap_or_default(),
                spec: spec.package(owner).cloned().unwrap_or_default(),
                plan,
            });
            desired.insert(owner.clone(), d);
        }
        let edits = crate::workspace::edits_of(&plans)?;
        return crate::depth::feature_off(&ws, &desired, k, &edits);
    }
    if let Some(found) = crate::doc::find(&ws)? {
        return Ok(crate::workspace::plan_static(&ws, &found.doc, Some(found.path), k)?.off);
    }
    crate::depth::feature_off(&ws, &k.features, k, &crate::gate::EditSet::default())
}

// ---------------------------------------------------------------------------
// renderers (the lineage's shape)

pub fn render_map(m: &FeatureMap) -> String {
    let mut s = String::new();
    s.push_str("CODE PASSENGER :: FEATURE MAP\n─────────────────────────────\n");
    s.push_str(&format!("root: {}\n\n", m.root));
    for p in &m.packages {
        s.push_str(&format!("CRATE {}\n", p.name));
        s.push_str(&format!("  gated_items: {}\n", p.gated_items));
        s.push_str("  features:\n");
        if p.features.is_empty() {
            s.push_str("    NONE\n");
        }
        for f in &p.features {
            s.push_str(&format!("    {}{} = [{}]\n", f.name, if f.default { " (default)" } else { "" }, f.enables.join(", ")));
        }
        s.push_str("  deps:\n");
        if p.deps.is_empty() {
            s.push_str("    NONE\n");
        }
        for d in &p.deps {
            s.push_str(&format!(
                "    {} kind={} optional={} sites={} ungated={}\n",
                d.name, d.kind, d.optional, d.sites, d.ungated
            ));
        }
        s.push('\n');
    }
    s
}

pub fn render_sites(x: &FeatureSites) -> String {
    let mut s = String::new();
    s.push_str("CODE PASSENGER :: FEATURE SITES\n───────────────────────────────\n");
    s.push_str(&format!("root: {}\ntarget: {}\nkind: {}\ndeps: [{}]\n\n", x.root, x.target, x.kind, x.deps.join(", ")));
    if x.files.is_empty() {
        s.push_str("  NONE no use sites\n");
    }
    for f in &x.files {
        s.push_str(&format!("  FILE {} sites={}\n", f.file, f.sites.len()));
        for site in &f.sites {
            let line = site.line.map(|l| l.to_string()).unwrap_or_else(|| "?".into());
            s.push_str(&format!("    L{line} {} {} scope={} cfg={}\n", site.kind, site.path, site.scope, site.cfg));
        }
    }
    s.push_str(&format!("\ntotal_sites: {}\n", x.total));
    s
}

pub fn render_probe(p: &FeatureProbe) -> String {
    let mut s = String::new();
    s.push_str("CODE PASSENGER :: FEATURE PROBE\n───────────────────────────────\n");
    s.push_str(&format!("root: {}\ntarget: {}\nkind: {}\ndeps: [{}]\nspec: {}\n\n", p.root, p.target, p.kind, p.deps.join(", "), p.spec.as_deref().unwrap_or("<current manifests>")));
    s.push_str(&format!("ungated: {}\n", p.ungated.len()));
    for u in &p.ungated {
        let line = u.line.map(|l| l.to_string()).unwrap_or_else(|| "?".into());
        s.push_str(&format!("  {}:{line} {} uses {} under cfg={} needs={} ({})\n", u.file, u.scope, u.dep, u.site_cfg, u.required, u.verdict));
    }
    s.push_str(&format!("proposed: {}\n", p.proposed.len()));
    for g in &p.proposed {
        let line = g.line.map(|l| l.to_string()).unwrap_or_else(|| "?".into());
        s.push_str(&format!("  {}:{line} {} {}\n", g.file, g.attribute, g.item));
    }
    s.push_str(&format!("lost: {}\n", p.lost.len()));
    for l in &p.lost {
        s.push_str(&format!("  {l}\n"));
    }
    s.push_str(&crate::depth::render(&p.off));
    s.push_str("writes: false\n");
    s
}