use std::borrow::Cow;
use std::io;
use std::path::{Path, PathBuf};
use thiserror::Error;
use uv_fs::{CWD, Simplified, ValidatedReader, is_virtualenv_base, normalize_path};
use crate::{Pep723Error, Pep723Metadata};
#[derive(Debug, Error)]
pub enum ScriptDiscoveryError {
#[error("Failed to walk workspace while discovering PEP 723 scripts")]
Walk(#[source] ignore::Error),
#[error("Failed to read candidate PEP 723 script: {}", path.simplified_display())]
Read {
path: PathBuf,
#[source]
source: io::Error,
},
#[error("Failed to parse PEP 723 script: {}", path.simplified_display())]
Parse {
path: PathBuf,
#[source]
source: Pep723Error,
},
}
pub fn find_scripts(
workspace_root: &Path,
cache_root: &Path,
) -> impl Iterator<Item = Result<PathBuf, ScriptDiscoveryError>> {
let cache_root = if cache_root.is_absolute() {
Cow::Borrowed(cache_root)
} else {
Cow::Owned(CWD.join(cache_root))
};
let cache_root = normalize_path(cache_root);
let cache_is_nested =
cache_root.as_ref() != workspace_root && cache_root.starts_with(workspace_root);
let cache_root = cache_is_nested.then(|| cache_root.into_owned());
let mut builder = ignore::WalkBuilder::new(workspace_root);
ignore::WalkBuilder::hidden(&mut builder, false);
builder
.require_git(false)
.filter_entry(move |entry| {
let path = entry.path();
if cache_root
.as_ref()
.is_some_and(|cache_root| path.starts_with(cache_root))
{
return false;
}
if !entry
.file_type()
.is_some_and(|file_type| file_type.is_dir())
{
return true;
}
if entry.file_name() == ".git" {
return false;
}
if entry.file_name() == ".venv" {
return false;
}
!is_virtualenv_base(path)
});
builder.build().filter_map(|entry| {
let entry = match entry {
Ok(entry) => entry,
Err(source) => return Some(Err(ScriptDiscoveryError::Walk(source))),
};
if !entry
.file_type()
.is_some_and(|file_type| file_type.is_file())
|| !is_python_script_path(entry.path())
{
return None;
}
let contents = match read_script_candidate(entry.path()) {
Ok(Some(contents)) => contents,
Ok(None) => return None,
Err(source) => {
return Some(Err(ScriptDiscoveryError::Read {
path: entry.into_path(),
source,
}));
}
};
match Pep723Metadata::parse(&contents) {
Ok(Some(_)) => Some(Ok(entry.into_path())),
Ok(None) => None,
Err(source) => Some(Err(ScriptDiscoveryError::Parse {
path: entry.into_path(),
source,
})),
}
})
}
fn read_script_candidate(path: &Path) -> io::Result<Option<Vec<u8>>> {
if path.extension().is_some() {
return fs_err::read(path).map(Some);
}
ValidatedReader::new(fs_err::File::open(path)?)
.require_prefix("#!")
.require_utf8()
.read()
}
fn is_python_script_path(path: &Path) -> bool {
path.extension().is_none_or(|extension| {
extension.eq_ignore_ascii_case("py") || extension.eq_ignore_ascii_case("pyw")
})
}