fallow-config 2.77.0

Configuration types and workspace discovery for fallow codebase intelligence
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
//! Parser for the `catalog:` and `catalogs:` sections of `pnpm-workspace.yaml`.
//!
//! pnpm supports two catalog forms:
//! - the top-level `catalog:` map (the "default" catalog)
//! - the top-level `catalogs:` map of named catalogs
//!
//! ```yaml
//! catalog:
//!   react: ^18.2.0
//!   "@scope/lib": ^1.0.0
//!
//! catalogs:
//!   react17:
//!     react: ^17.0.2
//!     react-dom: ^17.0.2
//! ```
//!
//! Workspace packages reference catalog entries from their `dependencies`
//! (and friends) with the `catalog:` protocol:
//!
//! ```json
//! { "dependencies": { "react": "catalog:", "old-react": "catalog:react17" } }
//! ```
//!
//! For the unused-catalog-entry detector we need both the structured catalog
//! map and the 1-based line number of each entry in the source so findings
//! can point users to the exact line. `serde_yaml_ng` gives us the structural
//! parse; a second targeted scan over the raw source recovers the line
//! numbers.

/// Structured catalog data extracted from a `pnpm-workspace.yaml` file.
#[derive(Debug, Clone, Default)]
pub struct PnpmCatalogData {
    /// Catalogs found in the file. The default catalog (top-level `catalog:`)
    /// always appears first with `name = "default"` when present; named
    /// catalogs follow in YAML source order.
    pub catalogs: Vec<PnpmCatalog>,
    /// Named catalogs under `catalogs:` that declare no package entries.
    ///
    /// The top-level `catalog:` map is intentionally not represented here:
    /// some repos keep it as a stable hook even when currently empty.
    pub empty_named_catalog_groups: Vec<PnpmCatalogGroup>,
}

/// A single catalog (the default or a named one).
#[derive(Debug, Clone)]
pub struct PnpmCatalog {
    /// Catalog name. `"default"` for the top-level `catalog:` map, or the
    /// named catalog key for entries declared under `catalogs.<name>:`.
    pub name: String,
    /// Entries declared in this catalog, in source order.
    pub entries: Vec<PnpmCatalogEntry>,
}

/// A single entry inside a catalog.
#[derive(Debug, Clone)]
pub struct PnpmCatalogEntry {
    /// Package name declared in the catalog (e.g. `"react"`, `"@scope/lib"`).
    pub package_name: String,
    /// 1-based line number of the entry within the source file.
    pub line: u32,
}

/// A named catalog group under `catalogs:` with no package entries.
#[derive(Debug, Clone)]
pub struct PnpmCatalogGroup {
    /// Catalog group name (e.g. `"react17"` for `catalogs.react17`).
    pub name: String,
    /// 1-based line number of the group header within the source file.
    pub line: u32,
}

/// Parse the catalog sections of a `pnpm-workspace.yaml` file.
///
/// Returns an empty `PnpmCatalogData` when the file has no catalog data, when
/// the YAML is malformed, or when the catalog sections are present but empty.
/// All non-catalog top-level keys (`packages`, `catalog`, `catalogs`, etc.)
/// are ignored.
#[must_use]
pub fn parse_pnpm_catalog_data(source: &str) -> PnpmCatalogData {
    let value: serde_yaml_ng::Value = match serde_yaml_ng::from_str(source) {
        Ok(v) => v,
        Err(_) => return PnpmCatalogData::default(),
    };
    let Some(mapping) = value.as_mapping() else {
        return PnpmCatalogData::default();
    };

    let line_index = build_line_index(source);
    let mut catalogs = Vec::new();
    let mut empty_named_catalog_groups = Vec::new();

    if let Some(default_value) = mapping.get("catalog")
        && let Some(default_map) = default_value.as_mapping()
    {
        let entries = collect_entries(default_map, &line_index, "default");
        if !entries.is_empty() {
            catalogs.push(PnpmCatalog {
                name: "default".to_string(),
                entries,
            });
        }
    }

    if let Some(named_value) = mapping.get("catalogs")
        && let Some(named_map) = named_value.as_mapping()
    {
        for (name_value, catalog_value) in named_map {
            let Some(name) = name_value.as_str() else {
                continue;
            };
            if let Some(catalog_map) = catalog_value.as_mapping() {
                let entries = collect_entries(catalog_map, &line_index, name);
                if entries.is_empty() {
                    if let Some(line) = line_index.group_line_for(name) {
                        empty_named_catalog_groups.push(PnpmCatalogGroup {
                            name: name.to_string(),
                            line,
                        });
                    }
                } else {
                    catalogs.push(PnpmCatalog {
                        name: name.to_string(),
                        entries,
                    });
                }
            } else if catalog_value.is_null()
                && let Some(line) = line_index.group_line_for(name)
            {
                empty_named_catalog_groups.push(PnpmCatalogGroup {
                    name: name.to_string(),
                    line,
                });
            }
        }
    }

    PnpmCatalogData {
        catalogs,
        empty_named_catalog_groups,
    }
}

