diff --git a/crates/deploy/Cargo.toml b/crates/deploy/Cargo.toml index 7f9bf13..bedbe9e 100644 --- a/crates/deploy/Cargo.toml +++ b/crates/deploy/Cargo.toml @@ -41,3 +41,7 @@ required-features = ["testserver"] [[example]] name = "testserver" required-features = ["testserver"] + +[[test]] +name = "remote" +required-features = ["testserver"] diff --git a/crates/deploy/src/browse.rs b/crates/deploy/src/browse.rs new file mode 100644 index 0000000..0b7c522 --- /dev/null +++ b/crates/deploy/src/browse.rs @@ -0,0 +1,296 @@ +//! The remote browser's operations (D2): list a folder, read and write a +//! file, rename, delete and create folders on the server. +//! +//! Browser paths are relative to the server's root with `/` (`""` is the +//! root itself); `..`, control characters and absolute paths are refused, +//! so the browser never leaves the deployment root. Every operation opens +//! its own connection and closes it. + +use crate::ServerKind; +use crate::error::{DeployError, Result}; +use crate::job::{Job, Level, connect}; +use crate::mapping::{join, normalize_relative, remote_path}; +use crate::remote::{Entry, Remote}; +use crate::secrets::Secret; + +/// Largest file [`read`] returns as text. +pub const MAX_TEXT: u64 = 4 * 1024 * 1024; + +/// What [`read`] found. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct RemoteText { + /// The UTF-8 text; `None` when the file does not exist on the server. + pub text: Option, + /// The file is not UTF-8 text (or holds a NUL byte). + pub binary: bool, + /// The file is larger than [`MAX_TEXT`]. + pub too_large: bool, +} + +/// Which file [`read`] reads. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Target { + /// A project-relative path, mapped through the server's mappings. + Mapped(String), + /// A browser path, relative to the server's root. + Browser(String), +} + +/// The server path of the browser path `rel`. +/// +/// # Errors +/// [`DeployError::Invalid`] for an absolute path, `..` or control +/// characters. +pub fn server_path(job: &Job, rel: &str) -> Result { + if rel.starts_with('/') || rel.starts_with('\\') { + return Err(DeployError::Invalid(format!( + "{rel:?} must be relative to the server's root folder" + ))); + } + let rel = normalize_relative(rel) + .ok_or_else(|| DeployError::Invalid(format!("{rel:?} leaves the server's root folder")))?; + Ok(if job.server.kind == ServerKind::Folder { + rel + } else { + join(&[&job.server.root, &rel]) + }) +} + +/// Runs `op` on a fresh connection and closes it; errors are redacted. +fn with_remote(job: &Job, op: impl FnOnce(&mut dyn Remote) -> Result) -> Result { + let secret = job.secret.as_ref().map(Secret::expose); + let mut remote = connect(job)?; + let result = op(remote.as_mut()); + remote.close(); + result.map_err(|e| e.redacted(secret)) +} + +/// The entries of the browser folder `rel`, folders first, then by name. +/// +/// # Errors +/// What the connection or the listing returns. +pub fn list(job: &Job, rel: &str) -> Result> { + let path = server_path(job, rel)?; + with_remote(job, |remote| { + let mut entries = remote.list(&path)?; + entries.sort_by(|a, b| b.is_dir.cmp(&a.is_dir).then_with(|| a.name.cmp(&b.name))); + Ok(entries) + }) +} + +/// Reads one file as text, at most [`MAX_TEXT`] bytes. +/// +/// # Errors +/// [`DeployError::Invalid`] for a path that is excluded or not mapped, +/// otherwise what the connection or the transfer returns. +pub fn read(job: &Job, target: &Target) -> Result { + let path = match target { + Target::Mapped(rel) => remote_path(&job.server, rel).ok_or_else(|| { + DeployError::Invalid(format!( + "{rel} is excluded or not mapped on {}", + job.server.name + )) + })?, + Target::Browser(rel) => server_path(job, rel)?, + }; + with_remote(job, |remote| { + match remote.kind(&path)? { + None => return Ok(RemoteText::default()), + Some(true) => { + return Err(DeployError::Invalid(format!( + "{path} is a folder on the server" + ))); + } + Some(false) => {} + } + let mut bytes = Vec::new(); + let mut total = 0u64; + let cancel = job.cancel.clone(); + let read = remote.get(&path, &mut bytes, &mut |n| { + total = total.saturating_add(n); + if total > MAX_TEXT { + return Err(DeployError::Cancelled); + } + cancel.check() + }); + match read { + Err(DeployError::Cancelled) if total > MAX_TEXT => Ok(RemoteText { + text: None, + binary: false, + too_large: true, + }), + Err(e) => Err(e), + Ok(()) => Ok(match String::from_utf8(bytes) { + Ok(text) if !text.contains('\0') => RemoteText { + text: Some(text), + binary: false, + too_large: false, + }, + _ => RemoteText { + text: None, + binary: true, + too_large: false, + }, + }), + } + }) +} + +/// Writes `bytes` to the browser path `rel`, creating its folder. +/// +/// # Errors +/// What the connection or the transfer returns. +pub fn write(job: &Job, rel: &str, bytes: &[u8]) -> Result<()> { + let path = server_path(job, rel)?; + let cancel = job.cancel.clone(); + with_remote(job, |remote| { + if let Some(slash) = path.rfind('/') + && slash > 0 + { + remote.mkdir_all(path.get(..slash).unwrap_or_default())?; + } + remote.put(&path, &mut &bytes[..], &mut |_| cancel.check()) + })?; + job.monitor + .log(Level::Info, format!("saved {path} on the server")); + Ok(()) +} + +/// Renames or moves the browser path `from` to `to`. +/// +/// # Errors +/// What the connection or the server returns. +pub fn rename(job: &Job, from: &str, to: &str) -> Result<()> { + let from = server_path(job, from)?; + let to = server_path(job, to)?; + with_remote(job, |remote| remote.rename(&from, &to))?; + job.monitor + .log(Level::Info, format!("renamed {from} to {to}")); + Ok(()) +} + +/// Creates the browser folder `rel` and its missing parents. +/// +/// # Errors +/// What the connection or the server returns. +pub fn mkdir(job: &Job, rel: &str) -> Result<()> { + let path = server_path(job, rel)?; + with_remote(job, |remote| remote.mkdir_all(&path))?; + job.monitor + .log(Level::Info, format!("created the folder {path}")); + Ok(()) +} + +/// Removes `path` on the server; a folder with everything inside it. +/// Returns how many files and folders were removed. +fn remove_tree(job: &Job, remote: &mut dyn Remote, path: &str, depth: usize) -> Result { + job.cancel.check()?; + match remote.kind(path)? { + None => Ok(0), + Some(false) => { + remote.remove_file(path)?; + job.monitor.log(Level::Info, format!("deleted {path}")); + Ok(1) + } + Some(true) => { + if depth > 64 { + return Err(DeployError::Transfer(format!( + "{path} is nested too deeply" + ))); + } + let mut count = 0; + for entry in remote.list(path)? { + count += remove_tree(job, remote, &format!("{path}/{}", entry.name), depth + 1)?; + } + remote.remove_dir(path)?; + job.monitor + .log(Level::Info, format!("deleted the folder {path}")); + Ok(count + 1) + } + } +} + +/// Deletes the browser path `rel` on the server, a folder with its +/// contents. The root itself cannot be deleted. Callers ask the user +/// first; the engine refuses without an explicit confirmation. +/// +/// # Errors +/// [`DeployError::Invalid`] for the root, otherwise what the connection or +/// the server returns. +pub fn delete(job: &Job, rel: &str) -> Result { + let path = server_path(job, rel)?; + if normalize_relative(rel).unwrap_or_default().is_empty() { + return Err(DeployError::Invalid( + "the server's root folder cannot be deleted from Lutra".into(), + )); + } + with_remote(job, |remote| remove_tree(job, remote, &path, 0)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::config::{AuthKind, Server}; + use crate::{Cancel, Monitor}; + + fn job(root: &std::path::Path) -> Job { + Job { + server: Server { + id: "f".into(), + name: "F".into(), + kind: ServerKind::Folder, + host: String::new(), + port: None, + user: String::new(), + root: root.display().to_string(), + auth: AuthKind::Password, + key_path: None, + mappings: vec![], + excluded: vec![], + upload_on_save: false, + }, + project_root: root.to_path_buf(), + secret: None, + known_hosts: root.join("kh"), + cancel: Cancel::new(), + monitor: Monitor::new(), + } + } + + #[test] + fn browser_operations_on_a_folder() { + let dir = tempfile::tempdir().unwrap(); + let j = job(dir.path()); + mkdir(&j, "a/b").unwrap(); + write(&j, "a/b/x.php", b">(), + ["b", "bin.dat"] + ); + assert_eq!( + read(&j, &Target::Browser("a/b/x.php".into())) + .unwrap() + .text + .as_deref(), + Some(" Result<()> { + self.ftp() + .rm(path) + .map_err(|e| ftp_error(&format!("cannot remove {path}"), &e)) + } + + fn remove_dir(&mut self, path: &str) -> Result<()> { + self.ftp() + .rmdir(path) + .map_err(|e| ftp_error(&format!("cannot remove the folder {path}"), &e)) + } + + fn rename(&mut self, from: &str, to: &str) -> Result<()> { + self.ftp() + .rename(from, to) + .map_err(|e| ftp_error(&format!("cannot rename {from} to {to}"), &e)) + } + /// Sends `QUIT`; a failure is ignored because the connection is /// dropped right after. fn close(&mut self) { diff --git a/crates/deploy/src/job.rs b/crates/deploy/src/job.rs index 95a4ea8..938b60c 100644 --- a/crates/deploy/src/job.rs +++ b/crates/deploy/src/job.rs @@ -9,7 +9,7 @@ //! Folder walks skip symbolic links to folders and the version-control //! folders `.git`, `.svn` and `.hg`, which are never deployed. -use std::collections::BTreeSet; +use std::collections::{BTreeMap, BTreeSet}; use std::fs::File; use std::path::Path; use std::sync::{Arc, Mutex, PoisonError}; @@ -18,7 +18,7 @@ use serde::Serialize; use crate::config::{Server, ServerKind, io_error}; use crate::error::{DeployError, Result}; -use crate::mapping::{is_excluded, normalize_relative, remote_path}; +use crate::mapping::{is_excluded, join, normalize_relative, remote_path}; use crate::remote::{Cancel, Folder, Remote}; use crate::secrets::Secret; @@ -56,7 +56,7 @@ pub struct LogLine { #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)] #[serde(rename_all = "camelCase")] pub struct Progress { - /// `connecting`, `planning`, `transferring`. + /// `connecting`, `planning`, `comparing`, `transferring`. pub phase: String, /// The file being transferred, project-relative. #[serde(skip_serializing_if = "Option::is_none")] @@ -117,7 +117,7 @@ impl Monitor { } /// Adds a log line. - fn log(&self, level: Level, message: String) { + pub(crate) fn log(&self, level: Level, message: String) { self.0 .lock() .unwrap_or_else(PoisonError::into_inner) @@ -156,6 +156,8 @@ pub struct Summary { pub skipped: usize, /// Files that failed. pub failed: usize, + /// Files deleted on the server (sync only). + pub deleted: usize, } /// One planned file. @@ -427,25 +429,7 @@ fn walk_remote( Some(false) => { *skipped += 1; } - Some(true) if depth <= MAX_DEPTH => { - for entry in remote.list(&path)? { - if VCS_DIRS.contains(&entry.name.as_str()) { - continue; - } - let child = if rel.is_empty() { - entry.name - } else { - format!("{rel}/{}", entry.name) - }; - walk_remote(job, remote, &child, depth + 1, plan, skipped)?; - if plan.len() > MAX_FILES { - return Err(DeployError::Invalid(format!( - "more than {MAX_FILES} files; download a smaller folder" - ))); - } - } - } - Some(true) => {} + Some(true) => walk_remote_tree(job, remote, rel, &path, depth, plan)?, } Ok(()) } @@ -539,6 +523,266 @@ fn download_one(job: &Job, remote: &mut dyn Remote, file: &Planned) -> Result, +) -> Result<()> { + if depth > MAX_DEPTH { + return Ok(()); + } + for entry in remote.list(path)? { + job.cancel.check()?; + if VCS_DIRS.contains(&entry.name.as_str()) { + continue; + } + let child = if rel.is_empty() { + entry.name.clone() + } else { + format!("{rel}/{}", entry.name) + }; + let child_path = join(&[path, &entry.name]); + if remote_path(&job.server, &child).as_deref() != Some(child_path.as_str()) { + continue; + } + if entry.is_dir { + walk_remote_tree(job, remote, &child, &child_path, depth + 1, plan)?; + } else { + plan.push(Planned { + local: child, + remote: child_path, + size: entry.size.unwrap_or(0), + }); + } + if plan.len() > MAX_FILES { + return Err(DeployError::Invalid(format!( + "more than {MAX_FILES} files; choose a smaller folder" + ))); + } + } + Ok(()) +} + +/// Largest file whose contents [`compare`] reads to tell equal sizes +/// apart; larger files of equal size count as equal. +pub const MAX_COMPARE: u64 = 8 * 1024 * 1024; + +/// How a file differs between the project and the server. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum DiffStatus { + /// Only in the project. + LocalOnly, + /// Only on the server. + RemoteOnly, + /// On both, with different contents. + Different, +} + +/// One differing file of [`compare`]. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Difference { + /// Project-relative path. + pub path: String, + /// How it differs. + pub status: DiffStatus, + /// Its size in the project. + #[serde(skip_serializing_if = "Option::is_none")] + pub local_size: Option, + /// Its size on the server. + #[serde(skip_serializing_if = "Option::is_none")] + pub remote_size: Option, +} + +/// Whether the local `file` and its remote counterpart hold the same +/// bytes; callers check that both sizes match first. +fn same_contents(job: &Job, remote: &mut dyn Remote, file: &Planned) -> Result { + let path = job.project_root.join(&file.local); + let local = std::fs::read(&path).map_err(|e| io_error(&path, &e))?; + let mut theirs = Vec::with_capacity(local.len()); + let cancel = job.cancel.clone(); + remote.get(&file.remote, &mut theirs, &mut |_| cancel.check())?; + Ok(local == theirs) +} + +/// Compares the project-relative `paths` (files or folders) with the +/// server: files only in the project, only on the server, or with +/// different contents (sizes first; equal sizes up to [`MAX_COMPARE`] by +/// contents). Excluded and unmapped files are left out. Sorted by path. +/// +/// # Errors +/// [`DeployError::Invalid`] for a path outside the project, otherwise what +/// the connection or the listing returns. +pub fn compare(job: &Job, paths: &[String]) -> Result> { + let secret = job.secret.as_ref().map(Secret::expose); + job.monitor.update(|p| p.phase = "planning".into()); + let mut local = Vec::new(); + let mut skipped = 0; + let mut rels = Vec::new(); + for path in paths { + let rel = normalize_relative(path) + .ok_or_else(|| DeployError::Invalid(format!("{path:?} is not inside the project")))?; + if job.project_root.join(&rel).exists() { + walk_local(job, &rel, 0, &mut local, &mut skipped)?; + } + rels.push(rel); + } + let mut remote = connect(job)?; + let result = (|| { + let mut theirs = Vec::new(); + for rel in &rels { + let mut ignored = 0; + walk_remote(job, remote.as_mut(), rel, 0, &mut theirs, &mut ignored)?; + } + let mut by_path: BTreeMap = BTreeMap::new(); + for file in &local { + by_path.insert( + file.local.clone(), + Difference { + path: file.local.clone(), + status: DiffStatus::LocalOnly, + local_size: Some(file.size), + remote_size: None, + }, + ); + } + job.monitor.update(|p| { + p.phase = "comparing".into(); + p.files_total = theirs.len(); + }); + for file in &theirs { + job.cancel.check()?; + job.monitor.update(|p| p.file = Some(file.local.clone())); + match local.iter().find(|l| l.local == file.local) { + None => { + by_path.insert( + file.local.clone(), + Difference { + path: file.local.clone(), + status: DiffStatus::RemoteOnly, + local_size: None, + remote_size: Some(file.size), + }, + ); + } + Some(mine) => { + let differs = mine.size != file.size + || (mine.size <= MAX_COMPARE + && !same_contents(job, remote.as_mut(), mine)?); + if differs { + by_path.insert( + file.local.clone(), + Difference { + path: file.local.clone(), + status: DiffStatus::Different, + local_size: Some(mine.size), + remote_size: Some(file.size), + }, + ); + } else { + by_path.remove(&file.local); + } + } + } + job.monitor.update(|p| p.files_done += 1); + } + Ok(by_path.into_values().collect::>()) + })(); + remote.close(); + let found = result.map_err(|e: DeployError| e.redacted(secret))?; + job.monitor.log( + Level::Info, + format!("compared: {} differing files", found.len()), + ); + Ok(found) +} + +/// Uploads the project-relative files `upload` and deletes the files +/// `delete` on the server, in one connection. Callers show the plan first +/// and pass deletions only after the user confirmed them; the engine +/// refuses deletions without that confirmation. +/// +/// # Errors +/// Like [`upload`]; a failing file is counted in [`Summary::failed`]. +pub fn sync(job: &Job, upload: &[String], delete: &[String]) -> Result { + let secret = job.secret.as_ref().map(Secret::expose); + let mut plan = Vec::new(); + let mut summary = Summary::default(); + for path in upload { + let rel = normalize_relative(path) + .ok_or_else(|| DeployError::Invalid(format!("{path:?} is not inside the project")))?; + walk_local(job, &rel, 0, &mut plan, &mut summary.skipped)?; + } + let mut doomed = Vec::new(); + for path in delete { + let rel = normalize_relative(path) + .filter(|r| !r.is_empty()) + .ok_or_else(|| DeployError::Invalid(format!("{path:?} is not a project file")))?; + let remote = remote_path(&job.server, &rel) + .ok_or_else(|| DeployError::Invalid(format!("{rel} is excluded or not mapped")))?; + doomed.push((rel, remote)); + } + job.monitor.update(|p| { + p.files_total = plan.len() + doomed.len(); + p.bytes_total = plan.iter().map(|f| f.size).sum(); + }); + let mut remote = connect(job)?; + job.monitor.update(|p| p.phase = "transferring".into()); + let mut made: BTreeSet = BTreeSet::new(); + let result = (|| { + for file in &plan { + job.cancel.check()?; + job.monitor.update(|p| p.file = Some(file.local.clone())); + let outcome = + upload_one(job, remote.as_mut(), file, &mut made).map_err(|e| e.redacted(secret)); + job.monitor.update(|p| p.files_done += 1); + match outcome { + Ok(()) => { + summary.files += 1; + summary.bytes += file.size; + job.monitor + .log(Level::Info, format!("{} → {}", file.local, file.remote)); + } + Err(e) if is_fatal(&e) => return Err(e), + Err(e) => { + summary.failed += 1; + job.monitor + .log(Level::Error, format!("{}: {e}", file.local)); + } + } + } + for (rel, path) in &doomed { + job.cancel.check()?; + job.monitor.update(|p| p.file = Some(rel.clone())); + let outcome = remote.remove_file(path).map_err(|e| e.redacted(secret)); + job.monitor.update(|p| p.files_done += 1); + match outcome { + Ok(()) => { + summary.deleted += 1; + job.monitor + .log(Level::Warning, format!("deleted {path} on the server")); + } + Err(e) if is_fatal(&e) => return Err(e), + Err(e) => { + summary.failed += 1; + job.monitor.log(Level::Error, format!("{rel}: {e}")); + } + } + } + Ok(()) + })(); + remote.close(); + result.map(|()| summary) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/deploy/src/lib.rs b/crates/deploy/src/lib.rs index 89a835f..191111e 100644 --- a/crates/deploy/src/lib.rs +++ b/crates/deploy/src/lib.rs @@ -9,13 +9,16 @@ //! - [`remote`]: the operations every transport offers (the extension //! point for the remote browser and compare of D2), and the folder //! transport; `sftp` and `ftp` are the network ones. -//! - [`job`]: test connection, upload and download with progress, log and -//! cancel. +//! - [`job`]: test connection, upload, download, compare and sync with +//! progress, log and cancel. +//! - [`browse`]: the remote browser's list, read, write, rename, delete and +//! new folder. //! //! Pure Rust: `russh` and `russh-sftp` for SFTP, `suppaftp` with `rustls` //! for FTP and FTPS, `ring` for cryptography, `keyring` for the keychain. //! No credential is ever written to a file, a log or an error message. +pub mod browse; pub mod config; pub mod error; mod ftp; @@ -31,6 +34,6 @@ pub mod testserver; pub use config::{AuthKind, Deployment, Mapping, Server, ServerKind}; pub use error::{DeployError, Result}; -pub use job::{Job, Level, LogLine, Monitor, Progress, Summary}; +pub use job::{DiffStatus, Difference, Job, Level, LogLine, Monitor, Progress, Summary}; pub use remote::Cancel; pub use secrets::{Keychain, MemoryStore, Secret, SecretStore}; diff --git a/crates/deploy/src/mapping.rs b/crates/deploy/src/mapping.rs index 9f957c1..6a8cb78 100644 --- a/crates/deploy/src/mapping.rs +++ b/crates/deploy/src/mapping.rs @@ -86,7 +86,7 @@ pub fn is_excluded(server: &Server, path: &str) -> bool { /// Joins remote path pieces with `/`, skipping empty ones. Keeps a leading /// `/` of the first non-empty piece. -fn join(pieces: &[&str]) -> String { +pub(crate) fn join(pieces: &[&str]) -> String { let mut out = String::new(); for piece in pieces.iter().filter(|p| !p.is_empty()) { if out.is_empty() { diff --git a/crates/deploy/src/remote.rs b/crates/deploy/src/remote.rs index 23455b5..fdb40e4 100644 --- a/crates/deploy/src/remote.rs +++ b/crates/deploy/src/remote.rs @@ -115,6 +115,25 @@ pub trait Remote { /// [`DeployError::Transfer`] when the server refuses. fn list(&mut self, path: &str) -> Result>; + /// Removes the file `path`. + /// + /// # Errors + /// [`DeployError::Transfer`] when the server refuses. + fn remove_file(&mut self, path: &str) -> Result<()>; + + /// Removes the empty folder `path`. + /// + /// # Errors + /// [`DeployError::Transfer`] when the server refuses (also when the + /// folder is not empty). + fn remove_dir(&mut self, path: &str) -> Result<()>; + + /// Renames or moves `from` to `to` on the server. + /// + /// # Errors + /// [`DeployError::Transfer`] when the server refuses. + fn rename(&mut self, from: &str, to: &str) -> Result<()>; + /// Ends the session politely; failures are ignored because the /// connection is dropped anyway. fn close(&mut self); @@ -247,6 +266,27 @@ impl Remote for Folder { Ok(entries) } + fn remove_file(&mut self, path: &str) -> Result<()> { + let path = self.resolve(path)?; + std::fs::remove_file(&path).map_err(|e| io_error(&path, &e)) + } + + fn remove_dir(&mut self, path: &str) -> Result<()> { + let path = self.resolve(path)?; + if path == self.root { + return Err(DeployError::Invalid( + "the deployment folder itself cannot be removed".into(), + )); + } + std::fs::remove_dir(&path).map_err(|e| io_error(&path, &e)) + } + + fn rename(&mut self, from: &str, to: &str) -> Result<()> { + let from = self.resolve(from)?; + let to = self.resolve(to)?; + std::fs::rename(&from, &to).map_err(|e| io_error(&from, &e)) + } + fn close(&mut self) {} } diff --git a/crates/deploy/src/sftp.rs b/crates/deploy/src/sftp.rs index 965b3cf..04fde23 100644 --- a/crates/deploy/src/sftp.rs +++ b/crates/deploy/src/sftp.rs @@ -445,6 +445,24 @@ impl Remote for Sftp { Ok(entries) } + fn remove_file(&mut self, path: &str) -> Result<()> { + self.run("removing a file", self.sftp.remove_file(path.to_string()))? + .map_err(|e| sftp_error("cannot remove", path, &e)) + } + + fn remove_dir(&mut self, path: &str) -> Result<()> { + self.run("removing a folder", self.sftp.remove_dir(path.to_string()))? + .map_err(|e| sftp_error("cannot remove the folder", path, &e)) + } + + fn rename(&mut self, from: &str, to: &str) -> Result<()> { + self.run( + "renaming", + self.sftp.rename(from.to_string(), to.to_string()), + )? + .map_err(|e| sftp_error(&format!("cannot rename to {to}:"), from, &e)) + } + /// Closes the SFTP channel and the connection. Failures are ignored: /// the connection is dropped right after. fn close(&mut self) { diff --git a/crates/deploy/src/testserver.rs b/crates/deploy/src/testserver.rs index 6e748f7..a0c96ec 100644 --- a/crates/deploy/src/testserver.rs +++ b/crates/deploy/src/testserver.rs @@ -6,8 +6,8 @@ //! The SFTP server has a fixed Ed25519 host key (from a seed) and accepts //! one user with one password, or one public key. The FTP server speaks //! enough of RFC 959 for Lutra's client: USER, PASS, SYST, FEAT, TYPE, -//! PWD, CWD, MKD, SIZE, PASV, STOR, RETR, LIST, NOOP, QUIT. Both stop when -//! dropped. +//! PWD, CWD, MKD, RMD, DELE, RNFR, RNTO, SIZE, PASV, STOR, RETR, LIST, +//! NOOP, QUIT. Both stop when dropped. use std::collections::HashMap; use std::io::{BufRead, BufReader, Read, Seek, SeekFrom, Write}; @@ -465,6 +465,16 @@ impl russh_sftp::server::Handler for SftpHandler { Ok(ok(id)) } + async fn rename( + &mut self, + id: u32, + oldpath: String, + newpath: String, + ) -> Result { + std::fs::rename(self.path(&oldpath)?, self.path(&newpath)?).map_err(|e| io_status(&e))?; + Ok(ok(id)) + } + async fn rmdir(&mut self, id: u32, path: String) -> Result { std::fs::remove_dir(self.path(&path)?).map_err(|e| io_status(&e))?; Ok(ok(id)) @@ -532,6 +542,7 @@ fn ftp_session(stream: TcpStream, root: &Path, user: &str, password: &str) -> st let mut signed_in = false; let mut cwd = String::from("/"); let mut passive: Option = None; + let mut rename_from: Option = None; loop { let mut line = String::new(); if reader.read_line(&mut line)? == 0 { @@ -579,6 +590,27 @@ fn ftp_session(stream: TcpStream, root: &Path, user: &str, password: &str) -> st Some(Ok(())) => send(&format!("257 \"{arg}\" created"))?, _ => send("550 Cannot create")?, }, + "RMD" => match path(arg).map(std::fs::remove_dir) { + Some(Ok(())) => send("250 Removed")?, + _ => send("550 Cannot remove")?, + }, + "DELE" => match path(arg).map(std::fs::remove_file) { + Some(Ok(())) => send("250 Deleted")?, + _ => send("550 Cannot delete")?, + }, + "RNFR" => match path(arg).filter(|p| p.exists()) { + Some(p) => { + rename_from = Some(p); + send("350 Ready for RNTO")?; + } + None => send("550 No such file")?, + }, + "RNTO" => match (rename_from.take(), path(arg)) { + (Some(from), Some(to)) if std::fs::rename(&from, &to).is_ok() => { + send("250 Renamed")? + } + _ => send("550 Cannot rename")?, + }, "SIZE" => match path(arg).and_then(|p| std::fs::metadata(p).ok()) { Some(m) if m.is_file() => send(&format!("213 {}", m.len()))?, _ => send("550 No such file")?, diff --git a/crates/deploy/tests/remote.rs b/crates/deploy/tests/remote.rs new file mode 100644 index 0000000..d8cdc14 --- /dev/null +++ b/crates/deploy/tests/remote.rs @@ -0,0 +1,170 @@ +//! The remote browser, compare and sync (D2) against the local SFTP and +//! FTP test servers (127.0.0.1 only): list, read (text, binary, missing), +//! write, rename, new folder, recursive delete (never the root), compare a +//! folder, and sync with uploads and confirmed deletions. + +#![allow( + clippy::unwrap_used, + clippy::expect_used, + clippy::panic, + clippy::indexing_slicing +)] + +use std::path::Path; + +use lutra_deploy::browse::{self, RemoteText, Target}; +use lutra_deploy::known_hosts::{self, HostKey}; +use lutra_deploy::testserver::{FtpServer, SftpServer}; +use lutra_deploy::{AuthKind, Cancel, DiffStatus, Job, Monitor, Secret, Server, ServerKind, job}; + +const PASSWORD: &str = "Otter-Browse-Pa55!"; + +fn server(kind: ServerKind, port: u16) -> Server { + Server { + id: "t".into(), + name: "Test".into(), + kind, + host: "127.0.0.1".into(), + port: Some(port), + user: "lutra".into(), + root: "/www".into(), + auth: AuthKind::Password, + key_path: None, + mappings: vec![], + excluded: vec!["*.log".into()], + upload_on_save: false, + } +} + +fn job(server: Server, project: &Path, known: &Path) -> Job { + Job { + server, + project_root: project.to_path_buf(), + secret: Some(Secret::new(PASSWORD.into()).unwrap()), + known_hosts: known.to_path_buf(), + cancel: Cancel::new(), + monitor: Monitor::new(), + } +} + +/// Runs the whole browser, compare and sync scenario against one server. +fn scenario(j: &Job, remote: &Path) { + let project = &j.project_root; + std::fs::create_dir_all(project.join("src")).unwrap(); + std::fs::write(project.join("index.php"), " = browse::list(j, "") + .unwrap() + .into_iter() + .map(|e| e.name) + .collect(); + assert_eq!(names, ["src", "blob.bin", "index.php"]); + let a = browse::read(j, &Target::Mapped("src/a.php".into())).unwrap(); + assert_eq!(a.text.as_deref(), Some(" = + diffs.iter().map(|d| (d.path.clone(), d.status)).collect(); + assert_eq!( + seen, + [ + ("blob.bin".to_string(), DiffStatus::RemoteOnly), + ("src/a.php".to_string(), DiffStatus::Different), + ("src/new.php".to_string(), DiffStatus::LocalOnly), + ("src/old.php".to_string(), DiffStatus::RemoteOnly), + ] + ); + + let summary = job::sync( + j, + &["src/a.php".into(), "src/new.php".into()], + &["src/old.php".into()], + ) + .unwrap(); + assert_eq!((summary.files, summary.deleted, summary.failed), (2, 1, 0)); + assert!(!www.join("src/old.php").exists()); + assert!( + www.join("blob.bin").exists(), + "only confirmed files are deleted" + ); + let after = job::compare(j, &["src".into()]).unwrap(); + assert!(after.is_empty(), "{after:?}"); + let text = j + .monitor + .take_lines() + .into_iter() + .map(|l| l.message) + .collect::>() + .join("\n"); + assert!(text.contains("deleted /www/src/old.php")); + assert!(!text.contains(PASSWORD)); +} + +#[test] +fn sftp_browse_compare_and_sync() { + let remote = tempfile::tempdir().unwrap(); + let sftp = SftpServer::start(remote.path(), "lutra", Some(PASSWORD), None, 21).unwrap(); + let project = tempfile::tempdir().unwrap(); + let state = tempfile::tempdir().unwrap(); + let known = state.path().join("known_hosts"); + let s = server(ServerKind::Sftp, sftp.addr.port()); + known_hosts::trust( + &known, + &HostKey { + host: s.address(), + algorithm: sftp.algorithm.clone(), + fingerprint: sftp.fingerprint.clone(), + }, + ) + .unwrap(); + scenario(&job(s, project.path(), &known), remote.path()); +} + +#[test] +fn ftp_browse_compare_and_sync() { + let remote = tempfile::tempdir().unwrap(); + let ftp = FtpServer::start(remote.path(), "lutra", PASSWORD).unwrap(); + let project = tempfile::tempdir().unwrap(); + let known = project.path().join("unused"); + scenario( + &job( + server(ServerKind::Ftp, ftp.addr.port()), + project.path(), + &known, + ), + remote.path(), + ); +} diff --git a/crates/engine/src/cmd/deploy.rs b/crates/engine/src/cmd/deploy.rs index 17dade1..3a44168 100644 --- a/crates/engine/src/cmd/deploy.rs +++ b/crates/engine/src/cmd/deploy.rs @@ -29,6 +29,7 @@ use std::sync::mpsc; use std::sync::{Arc, Mutex, PoisonError}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; +use lutra_deploy::browse::{self, Target}; use lutra_deploy::known_hosts::{self, HostKey}; use lutra_deploy::secrets::account; use lutra_deploy::{ @@ -75,6 +76,7 @@ pub fn register(registry: &mut Registry) -> Result<(), EngineError> { registry.register(Box::new(CancelJob))?; registry.register(Box::new(Log))?; registry.register(Box::new(ClearLog))?; + super::deploy_remote::register(registry)?; Ok(()) } @@ -171,6 +173,9 @@ pub struct DeployState { next_id: u64, /// Uploads on save waiting for the slot, in order, without duplicates. queue: VecDeque, + /// Set while `deploy.upload` saves buffers first, so those saves queue + /// no upload on save of their own. + saving: bool, } impl Default for DeployState { @@ -182,10 +187,18 @@ impl Default for DeployState { log: VecDeque::new(), next_id: 1, queue: VecDeque::new(), + saving: false, } } } +impl State { + /// Whether no deployment job runs. + pub fn deploy_idle(&self) -> bool { + self.deploy.active.is_none() + } +} + impl DeployState { /// Uses `store` for passwords and passphrases instead of the keychain. pub fn set_secret_store(&mut self, store: Arc) { @@ -315,13 +328,29 @@ fn drain(state: &mut State) { /// What a job does. #[derive(Debug, Clone)] -enum Work { +pub(super) enum Work { /// Test the connection. Test, /// Upload these paths. Upload(Vec), /// Download these paths. Download(Vec), + /// List a browser folder. + Browse(String), + /// Read a file as text. + Read(Target), + /// Write a browser file. + Write(String, String), + /// Rename a browser path. + Rename(String, String), + /// Create a browser folder. + Mkdir(String), + /// Delete a browser path (confirmed). + Delete(String), + /// Compare project paths with the server. + Compare(Vec), + /// Upload these files and delete those (confirmed) on the server. + Sync(Vec, Vec), } impl Work { @@ -331,6 +360,13 @@ impl Work { Self::Test => "test", Self::Upload(_) => "upload", Self::Download(_) => "download", + Self::Browse(_) | Self::Read(_) => "browse", + Self::Write(..) => "save", + Self::Rename(..) => "rename", + Self::Mkdir(_) => "mkdir", + Self::Delete(_) => "delete", + Self::Compare(_) => "compare", + Self::Sync(..) => "sync", } } } @@ -431,7 +467,7 @@ fn spawn( /// Starts a job for a command and returns its pending outcome. The thread /// ignores a failed wake-up send: it only means the outcome was dropped /// because the host stopped waiting. -fn start( +pub(super) fn start( state: &mut State, command: &'static str, server_id: Option<&str>, @@ -444,11 +480,7 @@ fn start( let (tx, rx) = mpsc::channel(); let filled = Arc::clone(&slot); spawn(state, work, job, None, move |job, work| { - let value = match work { - Work::Test => test_value(job::test_connection(job)), - Work::Upload(paths) => summary_value(job::upload(job, paths)), - Work::Download(paths) => summary_value(job::download(job, paths)), - }; + let value = run_work(command, job, work); *filled.lock().unwrap_or_else(PoisonError::into_inner) = Some(value); let _ = tx.send(Ok(Value::Null)); })?; @@ -464,6 +496,44 @@ fn start( }))) } +/// Runs `work` on the job's thread and turns the result into the +/// command's value; the caller's mistakes (bad paths) become +/// `invalid_params` for `command`. +fn run_work(command: &'static str, job: &Job, work: &Work) -> Result { + let fail = |e: DeployError| engine_error(command, e); + match work { + Work::Test => test_value(job::test_connection(job)), + Work::Upload(paths) => summary_value(job::upload(job, paths)), + Work::Download(paths) => summary_value(job::download(job, paths)), + Work::Browse(rel) => { + let entries: Vec = browse::list(job, rel) + .map_err(fail)? + .into_iter() + .map(|e| json!({"name": e.name, "isDir": e.is_dir, "size": e.size})) + .collect(); + Ok(json!({"path": rel, "entries": entries})) + } + Work::Read(target) => { + let read = browse::read(job, target).map_err(fail)?; + Ok(json!({"text": read.text, "binary": read.binary, "tooLarge": read.too_large})) + } + Work::Write(rel, text) => browse::write(job, rel, text.as_bytes()) + .map(|()| json!({})) + .map_err(fail), + Work::Rename(from, to) => browse::rename(job, from, to) + .map(|()| json!({})) + .map_err(fail), + Work::Mkdir(rel) => browse::mkdir(job, rel).map(|()| json!({})).map_err(fail), + Work::Delete(rel) => browse::delete(job, rel) + .map(|n| json!({"deleted": n})) + .map_err(fail), + Work::Compare(paths) => job::compare(job, paths) + .map(|d| json!({"differences": d})) + .map_err(fail), + Work::Sync(upload, delete) => summary_value(job::sync(job, upload, delete)), + } +} + /// An upload or download summary as the command's value. fn summary_value(result: Result) -> Result { result @@ -563,7 +633,7 @@ fn start_queued(state: &mut State) { /// `file.saveAll`. A configuration that cannot be read is logged and /// otherwise ignored, so saving never fails because of deployment. pub fn saved(state: &mut State, path: &str) { - if state.project.is_none() || state.config.is_none() { + if state.project.is_none() || state.config.is_none() || state.deploy.saving { return; } let Ok((_, deployment)) = load(state, "file.save") else { @@ -1052,7 +1122,7 @@ impl Command for TrustHostKey { /// Params of `deploy.upload` and `deploy.download`. #[derive(Debug, Deserialize)] -#[serde(deny_unknown_fields)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] struct TransferParams { /// Project-relative (or absolute, inside the project) files or /// folders; `""` is the whole project. @@ -1060,10 +1130,52 @@ struct TransferParams { /// The server's id; the default server when absent. #[serde(default)] id: Option, + /// Upload only: save the dirty buffers under `paths` first (default + /// true). Ignored by download. + #[serde(default)] + save_first: Option, +} + +/// Saves every dirty buffer whose file lies under one of the +/// project-relative `paths` (`""` is the whole project), without queueing +/// uploads on save for them. +/// +/// # Errors +/// The first save that fails; the upload does not start then. +fn save_under(state: &mut State, paths: &[String]) -> Result<(), EngineError> { + let ids: Vec<_> = state + .buffers + .dirty_ids() + .into_iter() + .filter(|id| { + state.buffers.get(*id).is_some_and(|open| { + let rel = open.path.to_string_lossy().replace('\\', "/"); + paths.iter().any(|p| { + p.is_empty() + || rel == *p + || rel + .strip_prefix(p.as_str()) + .is_some_and(|rest| rest.starts_with('/')) + }) + }) + }) + .collect(); + state.deploy.saving = true; + let mut result = Ok(()); + for id in ids { + if let Err(e) = super::file::save_buffer(state, "deploy.upload", id) { + result = Err(EngineError::Failed(format!( + "saving before the upload failed, so nothing was uploaded: {e}" + ))); + break; + } + } + state.deploy.saving = false; + result } /// Turns client paths into project-relative ones. -fn relative_paths( +pub(super) fn relative_paths( state: &State, command: &str, given: &[String], @@ -1097,7 +1209,7 @@ impl Command for Upload { label: "Deployment: Upload to Server", menu_path: None, default_shortcut: None, - params: "{ paths: [project-relative file or folder, \"\" for the whole project], id?: server id (default server when absent) }; returns { files, bytes, skipped, failed }; progress as deployProgress, lines as deployLog; deploy.cancel stops it", + params: "{ paths: [project-relative file or folder, \"\" for the whole project], id?: server id (default server when absent), saveFirst?: boolean (default true: save the dirty buffers under paths first) }; returns { files, bytes, skipped, failed, deleted }; progress as deployProgress, lines as deployLog; deploy.cancel stops it", } } @@ -1109,6 +1221,9 @@ impl Command for Upload { let command = self.spec().id; let p: TransferParams = parse(command, params)?; let paths = relative_paths(state, command, &p.paths)?; + if state.deploy.active.is_none() && p.save_first.unwrap_or(true) { + save_under(state, &paths)?; + } start(state, command, p.id.as_deref(), Work::Upload(paths)) } } diff --git a/crates/engine/src/cmd/deploy_remote.rs b/crates/engine/src/cmd/deploy_remote.rs new file mode 100644 index 0000000..9e33b18 --- /dev/null +++ b/crates/engine/src/cmd/deploy_remote.rs @@ -0,0 +1,413 @@ +//! Remote browser, compare and sync commands (C9 D2). They share the job +//! slot of [`super::deploy`]: each runs as a pending outcome on a +//! `lutra-deploy` thread, one at a time. +//! +//! **Browser paths** are relative to the server's root folder with `/` +//! (`""` is the root); absolute paths and `..` are `invalid_params`. +//! +//! **Nothing is deleted on the server without an explicit confirmation:** +//! `deploy.deleteRemote` needs `confirm: true`, and `deploy.sync` needs +//! `confirmDelete: true` whenever its `delete` list is not empty. Without +//! it they fail with `invalid_params` before connecting. + +use serde::Deserialize; +use serde_json::Value; + +use super::deploy::{Work, relative_paths, start}; +use super::params::parse; +use crate::{Command, CommandSpec, EngineError, Outcome, Registry, State}; +use lutra_deploy::browse::Target; + +/// Longest text `deploy.writeRemote` accepts. +const MAX_WRITE: usize = 4 * 1024 * 1024; + +/// Registers the remote `deploy.*` commands. +/// +/// # Errors +/// [`EngineError::Internal`] if an id is taken. +pub fn register(registry: &mut Registry) -> Result<(), EngineError> { + registry.register(Box::new(Browse))?; + registry.register(Box::new(ReadRemote))?; + registry.register(Box::new(WriteRemote))?; + registry.register(Box::new(RenameRemote))?; + registry.register(Box::new(MkdirRemote))?; + registry.register(Box::new(DeleteRemote))?; + registry.register(Box::new(Compare))?; + registry.register(Box::new(Sync))?; + Ok(()) +} + +/// Ids of this module's commands. +#[cfg(test)] +pub(crate) const COMMAND_IDS: &[&str] = &[ + "deploy.browse", + "deploy.compare", + "deploy.deleteRemote", + "deploy.mkdirRemote", + "deploy.readRemote", + "deploy.renameRemote", + "deploy.sync", + "deploy.writeRemote", +]; + +/// Whether a job may start: a project and a free slot. +fn idle(state: &State) -> bool { + state.has_project() && state.deploy_idle() +} + +/// Params naming a browser path. +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct PathParams { + /// The browser path. + #[serde(default)] + path: String, + /// The server's id; the default server when absent. + #[serde(default)] + id: Option, +} + +/// `deploy.browse`. +struct Browse; + +impl Command for Browse { + fn spec(&self) -> &CommandSpec { + &CommandSpec { + id: "deploy.browse", + label: "Deployment: List Server Folder", + menu_path: None, + default_shortcut: None, + params: "{ path?: folder relative to the server's root (\"\" for the root), id?: server id }; returns { path, entries: [{ name, isDir, size? }] } folders first", + } + } + + fn enabled(&self, state: &State) -> bool { + idle(state) + } + + fn run(&self, state: &mut State, params: Value) -> Result { + let p: PathParams = parse(self.spec().id, params)?; + start(state, self.spec().id, p.id.as_deref(), Work::Browse(p.path)) + } +} + +/// Params of `deploy.readRemote`. +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +struct ReadParams { + /// A project-relative path, mapped to the server. + #[serde(default)] + path: Option, + /// A browser path, relative to the server's root. + #[serde(default)] + remote_path: Option, + /// The server's id; the default server when absent. + #[serde(default)] + id: Option, +} + +/// `deploy.readRemote`. +struct ReadRemote; + +impl Command for ReadRemote { + fn spec(&self) -> &CommandSpec { + &CommandSpec { + id: "deploy.readRemote", + label: "Deployment: Read Server File", + menu_path: None, + default_shortcut: None, + params: "{ path: project-relative file (mapped) | remotePath: file relative to the server's root, id?: server id }; returns { text: string|null (null when missing), binary, tooLarge } (at most 4 MiB)", + } + } + + fn enabled(&self, state: &State) -> bool { + idle(state) + } + + fn run(&self, state: &mut State, params: Value) -> Result { + let command = self.spec().id; + let p: ReadParams = parse(command, params)?; + let target = match (p.path, p.remote_path) { + (Some(path), None) => { + let rel = relative_paths(state, command, &[path])?; + Target::Mapped(rel.into_iter().next().unwrap_or_default()) + } + (None, Some(remote)) => Target::Browser(remote), + _ => { + return Err(EngineError::invalid_params( + command, + "give exactly one of path and remotePath", + )); + } + }; + start(state, command, p.id.as_deref(), Work::Read(target)) + } +} + +/// Params of `deploy.writeRemote`. +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +struct WriteParams { + /// The browser path of the file. + remote_path: String, + /// Its new text. + text: String, + /// The server's id; the default server when absent. + #[serde(default)] + id: Option, +} + +/// `deploy.writeRemote`. +struct WriteRemote; + +impl Command for WriteRemote { + fn spec(&self) -> &CommandSpec { + &CommandSpec { + id: "deploy.writeRemote", + label: "Deployment: Save Server File", + menu_path: None, + default_shortcut: None, + params: "{ remotePath: file relative to the server's root, text: at most 4 MiB, id?: server id }; writes the file on the server (creating its folder); returns {}", + } + } + + fn enabled(&self, state: &State) -> bool { + idle(state) + } + + fn run(&self, state: &mut State, params: Value) -> Result { + let command = self.spec().id; + let p: WriteParams = parse(command, params)?; + if p.text.len() > MAX_WRITE || p.remote_path.trim().is_empty() { + return Err(EngineError::invalid_params( + command, + "remotePath must name a file and text may hold at most 4 MiB", + )); + } + start( + state, + command, + p.id.as_deref(), + Work::Write(p.remote_path, p.text), + ) + } +} + +/// Params of `deploy.renameRemote`. +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct RenameParams { + /// The browser path to rename. + from: String, + /// Its new browser path. + to: String, + /// The server's id; the default server when absent. + #[serde(default)] + id: Option, +} + +/// `deploy.renameRemote`. +struct RenameRemote; + +impl Command for RenameRemote { + fn spec(&self) -> &CommandSpec { + &CommandSpec { + id: "deploy.renameRemote", + label: "Deployment: Rename on Server", + menu_path: None, + default_shortcut: None, + params: "{ from, to: paths relative to the server's root, id?: server id }; returns {}", + } + } + + fn enabled(&self, state: &State) -> bool { + idle(state) + } + + fn run(&self, state: &mut State, params: Value) -> Result { + let command = self.spec().id; + let p: RenameParams = parse(command, params)?; + if p.from.trim().is_empty() || p.to.trim().is_empty() { + return Err(EngineError::invalid_params( + command, + "from and to must name paths", + )); + } + start(state, command, p.id.as_deref(), Work::Rename(p.from, p.to)) + } +} + +/// `deploy.mkdirRemote`. +struct MkdirRemote; + +impl Command for MkdirRemote { + fn spec(&self) -> &CommandSpec { + &CommandSpec { + id: "deploy.mkdirRemote", + label: "Deployment: New Folder on Server", + menu_path: None, + default_shortcut: None, + params: "{ path: new folder relative to the server's root, id?: server id }; creates it and its parents; returns {}", + } + } + + fn enabled(&self, state: &State) -> bool { + idle(state) + } + + fn run(&self, state: &mut State, params: Value) -> Result { + let command = self.spec().id; + let p: PathParams = parse(command, params)?; + if p.path.trim().is_empty() { + return Err(EngineError::invalid_params( + command, + "path must name the new folder", + )); + } + start(state, command, p.id.as_deref(), Work::Mkdir(p.path)) + } +} + +/// Params of `deploy.deleteRemote`. +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct DeleteParams { + /// The browser path to delete. + path: String, + /// The user confirmed the deletion. + #[serde(default)] + confirm: bool, + /// The server's id; the default server when absent. + #[serde(default)] + id: Option, +} + +/// `deploy.deleteRemote`. +struct DeleteRemote; + +impl Command for DeleteRemote { + fn spec(&self) -> &CommandSpec { + &CommandSpec { + id: "deploy.deleteRemote", + label: "Deployment: Delete on Server", + menu_path: None, + default_shortcut: None, + params: "{ path: file or folder relative to the server's root (never the root), confirm: true (required: the user agreed), id?: server id }; a folder goes with everything inside; returns { deleted: count }", + } + } + + fn enabled(&self, state: &State) -> bool { + idle(state) + } + + fn run(&self, state: &mut State, params: Value) -> Result { + let command = self.spec().id; + let p: DeleteParams = parse(command, params)?; + if !p.confirm { + return Err(EngineError::invalid_params( + command, + "deleting on the server needs confirm: true after the user agreed", + )); + } + start(state, command, p.id.as_deref(), Work::Delete(p.path)) + } +} + +/// Params of `deploy.compare`. +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct CompareParams { + /// Project-relative files or folders; `""` is the whole project. + paths: Vec, + /// The server's id; the default server when absent. + #[serde(default)] + id: Option, +} + +/// `deploy.compare`. +struct Compare; + +impl Command for Compare { + fn spec(&self) -> &CommandSpec { + &CommandSpec { + id: "deploy.compare", + label: "Deployment: Compare with Server", + menu_path: None, + default_shortcut: None, + params: "{ paths: [project-relative file or folder, \"\" for the whole project], id?: server id }; returns { differences: [{ path, status: localOnly|remoteOnly|different, localSize?, remoteSize? }] } sorted by path; equal files are left out", + } + } + + fn enabled(&self, state: &State) -> bool { + idle(state) + } + + fn run(&self, state: &mut State, params: Value) -> Result { + let command = self.spec().id; + let p: CompareParams = parse(command, params)?; + let paths = relative_paths(state, command, &p.paths)?; + start(state, command, p.id.as_deref(), Work::Compare(paths)) + } +} + +/// Params of `deploy.sync`. +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +struct SyncParams { + /// Project-relative files to upload. + #[serde(default)] + upload: Vec, + /// Project-relative files to delete on the server. + #[serde(default)] + delete: Vec, + /// The user confirmed the deletions. + #[serde(default)] + confirm_delete: bool, + /// The server's id; the default server when absent. + #[serde(default)] + id: Option, +} + +/// `deploy.sync`. +struct Sync; + +impl Command for Sync { + fn spec(&self) -> &CommandSpec { + &CommandSpec { + id: "deploy.sync", + label: "Deployment: Sync with Server", + menu_path: None, + default_shortcut: None, + params: "{ upload?: [project-relative files], delete?: [project-relative files to delete on the server], confirmDelete: true (required when delete is not empty), id?: server id }; returns { files, bytes, skipped, failed, deleted }", + } + } + + fn enabled(&self, state: &State) -> bool { + idle(state) + } + + fn run(&self, state: &mut State, params: Value) -> Result { + let command = self.spec().id; + let p: SyncParams = parse(command, params)?; + if !p.delete.is_empty() && !p.confirm_delete { + return Err(EngineError::invalid_params( + command, + "deleting on the server needs confirmDelete: true after the user agreed", + )); + } + if p.upload.is_empty() && p.delete.is_empty() { + return Err(EngineError::invalid_params(command, "nothing to sync")); + } + let upload = if p.upload.is_empty() { + Vec::new() + } else { + relative_paths(state, command, &p.upload)? + }; + let delete = if p.delete.is_empty() { + Vec::new() + } else { + relative_paths(state, command, &p.delete)? + }; + start(state, command, p.id.as_deref(), Work::Sync(upload, delete)) + } +} diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index d93a635..5905bea 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -112,6 +112,19 @@ fn save(state: &mut State, command: &str, id: BufferId) -> Result Result { + save(state, command, id) +} + /// Params of `file.save`. #[derive(Deserialize)] #[serde(deny_unknown_fields)] diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index 916e2d3..0706c22 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -3,6 +3,7 @@ mod app; mod buffer; pub mod deploy; +mod deploy_remote; mod file; pub mod git; pub mod git_blame; @@ -98,6 +99,7 @@ pub(crate) const BUILTIN_COMMAND_IDS: &[&[&str]] = &[ app::COMMAND_IDS, buffer::COMMAND_IDS, deploy::COMMAND_IDS, + deploy_remote::COMMAND_IDS, file::COMMAND_IDS, git::COMMAND_IDS, git_blame::COMMAND_IDS, diff --git a/crates/engine/tests/deploy.rs b/crates/engine/tests/deploy.rs index 0a57f57..4781f40 100644 --- a/crates/engine/tests/deploy.rs +++ b/crates/engine/tests/deploy.rs @@ -384,3 +384,122 @@ fn bad_params_and_no_project() { Err(EngineError::Disabled(_)) )); } + +#[test] +fn remote_browser_compare_sync_and_save_first() { + let tmp = tempfile::tempdir().unwrap(); + let remote = tmp.path().join("remote"); + std::fs::create_dir_all(remote.join("www/public")).unwrap(); + std::fs::write(remote.join("www/public/old.php"), " **Status:** Deployment v1 (C9 D1, owner decision D27): servers per project, upload, download, upload on save, test connection, host keys, Deployment log. Remote browser, compare and sync follow in D2 · **Last updated:** 2026-11-06 +> **Status:** Deployment v1 (C9 D1, owner decision D27): servers per project, upload, download, upload on save, test connection, host keys, Deployment log. v2 (C9 D2): Remote Host browser, compare with the server, sync with a preview, save before upload · **Last updated:** 2026-11-06 Lutra uploads a PHP project to a server and downloads files back, the way people deploy shared hosting and small servers every day. @@ -41,14 +41,29 @@ Uploads and downloads never ask about a key; they fail with a message pointing t - **Project tree:** right-click a file or folder › **Upload to Server** / **Download from Server** (default server). - **Tools › Deployment:** Upload Current File, Download Current File, Upload Project, Test Connection, Deployment Log. - The same actions are in the command palette. Lutra assigns no default shortcuts; bind them in the keymap. -- Uploads send what is on disk; save first. Downloads replace the local files. +- An upload first saves the open, unsaved files it covers, so the server gets what the editor shows. Downloads replace the local files. - While a job runs, the status bar shows it with a Cancel button. One job runs at a time; uploads on save wait for the running one. - Every file, skip and error goes to the **Deployment** log in the bottom panel (newest 1,000 lines). A failing file is logged and the job goes on; a lost connection or a refused sign-in stops it. Each error says what to do. +## Remote Host + +**Tools › Deployment › Remote Host** opens the server's folders in the bottom panel (the default server; choose another in the toolbar). Paths are relative to the server's root folder; the browser never leaves it. + +- Click a folder to expand it, a file to open it. Files open **read-only**; **Edit** makes the text editable and **Upload** writes it back. Files that are not text, or larger than 4 MiB, are not shown. +- **Rename** and **Delete on Server** are on each row; **New Folder** goes into the selected folder. Delete always asks first, names what goes (a folder with everything inside it), and only the red button deletes. The root folder cannot be deleted. + +## Compare and sync + +- **Compare with Server** on a file (project tree, or Tools › Deployment › Compare Current File with Server) opens the diff viewer: the server's copy on the left (read-only), your working copy on the right (editable as usual). +- On a folder, or **Sync Project with Server…**, Lutra lists every file that differs: only in the project, only on the server, or changed (sizes first, then contents up to 8 MiB per file; larger files of equal size count as equal). Excluded and unmapped files are left out. +- The preview selects the uploads (new and changed files). Files only on the server would be **deleted on the server**; they are never selected for you, and once you select one, Sync stays disabled until you tick "I understand that … files will be deleted on the server". Sync goes from the project to the server only; to take a server change into the project, use Download. + ## For agents and scripts -The `deploy.*` engine commands (`deploy.servers`, `deploy.saveServer`, `deploy.setSecret`, `deploy.testConnection`, `deploy.trustHostKey`, `deploy.upload`, `deploy.download`, `deploy.cancel`, `deploy.log`, …) work over the control channel and MCP like every command; see `docs/architecture.md` › Deployment. Their results never contain a secret. +The `deploy.*` engine commands (`deploy.servers`, `deploy.saveServer`, `deploy.setSecret`, `deploy.testConnection`, `deploy.trustHostKey`, `deploy.upload`, `deploy.download`, `deploy.browse`, `deploy.readRemote`, `deploy.writeRemote`, `deploy.renameRemote`, `deploy.mkdirRemote`, `deploy.deleteRemote`, `deploy.compare`, `deploy.sync`, `deploy.cancel`, `deploy.log`, …) work over the control channel and MCP like every command; see `docs/architecture.md` › Deployment. Their results never contain a secret. `deploy.deleteRemote` refuses without `confirm: true`, and `deploy.sync` refuses deletions without `confirmDelete: true`: an agent must have asked the user. -## Not yet (D2) +## Not yet -A remote file browser, opening and editing remote files, compare with the server, and sync with a preview. +- Remote files open in the Remote Host viewer, not as editor tabs with highlighting. +- FTPS accepts only certificates the system trusts; servers with a self-signed certificate cannot be pinned yet. +- Linux has no keychain store yet. diff --git a/docs/gaps.md b/docs/gaps.md index 36e5fd8..136563b 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -22,7 +22,7 @@ Every known shortfall, ranked. This is the work list: unless the owner gives a t | G14 | Localization: English and German interface: ~~English message catalog for UI strings~~ (M1.11), engine messages (`EngineError.message`) as message keys, language switch, plurals, German catalog | later | ~38 h | | G15 | Database tools, HTTP client, Docker and remote | later | ~430 h | | G16 | Plug-ins and ecosystem | later | ~120 h | -| G17 | Deployment: **v1 done (C9 D1)**: SFTP, FTP, FTPS and folder servers per project, path mappings, excluded paths, upload/download of files and folders, upload on save (off by default), test connection, host-key check, keychain secrets, Deployment log. Open (D2): remote browser, edit remote files, compare with server, sync with preview | M7 | ~40 h | +| G17 | Deployment: **v1 + v2 done (C9 D1, D2)**: SFTP, FTP, FTPS and folder servers per project, path mappings, excluded paths, upload/download, upload on save, save before upload, host-key check, keychain secrets, Deployment log, Remote Host browser (view, edit and upload, rename, delete after a question, new folder), compare (file diff, folder list), sync with preview and confirmed deletions. Open: remote files as highlighted editor tabs, FTPS certificate pinning, Linux keychain | M7 | ~12 h | | G18 | Editor productivity: Local History, live and file templates, postfix completion, code generation, intention actions, auto import, scratch files, macros, compare files/folders, TODO view, language injections, code style/formatter | M6–M7 | ~400 h | | G19 | Remote development and Dev Containers | M9 | ~200 h | | G20 | AI features (chat, inline prompts, commit messages); MCP server is G7/M3 | M9 | ~60 h | @@ -55,6 +55,7 @@ G6 progress: M3.2 landed the LSP client library in `crates/lsp`: JSON-RPC framin | Date | Change | Summary | |---|---|---| +| 2026-11-06 | patch | G17: deployment v2 (C9 D2): remote browser, compare, sync | | 2026-11-06 | patch | G17: deployment v1 (C9 D1); remote browser, compare and sync left for D2 | | 2026-11-06 | minor | G3: more themes, theme import, editor font settings (C9 T1) | | 2026-11-01 | patch | G8: chunk staging, unstaging and revert from the gutter and the diff viewer (C8 C3) | diff --git a/ui/src/commands/modals.ts b/ui/src/commands/modals.ts index 15cc04b..1198abc 100644 --- a/ui/src/commands/modals.ts +++ b/ui/src/commands/modals.ts @@ -21,7 +21,7 @@ * are exclusive modals too. So is the branches popup (M4.5), and so are * "Clone Repository…" and "Manage Remotes…" (M4.10), the merge * dialog (M4.8) and the stash dialog (M4.9), the deployment servers - * dialog (G17) and the theme picker (C9 T1). + * dialog (G17), the sync preview (C9 D2) and the theme picker (C9 T1). */ import { defineStore } from "pinia"; import { ref, watch } from "vue"; @@ -40,6 +40,7 @@ export type ModalId = | "clone" | "remotes" | "deployment" + | "deploySync" | "merge" | "stash" | "themes"; diff --git a/ui/src/commands/uiCommands.ts b/ui/src/commands/uiCommands.ts index c73847f..758c172 100644 --- a/ui/src/commands/uiCommands.ts +++ b/ui/src/commands/uiCommands.ts @@ -21,6 +21,9 @@ export interface UiCommandSpec { /** The frontend's UI commands. */ export const UI_COMMANDS: readonly UiCommandSpec[] = [ + { id: "deployment.browse", labelKey: "command.deployment.browse", menuPath: "Tools/Deployment/Remote Host" }, + { id: "deployment.compare", labelKey: "command.deployment.compare", menuPath: "Tools/Deployment/Compare Current File with Server" }, + { id: "deployment.sync", labelKey: "command.deployment.sync", menuPath: "Tools/Deployment/Sync Project with Server…" }, { id: "deployment.download", labelKey: "command.deployment.download", menuPath: "Tools/Deployment/Download Current File" }, { id: "deployment.servers", labelKey: "command.deployment.servers", menuPath: "Tools/Deployment/Servers…" }, { id: "deployment.showLog", labelKey: "command.deployment.showLog", menuPath: "Tools/Deployment/Deployment Log" }, diff --git a/ui/src/components/deploy/DeployStatusItem.vue b/ui/src/components/deploy/DeployStatusItem.vue index d672b92..5550d7b 100644 --- a/ui/src/components/deploy/DeployStatusItem.vue +++ b/ui/src/components/deploy/DeployStatusItem.vue @@ -14,25 +14,43 @@ * - `deployment.uploadProject`: the whole project; * - `deployment.testConnection`: opens the servers dialog and tests the * default server, so a host key can be checked there; - * - `deployment.servers`: opens the servers dialog. + * - `deployment.servers`: opens the servers dialog; + * - `deployment.compare {path?, kind?}` (C9 D2): a file (the active one by + * default) opens a server tab in the diff viewer; `kind: "dir"` compares + * the folder and opens the sync preview; + * - `deployment.sync`: compares the whole project and opens the sync + * preview. * All are enabled with a project and while no job runs. It also mounts - * the dialog. + * the dialog and the sync preview, and resets the remote browser when the + * project closes. */ import { LoaderCircle, X } from "@lucide/vue"; -import { computed, onBeforeUnmount, onMounted } from "vue"; +import { computed, onBeforeUnmount, onMounted, watch } from "vue"; import { useCommandsStore } from "../../commands/store"; import { t } from "../../i18n"; import { useEditorStore } from "../../stores/editor"; import { useNotificationsStore } from "../../stores/notifications"; import { useProjectStore } from "../../stores/project"; import DeploymentDialog from "./DeploymentDialog.vue"; +import SyncDialog from "./SyncDialog.vue"; import { useDeployStore } from "./deploy"; +import { useRemoteBrowserStore } from "./remoteBrowser"; const deploy = useDeployStore(); const commands = useCommandsStore(); const editor = useEditorStore(); const project = useProjectStore(); const notifications = useNotificationsStore(); +const remoteBrowser = useRemoteBrowserStore(); + +watch( + () => project.root, + (root) => { + if (root === null) { + remoteBrowser.reset(); + } + }, +); /** The running job's text, or null while none runs. */ const progressText = computed(() => { @@ -130,6 +148,23 @@ onMounted(() => { }, enabled: idle, }), + commands.provide("deployment.compare", { + run: async (params) => { + const path = pathOf(params); + const kind = (params as { kind?: unknown } | null)?.kind; + if (path === null) { + return; + } + await withTarget(() => + kind === "dir" ? remoteBrowser.compareFolders([path]) : remoteBrowser.compareFile(path), + ); + }, + enabled: idle, + }), + commands.provide("deployment.sync", { + run: () => withTarget(() => remoteBrowser.compareFolders([""])), + enabled: idle, + }), commands.provide("deployment.servers", { run: () => deploy.showDialog(), enabled: () => project.root !== null, @@ -175,6 +210,7 @@ onBeforeUnmount(() => { + diff --git a/ui/src/components/deploy/SyncDialog.vue b/ui/src/components/deploy/SyncDialog.vue new file mode 100644 index 0000000..0621957 --- /dev/null +++ b/ui/src/components/deploy/SyncDialog.vue @@ -0,0 +1,295 @@ + + + + + diff --git a/ui/src/components/deploy/remoteBrowser.ts b/ui/src/components/deploy/remoteBrowser.ts new file mode 100644 index 0000000..11cd39f --- /dev/null +++ b/ui/src/components/deploy/remoteBrowser.ts @@ -0,0 +1,549 @@ +/** + * The remote browser, compare and sync (C9 D2), through the engine's + * `deploy.browse`, `readRemote`, `writeRemote`, `renameRemote`, + * `mkdirRemote`, `deleteRemote`, `compare` and `sync` commands. + * + * - **Tree:** folders load when expanded; paths are relative to the + * server's root (`""` is the root). The server is the default one unless + * one is chosen. + * - **Files** open in the tool window's viewer, read-only first; Edit + * makes the text editable and Upload writes it back to the server. + * - **Delete** happens only after the row's own question was answered; + * only then is `confirm: true` sent. + * - **Compare:** a file opens a server tab in the diff viewer; a folder (or + * the project) opens the sync preview with every differing file. + * Uploads are preselected; deletions on the server never are, and Sync + * with deletions needs the extra confirmation checkbox, which is what + * sends `confirmDelete: true`. + */ +import { defineStore } from "pinia"; +import { computed, ref, shallowRef } from "vue"; +import { runWaiting, type JsonValue } from "../../ipc"; +import { useNotificationsStore } from "../../stores/notifications"; +import { useDiffStore } from "../vcs/diff/diff"; +import { filesText, useDeployStore } from "./deploy"; + +/** Most entries kept from one listing. */ +export const MAX_ENTRIES = 5000; + +/** One entry of a server folder. */ +export interface RemoteEntry { + /** The name. */ + name: string; + /** Whether it is a folder. */ + isDir: boolean; + /** Its size, when known. */ + size: number | null; +} + +/** A loaded (or loading) server folder. */ +export interface DirState { + /** Its entries, folders first. */ + entries: RemoteEntry[]; + /** Whether the listing runs. */ + loading: boolean; + /** Why it failed, or null. */ + error: string | null; +} + +/** The file shown in the viewer. */ +export interface RemoteFile { + /** Its browser path. */ + path: string; + /** The text being shown or edited. */ + text: string; + /** The text as read from the server. */ + original: string; + /** Whether the text can be edited. */ + editing: boolean; + /** Why it cannot be shown, or null. */ + notice: string | null; +} + +/** One differing file of the sync preview. */ +export interface SyncItem { + /** Project-relative path. */ + path: string; + /** How it differs. */ + status: "localOnly" | "remoteOnly" | "different"; + /** Its local size. */ + localSize: number | null; + /** Its size on the server. */ + remoteSize: number | null; + /** Whether Sync acts on it (upload, or delete for `remoteOnly`). */ + selected: boolean; +} + +/** + * Joins a browser folder and a name. + * + * @param dir - the folder, "" for the root. + * @param name - the entry's name. + */ +export function childPath(dir: string, name: string): string { + return dir === "" ? name : `${dir}/${name}`; +} + +/** + * The folder part of a browser path. + * + * @param path - the path. + */ +export function parentPath(path: string): string { + const slash = path.lastIndexOf("/"); + return slash < 0 ? "" : path.slice(0, slash); +} + +/** + * Whether a name typed for a new entry is usable. + * + * @param name - the typed name. + */ +export function validName(name: string): boolean { + const n = name.trim(); + if (n === "" || n === "." || n === ".." || n.includes("/") || n.includes("\\")) { + return false; + } + for (let i = 0; i < n.length; i += 1) { + if (n.charCodeAt(i) < 0x20) { + return false; + } + } + return true; +} + +/** + * Reads a `deploy.browse` answer; malformed entries are dropped. + * + * @param raw - untrusted. + */ +export function toEntries(raw: unknown): RemoteEntry[] { + const list = typeof raw === "object" && raw !== null ? (raw as Record).entries : null; + if (!Array.isArray(list)) { + return []; + } + const out: RemoteEntry[] = []; + for (const item of (list as unknown[]).slice(0, MAX_ENTRIES)) { + const e = typeof item === "object" && item !== null ? (item as Record) : {}; + if (typeof e.name !== "string" || !validName(e.name)) { + continue; + } + out.push({ + name: e.name, + isDir: e.isDir === true, + size: typeof e.size === "number" && Number.isFinite(e.size) ? e.size : null, + }); + } + return out; +} + +/** + * Reads a `deploy.compare` answer into preview items: uploads selected, + * deletions not. + * + * @param raw - untrusted. + */ +export function toSyncItems(raw: unknown): SyncItem[] { + const list = typeof raw === "object" && raw !== null ? (raw as Record).differences : null; + if (!Array.isArray(list)) { + return []; + } + const out: SyncItem[] = []; + for (const item of (list as unknown[]).slice(0, MAX_ENTRIES)) { + const d = typeof item === "object" && item !== null ? (item as Record) : {}; + const status = d.status; + if (typeof d.path !== "string" || (status !== "localOnly" && status !== "remoteOnly" && status !== "different")) { + continue; + } + out.push({ + path: d.path, + status, + localSize: typeof d.localSize === "number" ? d.localSize : null, + remoteSize: typeof d.remoteSize === "number" ? d.remoteSize : null, + selected: status !== "remoteOnly", + }); + } + return out; +} + +/** The remote browser store. */ +export const useRemoteBrowserStore = defineStore("remoteBrowser", () => { + const notifications = useNotificationsStore(); + const deploy = useDeployStore(); + + /** Whether the tool window is shown. */ + const visible = ref(false); + /** Whether the bottom panel is expanded while it is shown. */ + const expanded = ref(true); + /** The chosen server, or null for the default one. */ + const serverId = ref(null); + /** Loaded folders by browser path. */ + const dirs = ref>({}); + /** Expanded folders. */ + const open = ref([]); + /** The selected path, or null. */ + const selected = ref(null); + /** The file in the viewer, or null. */ + const file = shallowRef(null); + /** The sync preview's items; null while the preview is closed. */ + const syncItems = ref(null); + /** The paths the preview compared. */ + const syncPaths = ref([]); + /** Whether the user confirmed the deletions of the preview. */ + const confirmDelete = ref(false); + /** Whether compare or sync runs. */ + const syncing = ref(false); + /** Why the last browser or preview action failed, or null. */ + const error = ref(null); + + /** The server's name as shown. */ + const serverName = computed(() => { + const id = serverId.value ?? deploy.defaultServer; + return deploy.servers.find((s) => s.id === id)?.name ?? ""; + }); + /** Deletions the preview would make. */ + const deletions = computed(() => (syncItems.value ?? []).filter((i) => i.selected && i.status === "remoteOnly")); + /** Whether Sync may run now. */ + const canSync = computed( + () => + (syncItems.value ?? []).some((i) => i.selected) && + (deletions.value.length === 0 || confirmDelete.value) && + !syncing.value, + ); + + /** The params every command gets: the chosen server. */ + function base(): Record { + return serverId.value === null ? {} : { id: serverId.value }; + } + + /** + * Runs one browser command; a failure lands in {@link error}. + * + * @param command - the command. + * @param params - its params (the server is added). + * @returns its value, or null when it failed. + */ + async function call(command: string, params: Record): Promise { + const result = await runWaiting(command, { ...base(), ...params }); + if (!result.ok) { + error.value = result.error.message; + return null; + } + error.value = null; + return result.value; + } + + /** + * Loads (or reloads) a folder. + * + * @param path - the browser folder. + */ + async function loadDir(path: string): Promise { + dirs.value = { ...dirs.value, [path]: { entries: dirs.value[path]?.entries ?? [], loading: true, error: null } }; + const result = await runWaiting("deploy.browse", { ...base(), path }); + dirs.value = { + ...dirs.value, + [path]: result.ok + ? { entries: toEntries(result.value), loading: false, error: null } + : { entries: [], loading: false, error: result.error.message }, + }; + } + + /** Shows the tool window and reads the root. */ + async function show(): Promise { + visible.value = true; + expanded.value = true; + if (deploy.servers.length === 0) { + await deploy.load(); + } + if (dirs.value[""] === undefined) { + await loadDir(""); + } + } + + /** Hides the tool window. */ + function hide(): void { + visible.value = false; + } + + /** + * Chooses the server and reads its root. + * + * @param id - the server, or null for the default one. + */ + async function setServer(id: string | null): Promise { + serverId.value = id; + dirs.value = {}; + open.value = []; + file.value = null; + selected.value = null; + await loadDir(""); + } + + /** Reads every loaded folder again. */ + async function refresh(): Promise { + const loaded = ["", ...open.value]; + dirs.value = {}; + for (const path of loaded) { + await loadDir(path); + } + } + + /** + * Expands or collapses a folder. + * + * @param path - the browser folder. + */ + async function toggle(path: string): Promise { + selected.value = path; + if (open.value.includes(path)) { + open.value = open.value.filter((p) => p !== path && !p.startsWith(`${path}/`)); + return; + } + open.value = [...open.value, path]; + if (dirs.value[path] === undefined) { + await loadDir(path); + } + } + + /** + * Opens a server file in the viewer, read-only. + * + * @param path - the browser path. + */ + async function openFile(path: string): Promise { + selected.value = path; + const value = await call("deploy.readRemote", { remotePath: path }); + if (value === null) { + return; + } + const v = typeof value === "object" && !Array.isArray(value) ? value : {}; + const text = typeof v.text === "string" ? v.text : null; + const notice = v.tooLarge === true ? "tooLarge" : v.binary === true ? "binary" : text === null ? "missing" : null; + file.value = { path, text: text ?? "", original: text ?? "", editing: false, notice }; + } + + /** Makes the viewer's text editable. */ + function edit(): void { + if (file.value && file.value.notice === null) { + file.value = { ...file.value, editing: true }; + } + } + + /** + * Changes the viewer's text while editing. + * + * @param text - the new text. + */ + function setText(text: string): void { + if (file.value?.editing) { + file.value = { ...file.value, text }; + } + } + + /** + * Writes the edited text to the server. + * + * @returns whether it was uploaded. + */ + async function upload(): Promise { + const f = file.value; + if (!f?.editing) { + return false; + } + const value = await call("deploy.writeRemote", { remotePath: f.path, text: f.text }); + if (value === null) { + return false; + } + file.value = { ...f, original: f.text, editing: false }; + notifications.notify({ level: "info", messageKey: "notification.deploy.remoteSaved", params: { path: f.path } }); + return true; + } + + /** Closes the viewer (an unsaved edit is dropped). */ + function closeFile(): void { + file.value = null; + } + + /** + * Renames an entry within its folder. + * + * @param path - the browser path. + * @param name - the new name. + */ + async function rename(path: string, name: string): Promise { + if (!validName(name)) { + return false; + } + const to = childPath(parentPath(path), name.trim()); + const value = await call("deploy.renameRemote", { from: path, to }); + if (value === null) { + return false; + } + await loadDir(parentPath(path)); + return true; + } + + /** + * Creates a folder. + * + * @param parent - the browser folder it goes in. + * @param name - its name. + */ + async function newFolder(parent: string, name: string): Promise { + if (!validName(name)) { + return false; + } + const value = await call("deploy.mkdirRemote", { path: childPath(parent, name.trim()) }); + if (value === null) { + return false; + } + await loadDir(parent); + return true; + } + + /** + * Deletes an entry on the server; callers ask first. + * + * @param path - the browser path. + */ + async function remove(path: string): Promise { + const value = await call("deploy.deleteRemote", { path, confirm: true }); + if (value === null) { + return false; + } + if (file.value?.path === path || file.value?.path.startsWith(`${path}/`)) { + file.value = null; + } + open.value = open.value.filter((p) => p !== path && !p.startsWith(`${path}/`)); + await loadDir(parentPath(path)); + return true; + } + + /** + * Compares one project file with the server in the diff viewer. + * + * @param path - project-relative path. + */ + async function compareFile(path: string): Promise { + await useDiffStore().openRemote(path, { serverId: serverId.value, server: serverName.value }); + } + + /** + * Compares project folders with the server and opens the sync preview. + * + * @param paths - project-relative folders, "" for the whole project. + */ + async function compareFolders(paths: string[]): Promise { + if (deploy.servers.length === 0) { + await deploy.load(); + } + syncPaths.value = paths; + confirmDelete.value = false; + syncItems.value = []; + syncing.value = true; + try { + const value = await call("deploy.compare", { paths }); + syncItems.value = value === null ? [] : toSyncItems(value); + } finally { + syncing.value = false; + } + } + + /** Closes the sync preview. */ + function closeSync(): void { + syncItems.value = null; + error.value = null; + } + + /** + * Runs the previewed sync: uploads the selected local and differing + * files and, only with {@link confirmDelete}, deletes the selected + * server-only files. + * + * @returns whether it ran without failures. + */ + async function runSync(): Promise { + const items = syncItems.value ?? []; + const upload = items.filter((i) => i.selected && i.status !== "remoteOnly").map((i) => i.path); + const del = deletions.value.map((i) => i.path); + if (!canSync.value) { + return false; + } + syncing.value = true; + try { + const params: Record = { upload, delete: del }; + if (del.length > 0) { + params.confirmDelete = true; + } + const value = await call("deploy.sync", params); + if (value === null) { + return false; + } + const v = typeof value === "object" && !Array.isArray(value) ? value : {}; + const count = (key: string): number => { + const n = v[key]; + return typeof n === "number" ? n : 0; + }; + notifications.notify({ + level: count("failed") > 0 ? "warning" : "info", + messageKey: "notification.deploy.synced", + params: { files: filesText(count("files")), deleted: filesText(count("deleted")), server: serverName.value }, + }); + syncItems.value = null; + if (visible.value) { + await refresh(); + } + return count("failed") === 0; + } finally { + syncing.value = false; + } + } + + /** Forgets everything when the project closes. */ + function reset(): void { + dirs.value = {}; + open.value = []; + file.value = null; + selected.value = null; + syncItems.value = null; + serverId.value = null; + } + + return { + visible, + expanded, + serverId, + dirs, + open, + selected, + file, + syncItems, + syncPaths, + confirmDelete, + syncing, + error, + serverName, + deletions, + canSync, + loadDir, + show, + hide, + setServer, + refresh, + toggle, + openFile, + edit, + setText, + upload, + closeFile, + rename, + newFolder, + remove, + compareFile, + compareFolders, + closeSync, + runSync, + reset, + }; +}); diff --git a/ui/src/components/layout/MainLayout.vue b/ui/src/components/layout/MainLayout.vue index 0d6ae1b..73bbdcc 100644 --- a/ui/src/components/layout/MainLayout.vue +++ b/ui/src/components/layout/MainLayout.vue @@ -17,7 +17,8 @@ * * The bottom panel ({@link BottomPanel}) holds the Find, Terminal and * Problems tool windows (and the Deployment log, G17, which appears with - * `deployment.showLog`), as tabs in its header while more than one is + * `deployment.showLog`, and the Remote Host browser, C9 D2, with + * `deployment.browse`), as tabs in its header while more than one is * shown. Find appears with the UI command `find.open` (`Mod+Alt+F`), * Terminal with `terminal.open` (`Mod+Shift+T`, M3.6), Problems with * `problems.open` (`Mod+Alt+P`, M3.3); all are supplied here so they work @@ -62,6 +63,8 @@ import LogToolWindow from "../vcs/log/LogToolWindow.vue"; import { SHOW_HISTORY_COMMAND, SHOW_LOG_COMMAND, useLogStore } from "../vcs/log/log"; import StashDialog from "../vcs/stash/StashDialog.vue"; import DeploymentLogToolWindow from "../deploy/DeploymentLogToolWindow.vue"; +import RemoteBrowserToolWindow from "../deploy/RemoteBrowserToolWindow.vue"; +import { useRemoteBrowserStore } from "../deploy/remoteBrowser"; import { useDeployStore } from "../deploy/deploy"; import { SHOW_COMMIT_COMMAND, TOGGLE_BLAME_COMMAND, setCommitOpener, toggleBlame } from "../editor/blame"; import { SHOW_CHUNK_COMMAND, openChunkPopup } from "../editor/chunkPopup"; @@ -117,11 +120,12 @@ const nav = useNavStore(); const changes = useChangesStore(); const vcsLog = useLogStore(); const deploy = useDeployStore(); +const remoteBrowser = useRemoteBrowserStore(); const editor = useEditorStore(); const project = useProjectStore(); /** Tool windows of the bottom panel. */ -type BottomTool = "find" | "terminal" | "problems" | "references" | "changes" | "log" | "deployment"; +type BottomTool = "find" | "terminal" | "problems" | "references" | "changes" | "log" | "deployment" | "remote"; /** The bottom tool window last chosen. */ const bottomTool = ref("find"); /** Bottom tool windows that are shown, in tab order. */ @@ -134,6 +138,7 @@ const bottomTools = computed(() => { if (changes.visible) tools.push({ id: "changes", title: t("vcs.changes.toolWindow.title") }); if (vcsLog.visible) tools.push({ id: "log", title: t("vcs.log.toolWindow.title") }); if (deploy.visible) tools.push({ id: "deployment", title: t("deploy.log.title") }); + if (remoteBrowser.visible) tools.push({ id: "remote", title: t("deploy.remote.title") }); return tools; }); /** The active bottom tool window: the chosen one if shown, else the first. */ @@ -155,7 +160,9 @@ const bottomStore = computed(() => ? vcsLog : bottomActive.value === "deployment" ? deploy - : find, + : bottomActive.value === "remote" + ? remoteBrowser + : find, ); /** Expansion of the panel, kept per tool window by its store. */ const bottomOpen = computed({ @@ -178,7 +185,8 @@ function chooseBottom(id: string): void { id === "references" || id === "changes" || id === "log" || - id === "deployment" + id === "deployment" || + id === "remote" ) { bottomTool.value = id; } @@ -288,6 +296,13 @@ onMounted(() => { }, enabled: () => project.root !== null && activeView() !== null, }), + commands.provide("deployment.browse", { + run: () => { + bottomTool.value = "remote"; + return remoteBrowser.show(); + }, + enabled: () => project.root !== null, + }), commands.provide("deployment.showLog", { run: () => { bottomTool.value = "deployment"; @@ -395,6 +410,10 @@ onBeforeUnmount(() => { v-if="deploy.visible" v-show="bottomActive === 'deployment'" /> + diff --git a/ui/src/components/project/TreeContextMenu.vue b/ui/src/components/project/TreeContextMenu.vue index 6f2c4fe..4b0a093 100644 --- a/ui/src/components/project/TreeContextMenu.vue +++ b/ui/src/components/project/TreeContextMenu.vue @@ -3,8 +3,10 @@ * The project tree's context menu (M4.3). For a file: Open, Show Diff * (`vcs.showDiff {path}`) and Show History (`vcs.showHistory {path}`, * M4.6), the Git items dimmed while their command is disabled. For a file - * and a folder: Upload to Server and Download from Server - * (`deployment.upload` / `deployment.download {path}`, G17), dimmed while + * and a folder: Upload to Server, Compare with Server (a diff for a file, + * the sync preview for a folder, C9 D2) and Download from Server + * (`deployment.upload` / `deployment.compare` / `deployment.download + * {path}`, G17), dimmed while * no project is open or a deployment job runs. * * Follows the WAI-ARIA menu pattern: it takes the focus when it opens, @@ -65,6 +67,12 @@ const deployItems = computed(() => [ enabled: commands.isEnabled("deployment.upload"), run: () => commands.execute("deployment.upload", { path: props.path }), }, + { + id: "compareServer", + label: t("project.tree.menu.compareServer"), + enabled: commands.isEnabled("deployment.compare"), + run: () => commands.execute("deployment.compare", { path: props.path, kind: props.kind ?? "file" }), + }, { id: "download", label: t("project.tree.menu.download"), diff --git a/ui/src/components/vcs/diff/DiffView.vue b/ui/src/components/vcs/diff/DiffView.vue index 2f76775..148fe20 100644 --- a/ui/src/components/vcs/diff/DiffView.vue +++ b/ui/src/components/vcs/diff/DiffView.vue @@ -99,6 +99,9 @@ const caption = computed(() => { if (tab.commit) { return t("vcs.diff.captionCommit", { path: tab.path, hash: tab.commit.hash.slice(0, SHORT_HASH) }); } + if (tab.remote) { + return t("vcs.diff.captionRemote", { path: tab.path, server: tab.remote.server }); + } return refFor(tab.staged) === "HEAD" ? t("vcs.diff.captionHead", { path: tab.path }) : t("vcs.diff.captionIndex", { path: tab.path }); @@ -275,7 +278,7 @@ onBeforeUnmount(() => { {{ caption }}
diff --git a/ui/src/components/vcs/diff/diff.ts b/ui/src/components/vcs/diff/diff.ts index e756617..ab5f814 100644 --- a/ui/src/components/vcs/diff/diff.ts +++ b/ui/src/components/vcs/diff/diff.ts @@ -31,6 +31,11 @@ * (right, `git.showAt {path, rev: hash}`) with its first parent (left, the * old path of a rename). Both sides are read-only texts; nothing is * re-read on `gitChanged` (commits do not change). + * - **Server tabs (C9 D2):** {@link openRemote} compares a file on a + * deployment server (left, read-only, `deploy.readRemote {path, id?}`, + * which answers like `git.show`) with the working copy (right, the + * ordinary buffer). Nothing is re-read on `gitChanged`; reopening the + * tab reads the server again. * - **Untrusted input:** `git.show` results are checked field by field. */ import { defineStore } from "pinia"; @@ -83,6 +88,26 @@ export interface DiffTab { name: string; /** For a commit tab: what it compares; absent for working-copy diffs. */ commit?: DiffCommit; + /** For a server tab: the deployment server compared with. */ + remote?: DiffRemote; +} + +/** The server a server tab compares the working copy with. */ +export interface DiffRemote { + /** The server's id, or null for the default server. */ + serverId: string | null; + /** Its name, for the caption. */ + server: string; +} + +/** + * The key of a server tab. + * + * @param path - project-relative path. + * @param serverId - the server, or null for the default one. + */ +export function remoteDiffKey(path: string, serverId: string | null): string { + return `remote:${serverId ?? ""}:${path}`; } /** What a diff tab shows. */ @@ -282,6 +307,17 @@ export const useDiffStore = defineStore("diff", () => { * @returns the checked result, or the error text. */ async function readLeft(tab: DiffTab): Promise { + if (tab.remote) { + const params: Record = { path: tab.path }; + if (tab.remote.serverId !== null) { + params.id = tab.remote.serverId; + } + const remote = await runWaiting("deploy.readRemote", params); + if (!remote.ok) { + return remote.error.message; + } + return toShowResult(remote.value) ?? t("common.error.unexpectedResult", { command: "deploy.readRemote" }); + } const result = await runWaiting("git.show", { path: tab.path, ref: refFor(tab.staged) }); if (!result.ok) { return result.error.message; @@ -448,6 +484,24 @@ export const useDiffStore = defineStore("diff", () => { } } + /** + * Opens (or activates and reloads) the comparison of a file with its + * copy on a deployment server. + * + * @param path - project-relative path. + * @param remote - the server. + */ + async function openRemote(path: string, remote: DiffRemote): Promise { + const key = remoteDiffKey(path, remote.serverId); + let tab = tabs.value.find((t) => t.key === key); + if (!tab) { + tab = { key, path, staged: false, name: baseName(path), remote }; + tabs.value.push(tab); + } + activate(key); + await load(tab); + } + /** * Re-reads the left side of every loaded text tab; a changed text * replaces the left document (`gitChanged`). @@ -456,7 +510,7 @@ export const useDiffStore = defineStore("diff", () => { await Promise.all( tabs.value.map(async (tab) => { const before = contents.value[tab.key]; - if (before?.phase !== "ready" || tab.commit) { + if (before?.phase !== "ready" || tab.commit || tab.remote) { return; } const generation = generations.get(tab.key); @@ -569,6 +623,7 @@ export const useDiffStore = defineStore("diff", () => { deactivate, open, openAtCommit, + openRemote, showDiff, refreshLeft, close, diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json index d4f3e09..370ab5e 100644 --- a/ui/src/i18n/en.json +++ b/ui/src/i18n/en.json @@ -1,8 +1,11 @@ { "app.statusBar.version": "{name} {version}", + "command.deployment.browse": "Remote Host", + "command.deployment.compare": "Compare Current File with Server", "command.deployment.download": "Download Current File from Server", "command.deployment.servers": "Deployment Servers…", "command.deployment.showLog": "Deployment Log", + "command.deployment.sync": "Sync Project with Server…", "command.deployment.testConnection": "Test Deployment Connection", "command.deployment.upload": "Upload Current File to Server", "command.deployment.uploadProject": "Upload Project to Server", @@ -135,6 +138,36 @@ "deploy.operation.upload": "Uploading", "deploy.progress.files": "{operation} {done}/{total} · {server}", "deploy.progress.short": "{operation} · {server}", + "deploy.remote.binary": "This file is not text, so it is not shown.", + "deploy.remote.cancel": "Cancel", + "deploy.remote.close": "Close", + "deploy.remote.compareProject": "Compare Project…", + "deploy.remote.defaultServer": "Default server ({name})", + "deploy.remote.delete": "Delete on Server", + "deploy.remote.deleteQuestion": "Delete {path} on the server, with everything inside it? This cannot be undone.", + "deploy.remote.edit": "Edit", + "deploy.remote.loading": "Loading…", + "deploy.remote.missing": "This file no longer exists on the server.", + "deploy.remote.newFolder": "New Folder", + "deploy.remote.newFolderIn": "New folder in {path}:", + "deploy.remote.ok": "OK", + "deploy.remote.readOnly": "read-only", + "deploy.remote.refresh": "Refresh", + "deploy.remote.rename": "Rename", + "deploy.remote.renameTo": "New name:", + "deploy.remote.server": "Server", + "deploy.remote.title": "Remote Host", + "deploy.remote.tooLarge": "This file is larger than 4 MiB, so it is not shown.", + "deploy.remote.upload": "Upload", + "deploy.sync.comparing": "Comparing with the server…", + "deploy.sync.confirmDelete": "I understand that {count} files will be deleted on the server.", + "deploy.sync.deleteOnServer": "delete on the server", + "deploy.sync.equal": "The project and the server are the same.", + "deploy.sync.run": "Sync", + "deploy.sync.showDiff": "Show Diff", + "deploy.sync.title": "Sync with {server}", + "deploy.sync.uploadChanged": "upload (changed)", + "deploy.sync.uploadNew": "upload (new)", "editor.assist.kind.class": "Class", "editor.assist.kind.color": "Colour", "editor.assist.kind.constant": "Constant", @@ -258,6 +291,8 @@ "notification.deploy.downloaded": "Downloaded {files} from {server}.", "notification.deploy.noServer": "No default deployment server yet. Add one, or choose the default.", "notification.deploy.partly": "Transferred {files}, but {failed} failed ({server}); see the Deployment log.", + "notification.deploy.remoteSaved": "Uploaded {path}.", + "notification.deploy.synced": "Synced with {server}: uploaded {files}, deleted {deleted}.", "notification.deploy.uploadFailed": "Upload failed: {reason}", "notification.deploy.uploadOnSaveFailed": "Upload on save to {server} failed: {error}", "notification.deploy.uploaded": "Uploaded {files} to {server}.", @@ -344,6 +379,7 @@ "project.openFolder": "Open Folder…", "project.toolWindow.title": "Project", "project.tree.loading": "Loading…", + "project.tree.menu.compareServer": "Compare with Server", "project.tree.menu.download": "Download from Server", "project.tree.menu.label": "Actions for {name}", "project.tree.menu.open": "Open", @@ -521,6 +557,7 @@ "vcs.diff.captionCommit": "{path}: before (left) and after (right) commit {hash}", "vcs.diff.captionHead": "{path}: last commit (left) and working copy (right)", "vcs.diff.captionIndex": "{path}: staged version (left) and working copy (right)", + "vcs.diff.captionRemote": "{path}: on {server} (left) and working copy (right)", "vcs.diff.chunkHint": "Click a change marker in the gutter to stage, unstage or revert that chunk.", "vcs.diff.closeTab": "Close the diff of {name}", "vcs.diff.failed": "The diff cannot be shown: {reason}", diff --git a/ui/tests/deploy/RemoteBrowser.test.ts b/ui/tests/deploy/RemoteBrowser.test.ts new file mode 100644 index 0000000..57ba5f6 --- /dev/null +++ b/ui/tests/deploy/RemoteBrowser.test.ts @@ -0,0 +1,203 @@ +/** + * Tests of the remote browser, compare and sync (C9 D2): reading untrusted + * listings and comparisons, names; the Remote Host tool window (root, + * expanding a folder, a file read-only then edited and uploaded, rename, + * new folder, and delete only after its question); the sync preview + * (uploads preselected, deletions never, Sync blocked until the deletion + * is confirmed, `confirmDelete` sent only then); and the server diff tab. + * The engine is a fake behind the mocked Tauri `invoke` and `listen`. + */ +import { flushPromises, mount, type VueWrapper } from "@vue/test-utils"; +import { createPinia, setActivePinia, type Pinia } from "pinia"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +const invoke = vi.hoisted(() => vi.fn()); +const listen = vi.hoisted(() => vi.fn()); +vi.mock("@tauri-apps/api/core", () => ({ invoke })); +vi.mock("@tauri-apps/api/event", () => ({ listen })); + +import RemoteBrowserToolWindow from "../../src/components/deploy/RemoteBrowserToolWindow.vue"; +import SyncDialog from "../../src/components/deploy/SyncDialog.vue"; +import { + childPath, + parentPath, + toEntries, + toSyncItems, + useRemoteBrowserStore, + validName, +} from "../../src/components/deploy/remoteBrowser"; +import { useDiffStore } from "../../src/components/vcs/diff/diff"; + +interface Call { + command: string; + params: Record; +} + +let calls: Call[]; +let pinia: Pinia; +let mounted: VueWrapper[]; + +function callsOf(command: string): Call[] { + return calls.filter((c) => c.command === command); +} + +beforeEach(() => { + pinia = createPinia(); + setActivePinia(pinia); + calls = []; + mounted = []; + invoke.mockReset(); + listen.mockReset(); + listen.mockResolvedValue(() => undefined); + invoke.mockImplementation((cmd: string, args?: { command: string; params: Record }) => { + if ((cmd !== "engine_execute" && cmd !== "engine_execute_waiting") || !args) { + return Promise.resolve(null); + } + calls.push({ command: args.command, params: args.params }); + switch (args.command) { + case "deploy.servers": + return Promise.resolve({ servers: [{ id: "s1", name: "Staging", kind: "sftp" }], defaultServer: "s1" }); + case "deploy.browse": + return Promise.resolve( + args.params.path === "" + ? { entries: [{ name: "public", isDir: true }, { name: "index.php", isDir: false, size: 5 }, { name: "../x", isDir: false }] } + : { entries: [{ name: "app.php", isDir: false, size: 3 }] }, + ); + case "deploy.readRemote": + return Promise.resolve({ text: " { + for (const wrapper of mounted) { + wrapper.unmount(); + } + document.body.innerHTML = ""; +}); + +async function mountBrowser(): Promise { + const wrapper = mount(RemoteBrowserToolWindow, { attachTo: document.body, global: { plugins: [pinia] } }); + mounted.push(wrapper); + await useRemoteBrowserStore(pinia).show(); + await flushPromises(); + return wrapper; +} + +describe("reading the engine's answers", () => { + it("drops unsafe names and malformed differences", () => { + expect(toEntries({ entries: [{ name: "a", isDir: true }, { name: ".." }, { name: "x/y" }, null] })).toEqual([ + { name: "a", isDir: true, size: null }, + ]); + const items = toSyncItems({ + differences: [{ path: "a", status: "remoteOnly" }, { path: "b", status: "localOnly" }, { path: "c", status: "gone" }], + }); + expect(items.map((i) => [i.path, i.selected])).toEqual([ + ["a", false], + ["b", true], + ]); + expect(validName("ok.php")).toBe(true); + expect(validName("a\nb")).toBe(false); + expect(validName("..")).toBe(false); + expect(childPath("", "a")).toBe("a"); + expect(parentPath("a/b/c")).toBe("a/b"); + }); +}); + +describe("Remote Host tool window", () => { + it("lists the root, expands a folder and edits a file", async () => { + const wrapper = await mountBrowser(); + expect(wrapper.findAll("[data-test='remote-row']").map((r) => r.attributes("data-path"))).toEqual(["public", "index.php"]); + await wrapper.find("[data-path='public'] .remote__name").trigger("click"); + await flushPromises(); + expect(callsOf("deploy.browse").at(-1)?.params).toEqual({ path: "public" }); + expect(wrapper.find("[data-path='public/app.php']").exists()).toBe(true); + await wrapper.find("[data-path='index.php'] .remote__name").trigger("click"); + await flushPromises(); + expect(callsOf("deploy.readRemote")[0]?.params).toEqual({ remotePath: "index.php" }); + const text = wrapper.find("[data-test='remote-text']"); + expect(text.element.readOnly).toBe(true); + await wrapper.find("[data-test='remote-edit']").trigger("click"); + await text.setValue(" { + const wrapper = await mountBrowser(); + await wrapper.find("[data-path='index.php'] [data-test='remote-rename']").trigger("click"); + await wrapper.find("[data-test='remote-form-name']").setValue("home.php"); + await wrapper.find("[data-test='remote-form']").trigger("submit"); + await flushPromises(); + expect(callsOf("deploy.renameRemote")[0]?.params).toEqual({ from: "index.php", to: "home.php" }); + await wrapper.find("[data-test='remote-new-folder']").trigger("click"); + await wrapper.find("[data-test='remote-form-name']").setValue("cache"); + await wrapper.find("[data-test='remote-form']").trigger("submit"); + await flushPromises(); + expect(callsOf("deploy.mkdirRemote")[0]?.params).toEqual({ path: "cache" }); + await wrapper.find("[data-path='public'] [data-test='remote-delete']").trigger("click"); + await flushPromises(); + expect(callsOf("deploy.deleteRemote")).toHaveLength(0); + expect(wrapper.find("[data-test='remote-form']").text()).toContain("public"); + await wrapper.find("[data-test='remote-delete-confirm']").trigger("click"); + await flushPromises(); + expect(callsOf("deploy.deleteRemote")[0]?.params).toEqual({ path: "public", confirm: true }); + }); +}); + +describe("sync preview", () => { + it("needs the extra confirmation before deleting on the server", async () => { + const wrapper = mount(SyncDialog, { attachTo: document.body, global: { plugins: [pinia] } }); + mounted.push(wrapper); + const browser = useRemoteBrowserStore(pinia); + await browser.compareFolders([""]); + await flushPromises(); + expect(callsOf("deploy.compare")[0]?.params).toEqual({ paths: [""] }); + expect(wrapper.findAll("[data-test='sync-item']")).toHaveLength(3); + expect(wrapper.find("[data-test='sync-confirm']").exists()).toBe(false); + await wrapper.find("input[data-path='old.php']").setValue(true); + expect(wrapper.find("[data-test='sync-confirm']").exists()).toBe(true); + expect(wrapper.find("[data-test='sync-run']").attributes("disabled")).toBeDefined(); + await wrapper.find("[data-test='sync-confirm'] input").setValue(true); + await wrapper.find("[data-test='sync-run']").trigger("click"); + await flushPromises(); + expect(callsOf("deploy.sync")[0]?.params).toEqual({ + upload: ["a.php", "new.php"], + delete: ["old.php"], + confirmDelete: true, + }); + }); + + it("syncs uploads without confirmDelete when nothing is deleted", async () => { + const wrapper = mount(SyncDialog, { attachTo: document.body, global: { plugins: [pinia] } }); + mounted.push(wrapper); + await useRemoteBrowserStore(pinia).compareFolders(["src"]); + await flushPromises(); + await wrapper.find("[data-test='sync-run']").trigger("click"); + await flushPromises(); + expect(callsOf("deploy.sync")[0]?.params).toEqual({ upload: ["a.php", "new.php"], delete: [] }); + }); +}); + +describe("server diff tab", () => { + it("reads the server's side through deploy.readRemote", async () => { + const diff = useDiffStore(pinia); + void diff.openRemote("a.php", { serverId: "s1", server: "Staging" }); + await flushPromises(); + expect(callsOf("deploy.readRemote")[0]?.params).toEqual({ path: "a.php", id: "s1" }); + expect(diff.activeTab?.remote?.server).toBe("Staging"); + }); +}); diff --git a/ui/tests/vcs/DiffView.test.ts b/ui/tests/vcs/DiffView.test.ts index 02fa0b0..777f0e1 100644 --- a/ui/tests/vcs/DiffView.test.ts +++ b/ui/tests/vcs/DiffView.test.ts @@ -475,7 +475,7 @@ describe("project tree context menu", () => { await tree.find("[data-path='a.php']").trigger("contextmenu", { clientX: 40, clientY: 50 }); const menu = document.querySelector("[data-test=tree-menu]"); expect(menu).not.toBeNull(); - expect([...document.querySelectorAll("[data-test=tree-menu-item]")].map((item) => item.textContent.trim())).toEqual(["Open", "Show Diff", "Show History", "Upload to Server", "Download from Server"]); + expect([...document.querySelectorAll("[data-test=tree-menu-item]")].map((item) => item.textContent.trim())).toEqual(["Open", "Show Diff", "Show History", "Upload to Server", "Compare with Server", "Download from Server"]); (document.querySelector("[data-item=showDiff]") as HTMLElement).click(); await flushPromises(); await flushPromises();