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                args: None,
303            });
304        }
305        report.skipped.vendored_roots.push(root_entry);
306    }
307    for root_entry in hidden.into_values() {
308        report.skipped.hidden_files += root_entry.files;
309        report.skipped.hidden_files_with_usages += root_entry.files_with_usages;
310        report.skipped.hidden_calls += root_entry.calls;
311        report.skipped.hidden_roots.push(root_entry);
312    }
313
314    summarize(&mut report);
315    Ok(report)
316}
317
318/// The display prefix, normalised: forward slashes, no trailing slash, and
319/// `None` for the root itself.
320fn display_prefix(display_root: Option<&str>) -> Option<String> {
321    let prefix = display_root?.replace('\\', "/");
322    let prefix = prefix.trim_end_matches('/');
323    let prefix = prefix.strip_prefix("./").unwrap_or(prefix);
324    if prefix.is_empty() || prefix == "." {
325        None
326    } else {
327        Some(prefix.to_string())
328    }
329}
330
331fn under(prefix: Option<&str>, relative: &str) -> String {
332    match prefix {
333        Some(prefix) => format!("{prefix}/{relative}"),
334        None => relative.to_string(),
335    }
336}
337
338fn single_file(path: &Path, prefix: Option<&str>) -> Vec<Candidate> {
339    let extension = path.extension().and_then(|e| e.to_str()).unwrap_or("");
340    let shebang = extension.is_empty();
341    if !shebang && !is_usage_extension(extension) {
342        return Vec::new();
343    }
344    let relative = match prefix {
345        Some(prefix) => prefix.to_string(),
346        None => path
347            .file_name()
348            .map(|n| n.to_string_lossy().to_string())
349            .unwrap_or_else(|| path.display().to_string()),
350    };
351    vec![Candidate {
352        path: path.to_path_buf(),
353        relative,
354        vendored_root: None,
355        hidden_root: None,
356        shebang,
357    }]
358}
359
360fn walk(root: &Path, follow_symlinks: bool, prefix: Option<&str>) -> Vec<Candidate> {
361    let matcher = IgnoreMatcher::new(root);
362    let walker = WalkBuilder::new(root)
363        // Hidden entries are filtered below, so `.venv` and `.tox` can be
364        // walked (and counted) while `.git` and `.arbor` are not.
365        .hidden(false)
366        .git_ignore(true)
367        .ignore(true)
368        .require_git(false)
369        .git_global(true)
370        .git_exclude(true)
371        .add_custom_ignore_filename(".arborignore")
372        .follow_links(follow_symlinks)
373        .filter_entry(|entry| {
374            if entry.depth() == 0 || !entry.file_type().is_some_and(|ft| ft.is_dir()) {
375                return true;
376            }
377            let name = entry.file_name().to_string_lossy();
378            !UNWALKED_HIDDEN_DIRS.contains(&name.as_ref()) && !name.ends_with("_cache")
379        })
380        .build();
381
382    let mut venv_dirs: HashMap<PathBuf, bool> = HashMap::new();
383    let mut candidates = Vec::new();
384    for entry in walker.filter_map(Result::ok) {
385        if !entry.file_type().is_some_and(|ft| ft.is_file()) {
386            continue;
387        }
388        let path = entry.path();
389        let extension = path.extension().and_then(|e| e.to_str()).unwrap_or("");
390        let shebang = extension.is_empty();
391        if !shebang && !is_usage_extension(extension) {
392            continue;
393        }
394        let relative_path = path.strip_prefix(root).unwrap_or(path);
395        let vendored_root =
396            vendored_root(root, relative_path, &mut venv_dirs).map(|dir| under(prefix, &dir));
397        // Built-in excludes (`build/`, `dist/`...) and configured ignores
398        // apply to project code. Vendored directories are matched first
399        // because the built-in excludes would hide them entirely.
400        if vendored_root.is_none() && matcher.is_ignored(path, false) {
401            continue;
402        }
403        let hidden_root = if vendored_root.is_none() {
404            hidden_root(relative_path).map(|dir| under(prefix, &dir))
405        } else {
406            None
407        };
408        candidates.push(Candidate {
409            path: path.to_path_buf(),
410            relative: under(prefix, &slash_path(relative_path)),
411            vendored_root,
412            hidden_root,
413            shebang,
414        });
415    }
416    candidates.sort_by(|a, b| a.relative.cmp(&b.relative));
417    candidates
418}
419
420/// The vendored directory containing `relative` (a path under `root`), as a
421/// relative path with a trailing `/`.
422fn vendored_root(
423    root: &Path,
424    relative: &Path,
425    venv_dirs: &mut HashMap<PathBuf, bool>,
426) -> Option<String> {
427    let parent = relative.parent()?;
428    let mut prefix = PathBuf::new();
429    for component in parent.components() {
430        let Component::Normal(name) = component else {
431            continue;
432        };
433        prefix.push(name);
434        let name = name.to_string_lossy();
435        let is_vendored = VENDORED_DIRS
436            .iter()
437            .any(|v| v.eq_ignore_ascii_case(name.as_ref()))
438            || *venv_dirs
439                .entry(prefix.clone())
440                .or_insert_with(|| root.join(&prefix).join("pyvenv.cfg").is_file());
441        if is_vendored {
442            return Some(format!("{}/", slash_path(&prefix)));
443        }
444    }
445    None
446}
447
448/// The outermost hidden directory containing `relative` (or the file itself
449/// when it is hidden), as a relative path with a trailing `/` for a
450/// directory.
451fn hidden_root(relative: &Path) -> Option<String> {
452    let mut prefix = PathBuf::new();
453    let mut components = relative.components().peekable();
454    while let Some(component) = components.next() {
455        let Component::Normal(name) = component else {
456            continue;
457        };
458        prefix.push(name);
459        if name.to_string_lossy().starts_with('.') {
460            let is_dir = components.peek().is_some();
461            let path = slash_path(&prefix);
462            return Some(if is_dir { format!("{path}/") } else { path });
463        }
464    }
465    None
466}
467
468fn slash_path(path: &Path) -> String {
469    path.to_string_lossy().replace('\\', "/")
470}
471
472fn analyze(candidate: &Candidate, options: &UsageScanOptions) -> Outcome {
473    if candidate.shebang && !has_python_shebang(&candidate.path) {
474        return Outcome::NotSource;
475    }
476    let size = std::fs::metadata(&candidate.path)
477        .map(|m| m.len())
478        .unwrap_or(0);
479    if size > options.max_file_bytes {
480        return Outcome::TooLarge;
481    }
482    let bytes = match std::fs::read(&candidate.path) {
483        Ok(bytes) => bytes,
484        Err(error) => return Outcome::Unreadable(error.to_string()),
485    };
486    let source = match String::from_utf8(bytes) {
487        Ok(source) => source,
488        Err(_) => return Outcome::Unreadable("not valid UTF-8".to_string()),
489    };
490    let parser = if candidate.shebang {
491        get_parser("py")
492    } else {
493        detect_language(&candidate.path)
494    };
495    let Some(parser) = parser else {
496        return Outcome::Parsed(FileUsages::new(&candidate.relative, "unknown"));
497    };
498    match parse_source_usages(&source, &candidate.relative, parser.as_ref()) {
499        Ok(Some(found)) => Outcome::Parsed(found),
500        Ok(None) => Outcome::Parsed(FileUsages::new(&candidate.relative, "unknown")),
501        Err(error) => Outcome::Unreadable(error.to_string()),
502    }
503}
504
505/// Whether an extensionless file starts with a Python shebang. Reads at most
506/// 256 bytes, so binaries and data files cost almost nothing.
507fn has_python_shebang(path: &Path) -> bool {
508    let mut head = [0u8; 256];
509    let read = std::fs::File::open(path)
510        .and_then(|mut file| file.read(&mut head))
511        .unwrap_or(0);
512    is_python_shebang(&head[..read])
513}
514
515fn summarize(report: &mut UsageReport) {
516    report.gaps.sort_by(|a, b| {
517        (a.file.as_str(), a.span.map(|s| s.start_byte), a.kind).cmp(&(
518            b.file.as_str(),
519            b.span.map(|s| s.start_byte),
520            b.kind,
521        ))
522    });
523    let summary = &mut report.summary;
524    summary.calls = report.usages.len();
525    summary.requests = report.usages.iter().filter(|c| c.request).count();
526    summary.clients = report.clients.len();
527    summary.imports = report.imports.len();
528    summary.gaps = report.gaps.len();
529    summary.calls_with_model = report
530        .usages
531        .iter()
532        .filter(|c| !c.values.is_empty())
533        .count();
534    for call in &report.usages {
535        *summary
536            .by_sdk
537            .entry(call.sdk.as_str().to_string())
538            .or_default() += 1;
539        *summary
540            .by_routing
541            .entry(call.routing.as_str().to_string())
542            .or_default() += 1;
543    }
544    for gap in &report.gaps {
545        *summary
546            .gaps_by_kind
547            .entry(gap.kind.as_str().to_string())
548            .or_default() += 1;
549    }
550}
551
552#[cfg(test)]
553mod tests {
554    use super::*;
555    use arbor_core::usages::Routing;
556    use std::fs;
557    use tempfile::tempdir;
558
559    const CHAT: &str = "from openai import OpenAI\nclient = OpenAI()\nclient.chat.completions.create(model=\"gpt-3.5-turbo\", messages=[])\n";
560
561    fn write(root: &Path, relative: &str, text: &str) {
562        let path = root.join(relative);
563        fs::create_dir_all(path.parent().unwrap()).unwrap();
564        fs::write(path, text).unwrap();
565    }
566
567    #[test]
568    fn project_usages_are_reported_with_relative_paths() {
569        let dir = tempdir().unwrap();
570        write(dir.path(), "app/chat.py", CHAT);
571        write(dir.path(), "app/util.py", "def f():\n    return 1\n");
572        write(dir.path(), "README.md", "client.chat.completions.create");
573
574        let report = scan_usages(dir.path(), &UsageScanOptions::default()).unwrap();
575        assert_eq!(report.summary.files_scanned, 2);
576        assert_eq!(report.summary.files_with_calls, 1);
577        assert_eq!(report.usages.len(), 1);
578        assert_eq!(report.usages[0].file, "app/chat.py");
579        assert_eq!(report.usages[0].routing, Routing::OpenaiDirect);
580        assert_eq!(report.summary.by_sdk.get("openai"), Some(&1));
581        assert_eq!(report.summary.by_routing.get("openai_direct"), Some(&1));
582        assert_eq!(report.summary.calls_with_model, 1);
583        assert!(report.gaps.is_empty());
584    }
585
586    #[test]
587    fn vendored_directories_are_excluded_and_counted() {
588        let dir = tempdir().unwrap();
589        write(dir.path(), "app.py", CHAT);
590        write(
591            dir.path(),
592            "venv/lib/python3.11/site-packages/openai/x.py",
593            CHAT,
594        );
595        write(dir.path(), ".venv/lib/site-packages/thing.py", "x = 1\n");
596        write(dir.path(), "third_party/node_modules/pkg/tool.py", CHAT);
597        // A virtual environment with an unusual name is found by pyvenv.cfg.
598        write(dir.path(), "myenv/pyvenv.cfg", "home = /usr/bin\n");
599        write(dir.path(), "myenv/lib/llm.py", CHAT);
600
601        let report = scan_usages(dir.path(), &UsageScanOptions::default()).unwrap();
602        assert_eq!(report.usages.len(), 1, "only project code is reported");
603        assert_eq!(report.usages[0].file, "app.py");
604        assert_eq!(report.summary.files_scanned, 1);
605
606        let skipped = &report.skipped;
607        assert_eq!(skipped.vendored_files, 4);
608        assert_eq!(skipped.vendored_files_with_usages, 3);
609        assert_eq!(skipped.vendored_calls, 3);
610        let roots: Vec<&str> = skipped
611            .vendored_roots
612            .iter()
613            .map(|r| r.path.as_str())
614            .collect();
615        assert_eq!(
616            roots,
617            vec![".venv/", "myenv/", "third_party/node_modules/", "venv/"]
618        );
619        let gaps: Vec<&str> = report
620            .gaps
621            .iter()
622            .filter(|g| g.kind == GapKind::VendoredPath)
623            .map(|g| g.file.as_str())
624            .collect();
625        assert_eq!(gaps, vec!["myenv/", "third_party/node_modules/", "venv/"]);
626    }
627
628    #[test]
629    fn gitignored_and_hidden_paths_are_not_part_of_the_project() {
630        let dir = tempdir().unwrap();
631        write(dir.path(), ".gitignore", "venv/\nignored/\n");
632        write(dir.path(), "venv/lib/site-packages/openai/x.py", CHAT);
633        write(dir.path(), "ignored/llm.py", CHAT);
634        write(dir.path(), ".github/scripts/llm.py", CHAT);
635        write(dir.path(), ".github/scripts/util.py", "x = 1\n");
636        write(dir.path(), ".git/hooks/pre-commit.py", CHAT);
637        write(dir.path(), ".mypy_cache/x.py", CHAT);
638        write(dir.path(), "build/lib/app.py", CHAT);
639        write(dir.path(), "app.py", CHAT);
640
641        let report = scan_usages(dir.path(), &UsageScanOptions::default()).unwrap();
642        assert_eq!(report.usages.len(), 1);
643        assert_eq!(report.skipped.vendored_files, 0);
644        // Hidden directories are counted, not dropped silently; version
645        // control and tool caches are not walked.
646        let skipped = &report.skipped;
647        assert_eq!(skipped.hidden_files, 2);
648        assert_eq!(skipped.hidden_files_with_usages, 1);
649        assert_eq!(skipped.hidden_calls, 1);
650        let roots: Vec<&str> = skipped
651            .hidden_roots
652            .iter()
653            .map(|r| r.path.as_str())
654            .collect();
655        assert_eq!(roots, vec![".github/"]);
656    }
657
658    #[test]
659    fn python_shebang_scripts_are_scanned() {
660        let dir = tempdir().unwrap();
661        write(
662            dir.path(),
663            "bin/summarize",
664            &format!("#!/usr/bin/env python3\n{CHAT}"),
665        );
666        write(dir.path(), "bin/deploy", "#!/bin/sh\necho openai\n");
667        write(dir.path(), "Makefile", "all:\n\techo openai\n");
668        fs::write(dir.path().join("blob"), [0u8, 159, 146, 150, 255]).unwrap();
669
670        let report = scan_usages(dir.path(), &UsageScanOptions::default()).unwrap();
671        assert_eq!(report.summary.files_scanned, 1);
672        assert_eq!(report.usages.len(), 1);
673        assert_eq!(report.usages[0].file, "bin/summarize");
674        assert!(report.skipped.unreadable.is_empty());
675
676        let single = scan_usages(
677            &dir.path().join("bin/summarize"),
678            &UsageScanOptions::default(),
679        )
680        .unwrap();
681        assert_eq!(single.usages.len(), 1);
682        let not_python =
683            scan_usages(&dir.path().join("bin/deploy"), &UsageScanOptions::default()).unwrap();
684        assert_eq!(not_python.summary.files_scanned, 0);
685    }
686
687    #[test]
688    fn files_with_syntax_errors_are_listed() {
689        let dir = tempdir().unwrap();
690        write(
691            dir.path(),
692            "broken.py",
693            "from openai import OpenAI\nclient = OpenAI()\ndef broken(:\n    pass\n",
694        );
695        write(dir.path(), "fine.py", CHAT);
696        // A file that mentions no SDK is not even parsed.
697        write(dir.path(), "other.py", "def broken(:\n");
698        let report = scan_usages(dir.path(), &UsageScanOptions::default()).unwrap();
699        assert_eq!(report.skipped.syntax_errors, vec!["broken.py"]);
700        assert_eq!(report.summary.files_scanned, 3);
701    }
702
703    #[test]
704    fn sdk_filter_and_single_file_scan() {
705        let dir = tempdir().unwrap();
706        write(
707            dir.path(),
708            "mixed.py",
709            "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",
710        );
711        let options = UsageScanOptions {
712            sdk: Some(Sdk::Anthropic),
713            ..UsageScanOptions::default()
714        };
715        let report = scan_usages(dir.path(), &options).unwrap();
716        assert_eq!(report.sdk, Some(Sdk::Anthropic));
717        assert_eq!(report.usages.len(), 1);
718        assert_eq!(report.usages[0].sdk, Sdk::Anthropic);
719        assert!(report.imports.iter().all(|i| i.sdk == Sdk::Anthropic));
720
721        let single =
722            scan_usages(&dir.path().join("mixed.py"), &UsageScanOptions::default()).unwrap();
723        assert_eq!(single.usages.len(), 2);
724        assert_eq!(single.usages[0].file, "mixed.py");
725    }
726
727    #[test]
728    fn display_root_prefixes_every_reported_path() {
729        let dir = tempdir().unwrap();
730        write(dir.path(), "src/app.py", CHAT);
731        write(dir.path(), "src/venv/lib/x.py", CHAT);
732        let options = UsageScanOptions {
733            display_root: Some("src\\".to_string()),
734            ..UsageScanOptions::default()
735        };
736        let report = scan_usages(&dir.path().join("src"), &options).unwrap();
737        assert_eq!(report.root, "src");
738        assert_eq!(report.usages[0].file, "src/app.py");
739        assert_eq!(report.clients[0].file, "src/app.py");
740        assert_eq!(report.skipped.vendored_roots[0].path, "src/venv/");
741        assert_eq!(report.gaps[0].file, "src/venv/");
742
743        for root in [None, Some(""), Some("."), Some("./")] {
744            assert_eq!(display_prefix(root), None, "{root:?}");
745        }
746        assert_eq!(display_prefix(Some("./a/b/")), Some("a/b".to_string()));
747    }
748
749    #[test]
750    fn oversized_and_non_utf8_files_are_listed() {
751        let dir = tempdir().unwrap();
752        write(dir.path(), "big.py", &"# openai\n".repeat(64));
753        fs::write(dir.path().join("latin1.py"), b"x = '\xe9'\nimport openai\n").unwrap();
754        let options = UsageScanOptions {
755            max_file_bytes: 100,
756            ..UsageScanOptions::default()
757        };
758        let report = scan_usages(dir.path(), &options).unwrap();
759        assert_eq!(report.skipped.too_large, vec!["big.py"]);
760        assert_eq!(report.skipped.unreadable.len(), 1);
761        assert!(report.skipped.unreadable[0].starts_with("latin1.py"));
762    }
763
764    #[test]
765    fn missing_path_is_an_error() {
766        let dir = tempdir().unwrap();
767        assert!(scan_usages(&dir.path().join("nope"), &UsageScanOptions::default()).is_err());
768    }
769
770    #[test]
771    fn report_json_round_trips() {
772        let dir = tempdir().unwrap();
773        write(dir.path(), "app.py", CHAT);
774        let report = scan_usages(dir.path(), &UsageScanOptions::default()).unwrap();
775        let json = serde_json::to_string(&report).unwrap();
776        let back: UsageReport = serde_json::from_str(&json).unwrap();
777        assert_eq!(back, report);
778        assert_eq!(back.version, USAGE_REPORT_VERSION);
779    }
780}