| 1 | |
|
| 2 | |
|
| 3 | |
|
| 4 | |
|
| 5 | | use anyhow::{bail, Context, Result}; |
| 6 | | use flow_core::Hash; |
| 7 | | use oxy_core::hash::ChangeHash; |
| 8 | | use oxy_core::objects::NodeKind; |
| 9 | | use oxy_core::repo::Repo; |
| 10 | | use oxy_core::state::FileContent; |
| 11 | | use std::path::Path; |
| 12 | |
|
| 13 | | pub type Files = Vec<(String, Hash)>; |
| 14 | |
|
| 15 | |
|
| 16 | 0× | pub fn export_state(repo: &Repo, heads: &[ChangeHash], dir: &Path) -> Result<Files> { |
| 17 | 0× | let snapshot = repo.load_state(heads).context("load the state")?.materialize(); |
| 18 | 0× | let mut files = Vec::new(); |
| 19 | 0× | for (path, f) in &snapshot.files { |
| 20 | 0× | if path.split('/').any(|p| p.is_empty() || p == "." || p == ".." || p == ".oxy") { |
| 21 | 0× | continue; |
| 22 | 0× | } |
| 23 | 0× | let target = dir.join(path); |
| 24 | 0× | match (&f.kind, &f.content) { |
| 25 | 0× | (NodeKind::Dir, _) | (_, FileContent::Dir) => std::fs::create_dir_all(&target)?, |
| 26 | 0× | (NodeKind::Subrepo, _) => {} |
| 27 | 0× | (kind, content) => { |
| 28 | 0× | let bytes = match content { |
| 29 | 0× | FileContent::Text { bytes, .. } => bytes.clone(), |
| 30 | 0× | FileContent::Opaque { blobs } => match blobs.first() { |
| 31 | 0× | Some(b) => repo.read_blob(b)?, |
| 32 | 0× | None => Vec::new(), |
| 33 | | }, |
| 34 | 0× | FileContent::Dir => unreachable!(), |
| 35 | | }; |
| 36 | 0× | if let Some(parent) = target.parent() { |
| 37 | 0× | std::fs::create_dir_all(parent)?; |
| 38 | 0× | } |
| 39 | 0× | if *kind == NodeKind::Symlink { |
| 40 | 0× | let to = String::from_utf8_lossy(&bytes).into_owned(); |
| 41 | 0× | std::os::unix::fs::symlink(&to, &target).with_context(|| format!("symlink {path}"))?; |
| 42 | | } else { |
| 43 | 0× | std::fs::write(&target, &bytes).with_context(|| format!("write {path}"))?; |
| 44 | 0× | if f.mode.exec { |
| 45 | | use std::os::unix::fs::PermissionsExt; |
| 46 | 0× | std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o755))?; |
| 47 | 0× | } |
| 48 | | } |
| 49 | 0× | files.push((path.clone(), *blake3::hash(&bytes).as_bytes())); |
| 50 | | } |
| 51 | | } |
| 52 | | } |
| 53 | 0× | Ok(files) |
| 54 | 0× | } |
| 55 | |
|
| 56 | |
|
| 57 | |
|
| 58 | 14× | pub fn copy_tree(src: &Path, dir: &Path) -> Result<Files> { |
| 59 | 14× | let mut files = Vec::new(); |
| 60 | 14× | let walk = ignore::WalkBuilder::new(src) |
| 61 | 14× | .hidden(false) |
| 62 | 14× | .git_ignore(true) |
| 63 | 14× | .require_git(false) |
| 64 | 14× | .add_custom_ignore_filename(".oxyignore") |
| 65 | 154× | .filter_entry(|e| e.file_name() != ".oxy" && e.file_name() != ".git") |
| 66 | 14× | .build(); |
| 67 | 168× | for entry in walk { |
| 68 | 168× | let entry = entry?; |
| 69 | 168× | let rel = entry.path().strip_prefix(src)?; |
| 70 | 168× | if rel.as_os_str().is_empty() { |
| 71 | 14× | continue; |
| 72 | 154× | } |
| 73 | 154× | let rel_s = rel.to_string_lossy().replace('\\', "/"); |
| 74 | 154× | let target = dir.join(rel); |
| 75 | 154× | let ft = entry.file_type().context("file type")?; |
| 76 | 154× | if ft.is_dir() { |
| 77 | 42× | std::fs::create_dir_all(&target)?; |
| 78 | 112× | } else if ft.is_symlink() { |
| 79 | 0× | let to = std::fs::read_link(entry.path())?; |
| 80 | 0× | std::os::unix::fs::symlink(&to, &target)?; |
| 81 | 0× | files.push((rel_s, *blake3::hash(to.to_string_lossy().as_bytes()).as_bytes())); |
| 82 | 112× | } else if ft.is_file() { |
| 83 | 112× | std::fs::copy(entry.path(), &target)?; |
| 84 | 112× | files.push((rel_s, *blake3::hash(&std::fs::read(entry.path())?).as_bytes())); |
| 85 | 0× | } |
| 86 | | } |
| 87 | 14× | Ok(files) |
| 88 | 14× | } |
| 89 | |
|
| 90 | |
|
| 91 | |
|
| 92 | 2× | pub fn image(dir: &Path, out: &Path) -> Result<()> { |
| 93 | 2× | let used: u64 = ignore::WalkBuilder::new(dir) |
| 94 | 2× | .hidden(false) |
| 95 | 2× | .ignore(false) |
| 96 | 2× | .git_ignore(false) |
| 97 | 2× | .build() |
| 98 | 2× | .flatten() |
| 99 | 13× | .filter_map(|e| e.metadata().ok()) |
| 100 | 13× | .map(|m| m.len().max(4096)) |
| 101 | 2× | .sum(); |
| 102 | 2× | let mib = used * 12 / 10 / (1 << 20) + 512; |
| 103 | 2× | let (uid, gid) = unsafe { (libc::getuid(), libc::getgid()) }; |
| 104 | 2× | let status = std::process::Command::new("mkfs.ext4") |
| 105 | 2× | .args(["-q", "-F", "-L", "workspace", "-E"]) |
| 106 | 2× | .arg(format!("root_owner={uid}:{gid}")) |
| 107 | 2× | .arg("-d") |
| 108 | 2× | .arg(dir) |
| 109 | 2× | .arg(out) |
| 110 | 2× | .arg(format!("{mib}M")) |
| 111 | 2× | .status() |
| 112 | 2× | .context("run mkfs.ext4 (e2fsprogs 1.43 or later)")?; |
| 113 | 2× | if !status.success() { |
| 114 | 0× | bail!("mkfs.ext4 failed for the workspace image"); |
| 115 | 2× | } |
| 116 | 2× | Ok(()) |
| 117 | 2× | } |
| 118 | |
|
| 119 | |
|
| 120 | |
|
| 121 | |
|
| 122 | |
|
| 123 | |
|
| 124 | |
|
| 125 | 5× | pub fn restore_times(dir: &Path, files: &Files, before: Option<&crate::cache::Sources>) -> (crate::cache::Sources, usize) { |
| 126 | 5× | let mut out = crate::cache::Sources::new(); |
| 127 | 5× | let mut restored = 0; |
| 128 | 24× | for (path, hash) in files { |
| 129 | 24× | let p = dir.join(path); |
| 130 | 24× | let Ok(md) = std::fs::symlink_metadata(&p) else { continue }; |
| 131 | 24× | if !md.is_file() { |
| 132 | 5× | continue; |
| 133 | 19× | } |
| 134 | 19× | let hex = hex::encode(hash); |
| 135 | 19× | let kept = before.and_then(|b| b.get(path)).filter(|(h, _)| *h == hex).map(|(_, t)| *t); |
| 136 | 19× | let t = match kept { |
| 137 | 9× | Some(t) => { |
| 138 | 9× | let at = std::time::UNIX_EPOCH + std::time::Duration::from_secs(t.max(0) as u64); |
| 139 | 9× | if std::fs::File::options().write(true).open(&p).and_then(|f| f.set_modified(at)).is_err() { |
| 140 | 0× | continue; |
| 141 | 9× | } |
| 142 | 9× | restored += 1; |
| 143 | 9× | t |
| 144 | | } |
| 145 | 10× | None => md.modified().ok().and_then(|m| m.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| d.as_secs() as i64).unwrap_or(0), |
| 146 | | }; |
| 147 | 19× | out.insert(path.clone(), (hex, t)); |
| 148 | | } |
| 149 | | |
| 150 | | |
| 151 | | |
| 152 | | |
| 153 | 5× | restore_dir_times(dir, Path::new(""), before, &mut out, &mut restored); |
| 154 | 5× | (out, restored) |
| 155 | 5× | } |
| 156 | |
|
| 157 | |
|
| 158 | 8× | fn dir_key(rel: &Path) -> String { |
| 159 | 8× | format!("{}/", rel.display()) |
| 160 | 8× | } |
| 161 | |
|
| 162 | 8× | fn restore_dir_times( |
| 163 | 8× | root: &Path, |
| 164 | 8× | rel: &Path, |
| 165 | 8× | before: Option<&crate::cache::Sources>, |
| 166 | 8× | out: &mut crate::cache::Sources, |
| 167 | 8× | restored: &mut usize, |
| 168 | 8× | ) { |
| 169 | 8× | let here = root.join(rel); |
| 170 | 8× | let Ok(entries) = std::fs::read_dir(&here) else { return }; |
| 171 | 8× | let mut names: Vec<(String, bool)> = Vec::new(); |
| 172 | 27× | for e in entries.flatten() { |
| 173 | 27× | let is_dir = e.file_type().is_ok_and(|t| t.is_dir()); |
| 174 | 27× | names.push((e.file_name().to_string_lossy().into_owned(), is_dir)); |
| 175 | | } |
| 176 | 8× | names.sort(); |
| 177 | 27× | for (name, is_dir) in &names { |
| 178 | 27× | if *is_dir { |
| 179 | 3× | restore_dir_times(root, &rel.join(name), before, out, restored); |
| 180 | 24× | } |
| 181 | | } |
| 182 | 8× | let mut h = blake3::Hasher::new(); |
| 183 | 27× | for (name, is_dir) in &names { |
| 184 | 27× | h.update(name.as_bytes()); |
| 185 | 27× | h.update(if *is_dir { b"/\n".as_slice() } else { b"\n".as_slice() }); |
| 186 | | } |
| 187 | 8× | let hex = h.finalize().to_hex().to_string(); |
| 188 | 8× | let key = dir_key(rel); |
| 189 | 8× | let kept = before.and_then(|b| b.get(&key)).filter(|(h, _)| *h == hex).map(|(_, t)| *t); |
| 190 | 8× | let t = match kept { |
| 191 | 3× | Some(t) => { |
| 192 | 3× | let at = std::time::UNIX_EPOCH + std::time::Duration::from_secs(t.max(0) as u64); |
| 193 | 3× | if std::fs::File::open(&here).and_then(|f| f.set_modified(at)).is_err() { |
| 194 | 0× | return; |
| 195 | 3× | } |
| 196 | 3× | *restored += 1; |
| 197 | 3× | t |
| 198 | | } |
| 199 | 5× | None => std::fs::metadata(&here) |
| 200 | 5× | .ok() |
| 201 | 5× | .and_then(|m| m.modified().ok()) |
| 202 | 5× | .and_then(|m| m.duration_since(std::time::UNIX_EPOCH).ok()) |
| 203 | 5× | .map(|d| d.as_secs() as i64) |
| 204 | 5× | .unwrap_or(0), |
| 205 | | }; |
| 206 | 8× | out.insert(key, (hex, t)); |
| 207 | 8× | } |
| 208 | |
|
| 209 | |
|
| 210 | |
|
| 211 | |
|
| 212 | 1× | pub fn empty_ext4(out: &Path, mib: u32, label: &str) -> Result<()> { |
| 213 | 1× | let (uid, gid) = unsafe { (libc::getuid(), libc::getgid()) }; |
| 214 | 1× | let status = std::process::Command::new("mkfs.ext4") |
| 215 | 1× | .args(["-q", "-F", "-L", label, "-E"]) |
| 216 | 1× | .arg(format!("root_owner={uid}:{gid}")) |
| 217 | 1× | .arg(out) |
| 218 | 1× | .arg(format!("{mib}M")) |
| 219 | 1× | .status() |
| 220 | 1× | .context("run mkfs.ext4 (e2fsprogs 1.43 or later)")?; |
| 221 | 1× | if !status.success() { |
| 222 | 0× | bail!("mkfs.ext4 failed for a scratch disk"); |
| 223 | 1× | } |
| 224 | 1× | Ok(()) |
| 225 | 1× | } |
| 226 | |
|
| 227 | |
|
| 228 | |
|
| 229 | 28× | pub fn remove_tree(dir: &Path) -> std::io::Result<()> { |
| 230 | 28× | match std::fs::remove_dir_all(dir) { |
| 231 | 17× | Ok(()) => Ok(()), |
| 232 | 11× | Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), |
| 233 | | Err(_) => { |
| 234 | 0× | open_up(dir); |
| 235 | 0× | std::fs::remove_dir_all(dir) |
| 236 | | } |
| 237 | | } |
| 238 | 28× | } |
| 239 | |
|
| 240 | 0× | fn open_up(dir: &Path) { |
| 241 | | use std::os::unix::fs::PermissionsExt; |
| 242 | 0× | let Ok(meta) = std::fs::symlink_metadata(dir) else { return }; |
| 243 | 0× | if !meta.is_dir() { |
| 244 | 0× | return; |
| 245 | 0× | } |
| 246 | 0× | let _ = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700)); |
| 247 | 0× | if let Ok(entries) = std::fs::read_dir(dir) { |
| 248 | 0× | for e in entries.flatten() { |
| 249 | 0× | open_up(&e.path()); |
| 250 | 0× | } |
| 251 | 0× | } |
| 252 | 0× | } |
| 253 | |
|
| 254 | | #[cfg(test)] |
| 255 | | mod tests { |
| 256 | | use super::*; |
| 257 | | use std::time::UNIX_EPOCH; |
| 258 | |
|
| 259 | 5× | fn secs(p: &Path) -> i64 { |
| 260 | 5× | std::fs::metadata(p).unwrap().modified().unwrap().duration_since(UNIX_EPOCH).unwrap().as_secs() as i64 |
| 261 | 5× | } |
| 262 | |
|
| 263 | | |
| 264 | | |
| 265 | | #[test] |
| 266 | 1× | fn unchanged_sources_get_their_cached_times_back() { |
| 267 | 1× | let dir = tempfile::tempdir().unwrap(); |
| 268 | 3× | for (name, text) in [("same.rs", "a"), ("changed.rs", "b2"), ("new.rs", "c")] { |
| 269 | 3× | std::fs::write(dir.path().join(name), text).unwrap(); |
| 270 | 3× | } |
| 271 | 1× | std::os::unix::fs::symlink("same.rs", dir.path().join("link.rs")).unwrap(); |
| 272 | 10× | let h = |t: &str| *blake3::hash(t.as_bytes()).as_bytes(); |
| 273 | 1× | let files: Files = |
| 274 | 1× | vec![("same.rs".into(), h("a")), ("changed.rs".into(), h("b2")), ("new.rs".into(), h("c")), ("link.rs".into(), h("same.rs"))]; |
| 275 | 1× | let now = secs(&dir.path().join("same.rs")); |
| 276 | 1× | let before: crate::cache::Sources = |
| 277 | 1× | [("same.rs".to_string(), (hex::encode(h("a")), 1_000_000)), ("changed.rs".to_string(), (hex::encode(h("b1")), 1_000_000))] |
| 278 | 1× | .into(); |
| 279 | |
|
| 280 | 1× | let (sources, restored) = restore_times(dir.path(), &files, Some(&before)); |
| 281 | 1× | assert_eq!(restored, 1); |
| 282 | 1× | assert_eq!(secs(&dir.path().join("same.rs")), 1_000_000, "unchanged: fresh to cargo"); |
| 283 | 1× | assert!(secs(&dir.path().join("changed.rs")) >= now, "changed: newer than the cached build"); |
| 284 | 1× | assert_eq!(sources["same.rs"], (hex::encode(h("a")), 1_000_000)); |
| 285 | 1× | assert_eq!(sources["changed.rs"].0, hex::encode(h("b2")), "kept with its new content"); |
| 286 | 1× | assert!(sources.contains_key("new.rs") && !sources.contains_key("link.rs"), "files only"); |
| 287 | |
|
| 288 | | |
| 289 | | |
| 290 | 1× | let (again, restored) = restore_times(dir.path(), &files, None); |
| 291 | 1× | assert_eq!((restored, again.len()), (0, 4)); |
| 292 | 1× | assert!(again.contains_key("/")); |
| 293 | |
|
| 294 | | |
| 295 | | |
| 296 | | |
| 297 | 1× | std::fs::create_dir(dir.path().join("migrations")).unwrap(); |
| 298 | 1× | std::fs::write(dir.path().join("migrations/0001.sql"), "x").unwrap(); |
| 299 | 1× | let mut files = files; |
| 300 | 1× | files.push(("migrations/0001.sql".into(), h("x"))); |
| 301 | 1× | let (mut kept, _) = restore_times(dir.path(), &files, None); |
| 302 | 1× | kept.get_mut("migrations/").unwrap().1 = 2_000_000; |
| 303 | 1× | kept.get_mut("migrations/0001.sql").unwrap().1 = 2_000_000; |
| 304 | 1× | let (_, restored) = restore_times(dir.path(), &files, Some(&kept)); |
| 305 | 1× | assert_eq!(secs(&dir.path().join("migrations")), 2_000_000, "unchanged listing: its old time"); |
| 306 | 1× | assert!(restored >= 2); |
| 307 | 1× | std::fs::write(dir.path().join("migrations/0002.sql"), "y").unwrap(); |
| 308 | 1× | files.push(("migrations/0002.sql".into(), h("y"))); |
| 309 | 1× | let (now_sources, _) = restore_times(dir.path(), &files, Some(&kept)); |
| 310 | 1× | assert!(secs(&dir.path().join("migrations")) > 2_000_000, "a new entry: it looks changed"); |
| 311 | 1× | assert_ne!(now_sources["migrations/"].0, kept["migrations/"].0); |
| 312 | 1× | } |
| 313 | | } |