wsb 0.275.7622

Workspace tools for every project under $PRJ: git across submodules, template stamping, GitHub, and the workbench
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
//! Every local path a manifest declares, and whether it still names anything.
//!
//! A manifest that depends on a sibling by path is making a claim about where
//! it sits in a tree — `../capdag/capdag-rs`, `file:../floom-uikit`,
//! `.package(path: "../../MacFabricLoomSDK")`. The claim is a count of `..`,
//! and the count is right until a repository moves.
//!
//! When one does, nothing says so. The manifest still parses, the file still
//! reads, and the failure arrives later and somewhere else: a build that
//! cannot resolve a dependency, an `ENOENT: stat` from a package manager
//! chasing a symlink into a directory that is not there, a language server
//! that silently stops resolving a package. Every one of those is hours from
//! its cause.
//!
//! So the claims are checked. This is the whole class, in one pass, over every
//! manifest kind this workspace uses — and it is part of `wsb check`, because
//! a path that no longer resolves is exactly what worktree integrity means.

use crate::prelude::*;
use std::path::{Path, PathBuf};

/// One declared path that names nothing.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Broken {
    /// The manifest making the claim, workspace-relative.
    pub manifest: String,
    /// What kind of declaration it is, for a reader who has to fix it.
    pub kind: &'static str,
    /// The path as written.
    pub declared: String,
    /// Where that resolves to, which is what does not exist.
    pub resolves_to: String,
}

/// Directories that hold other people's trees, or output.
fn skipped(name: &str) -> bool {
    matches!(
        name,
        "node_modules"
            | "target"
            | ".build"
            | ".git"
            | ".wsb"
            | "dist"
            | "out"
            | "build"
            | "DerivedData"
            | "vendor"
            | "__pycache__"
            | ".venv"
            | "retired_by_wsb"
            | "Pods"
    )
}

/// Every manifest under `root`, by file name.
fn manifests(root: &Path) -> Vec<PathBuf> {
    let mut found = Vec::new();
    let mut stack = vec![root.to_path_buf()];
    while let Some(dir) = stack.pop() {
        let Ok(entries) = std::fs::read_dir(&dir) else {
            continue;
        };
        for entry in entries.flatten() {
            let path = entry.path();
            let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
                continue;
            };
            if path.is_dir() {
                if !skipped(name) {
                    stack.push(path);
                }
                continue;
            }
            let by_name = matches!(
                name,
                "Cargo.toml" | "Package.swift" | "package.json" | "package-lock.json"
            );
            let by_extension = path
                .extension()
                .and_then(|e| e.to_str())
                .is_some_and(|ext| matches!(ext, "pbxproj" | "xcscheme" | "xcconfig"));
            if by_name || by_extension {
                found.push(path);
            }
        }
    }
    found.sort();
    found
}

/// Check every declared local path in the worktree.
///
/// Relative paths only: an absolute one is a claim about a machine rather than
/// about this tree, and one that is wrong is wrong for a different reason.
pub fn check(root: &Path) -> Vec<Broken> {
    let mut broken = Vec::new();
    for manifest in manifests(root) {
        let Ok(text) = std::fs::read_to_string(&manifest) else {
            continue;
        };
        let base = manifest.parent().unwrap_or(root);
        let name = manifest
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or_default();

        let declared: Vec<(&'static str, String)> = match name {
            "Cargo.toml" => quoted_after(&text, "path", "cargo path dependency"),
            "Package.swift" => swift_paths(&text),
            "package.json" => json_file_deps(&text),
            "package-lock.json" => lock_links(&text),
            _ => Vec::new(),
        };

        for (kind, path) in declared {
            if !path.starts_with('.') {
                continue;
            }
            let target = normalize(&base.join(&path));
            if target.exists() {
                continue;
            }
            broken.push(Broken {
                manifest: relative(&manifest, root),
                kind,
                declared: path,
                resolves_to: relative(&target, root),
            });
        }
    }
    broken
}

/// `path = "…"` — Cargo's spelling, and pyproject's.
fn quoted_after(text: &str, key: &str, kind: &'static str) -> Vec<(&'static str, String)> {
    let mut found = Vec::new();
    for line in text.lines() {
        let trimmed = line.trim_start();
        if trimmed.starts_with('#') {
            continue;
        }
        // Both `path = "…"` on its own line and `{ path = "…" }` inline.
        let mut rest = trimmed;
        while let Some(at) = rest.find(key) {
            rest = &rest[at + key.len()..];
            let after = rest.trim_start();
            let Some(after) = after.strip_prefix('=') else {
                continue;
            };
            let after = after.trim_start();
            if let Some(value) = quoted(after) {
                found.push((kind, value));
            }
        }
    }
    found
}

/// `.package(path: "…")` and `path: "…"` in a Swift manifest.
fn swift_paths(text: &str) -> Vec<(&'static str, String)> {
    let mut found = Vec::new();
    for line in text.lines() {
        let trimmed = line.trim_start();
        if trimmed.starts_with("//") {
            continue;
        }
        let mut rest = trimmed;
        while let Some(at) = rest.find("path:") {
            rest = &rest["path:".len() + at..];
            if let Some(value) = quoted(rest.trim_start()) {
                found.push(("swift package path", value));
            }
        }
    }
    found
}

