opi 0.5.3

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
433
434
435
436
437
438
439
//! Reading `package.json`.
//!
//! The manifest is the only project interface `opi` has. Everything downstream —
//! project detection, the task list — is derived from what this module returns,
//! so parsing happens once and the result is shared.

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

use serde::{Deserialize, Deserializer};

/// The parts of `package.json` that `opi` uses.
///
/// Unknown fields are ignored, so any real-world manifest parses.
#[derive(Debug, Default, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Manifest {
    pub name: Option<String>,
    pub version: Option<String>,
    pub package_manager: Option<String>,
    #[serde(default)]
    pub scripts: BTreeMap<String, String>,
    /// Descriptions, keyed by script name. Deliberately the `scripts-info`
    /// field `nr` already uses, so projects that maintain it benefit unchanged.
    #[serde(default, rename = "scripts-info")]
    pub scripts_info: BTreeMap<String, String>,
    /// Workspace member patterns. npm, yarn and bun declare these here; pnpm
    /// uses `pnpm-workspace.yaml` instead.
    #[serde(default, deserialize_with = "workspace_patterns")]
    pub workspaces: Vec<String>,
    /// The `opi` block, kept unparsed on purpose.
    ///
    /// Typed straight into a struct, a field of the wrong type would fail the
    /// whole `package.json` parse and make `opi` useless in a project whose
    /// `scripts` are perfectly fine. Reading it leniently keeps a typo here
    /// from costing everything else.
    #[serde(default)]
    opi: serde_json::Value,
    #[serde(default)]
    dependencies: BTreeMap<String, String>,
    #[serde(default, rename = "devDependencies")]
    dev_dependencies: BTreeMap<String, String>,
}

/// Accepts both shapes the `workspaces` field takes: a bare list, or an object
/// with a `packages` list. yarn introduced the second for its `nohoist` option
/// and real manifests still use it.
fn workspace_patterns<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<String>, D::Error> {
    #[derive(Deserialize)]
    #[serde(untagged)]
    enum Field {
        List(Vec<String>),
        Object {
            #[serde(default)]
            packages: Vec<String>,
        },
    }

    Ok(match Field::deserialize(deserializer)? {
        Field::List(patterns) | Field::Object { packages: patterns } => patterns,
    })
}

impl Manifest {
    /// Finds the nearest `package.json`, searching `dir` and then its parents.
    ///
    /// Running `opi` from somewhere inside a project should work the way `npm`
    /// does, rather than only from the directory holding the manifest.
    ///
    /// Returns the directory it was found in, which is the project root for
    /// everything downstream — workspace patterns resolve against it, and it
    /// names the project when the manifest does not.
    pub fn discover(dir: &Path) -> Result<(Self, PathBuf), ManifestError> {
        for candidate in dir.ancestors() {
            match Self::load(candidate) {
                Ok(manifest) => return Ok((manifest, candidate.to_path_buf())),
                Err(ManifestError::Missing { .. }) => {}
                Err(error) => return Err(error),
            }
        }

        Err(ManifestError::Missing {
            directory: dir.to_path_buf(),
        })
    }

    /// Loads and parses `package.json` from `dir`.
    pub fn load(dir: &Path) -> Result<Self, ManifestError> {
        let path = dir.join("package.json");
        let contents = match std::fs::read_to_string(&path) {
            Ok(contents) => contents,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
                return Err(ManifestError::Missing {
                    directory: dir.to_path_buf(),
                });
            }
            Err(error) => return Err(ManifestError::Unreadable { path, error }),
        };

        serde_json::from_str(&contents).map_err(|error| ManifestError::Malformed { path, error })
    }

    /// What the project says about one script, beyond its command.
    ///
    /// Every field is read defensively and independently: a `favorite` that is
    /// a string rather than a boolean costs that one field, not the entry and
    /// certainly not the manifest.
    pub fn script_meta(&self, script: &str) -> ScriptMeta {
        let Some(entry) = self
            .opi
            .get("scripts")
            .and_then(|scripts| scripts.get(script))
        else {
            return ScriptMeta::default();
        };

        ScriptMeta {
            description: entry
                .get("description")
                .and_then(serde_json::Value::as_str)
                .map(str::trim)
                .filter(|text| !text.is_empty())
                .map(str::to_owned),
            group: entry
                .get("group")
                .and_then(serde_json::Value::as_str)
                .map(str::trim)
                .filter(|text| !text.is_empty())
                .map(str::to_owned),
            favorite: entry
                .get("favorite")
                .and_then(serde_json::Value::as_bool)
                .unwrap_or(false),
            confirm: entry
                .get("confirm")
                .and_then(serde_json::Value::as_bool)
                .unwrap_or(false),
        }
    }

    /// The strings under `opi.<key>`, ignoring anything of another shape.
    pub fn opi_list(&self, key: &str) -> Vec<String> {
        self.opi
            .get(key)
            .and_then(serde_json::Value::as_array)
            .map(|values| {
                values
                    .iter()
                    .filter_map(|value| value.as_str().map(str::to_owned))
                    .collect()
            })
            .unwrap_or_default()
    }

    /// Whether the project depends on `package`, in either dependency set.
    ///
    /// Which one it is in does not matter here: a tool is available to run
    /// either way.
    pub fn depends_on(&self, package: &str) -> bool {
        self.dependencies.contains_key(package) || self.dev_dependencies.contains_key(package)
    }

    /// The description for `script`, if the project provides one.
    ///
    /// `opi.scripts.<name>.description` wins over `scripts-info`, and both may
    /// name the same script: that is the intended way to say something to
    /// `opi` without changing what `nr` and `npm-scripts-info` read.
    ///
    /// A blank entry counts as absent — an empty description column is better
    /// than a column of whitespace.
    pub fn description(&self, script: &str) -> Option<String> {
        self.script_meta(script).description.or_else(|| {
            self.scripts_info
                .get(script)
                .map(|text| text.trim())
                .filter(|text| !text.is_empty())
                .map(str::to_owned)
        })
    }
}