fn collect_entries(
    mapping: &serde_yaml_ng::Mapping,
    line_index: &CatalogLineIndex,
    catalog_name: &str,
) -> Vec<PnpmCatalogEntry> {
    mapping
        .iter()
        .filter_map(|(k, _)| {
            let pkg = k.as_str()?;
            let line = line_index.line_for(catalog_name, pkg)?;
            Some(PnpmCatalogEntry {
                package_name: pkg.to_string(),
                line,
            })
        })
        .collect()
}

/// Maps `(catalog_name, package_name)` to its 1-based source line.
///
/// `catalog_name` is `"default"` for entries under the top-level `catalog:`
/// key, or the named catalog key for entries under `catalogs.<name>:`.
struct CatalogLineIndex {
    entries: Vec<((String, String), u32)>,
    groups: Vec<(String, u32)>,
}

impl CatalogLineIndex {
    fn line_for(&self, catalog_name: &str, package_name: &str) -> Option<u32> {
        self.entries
            .iter()
            .find(|((cat, pkg), _)| cat == catalog_name && pkg == package_name)
            .map(|(_, line)| *line)
    }

    fn group_line_for(&self, catalog_name: &str) -> Option<u32> {
        self.groups
            .iter()
            .find(|(name, _)| name == catalog_name)
            .map(|(_, line)| *line)
    }
}

/// Walk the raw YAML source to map each catalog entry to its 1-based line
/// number. This is a small section-aware scanner: it tracks whether the
/// current line falls inside `catalog:` (the default catalog) or inside
/// `catalogs.<name>:` (a named catalog), and records each key at the
/// expected indentation level.
fn build_line_index(source: &str) -> CatalogLineIndex {
    let mut entries = Vec::new();
    let mut groups = Vec::new();
    let mut section: Section = Section::None;
    let mut named_catalog: Option<(String, usize)> = None;

    for (idx, raw_line) in source.lines().enumerate() {
        let line_no = u32::try_from(idx).unwrap_or(u32::MAX).saturating_add(1);
        let trimmed = strip_inline_comment(raw_line);
        let trimmed_left = trimmed.trim_start();
        let indent = trimmed.len() - trimmed_left.len();

        if trimmed_left.is_empty() {
            continue;
        }

        if indent == 0 {
            section = if trimmed_left.starts_with("catalogs:") {
                Section::NamedCatalogs
            } else if trimmed_left.starts_with("catalog:") {
                Section::DefaultCatalog
            } else {
                Section::None
            };
            named_catalog = None;
            continue;
        }

        match section {
            Section::None => {}
            Section::DefaultCatalog => {
                if let Some(name) = parse_key(trimmed_left) {
                    entries.push((("default".to_string(), name), line_no));
                }
            }
            Section::NamedCatalogs => {
                // Two indent levels are meaningful here:
                // - level 1 (`  react17:`): a named catalog header
                // - level 2 (`    react: ^17`): an entry inside the named catalog
                if let Some(name) = parse_key(trimmed_left) {
                    match &named_catalog {
                        Some((_, existing_indent)) if indent > *existing_indent => {
                            // Entry inside the active named catalog
                            entries.push((
                                (
                                    named_catalog
                                        .as_ref()
                                        .map_or_else(String::new, |(n, _)| n.clone()),
                                    name,
                                ),
                                line_no,
                            ));
                        }
                        _ => {
                            // New named catalog header (or first one seen)
                            groups.push((name.clone(), line_no));
                            named_catalog = Some((name, indent));
                        }
                    }
                }
            }
        }
    }

    CatalogLineIndex { entries, groups }
}

#[derive(Debug, Clone, Copy)]
enum Section {
    None,
    DefaultCatalog,
    NamedCatalogs,
}

/// Strip an unquoted trailing `# ...` comment from a single line. Preserves
/// `#` characters inside quoted strings so `"# in quotes": "value"` is left
/// alone.
pub(super) fn strip_inline_comment(line: &str) -> &str {
    let bytes = line.as_bytes();
    let mut in_single = false;
    let mut in_double = false;
    for (i, &b) in bytes.iter().enumerate() {
        match b {
            b'\'' if !in_double => in_single = !in_single,
            b'"' if !in_single => in_double = !in_double,
            b'#' if !in_single && !in_double => {
                let head = &line[..i];
                return head.trim_end();
            }
            _ => {}
        }
    }
    line.trim_end()
}

