Skip to main content

fallow_engine/
discover.rs

1//! Discovery helpers and types exposed through the engine boundary.
2
3use std::ffi::OsStr;
4use std::path::{Path, PathBuf};
5use std::time::Instant;
6
7use fallow_config::{
8    PackageJson, ResolvedConfig, WorkspaceDiagnostic, WorkspaceInfo, discover_workspaces,
9    find_undeclared_workspaces_with_ignores,
10};
11pub use fallow_types::discover::{DiscoveredFile, EntryPoint, EntryPointSource, FileId};
12
13/// Discovery vocabulary shared with the analysis backend: file extensions,
14/// production-exclusion globs, and the hidden directories traversal allows.
15pub use crate::core_backend::{
16    ALLOWED_HIDDEN_DIRS, PRODUCTION_EXCLUDE_PATTERNS, SOURCE_EXTENSIONS,
17};
18use rustc_hash::FxHashSet;
19
20use crate::{EngineError, EngineResult, plugins::PluginRegistry};
21
22const UNDECLARED_WORKSPACE_WARNING_PREVIEW: usize = 5;
23
24const SCRIPT_SCOPE_DENYLIST: &[&str] = &[
25    ".angular",
26    ".astro",
27    ".cache",
28    ".contentlayer",
29    ".docusaurus",
30    ".expo",
31    ".fallow",
32    ".git",
33    ".hg",
34    ".husky",
35    ".idea",
36    ".jj",
37    ".netlify",
38    ".next",
39    ".nuxt",
40    ".nx",
41    ".output",
42    ".parcel-cache",
43    ".pnpm",
44    ".pnpm-store",
45    ".react-router",
46    ".rollup.cache",
47    ".sst",
48    ".svelte-kit",
49    ".svn",
50    ".swc",
51    ".tanstack",
52    ".turbo",
53    ".velite",
54    ".vercel",
55    ".vinxi",
56    ".vscode",
57    ".wrangler",
58    ".wxt",
59    ".yalc",
60    ".yarn",
61];
62
63const ENV_WRAPPERS: &[&str] = &["cross-env", "dotenv", "env"];
64const NODE_RUNNERS: &[&str] = &["node", "ts-node", "tsx", "babel-node", "bun"];
65const SCRIPT_MULTIPLEXERS: &[&str] = &[
66    "concurrently",
67    "npm-run-all",
68    "npm-run-all2",
69    "run-s",
70    "run-p",
71    "run-s2",
72    "run-p2",
73];
74const BUN_RUNTIME_FLAGS: &[&str] = &["--bun", "--watch", "--hot", "--smol", "--no-clear-screen"];
75
76/// Discover workspace packages from the manifests only, through the engine
77/// boundary.
78///
79/// This reads no config, so it ignores the `workspaces.patterns` config key.
80/// A caller that has a resolved config uses
81/// [`discover_workspace_packages_with_patterns`] with
82/// `config.workspace_patterns`. Session-backed flows should prefer
83/// [`AnalysisSession::workspaces`](crate::session::AnalysisSession::workspaces)
84/// so discovery is reused with the rest of the analysis context.
85///
86/// The remaining callers run before any config exists (`fallow init`), or on
87/// paths that load no config today (`fallow coverage setup`, the base worktree
88/// context, and the `scope-workspaces` next step). A config load on these paths
89/// would add trust checks and warnings to commands that do not report them.
90#[must_use]
91pub fn discover_workspace_packages(root: &Path) -> Vec<WorkspaceInfo> {
92    discover_workspaces(root)
93}
94
95/// Like [`discover_workspace_packages`], with the `workspaces.patterns` of the
96/// resolved config added to the manifest patterns.
97#[must_use]
98pub fn discover_workspace_packages_with_patterns(
99    root: &Path,
100    workspace_patterns: &[String],
101) -> Vec<WorkspaceInfo> {
102    fallow_config::discover_workspaces_with_patterns(root, workspace_patterns)
103}
104
105/// Discover workspace packages and diagnostics through the engine boundary,
106/// with the `workspaces.patterns` of the resolved config added to the manifest
107/// patterns.
108///
109/// This is for CLI/API surfaces that need to render workspace diagnostics but
110/// do not otherwise need a full [`AnalysisSession`](crate::session::AnalysisSession).
111///
112/// # Errors
113///
114/// Returns an engine error when workspace manifest loading fails.
115pub fn discover_workspace_packages_for_config(
116    root: &Path,
117    ignore_patterns: &fallow_config::IgnorePatternSet,
118    workspace_patterns: &[String],
119) -> EngineResult<(Vec<WorkspaceInfo>, Vec<WorkspaceDiagnostic>)> {
120    fallow_config::discover_workspaces_with_diagnostics_and_patterns(
121        root,
122        ignore_patterns,
123        workspace_patterns,
124    )
125    .map_err(|err| EngineError::new(err.to_string()))
126}
127
128/// How a [`HiddenDirScope`] matches a hidden directory during the walk.
129///
130/// Mirrors `fallow_core::discover::HiddenDirMatch`; the two are kept in step
131/// by the conversion in `core_backend`.
132#[derive(Debug, Clone, Copy, PartialEq, Eq)]
133pub(crate) enum HiddenDirMatch {
134    /// Match by directory NAME at any depth beneath the scope root.
135    AnyDepth,
136    /// Match the exact root-relative directory PATH (issue #461).
137    ExactPath,
138}
139
140/// Package-scoped hidden directories that source discovery should traverse.
141#[derive(Debug, Clone, PartialEq, Eq)]
142pub struct HiddenDirScope {
143    root: PathBuf,
144    dirs: Vec<String>,
145    match_mode: HiddenDirMatch,
146}
147
148impl HiddenDirScope {
149    #[must_use]
150    const fn new(root: PathBuf, dirs: Vec<String>) -> Self {
151        Self {
152            root,
153            dirs,
154            match_mode: HiddenDirMatch::AnyDepth,
155        }
156    }
157
158    #[must_use]
159    const fn new_exact_paths(root: PathBuf, dirs: Vec<String>) -> Self {
160        Self {
161            root,
162            dirs,
163            match_mode: HiddenDirMatch::ExactPath,
164        }
165    }
166
167    #[must_use]
168    pub(crate) fn root(&self) -> &Path {
169        &self.root
170    }
171
172    #[must_use]
173    pub(crate) fn dirs(&self) -> &[String] {
174        &self.dirs
175    }
176
177    #[must_use]
178    pub(crate) const fn match_mode(&self) -> HiddenDirMatch {
179        self.match_mode
180    }
181}
182
183/// Reusable engine discovery prelude for one resolved project.
184#[derive(Debug, Clone)]
185pub struct AnalysisDiscovery {
186    files: Vec<DiscoveredFile>,
187    workspaces: Vec<WorkspaceInfo>,
188    root_pkg: Option<PackageJson>,
189    config_candidates: Vec<PathBuf>,
190    source_diagnostics: Vec<WorkspaceDiagnostic>,
191    discover_ms: f64,
192    workspaces_ms: f64,
193}
194
195impl AnalysisDiscovery {
196    fn from_parts(
197        sources: crate::core_backend::DiscoveredSources,
198        workspaces: Vec<WorkspaceInfo>,
199        root_pkg: Option<PackageJson>,
200        discover_ms: f64,
201        workspaces_ms: f64,
202    ) -> Self {
203        Self {
204            files: sources.files,
205            workspaces,
206            root_pkg,
207            config_candidates: sources.config_candidates,
208            source_diagnostics: sources.diagnostics,
209            discover_ms,
210            workspaces_ms,
211        }
212    }
213
214    /// Discovered source files, indexed by stable `FileId` for this session.
215    #[must_use]
216    pub(crate) fn files(&self) -> &[DiscoveredFile] {
217        &self.files
218    }
219
220    /// Discovered workspace packages for this session.
221    #[must_use]
222    pub(crate) fn workspaces(&self) -> &[WorkspaceInfo] {
223        &self.workspaces
224    }
225
226    pub(crate) fn root_pkg(&self) -> Option<&PackageJson> {
227        self.root_pkg.as_ref()
228    }
229
230    pub(crate) fn config_candidates(&self) -> &[PathBuf] {
231        &self.config_candidates
232    }
233
234    /// Source-discovery diagnostics this session's OWN walk produced. Held by
235    /// value because a concurrent walk on the same root replaces the process
236    /// registry's source-discovery set (issue #2366).
237    pub(crate) fn source_diagnostics(&self) -> &[WorkspaceDiagnostic] {
238        &self.source_diagnostics
239    }
240
241    pub(crate) fn discover_ms(&self) -> f64 {
242        self.discover_ms
243    }
244
245    pub(crate) fn workspaces_ms(&self) -> f64 {
246        self.workspaces_ms
247    }
248
249    /// Consume this discovery prelude and return its source file registry.
250    #[must_use]
251    pub(crate) fn into_files(self) -> Vec<DiscoveredFile> {
252        self.files
253    }
254}
255
256/// Run engine-owned workspace and source discovery for a resolved project.
257#[must_use]
258pub(crate) fn prepare_analysis_discovery(config: &ResolvedConfig) -> AnalysisDiscovery {
259    let workspaces_start = Instant::now();
260    let workspaces =
261        fallow_config::discover_workspaces_with_patterns(&config.root, &config.workspace_patterns);
262    let workspaces_ms = workspaces_start.elapsed().as_secs_f64() * 1000.0;
263    if !workspaces.is_empty() {
264        tracing::info!(count = workspaces.len(), "workspaces discovered");
265    }
266    warn_undeclared_workspaces(
267        &config.root,
268        &workspaces,
269        &config.ignore_patterns,
270        config.quiet,
271    );
272
273    let root_pkg = fallow_config::load_dir_package_json(&config.root);
274    let hidden_dir_scopes = collect_hidden_dir_scopes(config, root_pkg.as_ref(), &workspaces);
275
276    let discover_start = Instant::now();
277    let sources = discover_files_config_candidates_and_diagnostics(config, &hidden_dir_scopes);
278    let discover_ms = discover_start.elapsed().as_secs_f64() * 1000.0;
279
280    AnalysisDiscovery::from_parts(sources, workspaces, root_pkg, discover_ms, workspaces_ms)
281}
282
283/// Run source discovery with workspace metadata already resolved by config load.
284///
285/// This is the normal [`AnalysisSession`](crate::session::AnalysisSession) path:
286/// config loading already expanded workspace globs and collected diagnostics, so
287/// source discovery can reuse that set instead of walking workspace manifests a
288/// second time.
289#[must_use]
290pub(crate) fn prepare_analysis_discovery_with_workspaces(
291    config: &ResolvedConfig,
292    workspaces: &[WorkspaceInfo],
293    workspaces_ms: f64,
294) -> AnalysisDiscovery {
295    if !workspaces.is_empty() {
296        tracing::info!(count = workspaces.len(), "workspaces discovered");
297    }
298
299    let root_pkg = fallow_config::load_dir_package_json(&config.root);
300    let hidden_dir_scopes = collect_hidden_dir_scopes(config, root_pkg.as_ref(), workspaces);
301
302    let discover_start = Instant::now();
303    let sources = discover_files_config_candidates_and_diagnostics(config, &hidden_dir_scopes);
304    let discover_ms = discover_start.elapsed().as_secs_f64() * 1000.0;
305
306    AnalysisDiscovery::from_parts(
307        sources,
308        workspaces.to_vec(),
309        root_pkg,
310        discover_ms,
311        workspaces_ms,
312    )
313}
314
315fn format_undeclared_workspace_warning(
316    root: &Path,
317    undeclared: &[WorkspaceDiagnostic],
318) -> Option<String> {
319    if undeclared.is_empty() {
320        return None;
321    }
322
323    let preview = undeclared
324        .iter()
325        .take(UNDECLARED_WORKSPACE_WARNING_PREVIEW)
326        .map(|diagnostic| {
327            diagnostic
328                .path
329                .strip_prefix(root)
330                .unwrap_or(&diagnostic.path)
331                .display()
332                .to_string()
333                .replace('\\', "/")
334        })
335        .collect::<Vec<_>>();
336    let remaining = undeclared
337        .len()
338        .saturating_sub(UNDECLARED_WORKSPACE_WARNING_PREVIEW);
339    let tail = if remaining > 0 {
340        format!(" (and {remaining} more)")
341    } else {
342        String::new()
343    };
344    let noun = if undeclared.len() == 1 {
345        "directory with package.json is"
346    } else {
347        "directories with package.json are"
348    };
349    let guidance = if undeclared.len() == 1 {
350        "Add that path to package.json workspaces or pnpm-workspace.yaml if it should be analyzed as a workspace."
351    } else {
352        "Add those paths to package.json workspaces or pnpm-workspace.yaml if they should be analyzed as workspaces."
353    };
354
355    Some(format!(
356        "{} {} not declared as {}: {}{}. {}",
357        undeclared.len(),
358        noun,
359        if undeclared.len() == 1 {
360            "a workspace"
361        } else {
362            "workspaces"
363        },
364        preview.join(", "),
365        tail,
366        guidance
367    ))
368}
369
370fn warn_undeclared_workspaces(
371    root: &Path,
372    workspaces: &[WorkspaceInfo],
373    ignore_patterns: &fallow_config::IgnorePatternSet,
374    quiet: bool,
375) {
376    let undeclared = find_undeclared_workspaces_with_ignores(root, workspaces, ignore_patterns);
377    if undeclared.is_empty() {
378        return;
379    }
380
381    let existing = fallow_config::workspace_diagnostics_for(root);
382    let already_flagged: FxHashSet<PathBuf> = existing
383        .iter()
384        .map(|diagnostic| {
385            dunce::canonicalize(&diagnostic.path).unwrap_or_else(|_| diagnostic.path.clone())
386        })
387        .collect();
388    let undeclared: Vec<_> = undeclared
389        .into_iter()
390        .filter(|diagnostic| {
391            let canonical =
392                dunce::canonicalize(&diagnostic.path).unwrap_or_else(|_| diagnostic.path.clone());
393            !already_flagged.contains(&canonical)
394        })
395        .collect();
396    if undeclared.is_empty() {
397        return;
398    }
399
400    fallow_config::append_workspace_diagnostics(root, undeclared.clone());
401
402    if !quiet && let Some(message) = format_undeclared_workspace_warning(root, &undeclared) {
403        tracing::warn!("{message}");
404    }
405}
406
407/// Check if a hidden directory name is on the discovery allowlist.
408#[must_use]
409pub fn is_allowed_hidden_dir(name: &OsStr) -> bool {
410    ALLOWED_HIDDEN_DIRS
411        .iter()
412        .any(|&dir| OsStr::new(dir) == name)
413}
414
415fn push_plugin_hidden_dir_scope(
416    scopes: &mut Vec<HiddenDirScope>,
417    registry: &PluginRegistry,
418    pkg: &PackageJson,
419    root: &Path,
420) {
421    let dirs = registry.discovery_hidden_dirs(pkg, root);
422    if !dirs.is_empty() {
423        scopes.push(HiddenDirScope::new(root.to_path_buf(), dirs));
424    }
425}
426
427/// Collect plugin and script-derived hidden directory scopes.
428#[must_use]
429fn collect_hidden_dir_scopes(
430    config: &ResolvedConfig,
431    root_pkg: Option<&PackageJson>,
432    workspaces: &[WorkspaceInfo],
433) -> Vec<HiddenDirScope> {
434    let _span = tracing::info_span!("collect_hidden_dir_scopes").entered();
435    let registry = PluginRegistry::new(config.external_plugins.clone());
436    let mut scopes = Vec::new();
437
438    if let Some(pkg) = root_pkg {
439        push_plugin_hidden_dir_scope(&mut scopes, &registry, pkg, &config.root);
440        push_script_hidden_dir_scope(&mut scopes, pkg, &config.root);
441    }
442
443    for ws in workspaces {
444        if let Some(pkg) = fallow_config::load_dir_package_json(&ws.root) {
445            push_plugin_hidden_dir_scope(&mut scopes, &registry, &pkg, &ws.root);
446            push_script_hidden_dir_scope(&mut scopes, &pkg, &ws.root);
447        }
448    }
449
450    scopes
451}
452
453fn push_script_hidden_dir_scope(scopes: &mut Vec<HiddenDirScope>, pkg: &PackageJson, root: &Path) {
454    if let Some(scope) = build_script_scope(pkg, root) {
455        scopes.push(scope);
456    }
457}
458
459fn build_script_scope(pkg: &PackageJson, root: &Path) -> Option<HiddenDirScope> {
460    let scripts = pkg.scripts.as_ref()?;
461    let mut seen = FxHashSet::default();
462    let mut dirs: Vec<String> = Vec::new();
463
464    for (script_name, script_value) in scripts {
465        for cmd in parse_script_value(script_value) {
466            for path in cmd.config_args.iter().chain(cmd.file_args.iter()) {
467                for hidden in extract_hidden_dir_paths(path) {
468                    if hidden_dir_path_is_denied(&hidden) {
469                        continue;
470                    }
471                    if seen.insert(hidden.clone()) {
472                        tracing::debug!(
473                            dir = %hidden,
474                            script = %script_name,
475                            package_root = %root.display(),
476                            "inferred hidden_dir_scope from package.json#scripts"
477                        );
478                        dirs.push(hidden);
479                    }
480                }
481            }
482        }
483    }
484
485    if dirs.is_empty() {
486        None
487    } else {
488        Some(HiddenDirScope::new_exact_paths(root.to_path_buf(), dirs))
489    }
490}
491
492/// Whether the last component of a root-relative hidden directory path is on
493/// [`SCRIPT_SCOPE_DENYLIST`].
494///
495/// The denylist names directories, so it is matched against the directory's
496/// own name rather than the path that reaches it.
497fn hidden_dir_path_is_denied(path: &str) -> bool {
498    Path::new(path)
499        .file_name()
500        .and_then(|name| name.to_str())
501        .is_some_and(|name| SCRIPT_SCOPE_DENYLIST.contains(&name))
502}
503
504#[derive(Debug, PartialEq, Eq)]
505struct ScriptCommand {
506    config_args: Vec<String>,
507    file_args: Vec<String>,
508}
509
510fn parse_script_value(script: &str) -> Vec<ScriptCommand> {
511    let mut commands = Vec::new();
512
513    for segment in split_shell_operators(script) {
514        let segment = segment.trim();
515        if segment.is_empty() {
516            continue;
517        }
518        if let Some(cmd) = parse_command_segment(segment) {
519            commands.push(cmd);
520        }
521    }
522
523    commands
524}
525
526fn parse_command_segment(segment: &str) -> Option<ScriptCommand> {
527    let tokens: Vec<&str> = segment
528        .split_whitespace()
529        .map(strip_surrounding_quotes)
530        .collect();
531    if tokens.is_empty() {
532        return None;
533    }
534
535    let idx = skip_initial_wrappers(&tokens, 0)?;
536    let idx = advance_past_package_manager(&tokens, idx)?;
537    let binary = tokens[idx];
538
539    if SCRIPT_MULTIPLEXERS.contains(&binary) {
540        return Some(ScriptCommand {
541            config_args: Vec::new(),
542            file_args: Vec::new(),
543        });
544    }
545
546    let is_node_runner = NODE_RUNNERS.contains(&binary);
547    let (file_args, config_args) = extract_args_for_binary(&tokens, idx + 1, is_node_runner);
548
549    Some(ScriptCommand {
550        config_args,
551        file_args,
552    })
553}
554
555fn split_shell_operators(script: &str) -> Vec<&str> {
556    let mut segments = Vec::new();
557    let mut start = 0;
558    let bytes = script.as_bytes();
559    let len = bytes.len();
560    let mut index = 0;
561    let mut in_single_quote = false;
562    let mut in_double_quote = false;
563
564    while index < len {
565        let byte = bytes[index];
566
567        if byte == b'\'' && !in_double_quote {
568            in_single_quote = !in_single_quote;
569            index += 1;
570            continue;
571        }
572        if byte == b'"' && !in_single_quote {
573            in_double_quote = !in_double_quote;
574            index += 1;
575            continue;
576        }
577
578        if in_single_quote || in_double_quote {
579            index += 1;
580            continue;
581        }
582
583        if let Some(op_len) = shell_operator_len(bytes, index) {
584            segments.push(&script[start..index]);
585            index += op_len;
586            start = index;
587            continue;
588        }
589
590        index += 1;
591    }
592
593    if start < len {
594        segments.push(&script[start..]);
595    }
596
597    segments
598}
599
600fn shell_operator_len(bytes: &[u8], index: usize) -> Option<usize> {
601    let byte = bytes[index];
602    let next = bytes.get(index + 1).copied();
603
604    if matches!((byte, next), (b'&', Some(b'&')) | (b'|', Some(b'|'))) {
605        return Some(2);
606    }
607
608    if byte == b';' {
609        return Some(1);
610    }
611    if byte == b'|' && next != Some(b'|') {
612        return Some(1);
613    }
614    if byte == b'&' && next != Some(b'&') {
615        return Some(1);
616    }
617
618    None
619}
620
621fn strip_surrounding_quotes(token: &str) -> &str {
622    if token.len() >= 2 {
623        let first = token.as_bytes()[0];
624        let last = token.as_bytes()[token.len() - 1];
625        if (first == b'\'' || first == b'"') && first == last {
626            return &token[1..token.len() - 1];
627        }
628    }
629    token
630}
631
632fn skip_initial_wrappers(tokens: &[&str], mut index: usize) -> Option<usize> {
633    while index < tokens.len() && is_env_assignment(tokens[index]) {
634        index += 1;
635    }
636    if index >= tokens.len() {
637        return None;
638    }
639
640    while index < tokens.len() && ENV_WRAPPERS.contains(&tokens[index]) {
641        index += 1;
642        while index < tokens.len() && is_env_assignment(tokens[index]) {
643            index += 1;
644        }
645        if index < tokens.len() && tokens[index] == "--" {
646            index += 1;
647        }
648    }
649    if index >= tokens.len() {
650        return None;
651    }
652
653    Some(index)
654}
655
656fn advance_past_package_manager(tokens: &[&str], mut index: usize) -> Option<usize> {
657    let token = tokens[index];
658    if matches!(token, "npx" | "pnpx" | "bunx") {
659        index += 1;
660        while index < tokens.len() && tokens[index].starts_with('-') {
661            let flag = tokens[index];
662            index += 1;
663            if matches!(flag, "--package" | "-p") && index < tokens.len() {
664                index += 1;
665            }
666        }
667    } else if token == "bun" {
668        index += 1;
669        let mut saw_runtime_flag = false;
670        while index < tokens.len() && BUN_RUNTIME_FLAGS.contains(&tokens[index]) {
671            index += 1;
672            saw_runtime_flag = true;
673        }
674        if index >= tokens.len() {
675            return None;
676        }
677        let subcmd = tokens[index];
678        if subcmd == "exec" || subcmd == "x" {
679            index += 1;
680        } else if matches!(subcmd, "run" | "run-script") || !saw_runtime_flag {
681            return None;
682        }
683    } else if matches!(token, "yarn" | "pnpm" | "npm") {
684        if index + 1 < tokens.len() {
685            let subcmd = tokens[index + 1];
686            if subcmd == "exec" || subcmd == "dlx" {
687                index += 2;
688            } else {
689                return None;
690            }
691        } else {
692            return None;
693        }
694    }
695    if index >= tokens.len() {
696        return None;
697    }
698
699    Some(index)
700}
701
702fn extract_args_for_binary(
703    tokens: &[&str],
704    mut index: usize,
705    is_node_runner: bool,
706) -> (Vec<String>, Vec<String>) {
707    let mut file_args = Vec::new();
708    let mut config_args = Vec::new();
709
710    while index < tokens.len() {
711        let token = tokens[index];
712
713        if is_node_runner
714            && matches!(
715                token,
716                "-e" | "--eval" | "-p" | "--print" | "-r" | "--require"
717            )
718        {
719            index += 2;
720            continue;
721        }
722
723        if let Some(config) = extract_config_arg(token, tokens.get(index + 1).copied()) {
724            config_args.push(config);
725            if token.contains('=') || token.starts_with("--config=") || token.starts_with("-c=") {
726                index += 1;
727            } else {
728                index += 2;
729            }
730            continue;
731        }
732
733        if token.starts_with('-') {
734            index += 1;
735            continue;
736        }
737
738        if looks_like_file_path(token) {
739            file_args.push(token.to_string());
740        }
741        index += 1;
742    }
743
744    (file_args, config_args)
745}
746
747fn extract_config_arg(token: &str, next: Option<&str>) -> Option<String> {
748    if let Some(value) = token.strip_prefix("--config=")
749        && !value.is_empty()
750    {
751        return Some(value.to_string());
752    }
753    if let Some(value) = token.strip_prefix("-c=")
754        && !value.is_empty()
755    {
756        return Some(value.to_string());
757    }
758    if matches!(token, "--config" | "-c")
759        && let Some(next_token) = next
760        && !next_token.starts_with('-')
761    {
762        return Some(next_token.to_string());
763    }
764    None
765}
766
767fn is_env_assignment(token: &str) -> bool {
768    token.find('=').is_some_and(|eq_pos| {
769        let name = &token[..eq_pos];
770        !name.is_empty() && name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')
771    })
772}
773
774fn looks_like_file_path(token: &str) -> bool {
775    if !could_be_file_path(token) {
776        return false;
777    }
778
779    const EXTENSIONS: &[&str] = &[
780        ".js", ".ts", ".mjs", ".cjs", ".mts", ".cts", ".jsx", ".tsx", ".json", ".yaml", ".yml",
781        ".toml",
782    ];
783    if EXTENSIONS.iter().any(|ext| token.ends_with(ext)) {
784        return true;
785    }
786    token.starts_with("./")
787        || token.starts_with("../")
788        || (token.contains('/') && !token.starts_with('@') && !token.contains("://"))
789}
790
791fn could_be_file_path(token: &str) -> bool {
792    if token.contains("${{") || (token.contains("}}") && !token.contains("{{")) {
793        return false;
794    }
795
796    if token.contains('\\') {
797        return false;
798    }
799
800    if let Some(open) = token.find('[') {
801        let after_open = &token[open + 1..];
802        let close_offset = after_open.find(']');
803        if !matches!(close_offset, Some(offset) if offset > 0) {
804            return false;
805        }
806    }
807
808    true
809}
810
811/// Extract the root-relative path of every hidden (dot-prefixed) directory
812/// component on a relative path.
813///
814/// Each hidden directory on the path gets its own entry, because the walker
815/// filters one component at a time and every hidden level has to be admitted
816/// for the next one to be reached: `.foo/.bar/x.js` yields `[".foo",
817/// ".foo/.bar"]`. A hidden directory under a visible parent keeps that parent
818/// in its entry, so `tools/.bar/x.js` admits nothing named `.bar` anywhere
819/// else in the tree (issue #461).
820///
821/// Mirrors `fallow_core::discover::extract_hidden_dir_paths`.
822fn extract_hidden_dir_paths(path: &str) -> Vec<String> {
823    let path = Path::new(path);
824    if path.is_absolute() {
825        return Vec::new();
826    }
827
828    let mut hidden = Vec::new();
829    let components = path.components().collect::<Vec<_>>();
830    if components.iter().any(|component| {
831        matches!(
832            component,
833            std::path::Component::ParentDir | std::path::Component::RootDir
834        )
835    }) {
836        return Vec::new();
837    }
838
839    let mut prefix = PathBuf::new();
840    for (index, component) in components.iter().enumerate() {
841        let std::path::Component::Normal(value) = component else {
842            continue;
843        };
844        if index == components.len().saturating_sub(1) {
845            continue;
846        }
847        prefix.push(value);
848        let value = value.to_string_lossy();
849        if !value.starts_with('.') || value == "." || value == ".." {
850            continue;
851        }
852        hidden.push(prefix.to_string_lossy().into_owned());
853    }
854
855    hidden
856}
857
858/// Discover source files and non-source config candidates in one traversal.
859#[must_use]
860pub fn discover_files_and_config_candidates(
861    config: &ResolvedConfig,
862    additional_hidden_dir_scopes: &[HiddenDirScope],
863) -> (Vec<DiscoveredFile>, Vec<PathBuf>) {
864    crate::core_backend::discover_files_and_config_candidates(config, additional_hidden_dir_scopes)
865}
866
867/// The same traversal, keeping the source-discovery diagnostics it produced.
868#[must_use]
869fn discover_files_config_candidates_and_diagnostics(
870    config: &ResolvedConfig,
871    additional_hidden_dir_scopes: &[HiddenDirScope],
872) -> crate::core_backend::DiscoveredSources {
873    crate::core_backend::discover_files_config_candidates_and_diagnostics(
874        config,
875        additional_hidden_dir_scopes,
876    )
877}
878
879/// Discover the configured and inferred entry points of the root package and
880/// of each workspace package.
881#[must_use]
882pub(crate) fn discover_entry_points(
883    config: &ResolvedConfig,
884    files: &[DiscoveredFile],
885    workspaces: &[WorkspaceInfo],
886) -> Vec<EntryPoint> {
887    crate::core_backend::discover_entry_points(config, files, workspaces)
888}
889
890/// Discover entry points from plugin results.
891#[must_use]
892pub(crate) fn discover_plugin_entry_points(
893    plugin_result: &crate::plugins::AggregatedPluginResult,
894    config: &ResolvedConfig,
895    files: &[DiscoveredFile],
896) -> Vec<EntryPoint> {
897    crate::core_backend::discover_plugin_entry_points(plugin_result.backend(), config, files)
898}
899
900#[cfg(test)]
901mod tests {
902    use std::path::PathBuf;
903
904    use fallow_config::PackageJson;
905
906    use super::{
907        ALLOWED_HIDDEN_DIRS, HiddenDirScope, collect_hidden_dir_scopes, extract_hidden_dir_paths,
908        is_allowed_hidden_dir,
909    };
910
911    #[test]
912    fn hidden_dir_scope_exposes_root_and_dirs() {
913        let scope = HiddenDirScope::new(PathBuf::from("/repo/packages/app"), vec![".next".into()]);
914
915        assert_eq!(scope.root(), PathBuf::from("/repo/packages/app"));
916        assert_eq!(scope.dirs(), [".next"]);
917    }
918
919    #[test]
920    fn hidden_dir_allowlist_is_engine_owned() {
921        for dir in ALLOWED_HIDDEN_DIRS {
922            assert!(is_allowed_hidden_dir(std::ffi::OsStr::new(dir)));
923        }
924        assert!(!is_allowed_hidden_dir(std::ffi::OsStr::new(".git")));
925    }
926
927    #[test]
928    fn plugin_hidden_dir_scopes_are_engine_owned() {
929        let dir = tempfile::tempdir().expect("tempdir");
930        let config = fallow_config::FallowConfig::default().resolve(
931            dir.path().to_path_buf(),
932            fallow_config::OutputFormat::Human,
933            1,
934            true,
935            true,
936            None,
937        );
938        let pkg: PackageJson = serde_json::from_value(serde_json::json!({
939            "devDependencies": {
940                "@react-router/dev": "^7.0.0"
941            }
942        }))
943        .expect("valid package fixture");
944
945        let scopes = collect_hidden_dir_scopes(&config, Some(&pkg), &[]);
946
947        assert_eq!(scopes.len(), 1);
948        assert_eq!(scopes[0].root(), dir.path());
949        assert_eq!(scopes[0].dirs(), [".client", ".server"]);
950    }
951
952    #[test]
953    fn script_hidden_dir_scopes_are_engine_owned() {
954        let dir = tempfile::tempdir().expect("tempdir");
955        let config = fallow_config::FallowConfig::default().resolve(
956            dir.path().to_path_buf(),
957            fallow_config::OutputFormat::Human,
958            1,
959            true,
960            true,
961            None,
962        );
963        let pkg: PackageJson = serde_json::from_value(serde_json::json!({
964            "scripts": {
965                "lint": "eslint -c .config/eslint.config.js",
966                "build": "tsx ./.scripts/build.ts",
967                "cache": "tsx .nx/cache/build.ts",
968                "pnpm": "node node_modules/.pnpm/tool/bin.js"
969            }
970        }))
971        .expect("valid package fixture");
972
973        let scopes = collect_hidden_dir_scopes(&config, Some(&pkg), &[]);
974
975        assert_eq!(scopes.len(), 1);
976        assert_eq!(scopes[0].root(), dir.path());
977        let mut dirs = scopes[0].dirs().to_vec();
978        dirs.sort();
979        assert_eq!(dirs, [".config", ".scripts"]);
980    }
981
982    #[test]
983    fn hidden_dir_path_extraction_rejects_escape_paths() {
984        assert_eq!(
985            extract_hidden_dir_paths(".foo/.bar/x.js"),
986            vec![
987                ".foo".to_string(),
988                format!(".foo{}.bar", std::path::MAIN_SEPARATOR)
989            ]
990        );
991        assert!(extract_hidden_dir_paths("../../.config/eslint.config.js").is_empty());
992        assert!(extract_hidden_dir_paths(".env").is_empty());
993    }
994}