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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
//! Parser for the `overrides:` section of `pnpm-workspace.yaml` and the
//! `pnpm.overrides` section of a root `package.json`.
//!
//! pnpm supports forcing transitive dependency versions through two equivalent
//! locations:
//!
//! ```yaml
//! # pnpm-workspace.yaml (pnpm 9+, canonical)
//! overrides:
//!   axios: ^1.6.0
//!   "@types/react@<18": "18.0.0"
//!   "react>react-dom": ^17
//! ```
//!
//! ```json
//! // package.json (legacy form, still supported)
//! { "pnpm": { "overrides": { "axios": "^1.6.0" } } }
//! ```
//!
//! For the unused-dependency-override and misconfigured-dependency-override
//! detectors we need both the structured map of entries and the 1-based line
//! number of each entry in the source so findings can point users to the exact
//! line. `serde_yaml_ng` and `serde_json` give us the structural parse; a second
//! targeted scan over the raw source recovers the line numbers.
//!
//! The detector treats the following key shapes as valid pnpm syntax:
//! - `axios` (bare package)
//! - `@scope/pkg` (scoped package)
//! - `axios@>=1.0.0` (version selector on the overridden package)
//! - `react>react-dom` (parent matcher; override `react-dom` only inside `react`'s subtree)
//! - `react@1>zoo` (parent matcher with version selector on the parent)
//! - `@scope/parent>@scope/child` (scoped packages on both sides)
//!
//! Special values that are valid pnpm syntax and must NOT be flagged as
//! misconfigured: `-` (removal), `$ref` (self-reference to a workspace dep),
//! `npm:alias@^1` (npm-protocol alias).

use std::path::Path;

use super::pnpm_catalog::{parse_key, strip_inline_comment};

/// Where an override entry was declared.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OverrideSource {
    /// Top-level `overrides:` in `pnpm-workspace.yaml`.
    PnpmWorkspaceYaml,
    /// `pnpm.overrides` in a root `package.json`.
    PnpmPackageJson,
}

/// Structured override data extracted from one source.
#[derive(Debug, Clone, Default)]
pub struct PnpmOverrideData {
    /// Entries declared in source order.
    pub entries: Vec<PnpmOverrideEntry>,
}

/// A single override entry.
#[derive(Debug, Clone)]
pub struct PnpmOverrideEntry {
    /// The full original key as written in the source (e.g.
    /// `"react>react-dom"`, `"@types/react@<18"`). Preserved for round-trip
    /// reporting so agents see the unmodified spelling.
    pub raw_key: String,
    /// Parsed structure of the key. `None` when the key cannot be parsed into
    /// a pnpm-recognised shape; in that case the entry is reported as
    /// misconfigured rather than checked for usage.
    pub parsed_key: Option<ParsedOverrideKey>,
    /// The right-hand side of the entry (the version pnpm should force).
    /// `None` when the value is missing or unparsable.
    pub raw_value: Option<String>,
    /// 1-based line number of the entry within the source file.
    pub line: u32,
}

/// Parsed structure of an override key.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedOverrideKey {
    /// Optional parent package (left side of `>`). `None` for bare-target keys.
    pub parent_package: Option<String>,
    /// Optional version selector on the parent (e.g. `react@1>zoo` has
    /// `parent_version_selector = Some("1")`).
    pub parent_version_selector: Option<String>,
    /// The target package name (the entry pnpm rewrites).
    pub target_package: String,
    /// Optional version selector on the target (e.g. `@types/react@<18` has
    /// `target_version_selector = Some("<18")`).
    pub target_version_selector: Option<String>,
}

