use std::{ collections::{BTreeMap, BTreeSet}, fs, io, path::{Path, PathBuf}, }; use texrra_engine::native::ProjectSnapshot; pub(super) fn save( run: &Path, entry: &Path, declared: &BTreeSet, project: &ProjectSnapshot, edits: BTreeMap<&Path, &[u8]>, next_number: &mut u64, ) -> io::Result { let parent = run.parent().expect("the working directory has a parent"); let (staging, destination) = loop { *next_number += 1; let name = format!("texrra-sources-{}-{next_number}", std::process::id()); let destination = parent.join(&name); if destination.symlink_metadata().is_ok() { continue; } let staging = parent.join(format!(".{name}.pending")); match fs::create_dir(&staging) { Ok(()) => break (staging, destination), Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue, Err(error) => return Err(error), } }; let result = (|| { let sources = staging.join("sources"); fs::create_dir(&sources)?; let mut files = Vec::new(); for path in declared { let relative = path.strip_prefix(run).expect("declared sources stay in the working copy"); let name = relative.to_str().ok_or_else(|| { io::Error::new(io::ErrorKind::InvalidData, "A project file needs a UTF-8 name") })?; let saved = sources.join(relative); fs::create_dir_all(saved.parent().expect("a source file has a parent"))?; if let Some(data) = edits .get(path.as_path()) .copied() .or_else(|| project.file(path).map(|file| file.data.as_ref())) { fs::write(&saved, data)?; } if path != entry { files.push(name); } } let entry_name = entry.file_name().expect("the entry has a name").to_str().unwrap(); let manifest = fs::File::create(staging.join("project.json"))?; serde_json::to_writer_pretty(manifest, &serde_json::json!({ "entry": entry_name, "files": files, }))?; // Publish the metadata and every source at once. fs::rename(&staging, &destination) })(); if let Err(error) = result { let _ = fs::remove_dir_all(&staging); return Err(error); } Ok(destination) }