ikigai-cli 0.1.66

ikigai — a REPL client for resource-resolution kernels (native + WebAssembly).
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
//! Records which `ikigai-*` crates this binary links, and at which versions, for `ikigai
//! --version --verbose` (ledger #1338).
//!
//! The answer comes from the `Cargo.lock` this build resolved against, read here at build
//! time, so it is the binary's own record and not a guess made later from outside it. The
//! alternative it replaces read crates.io source paths out of the binary's panic locations,
//! which holds only while nothing builds with `-Zlocation-detail=none` and says nothing at all
//! for a path or git dependency.
//!
//! The lock alone over-reports. It is one resolve for the whole workspace: every member's
//! dev-dependencies are in it, and every optional dependency some feature could turn on. So
//! the walk starts at this package and follows, for each workspace member and each `ikigai-*`
//! crate from a registry, only the NORMAL dependencies its manifest declares (never
//! `[dev-dependencies]` or `[build-dependencies]`, neither of which is linked), and an
//! optional one only when an enabled feature turns it on, features followed the way Cargo
//! unifies them. A registry crate's manifest is the published one Cargo unpacked under its
//! home. Any other registry crate is followed by its edges in the lock.
//!
//! What it cannot see, stated so nobody reads more into the list than it says:
//!
//! - a target-specific dependency (`[target.'cfg(…)'.dependencies]`) is counted on every
//!   target. No `ikigai-*` crate is target-gated in this workspace today;
//! - a crate followed by its lock edges has them taken whole (the lock records neither which
//!   consumer activated an edge nor its kind). That is every non-`ikigai-*` registry crate,
//!   which matters only if one depends on an `ikigai-*` crate, and an `ikigai-*` one whose
//!   manifest is not under the cargo home (vendored sources), which then over-reports;
//! - `cargo install` WITHOUT `--locked` resolves afresh and ignores the packaged lock, so the
//!   lock read here may not be the resolve that compiled. Install with `--locked` (every
//!   runbook here does) and the two are the same lock.
//!
//! The output is `OUT_DIR/linked-ikigai.txt`: one `name version` line per crate, sorted, or a
//! single line beginning `unknown:` that says why the list could not be made. A build never
//! fails over it: the version flag answers either way.

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

fn main() {
    println!("cargo:rerun-if-changed=build.rs");
    let manifest_dir = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").expect("set by cargo"));
    let out_dir = PathBuf::from(std::env::var("OUT_DIR").expect("set by cargo"));
    let text = match linked(&manifest_dir) {
        Ok(crates) if crates.is_empty() => "unknown: no ikigai-* crate in the lock\n".to_string(),
        Ok(crates) => crates
            .iter()
            .map(|(name, version)| format!("{name} {version}\n"))
            .collect(),
        Err(why) => format!("unknown: {why}\n"),
    };
    std::fs::write(out_dir.join("linked-ikigai.txt"), text).expect("OUT_DIR is writable");
}

/// One `[[package]]` of the lock.
struct Locked {
    name: String,
    version: String,
    /// A workspace member (or a `[patch]` path): no `source` in the lock.
    path: bool,
    dependencies: Vec<String>,
}

