The sidecar preserves the entry's own kind and permissions. In particular, a symlink payload is the link itself, even when its target does not exist. This also keeps existing regular-file sidecars and both manifests readable.
(
source: &std::path::Path,
destination: &std::path::Path,
)
| 47 | // a symlink payload is the link itself, even when its target does not exist. |
| 48 | // This also keeps existing regular-file sidecars and both manifests readable. |
| 49 | fn copy_stash_entry( |
| 50 | source: &std::path::Path, |
| 51 | destination: &std::path::Path, |
| 52 | ) -> std::io::Result<()> { |
| 53 | let metadata = std::fs::symlink_metadata(source)?; |
| 54 | let source_type = metadata.file_type(); |
| 55 | if !source_type.is_file() && !source_type.is_dir() && !source_type.is_symlink() { |
| 56 | return Err(std::io::Error::new( |
| 57 | std::io::ErrorKind::Unsupported, |
| 58 | "cannot stash a special filesystem entry", |
| 59 | )); |
| 60 | } |
| 61 | if let Some(parent) = destination.parent() { |
| 62 | std::fs::create_dir_all(parent)?; |
| 63 | } |
| 64 | match std::fs::symlink_metadata(destination) { |
| 65 | Ok(existing) => { |
| 66 | // Never follow the destination's leaf symlink while restoring a |
| 67 | // regular file. A directory is removed only when empty, so a type |
| 68 | // change cannot erase unrelated children added since the stash. |
| 69 | if source_type.is_symlink() |
| 70 | || existing.file_type().is_symlink() |
| 71 | || source_type.is_dir() != existing.is_dir() |
| 72 | { |
| 73 | if existing.is_dir() { |
| 74 | std::fs::remove_dir(destination)?; |
| 75 | } else { |
| 76 | std::fs::remove_file(destination)?; |
| 77 | } |
| 78 | } |
| 79 | } |
| 80 | Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} |
| 81 | Err(error) => return Err(error), |
| 82 | } |
| 83 | if source_type.is_symlink() { |
| 84 | let target = std::fs::read_link(source)?; |
| 85 | #[cfg(unix)] |
| 86 | std::os::unix::fs::symlink(target, destination)?; |
| 87 | #[cfg(windows)] |
| 88 | std::os::windows::fs::symlink_file(target, destination)?; |
| 89 | #[cfg(not(any(unix, windows)))] |
| 90 | return Err(std::io::Error::new( |
| 91 | std::io::ErrorKind::Unsupported, |
| 92 | "symlink stashes are unsupported on this platform", |
| 93 | )); |
| 94 | } else if source_type.is_dir() { |
| 95 | std::fs::create_dir_all(destination)?; |
| 96 | std::fs::set_permissions(destination, metadata.permissions())?; |
| 97 | } else { |
| 98 | std::fs::copy(source, destination)?; |
| 99 | } |
| 100 | Ok(()) |
| 101 | } |
| 102 | |
| 103 | fn stash_entry_path(root: &std::path::Path, path: &str) -> Result<std::path::PathBuf, String> { |
| 104 | use std::path::Component; |
no test coverage detected