Skip to main content

arbor_watcher/
usages.rs

1//! Repository-wide SDK usage scan, behind `arbor usages` and the MCP tool
2//! `find_api_usages`.
3//!
4//! Walks the tree the way the indexer does (`.gitignore`, `.arborignore`,
5//! `.arbor/config.json` ignores and the built-in excludes), runs the per-file
6//! extractor from [`arbor_core::usages`] on every file that has one, and
7//! aggregates the result. It reads source text only; it never runs code and
8//! never touches the graph cache.
9//!
10//! Vendored and virtual-environment directories (`site-packages`, `venv`,
11//! `.venv`, `node_modules`, any directory holding a `pyvenv.cfg`...) are not
12//! project code. They are walked only to count what is skipped: their usages
13//! are excluded from the report and summarised as `vendored_path` gaps.
14//! Other hidden directories (`.github`, `.circleci`...) are counted the same
15//! way, without a gap; version-control, Arbor and tool-cache directories are
16//! not walked at all.
17//!
18//! Extensionless files are scanned when their first line is a Python
19//! shebang (`#!/usr/bin/env python3`).
20
21use crate::indexer::IgnoreMatcher;
22use arbor_core::languages::get_parser;
23use arbor_core::usages::{
24    is_python_shebang, is_usage_extension, ClientConstruction, FileUsages, GapKind, Sdk, SdkCall,
25    SdkImport, UsageGap, USAGE_LANGUAGES,
26};
27use arbor_core::{detect_language, parse_source_usages};
28use ignore::WalkBuilder;
29use rayon::prelude::*;
30use serde::{Deserialize, Serialize};
31use std::collections::{BTreeMap, HashMap};
32use std::io::Read;
33use std::path::{Component, Path, PathBuf};
34
35/// Version of the [`UsageReport`] JSON shape.
36pub const USAGE_REPORT_VERSION: u32 = 1;
37
38/// Directory names whose contents are third-party copies, not project code.
39pub const VENDORED_DIRS: &[&str] = &[
40    "site-packages",
41    "dist-packages",
42    "node_modules",
43    "venv",
44    ".venv",
45    "virtualenv",
46    "__pypackages__",
47    ".tox",
48    ".nox",
49    "vendor",
50    "_vendor",
51    "vendored",
52];
53
54/// Hidden directories that are never walked: version control, Arbor's own
55/// cache and tool caches. Any directory ending in `_cache` is skipped too.
56const UNWALKED_HIDDEN_DIRS: &[&str] = &[
57    ".git",
58    ".hg",
59    ".svn",
60    ".jj",
61    ".arbor",
62    ".idea",
63    ".cache",
64    ".ipynb_checkpoints",
65];
66
67/// Files larger than this are skipped and listed (generated or data files).
68pub const DEFAULT_MAX_FILE_BYTES: u64 = 4 * 1024 * 1024;
69
70/// What to scan.
71#[derive(Debug, Clone)]
72pub struct UsageScanOptions {
73    /// Keep only this provider's records.
74    pub sdk: Option<Sdk>,
75    pub follow_symlinks: bool,
76    pub max_file_bytes: u64,
77    /// How the caller names the scan root (`src`, `app/llm.py`). Reported
78    /// paths start with it, so they stay relative to wherever the caller
79    /// stands. `None`, `""` and `"."` report paths relative to the root.
80    pub display_root: Option<String>,
81}
82
83impl Default for UsageScanOptions {
84    fn default() -> Self {
85        Self {
86            sdk: None,
87            follow_symlinks: false,
88            max_file_bytes: DEFAULT_MAX_FILE_BYTES,
89            display_root: None,
90        }
91    }
92}
93
94/// Counts for a scan.
95#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
96pub struct UsageSummary {
97    /// Project files with a usage extractor that were analyzed.
98    pub files_scanned: usize,
99    /// Of those, files with at least one SDK call.
100    pub files_with_calls: usize,
101    pub calls: usize,
102    /// Of those, calls that send a request ([`SdkCall::request`]).
103    pub requests: usize,
104    pub clients: usize,
105    pub imports: usize,
106    pub gaps: usize,
107    /// Calls with at least one captured model value.
108    pub calls_with_model: usize,
109    /// Calls per provider.
110    pub by_sdk: BTreeMap<String, usize>,
111    /// Calls per routing.
112    pub by_routing: BTreeMap<String, usize>,
113    /// Gaps per kind.
114    pub gaps_by_kind: BTreeMap<String, usize>,
115}
116
117/// One skipped directory: vendored, a virtual environment, or hidden.
118#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
119pub struct SkippedRoot {
120    /// Path relative to the scan root, forward slashes, trailing `/`.
121    pub path: String,
122    /// Files with a usage extractor under it.
123    pub files: usize,
124    /// Of those, files with an SDK import or call.
125    pub files_with_usages: usize,
126    /// SDK calls in those files (excluded from `usages`).
127    pub calls: usize,
128}
129
130/// Everything excluded from the report, so nothing is dropped silently.
131#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
132pub struct Skipped {
133    pub vendored_files: usize,
134    pub vendored_files_with_usages: usize,
135    pub vendored_calls: usize,
136    pub vendored_roots: Vec<SkippedRoot>,
137    /// Files under hidden directories (`.github/scripts/llm.py`), counted
138    /// like vendored ones and excluded from the report.
139    #[serde(default)]
140    pub hidden_files: usize,
141    #[serde(default)]
142    pub hidden_files_with_usages: usize,
143    #[serde(default)]
144    pub hidden_calls: usize,
145    #[serde(default)]
146    pub hidden_roots: Vec<SkippedRoot>,
147    /// Files over the size limit, relative paths.
148    pub too_large: Vec<String>,
149    /// Files that could not be read as UTF-8 or parsed, with the reason.
150    pub unreadable: Vec<String>,
151    /// Project files whose syntax errors the parser recovered from. Their
152    /// usages are reported, but calls inside a broken region may be missing.
153    #[serde(default)]
154    pub syntax_errors: Vec<String>,
155}
156
157/// The result of [`scan_usages`].
158#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
159pub struct UsageReport {
160    pub version: u32,
161    /// The scanned path as the caller named it.
162    pub root: String,
163    /// The provider filter, if any.
164    pub sdk: Option<Sdk>,
165    /// Languages that have a usage extractor in this build.
166    pub languages: Vec<String>,
167    pub summary: UsageSummary,
168    /// SDK calls in project code, by file then position.
169    pub usages: Vec<SdkCall>,
170    pub clients: Vec<ClientConstruction>,
171    pub imports: Vec<SdkImport>,
172    pub gaps: Vec<UsageGap>,
173    pub skipped: Skipped,
174}
175
176/// One candidate file and, when skipped, the directory it is counted under.
177struct Candidate {
178    path: PathBuf,
179    relative: String,
180    vendored_root: Option<String>,
181    hidden_root: Option<String>,
182    /// No extension: scanned only if its first line is a Python shebang.
183    shebang: bool,
184}
185
186enum Outcome {
187    Parsed(FileUsages),
188    TooLarge,
189    Unreadable(String),
190    /// An extensionless file that is not a Python script.
191    NotSource,
192}
193
194/// Scans `root` (a directory or a single file) for tracked SDK usages.
195pub fn scan_usages(root: &Path, options: &UsageScanOptions) -> std::io::Result<UsageReport> {
196    let metadata = std::fs::metadata(root)?;
197    let prefix = display_prefix(options.display_root.as_deref());
198    let candidates = if metadata.is_file() {
199        single_file(root, prefix.as_deref())
200    } else {
201        walk(root, options.follow_symlinks, prefix.as_deref())
202    };
203
204    let outcomes: Vec<(Candidate, Outcome)> = candidates
205        .into_par_iter()
206        .map(|candidate| {
207            let outcome = analyze(&candidate, options);
208            (candidate, outcome)
209        })
210        .collect();
211
212    let mut report = UsageReport {
213        version: USAGE_REPORT_VERSION,
214        root: prefix.unwrap_or_else(|| root.display().to_string()),
215        sdk: options.sdk,
216        languages: USAGE_LANGUAGES.iter().map(|l| l.to_string()).collect(),
217        summary: UsageSummary::default(),
218        usages: Vec::new(),
219        clients: Vec::new(),
220        imports: Vec::new(),
221        gaps: Vec::new(),
222        skipped: Skipped::default(),
223    };
224    let mut vendored: BTreeMap<String, SkippedRoot> = BTreeMap::new();
225    let mut hidden: BTreeMap<String, SkippedRoot> = BTreeMap::new();
226
227    for (candidate, outcome) in outcomes {
228        let mut found = match outcome {
229            Outcome::Parsed(found) => found,
230            Outcome::NotSource => continue,
231            Outcome::TooLarge => {
232                report.skipped.too_large.push(candidate.relative);
233                continue;
234            }
235            Outcome::Unreadable(reason) => {
236                report
237                    .skipped
238                    .unreadable
239                    .push(format!("{}: {}", candidate.relative, reason));
240                continue;
241            }
242        };
243        if let Some(sdk) = options.sdk {
244            found.retain_sdk(sdk);
245        }
246
247        let skipped_under = match (candidate.vendored_root, candidate.hidden_root) {
248            (Some(root_path), _) => Some((&mut vendored, root_path)),
249            (None, Some(root_path)) => Some((&mut hidden, root_path)),
250            (None, None) => None,
251        };
252        if let Some((roots, root_path)) = skipped_under {
253            let entry = roots
254                .entry(root_path.clone())
255                .or_insert_with(|| SkippedRoot {
256                    path: root_path,
257                    files: 0,
258                    files_with_usages: 0,
259                    calls: 0,
260                });
261            entry.files += 1;
262            if !found.imports.is_empty() || !found.calls.is_empty() {
263                entry.files_with_usages += 1;
264                entry.calls += found.calls.len();
265            }
266            continue;
267        }
268
269        if found.syntax_errors {
270            report.skipped.syntax_errors.push(candidate.relative);
271        }
272        report.summary.files_scanned += 1;
273        if !found.calls.is_empty() {
274            report.summary.files_with_calls += 1;
275        }
276        report.usages.extend(found.calls);
277        report.clients.extend(found.clients);
278        report.imports.extend(found.imports);
279        report.gaps.extend(found.gaps);
280    }
281
282    for root_entry in vendored.into_values() {
283        report.skipped.vendored_files += root_entry.files;
284        report.skipped.vendored_files_with_usages += root_entry.files_with_usages;
285        report.skipped.vendored_calls += root_entry.calls;
286        if root_entry.files_with_usages > 0 {
287            report.gaps.push(UsageGap {
288                kind: GapKind::VendoredPath,
289                sdk: None,
290                file: root_entry.path.clone(),
291                span: None,
292                symbol: None,
293                chain: None,
294                key: None,
295                reason: "vendored".to_string(),
296                detail: format!(
297                    "{} SDK call(s) in {} file(s) under `{}` are excluded: it is a vendored or virtual-environment directory",
298                    root_entry.calls, root_entry.files_with_usages, root_entry.path
299                ),
300                values: Vec::new(),
301                values_complete: false,
302            });
303        }
304        report.skipped.vendored_roots.push(root_entry);
305    }
306    for root_entry in hidden.into_values() {
307        report.skipped.hidden_files += root_entry.files;
308        report.skipped.hidden_files_with_usages += root_entry.files_with_usages;
309        report.skipped.hidden_calls += root_entry.calls;
310        report.skipped.hidden_roots.push(root_entry);
311    }
312
313    summarize(&mut report);
314    Ok(report)
315}
316
317/// The display prefix, normalised: forward slashes, no trailing slash, and
318/// `None` for the root itself.
319fn display_prefix(display_root: Option<&str>) -> Option<String> {
320    let prefix = display_root?.replace('\\', "/");
321    let prefix = prefix.trim_end_matches('/');
322    let prefix = prefix.strip_prefix("./").unwrap_or(prefix);
323    if prefix.is_empty() || prefix == "." {
324        None
325    } else {
326        Some(prefix.to_string())
327    }
328}
329
330fn under(prefix: Option<&str>, relative: &str) -> String {
331    match prefix {
332        Some(prefix) => format!("{prefix}/{relative}"),
333        None => relative.to_string(),
334    }
335}
336
337fn single_file(path: &Path, prefix: Option<&str>) -> Vec<Candidate> {
338    let extension = path.extension().and_then(|e| e.to_str()).unwrap_or("");
339    let shebang = extension.is_empty();
340    if !shebang && !is_usage_extension(extension) {
341        return Vec::new();
342    }
343    let relative = match prefix {
344        Some(prefix) => prefix.to_string(),
345        None => path
346            .file_name()
347            .map(|n| n.to_string_lossy().to_string())
348            .unwrap_or_else(|| path.display().to_string()),
349    };
350    vec![Candidate {
351        path: path.to_path_buf(),
352        relative,
353        vendored_root: None,
354        hidden_root: None,
355        shebang,
356    }]
357}
358
359fn walk(root: &Path, follow_symlinks: bool, prefix: Option<&str>) -> Vec<Candidate> {
360    let matcher = IgnoreMatcher::new(root);
361    let walker = WalkBuilder::new(root)
362        // Hidden entries are filtered below, so `.venv` and `.tox` can be
363        // walked (and counted) while `.git` and `.arbor` are not.
364        .hidden(false)
365        .git_ignore(true)
366        .ignore(true)
367        .require_git(false)
368        .git_global(true)
369        .git_exclude(true)
370        .add_custom_ignore_filename(".arborignore")
371        .follow_links(follow_symlinks)
372        .filter_entry(|entry| {
373            if entry.depth() == 0 || !entry.file_type().is_some_and(|ft| ft.is_dir()) {
374                return true;
375            }
376            let name = entry.file_name().to_string_lossy();
377            !UNWALKED_HIDDEN_DIRS.contains(&name.as_ref()) && !name.ends_with("_cache")
378        })
379        .build();
380
381    let mut venv_dirs: HashMap<PathBuf, bool> = HashMap::new();
382    let mut candidates = Vec::new();
383    for entry in walker.filter_map(Result::ok) {
384        if !entry.file_type().is_some_and(|ft| ft.is_file()) {
385            continue;
386        }
387        let path = entry.path();
388        let extension = path.extension().and_then(|e| e.to_str()).unwrap_or("");
389        let shebang = extension.is_empty();
390        if !shebang && !is_usage_extension(extension) {
391            continue;
392        }
393        let relative_path = path.strip_prefix(root).unwrap_or(path);
394        let vendored_root =
395            vendored_root(root, relative_path, &mut venv_dirs).map(|dir| under(prefix, &dir));
396        // Built-in excludes (`build/`, `dist/`...) and configured ignores
397        // apply to project code. Vendored directories are matched first
398        // because the built-in excludes would hide them entirely.
399        if vendored_root.is_none() && matcher.is_ignored(path, false) {
400            continue;
401        }
402        let hidden_root = if vendored_root.is_none() {
403            hidden_root(relative_path).map(|dir| under(prefix, &dir))
404        } else {
405            None
406        };
407        candidates.push(Candidate {
408            path: path.to_path_buf(),
409            relative: under(prefix, &slash_path(relative_path)),
410            vendored_root,
411            hidden_root,
412            shebang,
413        });
414    }
415    candidates.sort_by(|a, b| a.relative.cmp(&b.relative));
416    candidates
417}
418
419/// The vendored directory containing `relative` (a path under `root`), as a
420/// relative path with a trailing `/`.
421fn vendored_root(
422    root: &Path,
423    relative: &Path,
424    venv_dirs: &mut HashMap<PathBuf, bool>,
425) -> Option<String> {
426    let parent = relative.parent()?;
427    let mut prefix = PathBuf::new();
428    for component in parent.components() {
429        let Component::Normal(name) = component else {
430            continue;
431        };
432        prefix.push(name);
433        let name = name.to_string_lossy();
434        let is_vendored = VENDORED_DIRS
435            .iter()
436            .any(|v| v.eq_ignore_ascii_case(name.as_ref()))
437            || *venv_dirs
438                .entry(prefix.clone())
439                .or_insert_with(|| root.join(&prefix).join("pyvenv.cfg").is_file());
440        if is_vendored {
441            return Some(format!("{}/", slash_path(&prefix)));
442        }
443    }
444    None
445}
446
447/// The outermost hidden directory containing `relative` (or the file itself
448/// when it is hidden), as a relative path with a trailing `/` for a
449/// directory.
450fn hidden_root(relative: &Path) -> Option<String> {
451    let mut prefix = PathBuf::new();
452    let mut components = relative.components().peekable();
453    while let Some(component) = components.next() {
454        let Component::Normal(name) = component else {
455            continue;
456        };
457        prefix.push(name);
458        if name.to_string_lossy().starts_with('.') {
459            let is_dir = components.peek().is_some();
460            let path = slash_path(&prefix);
461            return Some(if is_dir { format!("{path}/") } else { path });
462        }
463    }
464    None
465}
466
467fn slash_path(path: &Path) -> String {
468    path.to_string_lossy().replace('\\', "/")
469}
470
471fn analyze(candidate: &Candidate, options: &UsageScanOptions) -> Outcome {
472    if candidate.shebang && !has_python_shebang(&candidate.path) {
473        return Outcome::NotSource;
474    }
475    let size = std::fs::metadata(&candidate.path)
476        .map(|m| m.len())
477        .unwrap_or(0);
478    if size > options.max_file_bytes {
479        return Outcome::TooLarge;
480    }
481    let bytes = match std::fs::read(&candidate.path) {
482        Ok(bytes) => bytes,
483        Err(error) => return Outcome::Unreadable(error.to_string()),
484    };
485    let source = match String::from_utf8(bytes) {
486        Ok(source) => source,
487        Err(_) => return Outcome::Unreadable("not valid UTF-8".to_string()),
488    };
489    let parser = if candidate.shebang {
490        get_parser("py")
491    } else {
492        detect_language(&candidate.path)
493    };
494    let Some(parser) = parser else {
495        return Outcome::Parsed(FileUsages::new(&candidate.relative, "unknown"));
496    };
497    match parse_source_usages(&source, &candidate.relative, parser.as_ref()) {
498        Ok(Some(found)) => Outcome::Parsed(found),
499        Ok(None) => Outcome::Parsed(FileUsages::new(&candidate.relative, "unknown")),
500        Err(error) => Outcome::Unreadable(error.to_string()),
501    }
502}
503
504/// Whether an extensionless file starts with a Python shebang. Reads at most
505/// 256 bytes, so binaries and data files cost almost nothing.
506fn has_python_shebang(path: &Path) -> bool {
507    let mut head = [0u8; 256];
508    let read = std::fs::File::open(path)
509        .and_then(|mut file| file.read(&mut head))
510        .unwrap_or(0);
511    is_python_shebang(&head[..read])
512}
513
514fn summarize(report: &mut UsageReport) {
515    report.gaps.sort_by(|a, b| {
516        (a.file.as_str(), a.span.map(|s| s.start_byte), a.kind).cmp(&(
517            b.file.as_str(),
518            b.span.map(|s| s.start_byte),
519            b.kind,
520        ))
521    });
522    let summary = &mut report.summary;
523    summary.calls = report.usages.len();
524    summary.requests = report.usages.iter().filter(|c| c.request).count();
525    summary.clients = report.clients.len();
526    summary.imports = report.imports.len();
527    summary.gaps = report.gaps.len();
528    summary.calls_with_model = report
529        .usages
530        .iter()
531        .filter(|c| !c.values.is_empty())
532        .count();
533    for call in &report.usages {
534        *summary
535            .by_sdk
536            .entry(call.sdk.as_str().to_string())
537            .or_default() += 1;
538        *summary
539            .by_routing
540            .entry(call.routing.as_str().to_string())
541            .or_default() += 1;
542    }
543    for gap in &report.gaps {
544        *summary
545            .gaps_by_kind
546            .entry(gap.kind.as_str().to_string())
547            .or_default() += 1;
548    }
549}
550
551#[cfg(test)]
552mod tests {
553    use super::*;
554    use arbor_core::usages::Routing;
555    use std::fs;
556    use tempfile::tempdir;
557
558    const CHAT: &str = "from openai import OpenAI\nclient = OpenAI()\nclient.chat.completions.create(model=\"gpt-3.5-turbo\", messages=[])\n";
559
560    fn write(root: &Path, relative: &str, text: &str) {
561        let path = root.join(relative);
562        fs::create_dir_all(path.parent().unwrap()).unwrap();
563        fs::write(path, text).unwrap();
564    }
565
566    #[test]
567    fn project_usages_are_reported_with_relative_paths() {
568        let dir = tempdir().unwrap();
569        write(dir.path(), "app/chat.py", CHAT);
570        write(dir.path(), "app/util.py", "def f():\n    return 1\n");
571        write(dir.path(), "README.md", "client.chat.completions.create");
572
573        let report = scan_usages(dir.path(), &UsageScanOptions::default()).unwrap();
574        assert_eq!(report.summary.files_scanned, 2);
575        assert_eq!(report.summary.files_with_calls, 1);
576        assert_eq!(report.usages.len(), 1);
577        assert_eq!(report.usages[0].file, "app/chat.py");
578        assert_eq!(report.usages[0].routing, Routing::OpenaiDirect);
579        assert_eq!(report.summary.by_sdk.get("openai"), Some(&1));
580        assert_eq!(report.summary.by_routing.get("openai_direct"), Some(&1));
581        assert_eq!(report.summary.calls_with_model, 1);
582        assert!(report.gaps.is_empty());
583    }
584
585    #[test]
586    fn vendored_directories_are_excluded_and_counted() {
587        let dir = tempdir().unwrap();
588        write(dir.path(), "app.py", CHAT);
589        write(
590            dir.path(),
591            "venv/lib/python3.11/site-packages/openai/x.py",
592            CHAT,
593        );
594        write(dir.path(), ".venv/lib/site-packages/thing.py", "x = 1\n");
595        write(dir.path(), "third_party/node_modules/pkg/tool.py", CHAT);
596        // A virtual environment with an unusual name is found by pyvenv.cfg.
597        write(dir.path(), "myenv/pyvenv.cfg", "home = /usr/bin\n");
598        write(dir.path(), "myenv/lib/llm.py", CHAT);
599
600        let report = scan_usages(dir.path(), &UsageScanOptions::default()).unwrap();
601        assert_eq!(report.usages.len(), 1, "only project code is reported");
602        assert_eq!(report.usages[0].file, "app.py");
603        assert_eq!(report.summary.files_scanned, 1);
604
605        let skipped = &report.skipped;
606        assert_eq!(skipped.vendored_files, 4);
607        assert_eq!(skipped.vendored_files_with_usages, 3);
608        assert_eq!(skipped.vendored_calls, 3);
609        let roots: Vec<&str> = skipped
610            .vendored_roots
611            .iter()
612            .map(|r| r.path.as_str())
613            .collect();
614        assert_eq!(
615            roots,
616            vec![".venv/", "myenv/", "third_party/node_modules/", "venv/"]
617        );
618        let gaps: Vec<&str> = report
619            .gaps
620            .iter()
621            .filter(|g| g.kind == GapKind::VendoredPath)
622            .map(|g| g.file.as_str())
623            .collect();
624        assert_eq!(gaps, vec!["myenv/", "third_party/node_modules/", "venv/"]);
625    }
626
627    #[test]
628    fn gitignored_and_hidden_paths_are_not_part_of_the_project() {
629        let dir = tempdir().unwrap();
630        write(dir.path(), ".gitignore", "venv/\nignored/\n");
631        write(dir.path(), "venv/lib/site-packages/openai/x.py", CHAT);
632        write(dir.path(), "ignored/llm.py", CHAT);
633        write(dir.path(), ".github/scripts/llm.py", CHAT);
634        write(dir.path(), ".github/scripts/util.py", "x = 1\n");
635        write(dir.path(), ".git/hooks/pre-commit.py", CHAT);
636        write(dir.path(), ".mypy_cache/x.py", CHAT);
637        write(dir.path(), "build/lib/app.py", CHAT);
638        write(dir.path(), "app.py", CHAT);
639
640        let report = scan_usages(dir.path(), &UsageScanOptions::default()).unwrap();
641        assert_eq!(report.usages.len(), 1);
642        assert_eq!(report.skipped.vendored_files, 0);
643        // Hidden directories are counted, not dropped silently; version
644        // control and tool caches are not walked.
645        let skipped = &report.skipped;
646        assert_eq!(skipped.hidden_files, 2);
647        assert_eq!(skipped.hidden_files_with_usages, 1);
648        assert_eq!(skipped.hidden_calls, 1);
649        let roots: Vec<&str> = skipped
650            .hidden_roots
651            .iter()
652            .map(|r| r.path.as_str())
653            .collect();
654        assert_eq!(roots, vec![".github/"]);
655    }
656
657    #[test]
658    fn python_shebang_scripts_are_scanned() {
659        let dir = tempdir().unwrap();
660        write(
661            dir.path(),
662            "bin/summarize",
663            &format!("#!/usr/bin/env python3\n{CHAT}"),
664        );
665        write(dir.path(), "bin/deploy", "#!/bin/sh\necho openai\n");
666        write(dir.path(), "Makefile", "all:\n\techo openai\n");
667        fs::write(dir.path().join("blob"), [0u8, 159, 146, 150, 255]).unwrap();
668
669        let report = scan_usages(dir.path(), &UsageScanOptions::default()).unwrap();
670        assert_eq!(report.summary.files_scanned, 1);
671        assert_eq!(report.usages.len(), 1);
672        assert_eq!(report.usages[0].file, "bin/summarize");
673        assert!(report.skipped.unreadable.is_empty());
674
675        let single = scan_usages(
676            &dir.path().join("bin/summarize"),
677            &UsageScanOptions::default(),
678        )
679        .unwrap();
680        assert_eq!(single.usages.len(), 1);
681        let not_python =
682            scan_usages(&dir.path().join("bin/deploy"), &UsageScanOptions::default()).unwrap();
683        assert_eq!(not_python.summary.files_scanned, 0);
684    }
685
686    #[test]
687    fn files_with_syntax_errors_are_listed() {
688        let dir = tempdir().unwrap();
689        write(
690            dir.path(),
691            "broken.py",
692            "from openai import OpenAI\nclient = OpenAI()\ndef broken(:\n    pass\n",
693        );
694        write(dir.path(), "fine.py", CHAT);
695        // A file that mentions no SDK is not even parsed.
696        write(dir.path(), "other.py", "def broken(:\n");
697        let report = scan_usages(dir.path(), &UsageScanOptions::default()).unwrap();
698        assert_eq!(report.skipped.syntax_errors, vec!["broken.py"]);
699        assert_eq!(report.summary.files_scanned, 3);
700    }
701
702    #[test]
703    fn sdk_filter_and_single_file_scan() {
704        let dir = tempdir().unwrap();
705        write(
706            dir.path(),
707            "mixed.py",
708            "from openai import OpenAI\nfrom anthropic import Anthropic\nOpenAI().chat.completions.create(model=\"gpt-4\", messages=[])\nAnthropic().messages.create(model=\"claude-2.1\", max_tokens=1, messages=[])\n",
709        );
710        let options = UsageScanOptions {
711            sdk: Some(Sdk::Anthropic),
712            ..UsageScanOptions::default()
713        };
714        let report = scan_usages(dir.path(), &options).unwrap();
715        assert_eq!(report.sdk, Some(Sdk::Anthropic));
716        assert_eq!(report.usages.len(), 1);
717        assert_eq!(report.usages[0].sdk, Sdk::Anthropic);
718        assert!(report.imports.iter().all(|i| i.sdk == Sdk::Anthropic));
719
720        let single =
721            scan_usages(&dir.path().join("mixed.py"), &UsageScanOptions::default()).unwrap();
722        assert_eq!(single.usages.len(), 2);
723        assert_eq!(single.usages[0].file, "mixed.py");
724    }
725
726    #[test]
727    fn display_root_prefixes_every_reported_path() {
728        let dir = tempdir().unwrap();
729        write(dir.path(), "src/app.py", CHAT);
730        write(dir.path(), "src/venv/lib/x.py", CHAT);
731        let options = UsageScanOptions {
732            display_root: Some("src\\".to_string()),
733            ..UsageScanOptions::default()
734        };
735        let report = scan_usages(&dir.path().join("src"), &options).unwrap();
736        assert_eq!(report.root, "src");
737        assert_eq!(report.usages[0].file, "src/app.py");
738        assert_eq!(report.clients[0].file, "src/app.py");
739        assert_eq!(report.skipped.vendored_roots[0].path, "src/venv/");
740        assert_eq!(report.gaps[0].file, "src/venv/");
741
742        for root in [None, Some(""), Some("."), Some("./")] {
743            assert_eq!(display_prefix(root), None, "{root:?}");
744        }
745        assert_eq!(display_prefix(Some("./a/b/")), Some("a/b".to_string()));
746    }
747
748    #[test]
749    fn oversized_and_non_utf8_files_are_listed() {
750        let dir = tempdir().unwrap();
751        write(dir.path(), "big.py", &"# openai\n".repeat(64));
752        fs::write(dir.path().join("latin1.py"), b"x = '\xe9'\nimport openai\n").unwrap();
753        let options = UsageScanOptions {
754            max_file_bytes: 100,
755            ..UsageScanOptions::default()
756        };
757        let report = scan_usages(dir.path(), &options).unwrap();
758        assert_eq!(report.skipped.too_large, vec!["big.py"]);
759        assert_eq!(report.skipped.unreadable.len(), 1);
760        assert!(report.skipped.unreadable[0].starts_with("latin1.py"));
761    }
762
763    #[test]
764    fn missing_path_is_an_error() {
765        let dir = tempdir().unwrap();
766        assert!(scan_usages(&dir.path().join("nope"), &UsageScanOptions::default()).is_err());
767    }
768
769    #[test]
770    fn report_json_round_trips() {
771        let dir = tempdir().unwrap();
772        write(dir.path(), "app.py", CHAT);
773        let report = scan_usages(dir.path(), &UsageScanOptions::default()).unwrap();
774        let json = serde_json::to_string(&report).unwrap();
775        let back: UsageReport = serde_json::from_str(&json).unwrap();
776        assert_eq!(back, report);
777        assert_eq!(back.version, USAGE_REPORT_VERSION);
778    }
779}