/// Parse the `overrides:` section of `pnpm-workspace.yaml`. Returns an empty
/// `PnpmOverrideData` when the file has no overrides, when the YAML is
/// malformed, or when the section is present but empty.
#[must_use]
pub fn parse_pnpm_workspace_overrides(source: &str) -> PnpmOverrideData {
    let value: serde_yaml_ng::Value = match serde_yaml_ng::from_str(source) {
        Ok(v) => v,
        Err(_) => return PnpmOverrideData::default(),
    };
    let Some(mapping) = value.as_mapping() else {
        return PnpmOverrideData::default();
    };
    let Some(overrides_value) = mapping.get("overrides") else {
        return PnpmOverrideData::default();
    };
    let Some(overrides_map) = overrides_value.as_mapping() else {
        return PnpmOverrideData::default();
    };

    let line_index = build_yaml_line_index(source);
    let entries = overrides_map
        .iter()
        .filter_map(|(k, v)| {
            let raw_key = k.as_str()?.to_string();
            let raw_value = match v {
                serde_yaml_ng::Value::String(s) => Some(s.clone()),
                serde_yaml_ng::Value::Null => None,
                other => Some(yaml_value_to_string(other)),
            };
            let line = line_index.line_for(&raw_key)?;
            let parsed_key = parse_override_key(&raw_key);
            Some(PnpmOverrideEntry {
                raw_key,
                parsed_key,
                raw_value,
                line,
            })
        })
        .collect();

    PnpmOverrideData { entries }
}

/// Parse the `pnpm.overrides` section of a root `package.json`. Returns an
/// empty `PnpmOverrideData` when the file has no overrides, when the JSON is
/// malformed, or when the section is present but empty.
#[must_use]
pub fn parse_pnpm_package_json_overrides(source: &str) -> PnpmOverrideData {
    let value: serde_json::Value = match serde_json::from_str(source) {
        Ok(v) => v,
        Err(_) => return PnpmOverrideData::default(),
    };
    let Some(overrides) = value.get("pnpm").and_then(|p| p.get("overrides")) else {
        return PnpmOverrideData::default();
    };
    let Some(overrides_obj) = overrides.as_object() else {
        return PnpmOverrideData::default();
    };

    let line_index = build_package_json_line_index(source);
    let entries = overrides_obj
        .iter()
        .filter_map(|(raw_key, v)| {
            let raw_value = match v {
                serde_json::Value::String(s) => Some(s.clone()),
                serde_json::Value::Null => None,
                other => Some(other.to_string()),
            };
            let line = line_index.line_for(raw_key)?;
            let parsed_key = parse_override_key(raw_key);
            Some(PnpmOverrideEntry {
                raw_key: raw_key.clone(),
                parsed_key,
                raw_value,
                line,
            })
        })
        .collect();

    PnpmOverrideData { entries }
}

/// Parse an override key into `parent`, `target`, and optional version
/// selectors. Returns `None` when the key cannot be split into a recognised
/// shape (empty key, parent or target missing).
#[must_use]
pub fn parse_override_key(key: &str) -> Option<ParsedOverrideKey> {
    let trimmed = key.trim();
    if trimmed.is_empty() {
        return None;
    }

    // Split on the last `>`. pnpm parses single-depth parent matchers; multi-hop
    // `a>b>c` is not officially documented but the resolver treats the rightmost
    // segment as the target and everything left as the parent chain. We split
    // on the LAST `>` so the parent side keeps any earlier `>` for future
    // multi-hop support.
    let (parent_part, target_part) = if let Some(idx) = trimmed.rfind('>') {
        (Some(trimmed[..idx].trim()), trimmed[idx + 1..].trim())
    } else {
        (None, trimmed)
    };

    let (target_package, target_version_selector) = split_pkg_and_selector(target_part)?;

    let (parent_package, parent_version_selector) = match parent_part {
        Some(parent) if !parent.is_empty() => {
            let (pkg, selector) = split_pkg_and_selector(parent)?;
            (Some(pkg), selector)
        }
        // `>target` (leading separator with empty parent) is malformed: the
        // user clearly intended a parent chain but left the parent slot blank.
        Some(_) => return None,
        None => (None, None),
    };

    Some(ParsedOverrideKey {
        parent_package,
        parent_version_selector,
        target_package,
        target_version_selector,
    })
}