/// What a project says about one of its scripts.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct ScriptMeta {
    /// Wins over `scripts-info`, which stays valid for `nr` and its kin.
    pub description: Option<String>,
    /// Overrides the group derived from the script's name.
    pub group: Option<String>,
    /// Lifted out of its group, to the top of the list.
    pub favorite: bool,
    /// Asked about before it runs.
    pub confirm: bool,
}

/// Why `package.json` could not be turned into a [`Manifest`].
///
/// The three cases stay distinct because they need different remedies.
#[derive(Debug)]
pub enum ManifestError {
    Missing {
        directory: PathBuf,
    },
    Unreadable {
        path: PathBuf,
        error: std::io::Error,
    },
    Malformed {
        path: PathBuf,
        error: serde_json::Error,
    },
}

impl fmt::Display for ManifestError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Missing { directory } => {
                write!(f, "No package.json in {}", directory.display())
            }
            Self::Unreadable { path, error } => {
                write!(f, "Cannot read {}: {error}", path.display())
            }
            Self::Malformed { path, error } => {
                write!(f, "Cannot parse {}: {error}", path.display())
            }
        }
    }
}

impl std::error::Error for ManifestError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Missing { .. } => None,
            Self::Unreadable { error, .. } => Some(error),
            Self::Malformed { error, .. } => Some(error),
        }
    }
}

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

    fn load(contents: &str) -> Result<Manifest, ManifestError> {
        let dir = tempfile::tempdir().expect("temp dir");
        fs::write(dir.path().join("package.json"), contents).expect("write");
        Manifest::load(dir.path())
    }

    #[test]
    fn reads_scripts_and_descriptions() {
        let manifest = load(r#"{"scripts":{"dev":"astro dev"},"scripts-info":{"dev":"Start"}}"#)
            .expect("parse");
        assert_eq!(
            manifest.scripts.get("dev").map(String::as_str),
            Some("astro dev")
        );
        assert_eq!(manifest.description("dev").as_deref(), Some("Start"));
    }

    #[test]
    fn missing_sections_are_empty_not_an_error() {
        let manifest = load(r#"{"name":"x"}"#).expect("parse");
        assert!(manifest.scripts.is_empty());
        assert!(manifest.scripts_info.is_empty());
    }

    #[test]
    fn blank_description_counts_as_absent() {
        let manifest =
            load(r#"{"scripts":{"dev":"x"},"scripts-info":{"dev":"   "}}"#).expect("parse");
        assert_eq!(manifest.description("dev"), None);
    }

    #[test]
    fn unknown_fields_are_ignored() {
        let manifest = load(r#"{"dependencies":{"astro":"^6"},"type":"module"}"#).expect("parse");
        assert!(manifest.name.is_none());
    }

    #[test]
    fn workspaces_accepts_a_bare_list() {
        let manifest = load(r#"{"workspaces":["packages/*","apps/*"]}"#).expect("parse");
        assert_eq!(manifest.workspaces, ["packages/*", "apps/*"]);
    }

    #[test]
    fn workspaces_accepts_the_object_form() {
        let manifest = load(r#"{"workspaces":{"packages":["packages/*"],"nohoist":["**/x"]}}"#)
            .expect("parse");
        assert_eq!(manifest.workspaces, ["packages/*"]);
    }

    #[test]
    fn no_workspaces_field_is_empty() {
        assert!(
            load(r#"{"name":"x"}"#)
                .expect("parse")
                .workspaces
                .is_empty()
        );
    }

    #[test]
    fn discover_walks_up_to_the_nearest_manifest() {
        let dir = tempfile::tempdir().expect("temp dir");
        fs::write(dir.path().join("package.json"), r#"{"name":"root"}"#).expect("write");
        let deep = dir.path().join("src").join("components");
        fs::create_dir_all(&deep).expect("mkdir");

        let (manifest, root) = Manifest::discover(&deep).expect("discover");
        assert_eq!(manifest.name.as_deref(), Some("root"));
        assert_eq!(
            root.canonicalize().expect("canonicalize"),
            dir.path().canonicalize().expect("canonicalize")
        );
    }

    #[test]
    fn discover_stops_at_the_closest_manifest() {
        let dir = tempfile::tempdir().expect("temp dir");
        fs::write(dir.path().join("package.json"), r#"{"name":"root"}"#).expect("write");
        let inner = dir.path().join("apps").join("blog");
        fs::create_dir_all(&inner).expect("mkdir");
        fs::write(inner.join("package.json"), r#"{"name":"blog"}"#).expect("write");

        let (manifest, _) = Manifest::discover(&inner).expect("discover");
        assert_eq!(manifest.name.as_deref(), Some("blog"));
    }

    #[test]
    fn opi_beats_scripts_info_without_invalidating_it() {
        // Both may name the same script: that is how a project says something
        // to opi without changing what nr reads.
        let manifest = load(
            r#"{"scripts":{"dev":"x"},"scripts-info":{"dev":"Start development server"},
                "opi":{"scripts":{"dev":{"description":"Start OPI development environment"}}}}"#,
        )
        .expect("parse");
        assert_eq!(
            manifest.description("dev").as_deref(),
            Some("Start OPI development environment")
        );
        assert_eq!(
            manifest.scripts_info.get("dev").map(String::as_str),
            Some("Start development server"),
            "the older line is untouched"
        );
    }

    #[test]
    fn script_metadata_is_read_field_by_field() {
        let manifest = load(
            r#"{"scripts":{"deploy":"x"},
                "opi":{"scripts":{"deploy":{"group":"Deployment","confirm":true}}}}"#,
        )
        .expect("parse");
        let meta = manifest.script_meta("deploy");
        assert_eq!(meta.group.as_deref(), Some("Deployment"));
        assert!(meta.confirm);
        assert!(!meta.favorite, "absent means false, not unknown");
    }

    #[test]
    fn a_field_of_the_wrong_type_costs_only_that_field() {
        let manifest = load(
            r#"{"scripts":{"dev":"x"},
                "opi":{"scripts":{"dev":{"favorite":"yes please","group":"Development"}}}}"#,
        )
        .expect("parse");
        let meta = manifest.script_meta("dev");
        assert!(!meta.favorite, "a string is not a boolean");
        assert_eq!(
            meta.group.as_deref(),
            Some("Development"),
            "and the rest survives"
        );
    }

    #[test]
    fn metadata_for_an_unknown_script_is_simply_empty() {
        let manifest =
            load(r#"{"scripts":{"dev":"x"},"opi":{"scripts":{"gone":{"favorite":true}}}}"#)
                .expect("parse");
        assert_eq!(manifest.script_meta("dev"), ScriptMeta::default());
    }

    #[test]
    fn the_opi_block_is_read_leniently() {
        let manifest =
            load(r#"{"scripts":{"dev":"x"},"opi":{"clean":["dist",".astro"]}}"#).expect("parse");
        assert_eq!(manifest.opi_list("clean"), ["dist", ".astro"]);
        assert!(manifest.opi_list("health").is_empty());
    }

    #[test]
    fn a_malformed_opi_block_does_not_cost_the_scripts() {
        // Typed into a struct, a wrong type here would fail the whole parse and
        // make opi useless in a project whose scripts are fine.
        for broken in [
            r#"{"scripts":{"dev":"x"},"opi":"not an object"}"#,
            r#"{"scripts":{"dev":"x"},"opi":{"clean":"not a list"}}"#,
            r#"{"scripts":{"dev":"x"},"opi":{"clean":[1,2,{"a":"b"}]}}"#,
            r#"{"scripts":{"dev":"x"},"opi":42}"#,
        ] {
            let manifest = load(broken).unwrap_or_else(|_| panic!("should parse: {broken}"));
            assert_eq!(manifest.scripts.len(), 1, "for {broken}");
            assert!(manifest.opi_list("clean").is_empty(), "for {broken}");
        }
    }

    #[test]
    fn dependencies_are_found_in_either_set() {
        let manifest =
            load(r#"{"dependencies":{"astro":"^7"},"devDependencies":{"@biomejs/biome":"^2"}}"#)
                .expect("parse");
        assert!(manifest.depends_on("astro"));
        assert!(manifest.depends_on("@biomejs/biome"));
        assert!(!manifest.depends_on("eslint"));
    }

    #[test]
    fn missing_file_is_its_own_error() {
        let dir = tempfile::tempdir().expect("temp dir");
        assert!(matches!(
            Manifest::load(dir.path()),
            Err(ManifestError::Missing { .. })
        ));
    }

    #[test]
    fn malformed_json_is_reported() {
        assert!(matches!(
            load("{ not json"),
            Err(ManifestError::Malformed { .. })
        ));
    }
}