/// The `(name, version)` of every `ikigai-*` crate this package links, itself excluded.
fn linked(manifest_dir: &Path) -> Result<BTreeSet<(String, String)>, String> {
    let lock_path = manifest_dir
        .ancestors()
        .map(|dir| dir.join("Cargo.lock"))
        .find(|path| path.is_file())
        .ok_or("no Cargo.lock beside this package or above it")?;
    println!("cargo:rerun-if-changed={}", lock_path.display());
    let root = lock_path.parent().expect("a file has a parent");
    let lock = read_toml(&lock_path)?;
    let packages: Vec<Locked> = lock
        .get("package")
        .and_then(toml::Value::as_array)
        .ok_or("the lock has no [[package]] table")?
        .iter()
        .filter_map(|p| {
            Some(Locked {
                name: p.get("name")?.as_str()?.to_string(),
                version: p.get("version")?.as_str()?.to_string(),
                path: p.get("source").is_none(),
                dependencies: p
                    .get("dependencies")
                    .and_then(toml::Value::as_array)
                    .map(|deps| {
                        deps.iter()
                            .filter_map(|d| d.as_str().map(str::to_string))
                            .collect()
                    })
                    .unwrap_or_default(),
            })
        })
        .collect();

    let members = member_manifests(root)?;
    let workspace_deps = read_toml(&root.join("Cargo.toml"))
        .ok()
        .and_then(|t| t.get("workspace")?.get("dependencies")?.as_table().cloned())
        .unwrap_or_default();

    let this = std::env::var("CARGO_PKG_NAME").expect("set by cargo");
    let this_version = std::env::var("CARGO_PKG_VERSION").expect("set by cargo");
    let start = packages
        .iter()
        .position(|p| p.path && p.name == this && p.version == this_version)
        .ok_or_else(|| format!("{this} {this_version} is not in {}", lock_path.display()))?;
    let start_features = enabled_features(members.get(&this));

    // A crate walked by its manifest is revisited whenever its feature set grows, which is
    // Cargo's unification; a crate walked by its lock edges is visited once, since those edges
    // do not depend on what was asked of it.
    let registry_manifests = RegistryManifests::new();
    let mut member_features: BTreeMap<usize, BTreeSet<String>> = BTreeMap::new();
    let mut seen_registry: BTreeSet<usize> = BTreeSet::new();
    let mut work: Vec<(usize, BTreeSet<String>)> = vec![(start, start_features)];
    while let Some((at, requested)) = work.pop() {
        let package = &packages[at];
        let manifest = if package.path {
            match members.get(&package.name) {
                Some(manifest) => Some(manifest.clone()),
                None => return Err(format!("no manifest found for member {}", package.name)),
            }
        } else if package.name.starts_with("ikigai-") {
            // An `ikigai-*` crate from a registry is walked by its PUBLISHED manifest, like a
            // member: in a packaged build (what `cargo install` compiles) every sibling is one,
            // and its lock edges list each optional dependency the resolve could turn on.
            registry_manifests.get(&package.name, &package.version)
        } else {
            None
        };
        let Some(manifest) = manifest else {
            if seen_registry.insert(at) {
                for dep in &package.dependencies {
                    for to in lock_targets(&packages, dep) {
                        // What a crate walked by its edges asks of the next is unknown here,
                        // so it is asked for its default features.
                        work.push((to, BTreeSet::from(["default".to_string()])));
                    }
                }
            }
            continue;
        };
        let manifest = &manifest;
        let first = !member_features.contains_key(&at);
        let known = member_features.entry(at).or_default();
        let before = known.len();
        known.extend(closure(manifest, &requested));
        if !first && known.len() == before {
            continue;
        }
        let features = known.clone();
        for dep in normal_dependencies(manifest, &workspace_deps) {
            if dep.optional && !turns_on(&features, &dep.key) {
                continue;
            }
            let mut asked: BTreeSet<String> = dep.features.iter().cloned().collect();
            if dep.default_features {
                asked.insert("default".to_string());
            }
            for feature in &features {
                if let Some((key, wanted)) = feature.split_once('/') {
                    if key.trim_end_matches('?') == dep.key {
                        asked.insert(wanted.to_string());
                    }
                }
            }
            let targets: Vec<usize> = package
                .dependencies
                .iter()
                .flat_map(|d| lock_targets(&packages, d))
                .filter(|&to| packages[to].name == dep.package)
                .collect();
            for to in targets {
                work.push((to, asked.clone()));
            }
        }
    }

    Ok(member_features
        .keys()
        .chain(seen_registry.iter())
        .filter(|&&at| at != start)
        .map(|&at| &packages[at])
        .filter(|p| p.name.starts_with("ikigai-"))
        .map(|p| (p.name.clone(), p.version.clone()))
        .collect())
}

/// The published manifests of registry crates, as Cargo unpacked them before this build:
/// `<cargo home>/registry/src/<index>/<name>-<version>/Cargo.toml`. Not found (vendored
/// sources, an unusual cargo home) ⇒ `None`, and the crate is walked by its lock edges.
struct RegistryManifests {
    roots: Vec<PathBuf>,
}

