opi 0.13.2

Operations Interface — a project control center for your terminal
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
//! Workspace member discovery.
//!
//! A monorepo root usually carries orchestrating scripts of its own while the
//! interesting per-app scripts live in its members. Finding the members lets
//! `opi` offer both from one place.
//!
//! Patterns come from `pnpm-workspace.yaml` or the `workspaces` field, and are
//! matched against the filesystem. Nothing here runs the package manager.

use std::path::{Path, PathBuf};

use crate::manifest::Manifest;

/// A workspace member.
#[derive(Debug, Clone)]
pub struct Member {
    /// The package's `name`, used to address it when running a script.
    pub name: String,
    /// Where it lives. Its own tools are installed there, not at the root:
    /// pnpm does not hoist a member's binaries.
    pub path: PathBuf,
    pub manifest: Manifest,
}

/// Finds the members of the workspace rooted at `dir` that have something to
/// run.
///
/// Returns an empty list for a project that declares no workspace, so the
/// caller needs no special case for the ordinary single-package repository.
/// A member without scripts has nothing to offer a menu, so it is left out
/// here — [`all`] answers the question for callers that need every member
/// regardless, such as health, clean and security, which look inside a
/// member's directory rather than at its scripts.
pub fn members(dir: &Path, manifest: &Manifest) -> Vec<Member> {
    all(dir, manifest)
        .into_iter()
        .filter(|member| !member.manifest.scripts.is_empty())
        .collect()
}

/// Finds every member of the workspace rooted at `dir`, whether or not it
/// declares scripts.
///
/// Returns an empty list for a project that declares no workspace, so the
/// caller needs no special case for the ordinary single-package repository.
pub fn all(dir: &Path, manifest: &Manifest) -> Vec<Member> {
    let (includes, excludes) = patterns(dir, manifest);
    if includes.is_empty() {
        return Vec::new();
    }

    // A workspace may list "." among its packages, making the root its own
    // member. Its scripts are already on screen, so including it again shows
    // every one of them twice.
    let root = dir.canonicalize().ok();

    let mut members: Vec<Member> = expand(dir, &includes)
        .into_iter()
        .filter(|path| path.canonicalize().ok() != root)
        .filter(|path| !matches_any(dir, path, &excludes))
        .filter_map(|path| {
            let manifest = Manifest::load(&path).ok()?;
            let name = manifest.name.clone().or_else(|| {
                path.file_name()
                    .map(|name| name.to_string_lossy().into_owned())
            })?;
            Some(Member {
                name,
                path,
                manifest,
            })
        })
        .collect();

    members.sort_by(|a, b| a.name.cmp(&b.name));
    members.dedup_by(|a, b| a.name == b.name);
    members
}

/// The include and exclude patterns declared by the workspace.
/// Whether this project declares a workspace at all.
///
/// Deliberately not "does [`members`] return anything": that drops members
/// without scripts, because a package with none has nothing to show in the
/// list. [`all`] is the answer for a caller that needs those too; this is for
/// a caller that only needs to know whether a workspace exists at all.
pub fn declared(dir: &Path, manifest: &Manifest) -> bool {
    !patterns(dir, manifest).0.is_empty()
}

fn patterns(dir: &Path, manifest: &Manifest) -> (Vec<String>, Vec<String>) {
    let declared = pnpm_packages(&dir.join("pnpm-workspace.yaml"))
        .unwrap_or_else(|| manifest.workspaces.clone());

    let (excludes, includes): (Vec<String>, Vec<String>) = declared
        .into_iter()
        .partition(|pattern| pattern.starts_with('!'));

    (
        includes,
        excludes
            .into_iter()
            .map(|pattern| pattern[1..].to_owned())
            .collect(),
    )
}

/// Reads the `packages:` list out of a `pnpm-workspace.yaml`.
///
/// Deliberately reads only that one block. Real files carry several unrelated
/// top-level keys whose values are also lists — `minimumReleaseAgeExclude` and
/// `trustPolicyExclude` among them — and a parser that collected every `- item`
/// in the file would treat those version pins as workspace packages.
///
/// Returns `None` when the file is absent or declares no `packages:` key, so
/// the caller can fall back to the manifest.
fn pnpm_packages(path: &Path) -> Option<Vec<String>> {
    let contents = std::fs::read_to_string(path).ok()?;
    let mut packages = Vec::new();
    let mut inside = false;

    for line in contents.lines() {
        let trimmed = line.trim_end();
        if trimmed.trim_start().starts_with('#') || trimmed.trim().is_empty() {
            continue;
        }

        if inside {
            // Any line back at column zero ends the block.
            if !trimmed.starts_with([' ', '\t']) {
                break;
            }
            if let Some(entry) = trimmed.trim_start().strip_prefix("- ") {
                packages.push(unquote(entry));
            }
            continue;
        }

        if trimmed.starts_with("packages:") {
            inside = true;
        }
    }

    inside.then_some(packages)
}