/// Parse a key declaration of the form `key:` or `key: value`, returning just
/// the (unquoted) key. Returns `None` when the line is not a key declaration
/// (e.g., a list item `- foo`, a block scalar marker, or malformed).
pub(super) fn parse_key(line: &str) -> Option<String> {
    let bytes = line.as_bytes();
    if bytes.is_empty() {
        return None;
    }
    let first = bytes[0];
    if first == b'-' || first == b'#' {
        return None;
    }

    if first == b'"' || first == b'\'' {
        // Quoted key: find the matching quote, then expect `:` after it.
        let quote = first;
        let mut i = 1;
        while i < bytes.len() {
            let b = bytes[i];
            if b == b'\\' && i + 1 < bytes.len() {
                i += 2;
                continue;
            }
            if b == quote {
                // Found closing quote
                let key = &line[1..i];
                let rest = &line[i + 1..];
                let trimmed = rest.trim_start();
                if trimmed.starts_with(':') {
                    return Some(unescape_key(key));
                }
                return None;
            }
            i += 1;
        }
        return None;
    }

    let colon_pos = bytes.iter().position(|&b| b == b':')?;
    let key = line[..colon_pos].trim();
    if key.is_empty() {
        return None;
    }
    // Disallow YAML flow / anchor / tag indicators in unquoted keys (we only
    // care about simple `pkg: version` shapes in catalog maps).
    if key.contains(['{', '[', '&', '*', '!']) {
        return None;
    }
    Some(key.to_string())
}

