use std::ffi::OsString;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use serde::{Deserialize, Serialize};
use super::uv_pin::{self, MAX_DOWNLOAD, PinnedFile, PinnedUv};
use crate::env::Env;
use crate::error::{CoreError, ErrorCode};
use crate::paths::SurjectionHome;
use crate::scan::external::TOOLS_DIR;
use crate::scan::external::download::{
Download, Hashing, UreqDownload, canceled, copy, finish_file, hash_file, io, make_executable,
};
pub const UV_DIR: &str = "uv";
const MARKER: &str = "installed.json";
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct UvFile {
pub path: String,
pub sha256: String,
pub size: u64,
}
impl From<&PinnedFile> for UvFile {
fn from(pinned: &PinnedFile) -> Self {
Self {
path: pinned.path.to_owned(),
sha256: pinned.sha256.to_owned(),
size: pinned.size,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct UvPin {
pub archive: String,
pub archive_sha256: String,
pub archive_size: u64,
pub uv: UvFile,
pub uvx: UvFile,
}
impl From<&PinnedUv> for UvPin {
fn from(pinned: &PinnedUv) -> Self {
Self {
archive: pinned.archive.to_owned(),
archive_sha256: pinned.archive_sha256.to_owned(),
archive_size: pinned.archive_size,
uv: UvFile::from(&pinned.uv),
uvx: UvFile::from(&pinned.uvx),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct Marker {
version: String,
#[serde(flatten)]
pin: UvPin,
}
pub fn root(home: &SurjectionHome) -> PathBuf {
home.path.join(TOOLS_DIR).join(UV_DIR)
}
pub(super) fn env_in(root: &Path) -> Vec<(String, OsString)> {
let dir = |name: &str| root.join(name).into_os_string();
vec![
("UV_CACHE_DIR".to_owned(), dir("cache")),
("UV_PYTHON_INSTALL_DIR".to_owned(), dir("python")),
("UV_PYTHON_BIN_DIR".to_owned(), dir("python-bin")),
("UV_PYTHON_INSTALL_BIN".to_owned(), "0".into()),
("UV_PYTHON_INSTALL_REGISTRY".to_owned(), "0".into()),
("UV_TOOL_DIR".to_owned(), dir("tool")),
("UV_TOOL_BIN_DIR".to_owned(), dir("tool-bin")),
("UV_CREDENTIALS_DIR".to_owned(), dir("credentials")),
("UV_NO_CONFIG".to_owned(), "1".into()),
("UV_MANAGED_PYTHON".to_owned(), "1".into()),
]
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PrivateUv {
root: PathBuf,
version: String,
pin: UvPin,
}
impl PrivateUv {
pub fn pinned(home: &SurjectionHome) -> Result<Self, CoreError> {
let pin = uv_pin::pinned().ok_or_else(|| {
CoreError::new(
ErrorCode::NotSupportedOnOs,
format!(
"Surjection cannot set up uv for {} on {}; install uv yourself \
(https://docs.astral.sh/uv/getting-started/installation/)",
std::env::consts::OS,
std::env::consts::ARCH
),
)
})?;
Ok(Self::new(home, uv_pin::VERSION, UvPin::from(pin)))
}
pub fn new(home: &SurjectionHome, version: &str, pin: UvPin) -> Self {
Self {
root: root(home),
version: version.to_owned(),
pin,
}
}
pub fn for_env(env: &Env, home: &SurjectionHome) -> Result<Self, CoreError> {
#[cfg(debug_assertions)]
if let Some(archive) = test_archive(env) {
let sidecar = test_pin_path(&archive);
let text = std::fs::read_to_string(&sidecar)
.map_err(|err| io("cannot read the test uv pin", &sidecar, &err))?;
let pin = serde_json::from_str(&text).map_err(|err| {
CoreError::new(
ErrorCode::IoError,
format!("the test uv pin does not parse: {err}"),
)
.with_path(&sidecar)
})?;
return Ok(Self::new(home, uv_pin::VERSION, pin));
}
#[cfg(not(debug_assertions))]
let _ = env;
Self::pinned(home)
}
pub fn version(&self) -> &str {
&self.version
}
pub fn pin(&self) -> &UvPin {
&self.pin
}
pub fn root(&self) -> PathBuf {
self.root.clone()
}
pub fn dir(&self) -> PathBuf {
self.root.join(&self.version)
}
pub fn uv(&self) -> PathBuf {
self.dir()
.join(format!("uv{}", std::env::consts::EXE_SUFFIX))
}
pub fn uvx(&self) -> PathBuf {
self.dir()
.join(format!("uvx{}", std::env::consts::EXE_SUFFIX))
}
fn marker(&self) -> Marker {
Marker {
version: self.version.clone(),
pin: self.pin.clone(),
}
}
pub fn installed(&self) -> bool {
let Ok(text) = std::fs::read_to_string(self.dir().join(MARKER)) else {
return false;
};
let Ok(marker) = serde_json::from_str::<Marker>(&text) else {
return false;
};
let sized = |path: PathBuf, size: u64| {
std::fs::metadata(path).is_ok_and(|meta| meta.is_file() && meta.len() == size)
};
marker == self.marker()
&& sized(self.uv(), self.pin.uv.size)
&& sized(self.uvx(), self.pin.uvx.size)
}
pub fn verify(&self) -> Result<(), String> {
for (path, pinned) in [(self.uv(), &self.pin.uv), (self.uvx(), &self.pin.uvx)] {
match hash_file(&path) {
Ok((size, digest)) if size == pinned.size && digest == pinned.sha256 => {}
Ok(_) => {
let _ = std::fs::remove_file(self.dir().join(MARKER));
return Err(format!(
"the uv Surjection set up is not the pinned build ({} has another \
SHA-256); set it up again (`surject scanner setup`, or Settings > \
Security)",
path.display()
));
}
Err(err) => {
return Err(format!(
"the uv Surjection set up cannot be read to check its SHA-256 ({}: {})",
path.display(),
err.kind()
));
}
}
}
Ok(())
}
pub fn install(
&self,
download: &dyn Download,
progress: &mut dyn FnMut(u64, u64),
cancel: Option<&AtomicBool>,
) -> Result<(), CoreError> {
if self.installed() && self.verify().is_ok() {
return Ok(());
}
for file in [&self.pin.uv, &self.pin.uvx] {
check_entry_path(&file.path)?;
}
if self.pin.uv.path == self.pin.uvx.path {
return Err(not_pinned("the pin names the same entry for uv and uvx"));
}
let dir = self.dir();
std::fs::create_dir_all(&dir).map_err(|err| io("cannot create folder", &dir, &err))?;
self.remove_partial_files();
let archive = crate::apply::temp_path(&dir.join("uv-archive"))?;
let uv = crate::apply::temp_path(&self.uv())?;
let uvx = crate::apply::temp_path(&self.uvx())?;
let mut result = self
.download_verified(download, &archive, progress, cancel)
.and_then(|()| self.extract(&archive, &uv, &uvx, cancel));
if cancel.is_some_and(|flag| flag.load(Ordering::Relaxed)) {
result = Err(canceled());
}
let _ = std::fs::remove_file(&archive);
let placed = result.and_then(|()| {
make_executable(&uv)?;
make_executable(&uvx)?;
let _ = std::fs::remove_file(dir.join(MARKER));
for (temp, target) in [(&uv, self.uv()), (&uvx, self.uvx())] {
std::fs::rename(temp, &target)
.map_err(|err| io("cannot move uv into place", &target, &err))?;
}
Ok(())
});
if let Err(err) = placed {
let _ = std::fs::remove_file(&uv);
let _ = std::fs::remove_file(&uvx);
let _ = std::fs::remove_dir(&dir);
let _ = std::fs::remove_dir(&self.root);
return Err(err);
}
let marker = serde_json::to_vec_pretty(&self.marker()).map_err(|err| {
CoreError::new(ErrorCode::IoError, format!("cannot write {MARKER}: {err}"))
})?;
crate::apply::write_atomic(&crate::fs::RealFs, &dir.join(MARKER), &marker)?;
self.remove_other_versions();
Ok(())
}
fn download_verified(
&self,
download: &dyn Download,
temp: &Path,
progress: &mut dyn FnMut(u64, u64),
cancel: Option<&AtomicBool>,
) -> Result<(), CoreError> {
let file =
std::fs::File::create(temp).map_err(|err| io("cannot create file", temp, &err))?;
let mut sink = Hashing::new(std::io::BufWriter::new(file));
let url = uv_pin::download_url(&self.version, &self.pin.archive);
let size = self.pin.archive_size;
download.fetch(
&url,
&mut sink,
MAX_DOWNLOAD.max(size),
&mut |received, total| {
progress(received, if total == 0 { size } else { total });
},
cancel,
)?;
let (written, digest) = finish_file(sink, temp)?;
if written != size || digest != self.pin.archive_sha256 {
return Err(CoreError::new(
ErrorCode::ScannerVerificationFailed,
format!(
"the download of uv {} ({}) is not the pinned build (expected {size} bytes \
with SHA-256 {}, got {written} bytes with SHA-256 {digest}); nothing was \
installed",
self.version, self.pin.archive, self.pin.archive_sha256
),
));
}
Ok(())
}
fn extract(
&self,
archive: &Path,
uv: &Path,
uvx: &Path,
cancel: Option<&AtomicBool>,
) -> Result<(), CoreError> {
let wanted = [(&self.pin.uv, uv), (&self.pin.uvx, uvx)];
let mut found = [false; 2];
let file =
std::fs::File::open(archive).map_err(|err| io("cannot read file", archive, &err))?;
let broken = |why: String| {
not_pinned(&format!(
"the uv archive {} cannot be read: {why}",
self.pin.archive
))
};
if self.pin.archive.ends_with(".zip") {
let mut zip = zip::ZipArchive::new(std::io::BufReader::new(file))
.map_err(|err| broken(err.to_string()))?;
for index in 0..zip.len() {
let mut entry = zip.by_index(index).map_err(|err| broken(err.to_string()))?;
let name = entry
.name()
.map_err(|err| broken(err.to_string()))?
.into_owned();
let Some(at) = wanted.iter().position(|(pin, _)| pin.path == name) else {
continue;
};
let (pin, target) = wanted[at];
check_found(&mut found[at], pin, entry.is_file())?;
extract_entry(&mut entry, pin, target, cancel)?;
}
} else {
let gz = flate2::read::GzDecoder::new(std::io::BufReader::new(file));
let mut tar = tar::Archive::new(gz);
let entries = tar.entries().map_err(|err| broken(err.to_string()))?;
for entry in entries {
let mut entry = entry.map_err(|err| broken(err.to_string()))?;
let name = entry.path_bytes().into_owned();
let Some(at) = wanted
.iter()
.position(|(pin, _)| pin.path.as_bytes() == name.as_slice())
else {
continue;
};
let (pin, target) = wanted[at];
let regular = matches!(
entry.header().entry_type(),
tar::EntryType::Regular | tar::EntryType::Continuous
);
check_found(&mut found[at], pin, regular)?;
extract_entry(&mut entry, pin, target, cancel)?;
}
}
for ((pin, _), found) in wanted.iter().zip(found) {
if !found {
return Err(not_pinned(&format!(
"the uv archive {} has no {}; nothing was installed",
self.pin.archive, pin.path
)));
}
}
Ok(())
}
pub fn remove(&self) -> Result<bool, CoreError> {
remove_root(&self.root)
}
pub fn env(&self) -> Vec<(String, OsString)> {
env_in(&self.root)
}
fn remove_partial_files(&self) {
let Ok(entries) = std::fs::read_dir(self.dir()) else {
return;
};
for entry in entries.flatten() {
let name = entry.file_name().to_string_lossy().into_owned();
if name.starts_with('.') && name.contains(".surjection-") && name.ends_with(".tmp") {
let _ = std::fs::remove_file(entry.path());
}
}
}
fn remove_other_versions(&self) {
let Ok(entries) = std::fs::read_dir(&self.root) else {
return;
};
for entry in entries.flatten() {
let name = entry.file_name().to_string_lossy().into_owned();
if name != self.version
&& name.starts_with(|c: char| c.is_ascii_digit())
&& entry.file_type().is_ok_and(|kind| kind.is_dir())
{
let _ = std::fs::remove_dir_all(entry.path());
}
}
}
}
pub(super) fn remove_root(root: &Path) -> Result<bool, CoreError> {
if !root.exists() {
return Ok(false);
}
std::fs::remove_dir_all(root).map_err(|err| io("cannot remove folder", root, &err))?;
Ok(true)
}
fn not_pinned(why: &str) -> CoreError {
CoreError::new(ErrorCode::ScannerVerificationFailed, why.to_owned())
}
pub(super) fn check_entry_path(path: &str) -> Result<(), CoreError> {
let fine = !path.is_empty()
&& !path.starts_with('/')
&& !path.contains('\\')
&& !path.contains(':')
&& path
.split('/')
.all(|part| !part.is_empty() && part != "." && part != "..");
if fine {
Ok(())
} else {
Err(not_pinned(&format!(
"the uv pin names an unsafe archive entry ({path})"
)))
}
}
fn check_found(found: &mut bool, pin: &UvFile, regular: bool) -> Result<(), CoreError> {
if *found {
return Err(not_pinned(&format!(
"the uv archive holds {} twice; nothing was installed",
pin.path
)));
}
if !regular {
return Err(not_pinned(&format!(
"{} in the uv archive is not a regular file (a link or a folder); nothing was \
installed",
pin.path
)));
}
*found = true;
Ok(())
}
fn extract_entry(
reader: &mut dyn Read,
pin: &UvFile,
target: &Path,
cancel: Option<&AtomicBool>,
) -> Result<(), CoreError> {
let file =
std::fs::File::create(target).map_err(|err| io("cannot create file", target, &err))?;
let mut sink = Hashing::new(std::io::BufWriter::new(file));
let max = pin.size;
copy(reader, &mut sink, max, pin.size, &mut |_, _| {}, cancel).map_err(|err| {
if cancel.is_some_and(|flag| flag.load(Ordering::Relaxed)) {
canceled()
} else if err.kind() == std::io::ErrorKind::FileTooLarge {
not_pinned(&format!(
"{} in the uv archive is larger than the pinned build; nothing was installed",
pin.path
))
} else {
not_pinned(&format!(
"{} in the uv archive cannot be read: {err}",
pin.path
))
}
})?;
let (written, digest) = finish_file(sink, target)?;
if written != pin.size || digest != pin.sha256 {
return Err(not_pinned(&format!(
"{} in the uv archive is not the pinned build (expected {} bytes with SHA-256 {}, \
got {written} bytes with SHA-256 {digest}); nothing was installed",
pin.path, pin.size, pin.sha256
)));
}
Ok(())
}
#[cfg(debug_assertions)]
fn test_archive(env: &Env) -> Option<PathBuf> {
env.var(crate::brand::TEST_UV_ARCHIVE_ENV_VAR)
.map(PathBuf::from)
.filter(|path| path.is_absolute())
}
pub fn test_pin_path(archive: &Path) -> PathBuf {
let mut name = archive.file_name().unwrap_or_default().to_owned();
name.push(".pin.json");
archive.with_file_name(name)
}
pub fn uv_download(env: &Env) -> Box<dyn Download> {
#[cfg(debug_assertions)]
if let Some(archive) = test_archive(env) {
return Box::new(TestArchive(archive));
}
Box::new(UreqDownload::new(env))
}
#[cfg(debug_assertions)]
#[derive(Debug)]
struct TestArchive(PathBuf);
#[cfg(debug_assertions)]
impl Download for TestArchive {
fn fetch(
&self,
url: &str,
out: &mut dyn std::io::Write,
max: u64,
progress: &mut dyn FnMut(u64, u64),
cancel: Option<&AtomicBool>,
) -> Result<u64, CoreError> {
let failed = |why: String| CoreError::new(ErrorCode::ScannerDownloadFailed, why);
let name = self.0.file_name().unwrap_or_default().to_string_lossy();
if !url.ends_with(&format!("/{name}")) {
return Err(failed(format!("the test archive is not {url}")));
}
let mut file = std::fs::File::open(&self.0)
.map_err(|err| failed(format!("cannot read the test archive: {err}")))?;
let total = file.metadata().map(|meta| meta.len()).unwrap_or(0);
copy(&mut file, out, max, total, progress, cancel).map_err(|err| {
if cancel.is_some_and(|flag| flag.load(Ordering::Relaxed)) {
canceled()
} else {
failed(err.to_string())
}
})
}
}