Rewrite your app in Rust, piece by piece, checked against the original at every step. Works with TypeScript, JavaScript, Python, Go, Ruby, Java, C, PHP, C#, Kotlin, PowerShell and Swift.
Rust agent-skillsclaude-codeclicode-migrationcodexffigolangjavajavascriptmcpmigrationnapiperformanceportingpyo3pythonrewriterubyrusttypescript
refactor(app): one snapshot swap, and both paths when it cannot roll back (#1290)
吴佳浩Albenddd0893a429f
diff --git a/src/app.rs b/src/app.rsindex f2af064d..2eb70adb 100644--- a/src/app.rs+++ b/src/app.rs@@ -2542,18 +2542,38 @@ impl PendingSnapshot {name.push(".old");let old = self.dest.with_file_name(name);let _ = std::fs::remove_dir_all(&old);- let moved = std::fs::rename(&self.dest, &old).is_ok();- let renamed = std::fs::rename(&dir, &self.dest);- if renamed.is_ok() {- let _ = std::fs::remove_dir_all(&old);- } else {- if moved {- let _ = std::fs::rename(&old, &self.dest);- }- let _ = std::fs::remove_dir_all(&dir);- }- renamed.with_context(|| format!("replacing {}", self.dest.display()))+ swap_in(&dir, &self.dest, &old)+ }+}++/// Puts `staged` where `dest` is, keeping whatever was there under `old` until the swap succeeds.+/// A failed swap puts the previous folder back; if that fails too, both paths are named, so `dest`+/// is never silently left missing (issue #1118).+fn swap_in(staged: &Path, dest: &Path, old: &Path) -> Result<()> {+ let moved = std::fs::rename(dest, old).is_ok();+ let renamed = std::fs::rename(staged, dest);+ if renamed.is_ok() {+ let _ = std::fs::remove_dir_all(old);+ return Ok(());+ }+ let renamed = renamed.with_context(|| format!("replacing {}", dest.display()));+ if moved && let Err(restore) = std::fs::rename(old, dest) {+ // `commit` has already taken the pending folder, so nothing else cleans it up.+ let _ = std::fs::remove_dir_all(staged);+ // `{:#}` keeps the installation error's own cause, not just its context (review of #1290).+ let failed = renamed+ .as_ref()+ .err()+ .map(|e| format!("{e:#}"))+ .unwrap_or_default();+ anyhow::bail!(+ "{failed}; the previous folder could not be put back from {} either ({restore}), so \+ the folder holds neither",+ old.display()+ );}+ let _ = std::fs::remove_dir_all(staged);+ renamed}impl Drop for PendingSnapshot {@@ -2811,8 +2831,18 @@ pub fn record(opts: &RecordOptions) -> Result<RecordOutcome> {let mut outcome = crate::http::record(&repo, &config, &norm, opts, snapshot.path())?;let dropped = update_recorded_cases(&mut config, existing.as_ref(), &mut outcome)?;outcome.trycmd_test = save_config(&config)?;- snapshot.commit()?;- check_recording_complete(dropped, outcome.trycmd_test.as_deref())?;+ // Same as the CLI path: a failure says what was already published (issue #1118).+ let staged_snapshot = snapshot.path().is_some();+ snapshot.commit().with_context(|| {+ format!("{CONFIG_FILE} is published, but the captured-file snapshot is not")+ })?;+ check_recording_complete(dropped, outcome.trycmd_test.as_deref()).with_context(|| {+ if staged_snapshot {+ "the snapshot is published, but the recording is incomplete".to_string()+ } else {+ format!("{CONFIG_FILE} is published, but the recording is incomplete")+ }+ })?;if config.http.as_ref().is_some_and(|h| h.fresh.is_empty()) {let _ = std::fs::remove_dir_all(cases_dir(&repo)@@ -3045,9 +3075,23 @@ pub fn record(opts: &RecordOptions) -> Result<RecordOutcome> {}meta.cases.retain(|name, _| dir.join(format!("{name}.toml")).is_file());+ // The three publishes are still three steps, but a failure in one now says which ones already+ // happened, instead of leaving a recording that looks complete (issue #1118).outcome.trycmd_test = save_config(&config)?;- snapshot.commit()?;- meta.save(&dir)?;+ // The name on disk, not "config.json": `app record` writes `rust-anything.json` (review of #1290).+ let staged_snapshot = snapshot.path().is_some();+ snapshot.commit().with_context(|| {+ format!("{CONFIG_FILE} is published, but the fresh-file snapshot is not")+ })?;+ meta.save(&dir).with_context(|| {+ // With no fresh files there is no snapshot to publish, so the message must not claim one+ // (review of #1290).+ if staged_snapshot {+ "the fresh-file snapshot is published, but the CLI metadata is not".to_string()+ } else {+ format!("{CONFIG_FILE} is published, but the CLI metadata is not")+ }+ })?;check_recording_complete(dropped, outcome.trycmd_test.as_deref())?;if config.fresh.is_empty() {let fresh_dir = dir.join(FRESH_DIR);@@ -4725,6 +4769,60 @@ mod tests {assert_eq!(kept.as_deref(), Some("{}"));}+ #[test]+ fn a_swap_puts_the_staged_folder_where_the_old_one_was() {+ let dir = temp_dir("swap-ok").unwrap();+ let dest = dir.join("files");+ let staged = dir.join("files.pending");+ let old = dir.join("files.old");+ std::fs::create_dir_all(&dest).unwrap();+ std::fs::write(dest.join("seed.json"), "old").unwrap();+ std::fs::create_dir_all(&staged).unwrap();+ std::fs::write(staged.join("seed.json"), "new").unwrap();+ let swapped = swap_in(&staged, &dest, &old);+ let kept = std::fs::read_to_string(dest.join("seed.json")).ok();+ let leftover = old.exists() || staged.exists();+ let _ = std::fs::remove_dir_all(&dir);+ assert!(swapped.is_ok(), "{swapped:?}");+ assert_eq!(kept.as_deref(), Some("new"));+ assert!(+ !leftover,+ "neither the staged nor the old folder is left behind"+ );+ }++ #[test]+ fn a_failed_swap_puts_the_previous_folder_back_and_drops_the_staged_one() {+ let dir = temp_dir("swap-back").unwrap();+ let dest = dir.join("files");+ let staged = dir.join("files.pending");+ let old = dir.join("files.old");+ std::fs::create_dir_all(&dest).unwrap();+ std::fs::write(dest.join("seed.json"), "old").unwrap();+ // No staged folder: the swap cannot happen.+ let swapped = swap_in(&staged, &dest, &old);+ let kept = std::fs::read_to_string(dest.join("seed.json")).ok();+ let leftover = old.exists() || staged.exists();+ let _ = std::fs::remove_dir_all(&dir);+ assert!(swapped.is_err(), "a swap with nothing staged has to fail");+ assert_eq!(kept.as_deref(), Some("old"), "the previous folder is back");+ assert!(!leftover, "neither folder is left behind");+ }++ #[test]+ fn a_first_swap_with_no_previous_folder_reports_the_failure() {+ let dir = temp_dir("swap-first").unwrap();+ let dest = dir.join("files");+ let staged = dir.join("files.pending");+ let old = dir.join("files.old");+ // Neither exists: `moved` is false, so there is nothing to put back.+ let swapped = swap_in(&staged, &dest, &old);+ let _ = std::fs::remove_dir_all(&dir);+ let err = format!("{:#}", swapped.unwrap_err());+ assert!(err.contains("replacing"), "{err}");+ assert!(!err.contains("holds neither"), "{err}");+ }+#[test]fn a_byte_order_mark_at_the_start_of_an_inputs_file_is_skipped() {// Windows PowerShell 5 (`-Encoding utf8`) and older Notepad save a UTF-8 file with one.