/// `"name": "file:…"` in any dependency section.
fn json_file_deps(text: &str) -> Vec<(&'static str, String)> {
    let Ok(value) = serde_json::from_str::<serde_json::Value>(text) else {
        return Vec::new();
    };
    let mut found = Vec::new();
    for section in [
        "dependencies",
        "devDependencies",
        "optionalDependencies",
        "peerDependencies",
    ] {
        let Some(table) = value.get(section).and_then(serde_json::Value::as_object) else {
            continue;
        };
        for spec in table.values().filter_map(serde_json::Value::as_str) {
            if let Some(path) = spec
                .strip_prefix("file:")
                .or_else(|| spec.strip_prefix("link:"))
            {
                found.push(("npm file: dependency", path.to_string()));
            }
        }
    }
    found
}

/// A lockfile's linked packages — the copy of the claim that npm actually acts
/// on, and the one that goes stale without the manifest changing at all.
fn lock_links(text: &str) -> Vec<(&'static str, String)> {
    let Ok(value) = serde_json::from_str::<serde_json::Value>(text) else {
        return Vec::new();
    };
    let Some(packages) = value.get("packages").and_then(serde_json::Value::as_object) else {
        return Vec::new();
    };
    let mut found = Vec::new();
    for (key, entry) in packages {
        if key.starts_with("..") {
            found.push(("lockfile package", key.clone()));
        }
        if let Some(resolved) = entry.get("resolved").and_then(serde_json::Value::as_str) {
            if resolved.starts_with("..") {
                found.push(("lockfile link", resolved.to_string()));
            }
        }
    }
    found
}

/// The contents of the first double-quoted string.
fn quoted(text: &str) -> Option<String> {
    let rest = text.strip_prefix('"')?;
    let end = rest.find('"')?;
    Some(rest[..end].to_string())
}

/// `a/b/../c` → `a/c`, without touching the filesystem: the point is to report
/// where a path POINTS, including when nothing is there.
fn normalize(path: &Path) -> PathBuf {
    let mut out = PathBuf::new();
    for part in path.components() {
        match part {
            std::path::Component::ParentDir => {
                out.pop();
            }
            std::path::Component::CurDir => {}
            other => out.push(other.as_os_str()),
        }
    }
    out
}

fn relative(path: &Path, root: &Path) -> String {
    crate::platform::slash_path(path.strip_prefix(root).unwrap_or(path))
}

/// An absolute path, committed, under somebody's home directory.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HomeRooted {
    pub manifest: String,
    pub line: usize,
    pub path: String,
}

/// Absolute paths into a home directory, in files the repository carries.
///
/// A relative path can be wrong after a move; an absolute one under `/Users/x`
/// or `/home/x` is wrong for everybody except x, and stays wrong. It is not a
/// configuration — it is one machine's layout, committed.
///
/// This is what an Xcode legacy target's `buildToolPath` was: the full path to
/// a script in one developer's checkout, which stopped resolving on that
/// developer's own machine the day the client moved into the app superrepo,
/// and had never resolved on anybody else's.
///
/// Only files git TRACKS are considered. A machine-local `.wsb/state.json`
/// records absolute paths because that is exactly its job.
pub fn home_rooted(root: &Path) -> Vec<HomeRooted> {
    // `/Users/<name>/` and `/home/<name>/` — a home directory with something
    // in it. `/Users/Shared` and a bare `/home` are not one person's.
    let pattern = regex_lite_home();
    let mut found = Vec::new();
    for manifest in manifests(root) {
        let relative_path = relative(&manifest, root);
        if !tracked(&manifest) {
            continue;
        }
        let Ok(text) = std::fs::read_to_string(&manifest) else {
            continue;
        };
        for (number, line) in text.lines().enumerate() {
            for hit in pattern(line) {
                found.push(HomeRooted {
                    manifest: relative_path.clone(),
                    line: number + 1,
                    path: hit,
                });
            }
        }
    }
    found
}

/// Whether git has this file. An untracked one is somebody's own state.
///
/// Asked of the repository the file is IN. A superproject's git answers "not
/// tracked" for every file inside a submodule, which would silently excuse the
/// whole worktree from this check.
fn tracked(file: &Path) -> bool {
    let Some(repository) = repository_of(file) else {
        return false;
    };
    let Ok(relative_path) = file.strip_prefix(&repository) else {
        return false;
    };
    crate::git_backend::git_command()
        .arg("-C")
        .arg(&repository)
        .args(["ls-files", "--error-unmatch"])
        .arg(relative_path)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .map(|status| status.success())
        .unwrap_or(false)
}

/// The nearest enclosing repository — the one whose git knows this file.
fn repository_of(file: &Path) -> Option<PathBuf> {
    let mut at = file.parent()?;
    loop {
        // A submodule's `.git` is a FILE pointing at the real directory, so
        // existence is the test rather than being a directory.
        if at.join(".git").exists() {
            return Some(at.to_path_buf());
        }
        at = at.parent()?;
    }
}