/// Split a `pkg@selector` segment into `(package_name, Option<selector>)`.
/// Handles scoped packages (`@scope/name@<2`) by skipping the leading `@`.
/// Returns `None` when the package name is empty.
fn split_pkg_and_selector(segment: &str) -> Option<(String, Option<String>)> {
    let trimmed = segment.trim();
    if trimmed.is_empty() {
        return None;
    }

    let bytes = trimmed.as_bytes();
    let scoped = bytes.first().copied() == Some(b'@');
    let start = usize::from(scoped);
    let at_pos = trimmed[start..].find('@').map(|i| i + start);

    let (pkg, selector) = match at_pos {
        Some(pos) => (
            trimmed[..pos].to_string(),
            Some(trimmed[pos + 1..].to_string()),
        ),
        None => (trimmed.to_string(), None),
    };

    if pkg.is_empty() {
        return None;
    }
    Some((pkg, selector))
}

/// Check whether `value` is a valid pnpm override right-hand side, even if it
/// is not a semver range. Returns `false` when the value is empty, contains a
/// raw newline, or is otherwise garbage.
#[must_use]
pub fn is_valid_override_value(value: &str) -> bool {
    let trimmed = value.trim();
    if trimmed.is_empty() {
        return false;
    }
    if trimmed.contains('\n') {
        return false;
    }
    // pnpm accepts: semver ranges, `-` (removal), `$ref` (self-ref),
    // `npm:alias@^1` (alias), `workspace:*`. We do not validate semver ranges
    // here, only screen for obviously broken inputs.
    true
}

/// Convenience: is this entry effectively a misconfiguration the user should
/// see as an error?
#[must_use]
pub fn override_misconfig_reason(entry: &PnpmOverrideEntry) -> Option<MisconfigReason> {
    if entry.parsed_key.is_none() {
        return Some(MisconfigReason::UnparsableKey);
    }
    match &entry.raw_value {
        None => Some(MisconfigReason::EmptyValue),
        Some(v) if !is_valid_override_value(v) => Some(MisconfigReason::EmptyValue),
        _ => None,
    }
}

/// Why an override entry is misconfigured.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum MisconfigReason {
    /// The override key cannot be parsed into a recognised pnpm shape.
    UnparsableKey,
    /// The override value is missing or empty.
    EmptyValue,
}

impl MisconfigReason {
    /// Human-readable description.
    #[must_use]
    pub const fn describe(self) -> &'static str {
        match self {
            Self::UnparsableKey => "override key cannot be parsed",
            Self::EmptyValue => "override value is missing or empty",
        }
    }
}

struct YamlLineIndex {
    entries: Vec<(String, u32)>,
}

impl YamlLineIndex {
    fn line_for(&self, key: &str) -> Option<u32> {
        self.entries
            .iter()
            .find(|(k, _)| k == key)
            .map(|(_, line)| *line)
    }
}

/// Walk the raw YAML source to map each `overrides:` entry key to its 1-based
/// line number. Mirrors the catalog parser's section-aware scanner.
fn build_yaml_line_index(source: &str) -> YamlLineIndex {
    let mut entries = Vec::new();
    let mut in_overrides = false;

    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 {
            in_overrides = trimmed_left.starts_with("overrides:");
            continue;
        }

        if in_overrides && let Some(key) = parse_key(trimmed_left) {
            entries.push((key, line_no));
        }
    }

    YamlLineIndex { entries }
}