impl RegistryManifests {
    fn new() -> Self {
        let home = std::env::var_os("CARGO_HOME")
            .map(PathBuf::from)
            .or_else(|| {
                std::env::var_os("HOME")
                    .or_else(|| std::env::var_os("USERPROFILE"))
                    .map(|home| PathBuf::from(home).join(".cargo"))
            });
        let roots = home
            .and_then(|home| std::fs::read_dir(home.join("registry").join("src")).ok())
            .map(|dirs| dirs.filter_map(|d| d.ok()).map(|d| d.path()).collect())
            .unwrap_or_default();
        RegistryManifests { roots }
    }

    fn get(&self, name: &str, version: &str) -> Option<toml::Table> {
        self.roots
            .iter()
            .map(|root| root.join(format!("{name}-{version}")).join("Cargo.toml"))
            .find(|path| path.is_file())
            .and_then(|path| read_toml(&path).ok())
    }
}

fn read_toml(path: &Path) -> Result<toml::Table, String> {
    let text = std::fs::read_to_string(path)
        .map_err(|e| format!("cannot read {}: {e}", path.display()))?;
    text.parse::<toml::Table>()
        .map_err(|e| format!("cannot parse {}: {e}", path.display()))
}

/// Every workspace member's manifest by package name: the root's own package, and each
/// `[workspace] members` entry (a directory, or a `dir/*` glob, which is all this workspace
/// uses). A packaged crate has no `[workspace]`, so it is its own only member.
fn member_manifests(root: &Path) -> Result<BTreeMap<String, toml::Table>, String> {
    let root_manifest = read_toml(&root.join("Cargo.toml"))?;
    let mut dirs = vec![root.to_path_buf()];
    let globs = root_manifest
        .get("workspace")
        .and_then(|w| w.get("members"))
        .and_then(toml::Value::as_array)
        .cloned()
        .unwrap_or_default();
    for glob in globs.iter().filter_map(toml::Value::as_str) {
        match glob.strip_suffix("/*") {
            Some(parent) => {
                let parent = root.join(parent);
                let entries = std::fs::read_dir(&parent)
                    .map_err(|e| format!("cannot list {}: {e}", parent.display()))?;
                dirs.extend(entries.filter_map(|e| e.ok()).map(|e| e.path()));
            }
            None => dirs.push(root.join(glob)),
        }
    }
    let mut members = BTreeMap::new();
    for dir in dirs {
        let path = dir.join("Cargo.toml");
        if !path.is_file() {
            continue;
        }
        let manifest = read_toml(&path)?;
        let Some(name) = manifest
            .get("package")
            .and_then(|p| p.get("name"))
            .and_then(toml::Value::as_str)
        else {
            continue;
        };
        println!("cargo:rerun-if-changed={}", path.display());
        members.insert(name.to_string(), manifest);
    }
    Ok(members)
}

/// The features Cargo enabled for THIS package, read back from its `CARGO_FEATURE_*`
/// variables (upper-cased, `-` as `_`) against the names its manifest declares.
fn enabled_features(manifest: Option<&toml::Table>) -> BTreeSet<String> {
    let declared = manifest
        .and_then(|m| m.get("features"))
        .and_then(toml::Value::as_table)
        .map(|t| t.keys().cloned().collect::<Vec<_>>())
        .unwrap_or_default();
    let mut on: BTreeSet<String> = declared
        .into_iter()
        .filter(|name| {
            let var = format!("CARGO_FEATURE_{}", name.to_uppercase().replace('-', "_"));
            std::env::var_os(var).is_some()
        })
        .collect();
    // An optional dependency is also a feature of its own name; its variable is set too.
    if let Some(manifest) = manifest {
        for dep in normal_dependencies(manifest, &toml::Table::new()) {
            let var = format!("CARGO_FEATURE_{}", dep.key.to_uppercase().replace('-', "_"));
            if dep.optional && std::env::var_os(var).is_some() {
                on.insert(dep.key);
            }
        }
    }
    on
}

