Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat(cli): add atomic write and confirmation helpers
Richie McIlroye5097d837c02
diff --git a/apps/cli/src/atomic.rs b/apps/cli/src/atomic.rsnew file mode 100644index 000000000..98c0f1ffc--- /dev/null+++ b/apps/cli/src/atomic.rs@@ -0,0 +1,51 @@+use std::{io, path::Path};++#[cfg(not(windows))]+pub fn replace(temporary: &Path, destination: &Path) -> io::Result<()> {+ std::fs::rename(temporary, destination)+}++#[cfg(windows)]+pub fn replace(temporary: &Path, destination: &Path) -> io::Result<()> {+ use std::os::windows::ffi::OsStrExt;+ use windows::Win32::Storage::FileSystem::{+ MOVEFILE_REPLACE_EXISTING, MOVEFILE_WRITE_THROUGH, MoveFileExW,+ };+ use windows::core::PCWSTR;++ let temporary = temporary+ .as_os_str()+ .encode_wide()+ .chain(std::iter::once(0))+ .collect::<Vec<_>>();+ let destination = destination+ .as_os_str()+ .encode_wide()+ .chain(std::iter::once(0))+ .collect::<Vec<_>>();+ unsafe {+ MoveFileExW(+ PCWSTR(temporary.as_ptr()),+ PCWSTR(destination.as_ptr()),+ MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH,+ )+ .map_err(|error| io::Error::other(error.to_string()))+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn replaces_an_existing_file() {+ let directory = tempfile::tempdir().unwrap();+ let destination = directory.path().join("destination");+ let temporary = directory.path().join("temporary");+ std::fs::write(&destination, "old").unwrap();+ std::fs::write(&temporary, "new").unwrap();+ replace(&temporary, &destination).unwrap();+ assert_eq!(std::fs::read_to_string(destination).unwrap(), "new");+ assert!(!temporary.exists());+ }+}diff --git a/apps/cli/src/confirmation.rs b/apps/cli/src/confirmation.rsnew file mode 100644index 000000000..be89249ba--- /dev/null+++ b/apps/cli/src/confirmation.rs@@ -0,0 +1,25 @@+use std::io::{IsTerminal, Write};++pub fn require(yes: bool, action: &str) -> Result<(), String> {+ if yes {+ return Ok(());+ }+ if !std::io::stdin().is_terminal() {+ return Err(format!(+ "{action} requires --yes when stdin is not interactive"+ ));+ }+ eprint!("{action}? [y/N] ");+ std::io::stderr()+ .flush()+ .map_err(|error| error.to_string())?;+ let mut answer = String::new();+ std::io::stdin()+ .read_line(&mut answer)+ .map_err(|error| error.to_string())?;+ if matches!(answer.trim().to_ascii_lowercase().as_str(), "y" | "yes") {+ Ok(())+ } else {+ Err("Cancelled".to_string())+ }+}