/// Walk a raw `package.json` source string to map each `pnpm.overrides` entry
/// key to its 1-based line number. The scan tracks brace depth so nested
/// objects under unrelated keys (e.g., `dependenciesMeta`) cannot be misread
/// as override entries.
fn build_package_json_line_index(source: &str) -> YamlLineIndex {
    let mut entries = Vec::new();
    let mut depth: i32 = 0;
    let mut pnpm_depth: Option<i32> = None;
    let mut in_overrides_depth: Option<i32> = None;
    let mut in_string = false;
    let mut escape = false;
    let mut current_line = 1u32;
    let mut last_key: Option<String> = None;
    let mut key_buf = String::new();
    let mut collecting_key = false;

    for ch in source.chars() {
        if ch == '\n' {
            current_line += 1;
        }

        if in_string {
            if escape {
                if collecting_key {
                    key_buf.push(ch);
                }
                escape = false;
                continue;
            }
            if ch == '\\' {
                escape = true;
                if collecting_key {
                    key_buf.push(ch);
                }
                continue;
            }
            if ch == '"' {
                in_string = false;
                if collecting_key {
                    last_key = Some(std::mem::take(&mut key_buf));
                    collecting_key = false;
                }
                continue;
            }
            if collecting_key {
                key_buf.push(ch);
            }
            continue;
        }

        match ch {
            '"' => {
                in_string = true;
                // Start collecting a new key candidate. We commit it only when
                // followed by `:` at the appropriate depth.
                collecting_key = true;
                key_buf.clear();
            }
            '{' => depth += 1,
            '}' => {
                if Some(depth) == in_overrides_depth {
                    in_overrides_depth = None;
                }
                if Some(depth) == pnpm_depth {
                    pnpm_depth = None;
                }
                depth -= 1;
            }
            ':' => {
                if let Some(key) = last_key.take() {
                    // Promote into a section if the key opens an object
                    // immediately. We track section transitions by matching
                    // the key name + current depth.
                    if pnpm_depth.is_none() && depth == 1 && key == "pnpm" {
                        pnpm_depth = Some(depth);
                    } else if in_overrides_depth.is_none()
                        && pnpm_depth.is_some()
                        && depth == pnpm_depth.unwrap_or(0) + 1
                        && key == "overrides"
                    {
                        in_overrides_depth = Some(depth);
                    } else if let Some(d) = in_overrides_depth
                        && depth == d + 1
                    {
                        // This is an override entry key at the right depth.
                        entries.push((key, current_line));
                    }
                }
            }
            ',' => {
                last_key = None;
            }
            _ => {}
        }
    }

    YamlLineIndex { entries }
}

fn yaml_value_to_string(value: &serde_yaml_ng::Value) -> String {
    match value {
        serde_yaml_ng::Value::String(s) => s.clone(),
        serde_yaml_ng::Value::Number(n) => n.to_string(),
        serde_yaml_ng::Value::Bool(b) => b.to_string(),
        serde_yaml_ng::Value::Null => String::new(),
        _ => serde_yaml_ng::to_string(value).unwrap_or_default(),
    }
}

