Skip to main content

uv_scripts/
discovery.rs

1//! Discovery of PEP 723 scripts in a workspace tree.
2
3use std::borrow::Cow;
4use std::io;
5use std::path::{Path, PathBuf};
6
7use thiserror::Error;
8use uv_fs::{CWD, Simplified, ValidatedReader, is_virtualenv_base, normalize_path};
9
10use crate::{Pep723Error, Pep723Metadata};
11
12/// A failure encountered while discovering PEP 723 scripts.
13#[derive(Debug, Error)]
14pub enum ScriptDiscoveryError {
15    /// The workspace could not be traversed.
16    #[error("Failed to walk workspace while discovering PEP 723 scripts")]
17    Walk(#[source] ignore::Error),
18    /// A candidate script could not be read.
19    #[error("Failed to read candidate PEP 723 script: {}", path.simplified_display())]
20    Read {
21        path: PathBuf,
22        #[source]
23        source: io::Error,
24    },
25    /// A candidate script contains invalid PEP 723 metadata.
26    #[error("Failed to parse PEP 723 script: {}", path.simplified_display())]
27    Parse {
28        path: PathBuf,
29        #[source]
30        source: Pep723Error,
31    },
32}
33
34/// Find PEP 723 scripts under a workspace root.
35///
36/// Respects ignore files and excludes repository internals, virtual environments, and the uv cache
37/// from traversal. Script-specific errors are returned individually so callers can decide whether
38/// invalid candidates should fail discovery.
39pub fn find_scripts(
40    workspace_root: &Path,
41    cache_root: &Path,
42) -> impl Iterator<Item = Result<PathBuf, ScriptDiscoveryError>> {
43    // Avoid descending into the cache when it is inside the workspace. If the workspace itself is
44    // inside the cache, it is still the requested search root and must not be excluded.
45    let cache_root = if cache_root.is_absolute() {
46        Cow::Borrowed(cache_root)
47    } else {
48        Cow::Owned(CWD.join(cache_root))
49    };
50    let cache_root = normalize_path(cache_root);
51    // The filter closure requires owned data, but only capture the cache root when it is strictly
52    // inside the workspace. This avoids allocation and per-entry comparisons for external caches.
53    let cache_is_nested =
54        cache_root.as_ref() != workspace_root && cache_root.starts_with(workspace_root);
55    let cache_root = cache_is_nested.then(|| cache_root.into_owned());
56
57    let mut builder = ignore::WalkBuilder::new(workspace_root);
58    // Include scripts in hidden directories, such as `.github`.
59    ignore::WalkBuilder::hidden(&mut builder, false);
60    builder
61        // Respect `.gitignore` files in source archives and other workspaces without `.git`.
62        .require_git(false)
63        .filter_entry(move |entry| {
64            let path = entry.path();
65            if cache_root
66                .as_ref()
67                .is_some_and(|cache_root| path.starts_with(cache_root))
68            {
69                return false;
70            }
71
72            if !entry
73                .file_type()
74                .is_some_and(|file_type| file_type.is_dir())
75            {
76                return true;
77            }
78
79            // Hidden directories are included above, but Git internals cannot contain workspace
80            // scripts and can be very large.
81            if entry.file_name() == ".git" {
82                return false;
83            }
84
85            // Ignore rules have already been applied, but `.venv` is not guaranteed to be ignored.
86            if entry.file_name() == ".venv" {
87                return false;
88            }
89
90            // Detect virtual environments by their marker file so custom directory names are
91            // handled too.
92            !is_virtualenv_base(path)
93        });
94    builder.build().filter_map(|entry| {
95        let entry = match entry {
96            Ok(entry) => entry,
97            Err(source) => return Some(Err(ScriptDiscoveryError::Walk(source))),
98        };
99        if !entry
100            .file_type()
101            .is_some_and(|file_type| file_type.is_file())
102            || !is_python_script_path(entry.path())
103        {
104            return None;
105        }
106
107        let contents = match read_script_candidate(entry.path()) {
108            Ok(Some(contents)) => contents,
109            Ok(None) => return None,
110            Err(source) => {
111                return Some(Err(ScriptDiscoveryError::Read {
112                    path: entry.into_path(),
113                    source,
114                }));
115            }
116        };
117        match Pep723Metadata::parse(&contents) {
118            Ok(Some(_)) => Some(Ok(entry.into_path())),
119            Ok(None) => None,
120            Err(source) => Some(Err(ScriptDiscoveryError::Parse {
121                path: entry.into_path(),
122                source,
123            })),
124        }
125    })
126}
127
128/// Read a candidate script.
129///
130/// Extensionless candidates are only read past their prefix when they begin with a shebang.
131fn read_script_candidate(path: &Path) -> io::Result<Option<Vec<u8>>> {
132    if path.extension().is_some() {
133        return fs_err::read(path).map(Some);
134    }
135
136    ValidatedReader::new(fs_err::File::open(path)?)
137        .require_prefix("#!")
138        .require_utf8()
139        .read()
140}
141
142/// Return whether a path could contain a Python script.
143///
144/// PEP 723 does not require a specific filename, and uv can run explicitly requested scripts with
145/// arbitrary extensions or no extension. For discovery, restrict the search to Python extensions
146/// and extensionless files to avoid treating metadata examples embedded in documentation as scripts.
147/// Extensionless candidates are further restricted to shebang scripts and checked for binary
148/// content as they are read.
149fn is_python_script_path(path: &Path) -> bool {
150    path.extension().is_none_or(|extension| {
151        extension.eq_ignore_ascii_case("py") || extension.eq_ignore_ascii_case("pyw")
152    })
153}