diff --git a/crates/ide-ssh/src/ftp.rs b/crates/ide-ssh/src/ftp.rs index 0e347519a..6a93ba162 100644 --- a/crates/ide-ssh/src/ftp.rs +++ b/crates/ide-ssh/src/ftp.rs @@ -308,16 +308,30 @@ impl FtpFs { self.ftp.lock().await.mkdir(path).await.map_err(|e| err(path, e)) } + /// Downloads into a sibling temporary file and replaces `local` only once the + /// server confirmed the transfer, so a failed one leaves an existing file as it was. pub async fn download(&self, remote: &str, local: &Path) -> IdeResult<()> { if let Some(dir) = local.parent() { tokio::fs::create_dir_all(dir).await?; } - let mut ftp = self.ftp.lock().await; - let mut stream = ftp.retr_as_stream(remote).await.map_err(|e| err(remote, e))?; - let mut output = tokio::fs::File::create(local).await?; - tokio::io::copy(&mut stream, &mut output).await?; - output.flush().await?; - stream.finish().await.map_err(|e| err(remote, e)) + let name = local.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + let partial = local.with_file_name(format!(".{name}.download")); + let result = async { + let mut ftp = self.ftp.lock().await; + let mut stream = ftp.retr_as_stream(remote).await.map_err(|e| err(remote, e))?; + let mut output = tokio::fs::File::create(&partial).await?; + tokio::io::copy(&mut stream, &mut output).await?; + output.flush().await?; + drop(output); + stream.finish().await.map_err(|e| err(remote, e))?; + tokio::fs::rename(&partial, local).await?; + Ok(()) + } + .await; + if result.is_err() { + let _ = tokio::fs::remove_file(&partial).await; + } + result } /// `mkdir -p`. @@ -328,7 +342,9 @@ impl FtpFs { if let Some(p) = parent(dir) { Box::pin(self.mkdir_all(p)).await?; } - match self.ftp.lock().await.mkdir(dir).await { + // The connection's lock is released before `is_dir` takes it again. + let made = self.ftp.lock().await.mkdir(dir).await; + match made { Ok(()) => Ok(()), Err(e) => { if self.is_dir(dir).await {