| 1 | use std::ffi::OsString; |
| 2 | use std::fs; |
| 3 | use std::io::Write; |
| 4 | use std::path::{Path, PathBuf}; |
| 5 | |
| 6 | use super::error::InstallError; |
| 7 | |
| 8 | pub(super) fn read_if_exists(path: &Path) -> Result<Option<String>, InstallError> { |
| 9 | match fs::read_to_string(path) { |
| 10 | Ok(contents) => Ok(Some(contents)), |
| 11 | Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None), |
| 12 | Err(error) => Err(InstallError::io(path, error)), |
| 13 | } |
| 14 | } |
| 15 | |
| 16 | fn sibling(path: &Path, prefix: &str, suffix: &str) -> PathBuf { |
| 17 | let mut name = OsString::from(prefix); |
| 18 | name.push(path.file_name().unwrap_or_default()); |
| 19 | name.push(suffix); |
| 20 | path.with_file_name(name) |
| 21 | } |
| 22 | |
| 23 | pub(super) fn write_atomic(path: &Path, contents: &str) -> Result<(), InstallError> { |
| 24 | let resolved = fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()); |
| 25 | let path = resolved.as_path(); |
| 26 | let existing = fs::metadata(path).ok(); |
| 27 | if let Some(parent) = path.parent() { |
| 28 | fs::create_dir_all(parent).map_err(|error| InstallError::io(parent, error))?; |
| 29 | } |
| 30 | if existing.is_some() { |
| 31 | let backup = sibling(path, "", ".bak-rusty-teams"); |
| 32 | if !backup.exists() { |
| 33 | fs::copy(path, &backup).map_err(|error| InstallError::io(&backup, error))?; |
| 34 | } |
| 35 | } |
| 36 | let temporary = sibling(path, ".", ".rusty-teams.tmp"); |
| 37 | let result = write_temporary(&temporary, contents, existing.as_ref()) |
| 38 | .and_then(|()| fs::rename(&temporary, path)); |
| 39 | if let Err(error) = result { |
| 40 | let _ = fs::remove_file(&temporary); |
| 41 | return Err(InstallError::io(path, error)); |
| 42 | } |
| 43 | Ok(()) |
| 44 | } |
| 45 | |
| 46 | fn write_temporary( |
| 47 | temporary: &Path, |
| 48 | contents: &str, |
| 49 | existing: Option<&fs::Metadata>, |
| 50 | ) -> std::io::Result<()> { |
| 51 | let mut options = fs::OpenOptions::new(); |
| 52 | options.write(true).create(true).truncate(true); |
| 53 | #[cfg(unix)] |
| 54 | std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); |
| 55 | let mut file = options.open(temporary)?; |
| 56 | file.write_all(contents.as_bytes())?; |
| 57 | file.sync_all()?; |
| 58 | if let Some(metadata) = existing { |
| 59 | fs::set_permissions(temporary, metadata.permissions())?; |
| 60 | } |
| 61 | Ok(()) |
| 62 | } |