12345678module snapshot910import os11import src.storage1213pub struct RestoreReport {14pub:15 written int16 removed int17}18192021222324pub fn restore_files(store &storage.Store, root string, ig Ignore, target []FileEntry, remove []string) !RestoreReport {25 mut wanted := map[string]bool{}26 for entry in target {27 wanted[entry.path] = true28 }29 mut removed := 030 for path in remove {31 full := os.join_path(root, path)32 if !os.is_file(full) || ig.matches(path, false) || path in wanted {33 continue34 }35 os.rm(full)!36 removed++37 prune_empty_dirs(root, os.dir(full))38 }39 for entry in target {40 data := store.get_object(entry.hash)!41 write_file(os.join_path(root, entry.path), data, entry.executable)!42 }43 return RestoreReport{44 written: target.len45 removed: removed46 }47}4849fn write_file(path string, data []u8, executable bool) ! {50 os.mkdir_all(os.dir(path), os.MkdirParams{})!51 tmp := '${path}.koh-tmp-${os.getpid()}'52 os.write_file_array(tmp, data)!53 mode := if executable { 0o755 } else { 0o644 }54 os.chmod(tmp, mode)!55 os.mv(tmp, path, os.MvParams{})!56}575859fn prune_empty_dirs(root string, dir string) {60 mut current := dir61 for current.len > root.len && current.starts_with(root) {62 if (os.ls(current) or { return }).len > 0 {63 return64 }65 os.rmdir(current) or { return }66 current = os.dir(current)67 }68}