/// Strips surrounding quotes and a trailing comment.
fn unquote(entry: &str) -> String {
    let entry = entry.trim();
    let entry = match entry.chars().next() {
        Some(quote @ ('\'' | '"')) => entry
            .strip_prefix(quote)
            .and_then(|rest| rest.split(quote).next())
            .unwrap_or(entry),
        _ => entry.split('#').next().unwrap_or(entry).trim(),
    };
    entry.to_owned()
}

/// Resolves patterns to directories that hold a `package.json`.
fn expand(dir: &Path, patterns: &[String]) -> Vec<PathBuf> {
    let mut found = Vec::new();

    for pattern in patterns {
        let full = dir.join(pattern).join("package.json");
        let Some(pattern) = full.to_str() else {
            continue;
        };
        let Ok(paths) = glob::glob(pattern) else {
            continue;
        };
        for path in paths.flatten() {
            // A pattern like `packages/**/*` reaches into installed
            // dependencies, which are not workspace members.
            if path
                .components()
                .any(|part| part.as_os_str() == "node_modules")
            {
                continue;
            }
            if let Some(parent) = path.parent() {
                found.push(parent.to_path_buf());
            }
        }
    }

    found.sort();
    found.dedup();
    found
}

/// Whether `path` is covered by any of the exclude patterns.
fn matches_any(dir: &Path, path: &Path, patterns: &[String]) -> bool {
    patterns.iter().any(|pattern| {
        let pattern = dir.join(pattern);
        pattern
            .to_str()
            .and_then(|pattern| glob::Pattern::new(pattern).ok())
            .is_some_and(|pattern| pattern.matches_path(path))
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;

    /// Builds a workspace on disk and discovers its members.
    fn workspace(files: &[(&str, &str)]) -> (tempfile::TempDir, Vec<Member>) {
        let dir = tempfile::tempdir().expect("temp dir");
        for (path, contents) in files {
            let full = dir.path().join(path);
            if let Some(parent) = full.parent() {
                fs::create_dir_all(parent).expect("mkdir");
            }
            fs::write(full, contents).expect("write");
        }
        let manifest = Manifest::load(dir.path()).expect("root manifest");
        let members = members(dir.path(), &manifest);
        (dir, members)
    }

    fn names(members: &[Member]) -> Vec<&str> {
        members.iter().map(|member| member.name.as_str()).collect()
    }

    #[test]
    fn a_project_without_a_workspace_has_no_members() {
        let (_dir, members) = workspace(&[("package.json", r#"{"name":"solo"}"#)]);
        assert!(members.is_empty());
    }

    #[test]
    fn the_workspaces_field_finds_members() {
        let (_dir, members) = workspace(&[
            ("package.json", r#"{"name":"root","workspaces":["apps/*"]}"#),
            (
                "apps/blog/package.json",
                r#"{"name":"blog","scripts":{"dev":"x"}}"#,
            ),
            (
                "apps/shop/package.json",
                r#"{"name":"shop","scripts":{"dev":"x"}}"#,
            ),
        ]);
        assert_eq!(names(&members), ["blog", "shop"]);
    }

    #[test]
    fn pnpm_workspace_yaml_wins_over_the_manifest_field() {
        let (_dir, members) = workspace(&[
            (
                "package.json",
                r#"{"name":"root","workspaces":["ignored/*"]}"#,
            ),
            ("pnpm-workspace.yaml", "packages:\n  - 'apps/*'\n"),
            (
                "apps/blog/package.json",
                r#"{"name":"blog","scripts":{"dev":"x"}}"#,
            ),
            (
                "ignored/nope/package.json",
                r#"{"name":"nope","scripts":{"dev":"x"}}"#,
            ),
        ]);
        assert_eq!(names(&members), ["blog"]);
    }

    #[test]
    fn only_the_packages_block_of_the_yaml_is_read() {
        // Real pnpm-workspace.yaml files carry several unrelated top-level keys
        // whose values are also lists. Collecting every "- item" would turn
        // version pins into workspace packages.
        let yaml = "packages:\n  - 'apps/*'\n\nminimumReleaseAgeExclude:\n  - '@biomejs/*'\n  - 'apps/*'\n\noverrides:\n  nanoid: ^3.3.18\n";
        let (_dir, members) = workspace(&[
            ("package.json", r#"{"name":"root"}"#),
            ("pnpm-workspace.yaml", yaml),
            (
                "apps/blog/package.json",
                r#"{"name":"blog","scripts":{"dev":"x"}}"#,
            ),
        ]);
        assert_eq!(names(&members), ["blog"]);
    }

    #[test]
    fn negated_patterns_exclude_members() {
        let yaml = "packages:\n  - 'apps/*'\n  - '!apps/private'\n";
        let (_dir, members) = workspace(&[
            ("package.json", r#"{"name":"root"}"#),
            ("pnpm-workspace.yaml", yaml),
            (
                "apps/blog/package.json",
                r#"{"name":"blog","scripts":{"dev":"x"}}"#,
            ),
            (
                "apps/private/package.json",
                r#"{"name":"private","scripts":{"dev":"x"}}"#,
            ),
        ]);
        assert_eq!(names(&members), ["blog"]);
    }

    #[test]
    fn the_root_is_not_a_member_of_itself() {
        // Found in a real repository: pnpm-workspace.yaml listing "." made
        // every root script appear a second time under its own package name.
        let (_dir, members) = workspace(&[
            (
                "package.json",
                r#"{"name":"@casoon/thing","scripts":{"build":"x"}}"#,
            ),
            ("pnpm-workspace.yaml", "packages:\n  - '.'\n"),
        ]);
        assert!(members.is_empty());
    }

    #[test]
    fn a_workspace_with_no_scripted_members_is_still_a_workspace() {
        // The bug this pins: --updates asked whether `members` returned
        // anything, which drops members without scripts, and then queried pnpm
        // without -r. In a workspace whose root declares no dependencies that
        // answers `{}`, so it reported "everything is current" over stale
        // packages.
        let (dir, members) = workspace(&[
            ("package.json", r#"{"name":"root","workspaces":["apps/*"]}"#),
            ("apps/lib/package.json", r#"{"name":"lib"}"#),
        ]);
        assert!(members.is_empty(), "nothing to list");
        let manifest = Manifest::load(dir.path()).expect("manifest");
        assert!(declared(dir.path(), &manifest), "still a workspace");
    }

    #[test]
    fn a_plain_project_declares_no_workspace() {
        let (dir, _) = workspace(&[("package.json", r#"{"name":"solo"}"#)]);
        let manifest = Manifest::load(dir.path()).expect("manifest");
        assert!(!declared(dir.path(), &manifest));
    }

    #[test]
    fn members_without_scripts_are_left_out() {
        let (_dir, members) = workspace(&[
            ("package.json", r#"{"name":"root","workspaces":["apps/*"]}"#),
            (
                "apps/blog/package.json",
                r#"{"name":"blog","scripts":{"dev":"x"}}"#,
            ),
            ("apps/types/package.json", r#"{"name":"types"}"#),
        ]);
        assert_eq!(
            names(&members),
            ["blog"],
            "a member with nothing to run is noise"
        );
    }

    #[test]
    fn all_keeps_members_without_scripts_that_members_leaves_out() {
        // Health and clean look inside a member's directory, not at its
        // scripts — a library with none still has a `tsconfig.json` to lint
        // and a `dist/` to clean, so it must not vanish here the way it does
        // from the menu.
        let dir = tempfile::tempdir().expect("temp dir");
        for (path, contents) in [
            ("package.json", r#"{"name":"root","workspaces":["apps/*"]}"#),
            (
                "apps/blog/package.json",
                r#"{"name":"blog","scripts":{"dev":"x"}}"#,
            ),
            ("apps/types/package.json", r#"{"name":"types"}"#),
        ] {
            let full = dir.path().join(path);
            if let Some(parent) = full.parent() {
                fs::create_dir_all(parent).expect("mkdir");
            }
            fs::write(full, contents).expect("write");
        }
        let manifest = Manifest::load(dir.path()).expect("root manifest");

        assert_eq!(names(&members(dir.path(), &manifest)), ["blog"]);
        assert_eq!(names(&all(dir.path(), &manifest)), ["blog", "types"]);
    }

    #[test]
    fn node_modules_is_never_a_workspace_member() {
        // "packages/**/*" reaches into installed dependencies otherwise.
        let (_dir, members) = workspace(&[
            (
                "package.json",
                r#"{"name":"root","workspaces":["packages/**/*"]}"#,
            ),
            (
                "packages/ui/package.json",
                r#"{"name":"ui","scripts":{"dev":"x"}}"#,
            ),
            (
                "packages/ui/node_modules/dep/package.json",
                r#"{"name":"dep","scripts":{"dev":"x"}}"#,
            ),
        ]);
        assert_eq!(names(&members), ["ui"]);
    }

    #[test]
    fn a_member_without_a_name_falls_back_to_its_directory() {
        let (_dir, members) = workspace(&[
            ("package.json", r#"{"name":"root","workspaces":["apps/*"]}"#),
            ("apps/blog/package.json", r#"{"scripts":{"dev":"x"}}"#),
        ]);
        assert_eq!(names(&members), ["blog"]);
    }

    #[test]
    fn comments_and_quoting_styles_are_tolerated() {
        let yaml =
            "# leading comment\npackages:\n  # inner comment\n  - \"apps/*\"\n  - 'shared'\n";
        let (_dir, members) = workspace(&[
            ("package.json", r#"{"name":"root"}"#),
            ("pnpm-workspace.yaml", yaml),
            (
                "apps/blog/package.json",
                r#"{"name":"blog","scripts":{"dev":"x"}}"#,
            ),
            (
                "shared/package.json",
                r#"{"name":"shared","scripts":{"build":"x"}}"#,
            ),
        ]);
        assert_eq!(names(&members), ["blog", "shared"]);
    }
}