fn unescape_key(raw: &str) -> String {
    // Catalog package names rarely need full YAML unescaping; we just collapse
    // the common `\"` and `\\` sequences so quoted scoped names match the
    // serde_yaml_ng-parsed form exactly.
    let mut out = String::with_capacity(raw.len());
    let mut chars = raw.chars();
    while let Some(c) = chars.next() {
        if c == '\\'
            && let Some(next) = chars.next()
        {
            match next {
                'n' => out.push('\n'),
                't' => out.push('\t'),
                '"' => out.push('"'),
                '\\' => out.push('\\'),
                other => {
                    out.push('\\');
                    out.push(other);
                }
            }
        } else {
            out.push(c);
        }
    }
    out
}

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

    #[test]
    fn parses_default_catalog() {
        let yaml = "packages:\n  - 'packages/*'\n\ncatalog:\n  react: ^18.2.0\n  is-even: ^1.0.0\n";
        let data = parse_pnpm_catalog_data(yaml);
        assert_eq!(data.catalogs.len(), 1);
        let default = &data.catalogs[0];
        assert_eq!(default.name, "default");
        assert_eq!(default.entries.len(), 2);
        assert_eq!(default.entries[0].package_name, "react");
        assert_eq!(default.entries[0].line, 5);
        assert_eq!(default.entries[1].package_name, "is-even");
        assert_eq!(default.entries[1].line, 6);
    }

    #[test]
    fn parses_named_catalogs() {
        let yaml = "catalogs:\n  react17:\n    react: ^17.0.2\n    react-dom: ^17.0.2\n  ui:\n    headlessui: ^2.0.0\n";
        let data = parse_pnpm_catalog_data(yaml);
        assert_eq!(data.catalogs.len(), 2);
        assert_eq!(data.catalogs[0].name, "react17");
        assert_eq!(data.catalogs[0].entries.len(), 2);
        assert_eq!(data.catalogs[0].entries[0].package_name, "react");
        assert_eq!(data.catalogs[0].entries[0].line, 3);
        assert_eq!(data.catalogs[1].name, "ui");
        assert_eq!(data.catalogs[1].entries[0].package_name, "headlessui");
        assert_eq!(data.catalogs[1].entries[0].line, 6);
        assert!(data.empty_named_catalog_groups.is_empty());
    }

    #[test]
    fn handles_default_and_named_together() {
        let yaml = "catalog:\n  react: ^18\n\ncatalogs:\n  legacy:\n    react: ^17\n";
        let data = parse_pnpm_catalog_data(yaml);
        assert_eq!(data.catalogs.len(), 2);
        assert_eq!(data.catalogs[0].name, "default");
        assert_eq!(data.catalogs[0].entries[0].line, 2);
        assert_eq!(data.catalogs[1].name, "legacy");
        assert_eq!(data.catalogs[1].entries[0].line, 6);
    }

    #[test]
    fn handles_quoted_keys() {
        let yaml = "catalog:\n  \"@scope/lib\": ^1.0.0\n  'my-pkg': ^2.0.0\n";
        let data = parse_pnpm_catalog_data(yaml);
        let default = &data.catalogs[0];
        assert_eq!(default.entries[0].package_name, "@scope/lib");
        assert_eq!(default.entries[0].line, 2);
        assert_eq!(default.entries[1].package_name, "my-pkg");
        assert_eq!(default.entries[1].line, 3);
    }

    #[test]
    fn handles_inline_comments() {
        let yaml = "catalog:\n  react: ^18  # pin until #1234\n  is-even: ^1.0\n";
        let data = parse_pnpm_catalog_data(yaml);
        assert_eq!(data.catalogs[0].entries.len(), 2);
        assert_eq!(data.catalogs[0].entries[0].package_name, "react");
        assert_eq!(data.catalogs[0].entries[1].package_name, "is-even");
        assert_eq!(data.catalogs[0].entries[1].line, 3);
    }

    #[test]
    fn handles_four_space_indentation() {
        let yaml = "catalog:\n    react: ^18.2.0\n    vue: ^3.4.0\n";
        let data = parse_pnpm_catalog_data(yaml);
        assert_eq!(data.catalogs[0].entries.len(), 2);
        assert_eq!(data.catalogs[0].entries[0].line, 2);
        assert_eq!(data.catalogs[0].entries[1].line, 3);
    }

    #[test]
    fn empty_catalog_returns_no_catalogs() {
        let yaml = "catalog: {}\n";
        let data = parse_pnpm_catalog_data(yaml);
        assert!(data.catalogs.is_empty());
        assert!(data.empty_named_catalog_groups.is_empty());
    }

    #[test]
    fn tracks_empty_named_catalog_groups() {
        let yaml = "catalog:\n  react: ^18\n\ncatalogs:\n  react17: {}\n  legacy:\n    # retained note\n  vue3:\n    vue: ^3.4.0\n";
        let data = parse_pnpm_catalog_data(yaml);
        assert_eq!(data.catalogs.len(), 2);
        let empty: Vec<_> = data
            .empty_named_catalog_groups
            .iter()
            .map(|group| (group.name.as_str(), group.line))
            .collect();
        assert_eq!(empty, vec![("react17", 5), ("legacy", 6)]);
    }

    #[test]
    fn no_catalog_keys_returns_no_catalogs() {
        let yaml = "packages:\n  - 'packages/*'\n";
        let data = parse_pnpm_catalog_data(yaml);
        assert!(data.catalogs.is_empty());
    }

    #[test]
    fn malformed_yaml_returns_no_catalogs() {
        let yaml = "{this is\nnot: valid: yaml: at: all";
        let data = parse_pnpm_catalog_data(yaml);
        assert!(data.catalogs.is_empty());
    }

    #[test]
    fn empty_input_returns_no_catalogs() {
        let data = parse_pnpm_catalog_data("");
        assert!(data.catalogs.is_empty());
    }

    #[test]
    fn handles_object_form_entries() {
        // pnpm 9.4+ supports object form for entries with specifier + extras
        let yaml = "catalog:\n  react:\n    specifier: ^18.2.0\n  vue: ^3.4.0\n";
        let data = parse_pnpm_catalog_data(yaml);
        assert_eq!(data.catalogs[0].entries.len(), 2);
        let names: Vec<_> = data.catalogs[0]
            .entries
            .iter()
            .map(|e| e.package_name.as_str())
            .collect();
        assert!(names.contains(&"react"));
        assert!(names.contains(&"vue"));
    }

    #[test]
    fn skips_packages_section() {
        let yaml = "packages:\n  - 'apps/*'\n  - 'libs/*'\ncatalog:\n  react: ^18\n";
        let data = parse_pnpm_catalog_data(yaml);
        assert_eq!(data.catalogs.len(), 1);
        assert_eq!(data.catalogs[0].entries[0].line, 5);
    }

    #[test]
    fn strip_inline_comment_preserves_quoted_hash() {
        assert_eq!(strip_inline_comment("foo: \"a#b\" # tail"), "foo: \"a#b\"");
        assert_eq!(strip_inline_comment("# top-level"), "");
        assert_eq!(strip_inline_comment("plain: value"), "plain: value");
    }

    #[test]
    fn parse_key_handles_simple_and_quoted() {
        assert_eq!(parse_key("react: ^18"), Some("react".to_string()));
        assert_eq!(
            parse_key("\"@scope/lib\": ^1"),
            Some("@scope/lib".to_string())
        );
        assert_eq!(parse_key("'pkg': ^2"), Some("pkg".to_string()));
        assert_eq!(parse_key("- item"), None);
        assert_eq!(parse_key(""), None);
    }
}