/// Every `/Users/<name>/…` or `/home/<name>/…` in one line.
///
/// Hand-rolled rather than a regular expression: this crate has no regex
/// dependency, and the shape is two literals and a scan.
fn regex_lite_home() -> impl Fn(&str) -> Vec<String> {
    |line: &str| {
        let mut found = Vec::new();
        for prefix in ["/Users/", "/home/"] {
            let mut rest = line;
            while let Some(at) = rest.find(prefix) {
                let tail = &rest[at..];
                let end = tail
                    .find(|c: char| c.is_whitespace() || c == '"' || c == ';' || c == '\'')
                    .unwrap_or(tail.len());
                let path = &tail[..end];
                // A home directory with a name and something under it:
                // `/Users/x/y`, not `/Users` or `/home/`.
                let parts: Vec<&str> = path.trim_end_matches('/').split('/').collect();
                if parts.len() > 3 && !parts[2].is_empty() {
                    found.push(path.to_string());
                }
                rest = &tail[end.max(1)..];
            }
        }
        found
    }
}

/// A source file the repository does not have.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Hidden {
    /// The file, worktree-relative.
    pub path: String,
    /// The ignore rule that hides it, as `git check-ignore -v` states it.
    pub rule: String,
}

/// Source files git is ignoring.
///
/// The other half of "does the tree contain what the build reads". An ignore
/// pattern meant for output — `logs/`, `build/`, `dist/` — is unanchored
/// unless it is written with a leading slash, so it matches a directory of
/// that name at ANY depth. A source directory that happens to share the name
/// is then invisible: `git status` reports a clean tree, `git add -A` adds
/// nothing, `commit -a` records the deletions around it and none of it, and
/// the loss is discovered on another machine as a module that does not exist.
///
/// That is not hypothetical. `src/logs/` — the module that implements this
/// logging — was swallowed by a bare `logs/`, and the next machine to pull
/// could not compile.
///
/// Asked of git rather than of the patterns: `check-ignore` is the authority
/// on what git will do, and re-implementing pattern matching would produce a
/// second opinion that is wrong in exactly the cases that matter.
pub fn hidden_source(root: &Path) -> Vec<Hidden> {
    // EVERY repository, not just the outermost one. `git ls-files` answers
    // only about the repository it is run in, and a superproject's git knows
    // nothing about the files inside its submodules — which is nearly every
    // file here. Asked only at the top, this check reported a clean worktree
    // by looking at a fraction of it.
    let mut found = Vec::new();
    for repository in crate::catalogue::scan::repositories(root) {
        for mut hidden in hidden_source_in(&repository) {
            // Named from the worktree, so a report says where to look.
            if let Ok(prefix) = repository.strip_prefix(root) {
                if !prefix.as_os_str().is_empty() {
                    hidden.path = format!("{}/{}", crate::platform::slash_path(prefix), hidden.path);
                }
            }
            found.push(hidden);
        }
    }
    found
}

/// The same question, of one repository.
fn hidden_source_in(root: &Path) -> Vec<Hidden> {
    const SOURCE: [&str; 9] = ["rs", "swift", "go", "py", "ts", "tsx", "svelte", "proto", "sql"];
    // Directories that hold output or other people's trees. A source file
    // under one of these is ignored on purpose.
    const OUTPUT: [&str; 14] = [
        "node_modules", "target", ".build", "dist", "out", "build", "DerivedData",
        "__pycache__", ".venv", "vendor", "generated", "Generated", ".scrap",
        "coverage",
    ];

    // Through the one git constructor in this crate: it strips the repository
    // scoping a parent may have inherited — a check that read ANOTHER
    // repository's ignore rules would report confidently about the wrong tree
    // — and packages the subprocess into the run's output like every other.
    let listed = crate::git_backend::git_command()
        .arg("-C")
        .arg(root)
        .args(["ls-files", "--others", "--ignored", "--exclude-standard"])
        .output();
    let Ok(listed) = listed else {
        return Vec::new();
    };
    if !listed.status.success() {
        return Vec::new();
    }

    let mut hidden = Vec::new();
    for line in String::from_utf8_lossy(&listed.stdout).lines() {
        let path = Path::new(line);
        let is_source = path
            .extension()
            .and_then(|e| e.to_str())
            .is_some_and(|ext| SOURCE.contains(&ext));
        if !is_source {
            continue;
        }
        if path
            .components()
            .filter_map(|c| c.as_os_str().to_str())
            .any(|part| OUTPUT.contains(&part) || part.starts_with("dist-"))
        {
            continue;
        }
        // Which rule hides it, so the report says what to change.
        let rule = crate::git_backend::git_command()
            .arg("-C")
            .arg(root)
            .args(["check-ignore", "-v", line])
            .output()
            .ok()
            .map(|out| String::from_utf8_lossy(&out.stdout).trim().to_string())
            .filter(|text| !text.is_empty())
            .unwrap_or_else(|| "an ignore rule".to_string());
        hidden.push(Hidden {
            path: line.to_string(),
            rule,
        });
    }
    hidden
}

#[cfg(test)]
#[path = "local_paths_tests.rs"]
mod tests;