/// Source-name string for diagnostics.
#[must_use]
pub fn override_source_label(source: OverrideSource, path: &Path) -> String {
    match source {
        OverrideSource::PnpmWorkspaceYaml => "pnpm-workspace.yaml".to_string(),
        OverrideSource::PnpmPackageJson => path.display().to_string(),
    }
}

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

    #[test]
    fn parse_bare_target() {
        let parsed = parse_override_key("axios").unwrap();
        assert_eq!(parsed.target_package, "axios");
        assert!(parsed.parent_package.is_none());
        assert!(parsed.target_version_selector.is_none());
    }

    #[test]
    fn parse_scoped_target() {
        let parsed = parse_override_key("@types/react").unwrap();
        assert_eq!(parsed.target_package, "@types/react");
        assert!(parsed.target_version_selector.is_none());
    }

    #[test]
    fn parse_target_with_version_selector() {
        let parsed = parse_override_key("@types/react@<18").unwrap();
        assert_eq!(parsed.target_package, "@types/react");
        assert_eq!(parsed.target_version_selector.as_deref(), Some("<18"));
    }

    #[test]
    fn parse_parent_chain() {
        let parsed = parse_override_key("react>react-dom").unwrap();
        assert_eq!(parsed.parent_package.as_deref(), Some("react"));
        assert_eq!(parsed.target_package, "react-dom");
    }

    #[test]
    fn parse_parent_chain_with_selectors() {
        let parsed = parse_override_key("react@1>zoo").unwrap();
        assert_eq!(parsed.parent_package.as_deref(), Some("react"));
        assert_eq!(parsed.parent_version_selector.as_deref(), Some("1"));
        assert_eq!(parsed.target_package, "zoo");
    }

    #[test]
    fn parse_scoped_parent_and_target() {
        let parsed = parse_override_key("@react-spring/web>@react-spring/core").unwrap();
        assert_eq!(parsed.parent_package.as_deref(), Some("@react-spring/web"));
        assert_eq!(parsed.target_package, "@react-spring/core");
    }

    #[test]
    fn parse_empty_returns_none() {
        assert!(parse_override_key("").is_none());
        assert!(parse_override_key("   ").is_none());
    }

    #[test]
    fn parse_dangling_separator_returns_none() {
        assert!(parse_override_key("react>").is_none());
        assert!(parse_override_key(">react-dom").is_none());
    }

    #[test]
    fn is_valid_override_value_accepts_pnpm_idioms() {
        assert!(is_valid_override_value("^1.6.0"));
        assert!(is_valid_override_value("-"));
        assert!(is_valid_override_value("$foo"));
        assert!(is_valid_override_value("npm:@scope/alias@^1.0.0"));
        assert!(is_valid_override_value("workspace:*"));
    }

    #[test]
    fn is_valid_override_value_rejects_empty_and_newline() {
        assert!(!is_valid_override_value(""));
        assert!(!is_valid_override_value("   "));
        assert!(!is_valid_override_value("^1\n^2"));
    }

    #[test]
    fn parses_workspace_yaml_overrides() {
        let yaml = "packages:\n  - 'packages/*'\n\noverrides:\n  axios: ^1.6.0\n  \"@types/react@<18\": '18.0.0'\n  \"react>react-dom\": ^17\n";
        let data = parse_pnpm_workspace_overrides(yaml);
        assert_eq!(data.entries.len(), 3);
        assert_eq!(data.entries[0].raw_key, "axios");
        assert_eq!(data.entries[0].line, 5);
        assert_eq!(data.entries[0].raw_value.as_deref(), Some("^1.6.0"));

        assert_eq!(data.entries[1].raw_key, "@types/react@<18");
        assert_eq!(data.entries[1].line, 6);
        assert_eq!(data.entries[1].raw_value.as_deref(), Some("18.0.0"));
        assert_eq!(
            data.entries[1]
                .parsed_key
                .as_ref()
                .and_then(|p| p.target_version_selector.as_deref()),
            Some("<18")
        );

        assert_eq!(data.entries[2].raw_key, "react>react-dom");
        assert_eq!(data.entries[2].line, 7);
        assert_eq!(
            data.entries[2]
                .parsed_key
                .as_ref()
                .map(|p| p.target_package.as_str()),
            Some("react-dom")
        );
    }

    #[test]
    fn parses_package_json_overrides() {
        let json = r#"{
  "name": "root",
  "pnpm": {
    "overrides": {
      "axios": "^1.6.0",
      "react>react-dom": "^17"
    }
  },
  "dependenciesMeta": {
    "shouldNotMatch": { "injected": true }
  }
}"#;
        let data = parse_pnpm_package_json_overrides(json);
        assert_eq!(data.entries.len(), 2);
        assert_eq!(data.entries[0].raw_key, "axios");
        assert_eq!(data.entries[0].raw_value.as_deref(), Some("^1.6.0"));
        assert_eq!(data.entries[0].line, 5);
        assert_eq!(data.entries[1].raw_key, "react>react-dom");
        assert_eq!(data.entries[1].line, 6);
    }

    #[test]
    fn empty_workspace_overrides_returns_no_entries() {
        let data = parse_pnpm_workspace_overrides("overrides: {}\n");
        assert!(data.entries.is_empty());
    }

    #[test]
    fn malformed_yaml_returns_no_entries() {
        let data = parse_pnpm_workspace_overrides("{this is\nnot: valid: yaml");
        assert!(data.entries.is_empty());
    }

    #[test]
    fn package_json_without_pnpm_overrides_returns_no_entries() {
        let data = parse_pnpm_package_json_overrides(r#"{"dependencies": {"axios": "^1"}}"#);
        assert!(data.entries.is_empty());
    }

    #[test]
    fn malformed_json_returns_no_entries() {
        let data = parse_pnpm_package_json_overrides("{not valid json");
        assert!(data.entries.is_empty());
    }

    #[test]
    fn unparsable_key_carries_misconfig_signal() {
        let yaml = "overrides:\n  \">@bad-key>\": ^1.0.0\n";
        let data = parse_pnpm_workspace_overrides(yaml);
        assert_eq!(data.entries.len(), 1);
        assert!(data.entries[0].parsed_key.is_none());
        assert_eq!(
            override_misconfig_reason(&data.entries[0]),
            Some(MisconfigReason::UnparsableKey)
        );
    }
}