1use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
13use std::path::{Component, Path, PathBuf};
14
15use gitpoulpi_core::domain::{FileHash, Oid, PathHash, RepoRef, Snapshot};
16use gitpoulpi_core::{Error, Result};
17
18use crate::process::{run, run_bytes_with_stdin, run_with_env_and_stdin, run_with_stdin};
19
20pub const MODE_FILE: u32 = 0o100644;
21#[cfg_attr(not(unix), allow(dead_code))]
22pub const MODE_EXEC: u32 = 0o100755;
23pub const MODE_LINK: u32 = 0o120000;
24const ZERO_OID: &str = "0000000000000000000000000000000000000000";
25
26const MAX_ARG_BYTES: usize = 20_000;
28
29fn oid_of(text: &str) -> Result<Oid> {
30 Oid::from_hex(text.trim())
31 .ok_or_else(|| Error::Backend(format!("git printed `{}`, not an object id", text.trim())))
32}
33
34pub fn index_tree(repo: &RepoRef) -> Result<Oid> {
38 oid_of(&run(&repo.root, &["write-tree"])?)
39}
40
41pub fn index_restore(repo: &RepoRef, tree: Oid) -> Result<()> {
44 run(&repo.root, &["read-tree", &tree.to_hex()])?;
45 Ok(())
46}
47
48pub(crate) fn normalize(path: &str) -> Result<String> {
53 let norm = path.replace('\\', "/");
54 let norm = norm.trim_start_matches("./").trim_end_matches('/');
55 if norm.is_empty() {
56 return Err(Error::Backend("an empty path".into()));
57 }
58 for part in Path::new(norm).components() {
59 match part {
60 Component::Normal(name) if name == ".git" => {
61 return Err(Error::Backend(format!("{norm} is inside .git")))
62 }
63 Component::Normal(_) => {}
64 _ => {
65 return Err(Error::Backend(format!(
66 "{norm} is not a path inside the repository"
67 )))
68 }
69 }
70 }
71 Ok(norm.to_string())
72}
73
74pub fn normalize_all(paths: &[String]) -> Result<Vec<String>> {
75 let mut out = BTreeSet::new();
76 for p in paths {
77 out.insert(normalize(p)?);
78 }
79 Ok(out.into_iter().collect())
80}
81
82fn batches(specs: &[String]) -> Vec<&[String]> {
83 let mut out = Vec::new();
84 let (mut start, mut size) = (0, 0);
85 for (i, s) in specs.iter().enumerate() {
86 if size + s.len() + 1 > MAX_ARG_BYTES && i > start {
87 out.push(&specs[start..i]);
88 start = i;
89 size = 0;
90 }
91 size += s.len() + 1;
92 }
93 if start < specs.len() {
94 out.push(&specs[start..]);
95 }
96 out
97}
98
99fn index_entries(repo: &RepoRef, paths: &[String]) -> Result<BTreeMap<String, FileHash>> {
102 index_entries_and_unmerged(repo, paths).map(|(entries, _)| entries)
103}
104
105fn index_entries_and_unmerged(
108 repo: &RepoRef,
109 paths: &[String],
110) -> Result<(BTreeMap<String, FileHash>, BTreeSet<String>)> {
111 let mut unmerged = BTreeSet::new();
112 let specs: Vec<String> = paths.iter().map(|p| format!(":(literal){p}")).collect();
113 let mut out = BTreeMap::new();
114 for batch in batches(&specs) {
115 let mut args = vec!["ls-files", "-s", "-z", "--"];
116 args.extend(batch.iter().map(String::as_str));
117 let raw = run(&repo.root, &args)?;
118 for record in raw.split('\0').filter(|r| !r.is_empty()) {
119 let Some((meta, path)) = record.split_once('\t') else {
121 continue;
122 };
123 let mut fields = meta.split(' ');
124 let (Some(mode), Some(oid), Some(stage)) =
125 (fields.next(), fields.next(), fields.next())
126 else {
127 continue;
128 };
129 if stage != "0" {
130 unmerged.insert(path.to_string());
131 continue;
132 }
133 let (Ok(mode), Some(oid)) = (u32::from_str_radix(mode, 8), Oid::from_hex(oid)) else {
134 continue;
135 };
136 out.insert(path.to_string(), FileHash { mode, oid });
137 }
138 }
139 Ok((out, unmerged))
140}
141
142pub struct OnDisk {
144 pub mode: u32,
145}
146
147pub fn walk(repo: &RepoRef, paths: &[String]) -> BTreeMap<String, OnDisk> {
150 let mut out = BTreeMap::new();
151 for path in paths {
152 walk_one(&repo.root, path, &mut out);
153 }
154 out
155}
156
157fn walk_one(root: &Path, rel: &str, out: &mut BTreeMap<String, OnDisk>) {
158 let full = root.join(rel);
159 let Ok(meta) = std::fs::symlink_metadata(&full) else {
160 return;
161 };
162 if meta.is_dir() {
163 let Ok(entries) = std::fs::read_dir(&full) else {
164 return;
165 };
166 for entry in entries.flatten() {
167 let name = entry.file_name();
168 if name == ".git" {
169 continue;
170 }
171 walk_one(root, &format!("{rel}/{}", name.to_string_lossy()), out);
172 }
173 } else if meta.file_type().is_symlink() {
174 out.insert(rel.to_string(), OnDisk { mode: MODE_LINK });
175 } else if meta.is_file() {
176 out.insert(
177 rel.to_string(),
178 OnDisk {
179 mode: file_mode(&meta),
180 },
181 );
182 }
183}
184
185#[cfg(unix)]
186fn file_mode(meta: &std::fs::Metadata) -> u32 {
187 use std::os::unix::fs::PermissionsExt;
188 if meta.permissions().mode() & 0o111 != 0 {
189 MODE_EXEC
190 } else {
191 MODE_FILE
192 }
193}
194
195#[cfg(not(unix))]
196fn file_mode(_meta: &std::fs::Metadata) -> u32 {
197 MODE_FILE
198}
199
200fn hash_worktree(
204 repo: &RepoRef,
205 files: &BTreeMap<String, OnDisk>,
206 write: bool,
207) -> Result<BTreeMap<String, Oid>> {
208 let mut out = BTreeMap::new();
209 let regular: Vec<&String> = files
210 .iter()
211 .filter(|(_, f)| f.mode != MODE_LINK)
212 .map(|(p, _)| p)
213 .collect();
214 if let Some(bad) = regular.iter().find(|p| p.contains('\n')) {
215 return Err(Error::Backend(format!(
216 "cannot snapshot {bad:?}: its name contains a newline"
217 )));
218 }
219 for chunk in regular.chunks(500) {
220 let mut args = vec!["hash-object", "--no-filters", "--stdin-paths"];
221 if write {
222 args.push("-w");
223 }
224 let input = chunk
225 .iter()
226 .map(|p| p.as_str())
227 .collect::<Vec<_>>()
228 .join("\n");
229 let printed = run_with_stdin(&repo.root, &args, &format!("{input}\n"))?;
230 let ids: Vec<&str> = printed.lines().collect();
231 if ids.len() != chunk.len() {
232 return Err(Error::Backend(
233 "git hash-object answered for a different number of files".into(),
234 ));
235 }
236 for (path, id) in chunk.iter().zip(ids) {
237 out.insert((*path).clone(), oid_of(id)?);
238 }
239 }
240 for (path, file) in files {
241 if file.mode != MODE_LINK {
242 continue;
243 }
244 let target = std::fs::read_link(repo.root.join(path))
245 .map_err(|e| Error::Backend(format!("cannot read the link {path}: {e}")))?;
246 let bytes = target.to_string_lossy().replace('\\', "/").into_bytes();
247 let mut args = vec!["hash-object", "-t", "blob", "--stdin"];
248 if write {
249 args.push("-w");
250 }
251 let printed = run_bytes_with_stdin(&repo.root, &args, &bytes)?;
252 out.insert(path.clone(), oid_of(&String::from_utf8_lossy(&printed))?);
253 }
254 Ok(out)
255}
256
257fn gather(repo: &RepoRef, paths: &[String], write: bool) -> Result<Vec<PathHash>> {
260 let paths = normalize_all(paths)?;
261 if paths.is_empty() {
262 return Ok(Vec::new());
263 }
264 let index = index_entries(repo, &paths)?;
265 let disk = walk(repo, &paths);
266 let hashes = hash_worktree(repo, &disk, write)?;
267 let all: BTreeSet<&String> = index.keys().chain(disk.keys()).collect();
268 Ok(all
269 .into_iter()
270 .map(|path| PathHash {
271 path: path.clone(),
272 worktree: disk.get(path).and_then(|f| {
273 hashes.get(path).map(|oid| FileHash {
274 mode: f.mode,
275 oid: *oid,
276 })
277 }),
278 index: index.get(path).copied(),
279 })
280 .collect())
281}
282
283pub fn path_hashes(repo: &RepoRef, paths: &[String]) -> Result<Vec<PathHash>> {
284 gather(repo, paths, false)
285}
286
287static TEMP_COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
290
291fn temp_index() -> PathBuf {
292 let n = TEMP_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
293 std::env::temp_dir().join(format!(
294 "gitpoulpi-snapshot-{}-{n}.index",
295 std::process::id()
296 ))
297}
298
299pub fn snapshot_create(repo: &RepoRef, paths: &[String]) -> Result<Snapshot> {
300 let hashes = gather(repo, paths, true)?;
301 let mut input = String::new();
302 for h in &hashes {
303 for (side, file) in [("index", &h.index), ("worktree", &h.worktree)] {
304 if let Some(file) = file {
305 input.push_str(&format!(
306 "{:o} {}\t{side}/{}\0",
307 file.mode, file.oid, h.path
308 ));
309 }
310 }
311 }
312 let tmp = temp_index();
313 let tmp_str = tmp.to_string_lossy().to_string();
314 let env = [("GIT_INDEX_FILE", tmp_str.as_str())];
315 let built = (|| {
316 if !input.is_empty() {
317 run_with_env_and_stdin(
318 &repo.root,
319 &["update-index", "-z", "--index-info"],
320 &env,
321 &input,
322 )?;
323 }
324 run_with_env_and_stdin(&repo.root, &["write-tree"], &env, "")
325 })();
326 let _ = std::fs::remove_file(&tmp);
327 Ok(Snapshot {
328 tree: oid_of(&built?)?,
329 hashes,
330 })
331}
332
333fn read_snapshot(
335 repo: &RepoRef,
336 tree: Oid,
337) -> Result<(BTreeMap<String, FileHash>, BTreeMap<String, FileHash>)> {
338 let raw = run(&repo.root, &["ls-tree", "-r", "-z", &tree.to_hex()])?;
339 let (mut index, mut worktree) = (BTreeMap::new(), BTreeMap::new());
340 for record in raw.split('\0').filter(|r| !r.is_empty()) {
341 let Some((meta, path)) = record.split_once('\t') else {
343 continue;
344 };
345 let mut fields = meta.split(' ');
346 let (Some(mode), Some(_kind), Some(oid)) = (fields.next(), fields.next(), fields.next())
347 else {
348 continue;
349 };
350 let (Ok(mode), Some(oid)) = (u32::from_str_radix(mode, 8), Oid::from_hex(oid)) else {
351 continue;
352 };
353 let file = FileHash { mode, oid };
354 if let Some(p) = path.strip_prefix("index/") {
355 index.insert(p.to_string(), file);
356 } else if let Some(p) = path.strip_prefix("worktree/") {
357 worktree.insert(p.to_string(), file);
358 }
359 }
360 Ok((index, worktree))
361}
362
363fn read_blobs(repo: &RepoRef, oids: &HashSet<Oid>) -> Result<HashMap<Oid, Vec<u8>>> {
365 let mut out = HashMap::new();
366 if oids.is_empty() {
367 return Ok(out);
368 }
369 let input: String = oids.iter().map(|o| format!("{o}\n")).collect();
370 let raw = run_bytes_with_stdin(&repo.root, &["cat-file", "--batch"], input.as_bytes())?;
371 let mut at = 0usize;
372 for _ in 0..oids.len() {
373 let Some(nl) = raw[at..].iter().position(|b| *b == b'\n') else {
374 return Err(Error::Backend("truncated git cat-file output".into()));
375 };
376 let header = String::from_utf8_lossy(&raw[at..at + nl]).to_string();
377 at += nl + 1;
378 let mut parts = header.split(' ');
379 let (Some(id), Some(kind), Some(size)) = (parts.next(), parts.next(), parts.next()) else {
380 return Err(Error::Backend(format!(
381 "a snapshot object is missing ({header})"
382 )));
383 };
384 if kind != "blob" {
385 return Err(Error::Backend(format!(
386 "a snapshot object is missing ({header})"
387 )));
388 }
389 let size: usize = size
390 .parse()
391 .map_err(|_| Error::Backend("bad git cat-file size".into()))?;
392 let id = oid_of(id)?;
393 if raw.len() < at + size + 1 {
394 return Err(Error::Backend("truncated git cat-file output".into()));
395 }
396 out.insert(id, raw[at..at + size].to_vec());
397 at += size + 1;
398 }
399 Ok(out)
400}
401
402#[cfg(unix)]
403pub fn write_file(full: &Path, file: &FileHash, bytes: &[u8]) -> std::io::Result<()> {
404 use std::os::unix::fs::PermissionsExt;
405 remove_any(full)?;
406 if file.mode == MODE_LINK {
407 let target = String::from_utf8_lossy(bytes).to_string();
408 return std::os::unix::fs::symlink(target, full);
409 }
410 std::fs::write(full, bytes)?;
411 let mode = if file.mode == MODE_EXEC { 0o755 } else { 0o644 };
412 std::fs::set_permissions(full, std::fs::Permissions::from_mode(mode))
413}
414
415#[cfg(not(unix))]
416pub fn write_file(full: &Path, _file: &FileHash, bytes: &[u8]) -> std::io::Result<()> {
417 remove_any(full)?;
418 std::fs::write(full, bytes)
419}
420
421pub fn remove_any(full: &Path) -> std::io::Result<()> {
423 match std::fs::symlink_metadata(full) {
424 Ok(meta) if meta.is_dir() => std::fs::remove_dir_all(full),
425 Ok(_) => std::fs::remove_file(full),
426 Err(_) => Ok(()),
427 }
428}
429
430pub fn snapshot_restore(repo: &RepoRef, snapshot: Oid, paths: &[String]) -> Result<()> {
431 let paths = normalize_all(paths)?;
432 if paths.is_empty() {
433 return Ok(());
434 }
435 let (want_index, want_worktree) = read_snapshot(repo, snapshot)?;
436 let blobs = read_blobs(
438 repo,
439 &want_worktree
440 .values()
441 .map(|f| f.oid)
442 .collect::<HashSet<_>>(),
443 )?;
444
445 let current = walk(repo, &paths);
447 let mut removed: Vec<String> = Vec::new();
448 for path in current.keys() {
449 if !want_worktree.contains_key(path) {
450 remove_any(&repo.root.join(path))
451 .map_err(|e| Error::Backend(format!("cannot remove {path}: {e}")))?;
452 removed.push(path.clone());
453 }
454 }
455 for (path, file) in &want_worktree {
456 let full = repo.root.join(path);
457 if let Some(parent) = full.parent() {
458 let mut up = parent.to_path_buf();
460 while up != repo.root && !up.exists() {
461 match up.parent() {
462 Some(p) => up = p.to_path_buf(),
463 None => break,
464 }
465 }
466 if up.is_file() {
467 let _ = std::fs::remove_file(&up);
468 }
469 std::fs::create_dir_all(parent)
470 .map_err(|e| Error::Backend(format!("cannot create {}: {e}", parent.display())))?;
471 }
472 let bytes = blobs.get(&file.oid).expect("every wanted blob was read");
473 write_file(&full, file, bytes)
474 .map_err(|e| Error::Backend(format!("cannot restore {path}: {e}")))?;
475 }
476
477 let (have, unmerged) = index_entries_and_unmerged(repo, &paths)?;
481 let mut input = String::new();
482 for path in have.keys() {
483 if !want_index.contains_key(path) {
484 input.push_str(&format!("0 {ZERO_OID}\t{path}\0"));
485 }
486 }
487 for path in &unmerged {
488 if !have.contains_key(path) {
489 input.push_str(&format!("0 {ZERO_OID}\t{path}\0"));
490 }
491 }
492 for (path, file) in &want_index {
493 input.push_str(&format!("{:o} {}\t{path}\0", file.mode, file.oid));
494 }
495 if !input.is_empty() {
496 run_with_stdin(&repo.root, &["update-index", "-z", "--index-info"], &input)?;
497 }
498 crate::prune::prune_empty_parents(&repo.root, &removed, &|dir| {
501 let spec = format!(":(literal){dir}");
502 crate::process::run_z_fields(&repo.root, &["ls-files", "-z", "--", &spec])
503 .map_or(true, |f| !f.is_empty())
504 });
505 Ok(())
506}
507
508pub fn delete_files(repo: &RepoRef, paths: &[String]) -> Result<()> {
511 let paths = normalize_all(paths)?;
512 for path in &paths {
513 let full = repo.root.join(path);
514 remove_any(&full).map_err(|e| Error::Backend(format!("cannot delete {path}: {e}")))?;
515 }
516 Ok(())
517}
518
519pub fn patch_files(repo: &RepoRef, patch: &Path) -> Result<Vec<String>> {
522 if !patch.is_file() {
523 return Err(Error::Backend(format!("{} is not a file", patch.display())));
524 }
525 let arg = patch.to_string_lossy().to_string();
526 let raw = run(&repo.root, &["apply", "--numstat", "-z", &arg])?;
527 let mut tokens = raw.split('\0').filter(|t| !t.is_empty());
528 let mut out = BTreeSet::new();
529 while let Some(token) = tokens.next() {
530 let mut parts = token.splitn(3, '\t');
531 let (_, _, path) = (parts.next(), parts.next(), parts.next());
532 match path {
533 Some("") => {
534 for _ in 0..2 {
535 if let Some(name) = tokens.next() {
536 out.insert(name.to_string());
537 }
538 }
539 }
540 Some(path) => {
541 out.insert(path.to_string());
542 }
543 None => {}
544 }
545 }
546 if let Ok(bytes) = std::fs::read(patch) {
548 for line in String::from_utf8_lossy(&bytes).lines() {
549 if let Some(name) = line.strip_prefix("rename from ") {
550 out.insert(name.to_string());
551 }
552 }
553 }
554 Ok(out.into_iter().collect())
555}