/// `requested` expanded through the manifest's `[features]` table: a feature brings in what
/// it lists, recursively. `default` is a feature like any other here; asking for it is how a
/// dependency declared without `default-features = false` arrives.
fn closure(manifest: &toml::Table, requested: &BTreeSet<String>) -> BTreeSet<String> {
    let table = manifest
        .get("features")
        .and_then(toml::Value::as_table)
        .cloned()
        .unwrap_or_default();
    let mut on = BTreeSet::new();
    let mut work: Vec<String> = requested.iter().cloned().collect();
    while let Some(feature) = work.pop() {
        if !on.insert(feature.clone()) {
            continue;
        }
        if let Some(listed) = table.get(&feature).and_then(toml::Value::as_array) {
            work.extend(listed.iter().filter_map(|v| v.as_str().map(str::to_string)));
        }
    }
    on
}

/// Whether an enabled feature set turns on the optional dependency keyed `key`: by its own
/// implicit feature (`key`), by `dep:key`, or by `key/feature` (not the weak `key?/feature`,
/// which enables a feature only of a dependency something else turned on).
fn turns_on(features: &BTreeSet<String>, key: &str) -> bool {
    features.iter().any(|f| {
        f == key
            || f.strip_prefix("dep:") == Some(key)
            || f.split_once('/').is_some_and(|(k, _)| k == key)
    })
}

/// One `[dependencies]` entry, as far as linking cares.
struct Dependency {
    /// The key it is declared under (the name a feature uses for it).
    key: String,
    /// The package it names (`package = "…"` renames).
    package: String,
    optional: bool,
    default_features: bool,
    features: Vec<String>,
}

/// The NORMAL dependencies a manifest declares, target-specific ones included (see the module
/// note), each resolved through `[workspace.dependencies]` when it says `workspace = true`.
fn normal_dependencies(manifest: &toml::Table, workspace: &toml::Table) -> Vec<Dependency> {
    let mut tables: Vec<&toml::Table> = Vec::new();
    if let Some(t) = manifest.get("dependencies").and_then(toml::Value::as_table) {
        tables.push(t);
    }
    if let Some(targets) = manifest.get("target").and_then(toml::Value::as_table) {
        for target in targets.values() {
            if let Some(t) = target.get("dependencies").and_then(toml::Value::as_table) {
                tables.push(t);
            }
        }
    }
    let mut deps = Vec::new();
    for table in tables {
        for (key, value) in table {
            let own = value.as_table();
            let inherited = own
                .filter(|t| t.get("workspace").and_then(toml::Value::as_bool) == Some(true))
                .and_then(|_| workspace.get(key))
                .and_then(toml::Value::as_table);
            let field = |name: &str| {
                own.and_then(|t| t.get(name))
                    .or_else(|| inherited.and_then(|t| t.get(name)))
            };
            let flag = |names: [&str; 2], default: bool| {
                names
                    .iter()
                    .find_map(|n| field(n).and_then(toml::Value::as_bool))
                    .unwrap_or(default)
            };
            let mut features: Vec<String> = Vec::new();
            for t in [own, inherited].into_iter().flatten() {
                if let Some(list) = t.get("features").and_then(toml::Value::as_array) {
                    features.extend(list.iter().filter_map(|v| v.as_str().map(str::to_string)));
                }
            }
            deps.push(Dependency {
                key: key.clone(),
                package: field("package")
                    .and_then(toml::Value::as_str)
                    .unwrap_or(key)
                    .to_string(),
                optional: own
                    .and_then(|t| t.get("optional"))
                    .and_then(toml::Value::as_bool)
                    .unwrap_or(false),
                default_features: flag(["default-features", "default_features"], true),
                features,
            });
        }
    }
    deps
}

/// The lock packages a `dependencies` entry names: `name`, `name version`, or
/// `name version (source)`.
fn lock_targets(packages: &[Locked], entry: &str) -> Vec<usize> {
    let mut words = entry.split(' ');
    let name = words.next().unwrap_or("");
    let version = words.next();
    packages
        .iter()
        .enumerate()
        .filter(|(_, p)| p.name == name && version.is_none_or(|v| p.version == v))
        .map(|(at, _)| at)
        .collect()
}