1use 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#[derive(Debug, Error)]
14pub enum ScriptDiscoveryError {
15 #[error("Failed to walk workspace while discovering PEP 723 scripts")]
17 Walk(#[source] ignore::Error),
18 #[error("Failed to read candidate PEP 723 script: {}", path.simplified_display())]
20 Read {
21 path: PathBuf,
22 #[source]
23 source: io::Error,
24 },
25 #[error("Failed to parse PEP 723 script: {}", path.simplified_display())]
27 Parse {
28 path: PathBuf,
29 #[source]
30 source: Pep723Error,
31 },
32}
33
34pub fn find_scripts(
40 workspace_root: &Path,
41 cache_root: &Path,
42) -> impl Iterator<Item = Result<PathBuf, ScriptDiscoveryError>> {
43 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 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 ignore::WalkBuilder::hidden(&mut builder, false);
60 builder
61 .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 if entry.file_name() == ".git" {
82 return false;
83 }
84
85 if entry.file_name() == ".venv" {
87 return false;
88 }
89
90 !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
128fn 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
142fn 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}