Compare commits
3 commits
064f40839f
...
1c6c67194a
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1c6c67194a | ||
|
|
7601ce12f6 | ||
|
|
a8ad74755c |
31 changed files with 3340 additions and 59 deletions
|
|
@ -41,3 +41,7 @@ required-features = ["testserver"]
|
||||||
[[example]]
|
[[example]]
|
||||||
name = "testserver"
|
name = "testserver"
|
||||||
required-features = ["testserver"]
|
required-features = ["testserver"]
|
||||||
|
|
||||||
|
[[test]]
|
||||||
|
name = "remote"
|
||||||
|
required-features = ["testserver"]
|
||||||
|
|
|
||||||
296
crates/deploy/src/browse.rs
Normal file
296
crates/deploy/src/browse.rs
Normal file
|
|
@ -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<String>,
|
||||||
|
/// 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<String> {
|
||||||
|
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<T>(job: &Job, op: impl FnOnce(&mut dyn Remote) -> Result<T>) -> Result<T> {
|
||||||
|
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<Vec<Entry>> {
|
||||||
|
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<RemoteText> {
|
||||||
|
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<usize> {
|
||||||
|
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<usize> {
|
||||||
|
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"<?php").unwrap();
|
||||||
|
write(&j, "a/bin.dat", &[0, 1, 2]).unwrap();
|
||||||
|
let entries = list(&j, "a").unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
entries.iter().map(|e| e.name.as_str()).collect::<Vec<_>>(),
|
||||||
|
["b", "bin.dat"]
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
read(&j, &Target::Browser("a/b/x.php".into()))
|
||||||
|
.unwrap()
|
||||||
|
.text
|
||||||
|
.as_deref(),
|
||||||
|
Some("<?php")
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
read(&j, &Target::Browser("a/bin.dat".into()))
|
||||||
|
.unwrap()
|
||||||
|
.binary
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
read(&j, &Target::Browser("nope".into())).unwrap(),
|
||||||
|
RemoteText::default()
|
||||||
|
);
|
||||||
|
rename(&j, "a/b/x.php", "a/y.php").unwrap();
|
||||||
|
assert!(dir.path().join("a/y.php").is_file());
|
||||||
|
assert_eq!(delete(&j, "a").unwrap(), 4);
|
||||||
|
assert!(!dir.path().join("a").exists());
|
||||||
|
assert!(delete(&j, "").is_err());
|
||||||
|
assert!(list(&j, "../up").is_err());
|
||||||
|
assert!(list(&j, "/etc").is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -240,6 +240,24 @@ impl Remote for Ftp {
|
||||||
Ok(entries)
|
Ok(entries)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn remove_file(&mut self, path: &str) -> 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
|
/// Sends `QUIT`; a failure is ignored because the connection is
|
||||||
/// dropped right after.
|
/// dropped right after.
|
||||||
fn close(&mut self) {
|
fn close(&mut self) {
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,7 @@
|
||||||
//! Folder walks skip symbolic links to folders and the version-control
|
//! Folder walks skip symbolic links to folders and the version-control
|
||||||
//! folders `.git`, `.svn` and `.hg`, which are never deployed.
|
//! folders `.git`, `.svn` and `.hg`, which are never deployed.
|
||||||
|
|
||||||
use std::collections::BTreeSet;
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
use std::fs::File;
|
use std::fs::File;
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
use std::sync::{Arc, Mutex, PoisonError};
|
use std::sync::{Arc, Mutex, PoisonError};
|
||||||
|
|
@ -18,7 +18,7 @@ use serde::Serialize;
|
||||||
|
|
||||||
use crate::config::{Server, ServerKind, io_error};
|
use crate::config::{Server, ServerKind, io_error};
|
||||||
use crate::error::{DeployError, Result};
|
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::remote::{Cancel, Folder, Remote};
|
||||||
use crate::secrets::Secret;
|
use crate::secrets::Secret;
|
||||||
|
|
||||||
|
|
@ -56,7 +56,7 @@ pub struct LogLine {
|
||||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct Progress {
|
pub struct Progress {
|
||||||
/// `connecting`, `planning`, `transferring`.
|
/// `connecting`, `planning`, `comparing`, `transferring`.
|
||||||
pub phase: String,
|
pub phase: String,
|
||||||
/// The file being transferred, project-relative.
|
/// The file being transferred, project-relative.
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
|
@ -117,7 +117,7 @@ impl Monitor {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Adds a log line.
|
/// Adds a log line.
|
||||||
fn log(&self, level: Level, message: String) {
|
pub(crate) fn log(&self, level: Level, message: String) {
|
||||||
self.0
|
self.0
|
||||||
.lock()
|
.lock()
|
||||||
.unwrap_or_else(PoisonError::into_inner)
|
.unwrap_or_else(PoisonError::into_inner)
|
||||||
|
|
@ -156,6 +156,8 @@ pub struct Summary {
|
||||||
pub skipped: usize,
|
pub skipped: usize,
|
||||||
/// Files that failed.
|
/// Files that failed.
|
||||||
pub failed: usize,
|
pub failed: usize,
|
||||||
|
/// Files deleted on the server (sync only).
|
||||||
|
pub deleted: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// One planned file.
|
/// One planned file.
|
||||||
|
|
@ -427,25 +429,7 @@ fn walk_remote(
|
||||||
Some(false) => {
|
Some(false) => {
|
||||||
*skipped += 1;
|
*skipped += 1;
|
||||||
}
|
}
|
||||||
Some(true) if depth <= MAX_DEPTH => {
|
Some(true) => walk_remote_tree(job, remote, rel, &path, depth, plan)?,
|
||||||
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) => {}
|
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
@ -539,6 +523,266 @@ fn download_one(job: &Job, remote: &mut dyn Remote, file: &Planned) -> Result<u6
|
||||||
result.map(|()| bytes)
|
result.map(|()| bytes)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Adds the files below the remote folder `path` (the mapped folder of the
|
||||||
|
/// project-relative `rel`) to `plan`, from its listings: sizes come from
|
||||||
|
/// the server, excluded and unmapped entries are left out, and a child
|
||||||
|
/// that maps elsewhere is not followed here.
|
||||||
|
fn walk_remote_tree(
|
||||||
|
job: &Job,
|
||||||
|
remote: &mut dyn Remote,
|
||||||
|
rel: &str,
|
||||||
|
path: &str,
|
||||||
|
depth: usize,
|
||||||
|
plan: &mut Vec<Planned>,
|
||||||
|
) -> 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<u64>,
|
||||||
|
/// Its size on the server.
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub remote_size: Option<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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<bool> {
|
||||||
|
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<Vec<Difference>> {
|
||||||
|
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<String, Difference> = 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::<Vec<_>>())
|
||||||
|
})();
|
||||||
|
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<Summary> {
|
||||||
|
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<String> = 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)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
|
||||||
|
|
@ -9,13 +9,16 @@
|
||||||
//! - [`remote`]: the operations every transport offers (the extension
|
//! - [`remote`]: the operations every transport offers (the extension
|
||||||
//! point for the remote browser and compare of D2), and the folder
|
//! point for the remote browser and compare of D2), and the folder
|
||||||
//! transport; `sftp` and `ftp` are the network ones.
|
//! transport; `sftp` and `ftp` are the network ones.
|
||||||
//! - [`job`]: test connection, upload and download with progress, log and
|
//! - [`job`]: test connection, upload, download, compare and sync with
|
||||||
//! cancel.
|
//! 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`
|
//! Pure Rust: `russh` and `russh-sftp` for SFTP, `suppaftp` with `rustls`
|
||||||
//! for FTP and FTPS, `ring` for cryptography, `keyring` for the keychain.
|
//! 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.
|
//! No credential is ever written to a file, a log or an error message.
|
||||||
|
|
||||||
|
pub mod browse;
|
||||||
pub mod config;
|
pub mod config;
|
||||||
pub mod error;
|
pub mod error;
|
||||||
mod ftp;
|
mod ftp;
|
||||||
|
|
@ -31,6 +34,6 @@ pub mod testserver;
|
||||||
|
|
||||||
pub use config::{AuthKind, Deployment, Mapping, Server, ServerKind};
|
pub use config::{AuthKind, Deployment, Mapping, Server, ServerKind};
|
||||||
pub use error::{DeployError, Result};
|
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 remote::Cancel;
|
||||||
pub use secrets::{Keychain, MemoryStore, Secret, SecretStore};
|
pub use secrets::{Keychain, MemoryStore, Secret, SecretStore};
|
||||||
|
|
|
||||||
|
|
@ -86,7 +86,7 @@ pub fn is_excluded(server: &Server, path: &str) -> bool {
|
||||||
|
|
||||||
/// Joins remote path pieces with `/`, skipping empty ones. Keeps a leading
|
/// Joins remote path pieces with `/`, skipping empty ones. Keeps a leading
|
||||||
/// `/` of the first non-empty piece.
|
/// `/` of the first non-empty piece.
|
||||||
fn join(pieces: &[&str]) -> String {
|
pub(crate) fn join(pieces: &[&str]) -> String {
|
||||||
let mut out = String::new();
|
let mut out = String::new();
|
||||||
for piece in pieces.iter().filter(|p| !p.is_empty()) {
|
for piece in pieces.iter().filter(|p| !p.is_empty()) {
|
||||||
if out.is_empty() {
|
if out.is_empty() {
|
||||||
|
|
|
||||||
|
|
@ -115,6 +115,25 @@ pub trait Remote {
|
||||||
/// [`DeployError::Transfer`] when the server refuses.
|
/// [`DeployError::Transfer`] when the server refuses.
|
||||||
fn list(&mut self, path: &str) -> Result<Vec<Entry>>;
|
fn list(&mut self, path: &str) -> Result<Vec<Entry>>;
|
||||||
|
|
||||||
|
/// 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
|
/// Ends the session politely; failures are ignored because the
|
||||||
/// connection is dropped anyway.
|
/// connection is dropped anyway.
|
||||||
fn close(&mut self);
|
fn close(&mut self);
|
||||||
|
|
@ -247,6 +266,27 @@ impl Remote for Folder {
|
||||||
Ok(entries)
|
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) {}
|
fn close(&mut self) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -445,6 +445,24 @@ impl Remote for Sftp {
|
||||||
Ok(entries)
|
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:
|
/// Closes the SFTP channel and the connection. Failures are ignored:
|
||||||
/// the connection is dropped right after.
|
/// the connection is dropped right after.
|
||||||
fn close(&mut self) {
|
fn close(&mut self) {
|
||||||
|
|
|
||||||
|
|
@ -6,8 +6,8 @@
|
||||||
//! The SFTP server has a fixed Ed25519 host key (from a seed) and accepts
|
//! 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
|
//! 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,
|
//! 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
|
//! PWD, CWD, MKD, RMD, DELE, RNFR, RNTO, SIZE, PASV, STOR, RETR, LIST,
|
||||||
//! dropped.
|
//! NOOP, QUIT. Both stop when dropped.
|
||||||
|
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::io::{BufRead, BufReader, Read, Seek, SeekFrom, Write};
|
use std::io::{BufRead, BufReader, Read, Seek, SeekFrom, Write};
|
||||||
|
|
@ -465,6 +465,16 @@ impl russh_sftp::server::Handler for SftpHandler {
|
||||||
Ok(ok(id))
|
Ok(ok(id))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn rename(
|
||||||
|
&mut self,
|
||||||
|
id: u32,
|
||||||
|
oldpath: String,
|
||||||
|
newpath: String,
|
||||||
|
) -> Result<Status, Self::Error> {
|
||||||
|
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<Status, Self::Error> {
|
async fn rmdir(&mut self, id: u32, path: String) -> Result<Status, Self::Error> {
|
||||||
std::fs::remove_dir(self.path(&path)?).map_err(|e| io_status(&e))?;
|
std::fs::remove_dir(self.path(&path)?).map_err(|e| io_status(&e))?;
|
||||||
Ok(ok(id))
|
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 signed_in = false;
|
||||||
let mut cwd = String::from("/");
|
let mut cwd = String::from("/");
|
||||||
let mut passive: Option<TcpListener> = None;
|
let mut passive: Option<TcpListener> = None;
|
||||||
|
let mut rename_from: Option<PathBuf> = None;
|
||||||
loop {
|
loop {
|
||||||
let mut line = String::new();
|
let mut line = String::new();
|
||||||
if reader.read_line(&mut line)? == 0 {
|
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"))?,
|
Some(Ok(())) => send(&format!("257 \"{arg}\" created"))?,
|
||||||
_ => send("550 Cannot create")?,
|
_ => 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()) {
|
"SIZE" => match path(arg).and_then(|p| std::fs::metadata(p).ok()) {
|
||||||
Some(m) if m.is_file() => send(&format!("213 {}", m.len()))?,
|
Some(m) if m.is_file() => send(&format!("213 {}", m.len()))?,
|
||||||
_ => send("550 No such file")?,
|
_ => send("550 No such file")?,
|
||||||
|
|
|
||||||
170
crates/deploy/tests/remote.rs
Normal file
170
crates/deploy/tests/remote.rs
Normal file
|
|
@ -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"), "<?php // same").unwrap();
|
||||||
|
std::fs::write(project.join("src/a.php"), "<?php // local").unwrap();
|
||||||
|
std::fs::write(project.join("src/new.php"), "<?php // new").unwrap();
|
||||||
|
std::fs::write(project.join("src/x.log"), "ignored").unwrap();
|
||||||
|
let www = remote.join("www");
|
||||||
|
std::fs::create_dir_all(www.join("src")).unwrap();
|
||||||
|
std::fs::write(www.join("index.php"), "<?php // same").unwrap();
|
||||||
|
std::fs::write(www.join("src/a.php"), "<?php // SERVER").unwrap();
|
||||||
|
std::fs::write(www.join("src/old.php"), "<?php // old").unwrap();
|
||||||
|
std::fs::write(www.join("blob.bin"), [0u8, 159, 146, 150]).unwrap();
|
||||||
|
|
||||||
|
let names: Vec<String> = 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("<?php // SERVER"));
|
||||||
|
assert!(
|
||||||
|
browse::read(j, &Target::Browser("blob.bin".into()))
|
||||||
|
.unwrap()
|
||||||
|
.binary
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
browse::read(j, &Target::Browser("nope.php".into())).unwrap(),
|
||||||
|
RemoteText::default()
|
||||||
|
);
|
||||||
|
assert!(browse::read(j, &Target::Mapped("src/x.log".into())).is_err());
|
||||||
|
|
||||||
|
browse::write(j, "edited/e.php", b"<?php // edited").unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(www.join("edited/e.php")).unwrap(),
|
||||||
|
"<?php // edited"
|
||||||
|
);
|
||||||
|
browse::rename(j, "edited/e.php", "edited/f.php").unwrap();
|
||||||
|
assert!(www.join("edited/f.php").is_file());
|
||||||
|
browse::mkdir(j, "edited/deep/er").unwrap();
|
||||||
|
assert!(www.join("edited/deep/er").is_dir());
|
||||||
|
assert_eq!(browse::delete(j, "edited").unwrap(), 4);
|
||||||
|
assert!(!www.join("edited").exists());
|
||||||
|
assert!(browse::delete(j, "").is_err());
|
||||||
|
assert!(browse::list(j, "../..").is_err());
|
||||||
|
|
||||||
|
let diffs = job::compare(j, &[String::new()]).unwrap();
|
||||||
|
let seen: Vec<(String, DiffStatus)> =
|
||||||
|
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::<Vec<_>>()
|
||||||
|
.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(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
@ -29,6 +29,7 @@ use std::sync::mpsc;
|
||||||
use std::sync::{Arc, Mutex, PoisonError};
|
use std::sync::{Arc, Mutex, PoisonError};
|
||||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
|
use lutra_deploy::browse::{self, Target};
|
||||||
use lutra_deploy::known_hosts::{self, HostKey};
|
use lutra_deploy::known_hosts::{self, HostKey};
|
||||||
use lutra_deploy::secrets::account;
|
use lutra_deploy::secrets::account;
|
||||||
use lutra_deploy::{
|
use lutra_deploy::{
|
||||||
|
|
@ -75,6 +76,7 @@ pub fn register(registry: &mut Registry) -> Result<(), EngineError> {
|
||||||
registry.register(Box::new(CancelJob))?;
|
registry.register(Box::new(CancelJob))?;
|
||||||
registry.register(Box::new(Log))?;
|
registry.register(Box::new(Log))?;
|
||||||
registry.register(Box::new(ClearLog))?;
|
registry.register(Box::new(ClearLog))?;
|
||||||
|
super::deploy_remote::register(registry)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -171,6 +173,9 @@ pub struct DeployState {
|
||||||
next_id: u64,
|
next_id: u64,
|
||||||
/// Uploads on save waiting for the slot, in order, without duplicates.
|
/// Uploads on save waiting for the slot, in order, without duplicates.
|
||||||
queue: VecDeque<Queued>,
|
queue: VecDeque<Queued>,
|
||||||
|
/// Set while `deploy.upload` saves buffers first, so those saves queue
|
||||||
|
/// no upload on save of their own.
|
||||||
|
saving: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for DeployState {
|
impl Default for DeployState {
|
||||||
|
|
@ -182,10 +187,18 @@ impl Default for DeployState {
|
||||||
log: VecDeque::new(),
|
log: VecDeque::new(),
|
||||||
next_id: 1,
|
next_id: 1,
|
||||||
queue: VecDeque::new(),
|
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 {
|
impl DeployState {
|
||||||
/// Uses `store` for passwords and passphrases instead of the keychain.
|
/// Uses `store` for passwords and passphrases instead of the keychain.
|
||||||
pub fn set_secret_store(&mut self, store: Arc<dyn SecretStore>) {
|
pub fn set_secret_store(&mut self, store: Arc<dyn SecretStore>) {
|
||||||
|
|
@ -315,13 +328,29 @@ fn drain(state: &mut State) {
|
||||||
|
|
||||||
/// What a job does.
|
/// What a job does.
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
enum Work {
|
pub(super) enum Work {
|
||||||
/// Test the connection.
|
/// Test the connection.
|
||||||
Test,
|
Test,
|
||||||
/// Upload these paths.
|
/// Upload these paths.
|
||||||
Upload(Vec<String>),
|
Upload(Vec<String>),
|
||||||
/// Download these paths.
|
/// Download these paths.
|
||||||
Download(Vec<String>),
|
Download(Vec<String>),
|
||||||
|
/// 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<String>),
|
||||||
|
/// Upload these files and delete those (confirmed) on the server.
|
||||||
|
Sync(Vec<String>, Vec<String>),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Work {
|
impl Work {
|
||||||
|
|
@ -331,6 +360,13 @@ impl Work {
|
||||||
Self::Test => "test",
|
Self::Test => "test",
|
||||||
Self::Upload(_) => "upload",
|
Self::Upload(_) => "upload",
|
||||||
Self::Download(_) => "download",
|
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
|
/// 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
|
/// ignores a failed wake-up send: it only means the outcome was dropped
|
||||||
/// because the host stopped waiting.
|
/// because the host stopped waiting.
|
||||||
fn start(
|
pub(super) fn start(
|
||||||
state: &mut State,
|
state: &mut State,
|
||||||
command: &'static str,
|
command: &'static str,
|
||||||
server_id: Option<&str>,
|
server_id: Option<&str>,
|
||||||
|
|
@ -444,11 +480,7 @@ fn start(
|
||||||
let (tx, rx) = mpsc::channel();
|
let (tx, rx) = mpsc::channel();
|
||||||
let filled = Arc::clone(&slot);
|
let filled = Arc::clone(&slot);
|
||||||
spawn(state, work, job, None, move |job, work| {
|
spawn(state, work, job, None, move |job, work| {
|
||||||
let value = match work {
|
let value = run_work(command, job, 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)),
|
|
||||||
};
|
|
||||||
*filled.lock().unwrap_or_else(PoisonError::into_inner) = Some(value);
|
*filled.lock().unwrap_or_else(PoisonError::into_inner) = Some(value);
|
||||||
let _ = tx.send(Ok(Value::Null));
|
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<Value, EngineError> {
|
||||||
|
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<Value> = 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.
|
/// An upload or download summary as the command's value.
|
||||||
fn summary_value(result: Result<lutra_deploy::Summary, DeployError>) -> Result<Value, EngineError> {
|
fn summary_value(result: Result<lutra_deploy::Summary, DeployError>) -> Result<Value, EngineError> {
|
||||||
result
|
result
|
||||||
|
|
@ -563,7 +633,7 @@ fn start_queued(state: &mut State) {
|
||||||
/// `file.saveAll`. A configuration that cannot be read is logged and
|
/// `file.saveAll`. A configuration that cannot be read is logged and
|
||||||
/// otherwise ignored, so saving never fails because of deployment.
|
/// otherwise ignored, so saving never fails because of deployment.
|
||||||
pub fn saved(state: &mut State, path: &str) {
|
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;
|
return;
|
||||||
}
|
}
|
||||||
let Ok((_, deployment)) = load(state, "file.save") else {
|
let Ok((_, deployment)) = load(state, "file.save") else {
|
||||||
|
|
@ -1052,7 +1122,7 @@ impl Command for TrustHostKey {
|
||||||
|
|
||||||
/// Params of `deploy.upload` and `deploy.download`.
|
/// Params of `deploy.upload` and `deploy.download`.
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize)]
|
||||||
#[serde(deny_unknown_fields)]
|
#[serde(deny_unknown_fields, rename_all = "camelCase")]
|
||||||
struct TransferParams {
|
struct TransferParams {
|
||||||
/// Project-relative (or absolute, inside the project) files or
|
/// Project-relative (or absolute, inside the project) files or
|
||||||
/// folders; `""` is the whole project.
|
/// folders; `""` is the whole project.
|
||||||
|
|
@ -1060,10 +1130,52 @@ struct TransferParams {
|
||||||
/// The server's id; the default server when absent.
|
/// The server's id; the default server when absent.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
id: Option<String>,
|
id: Option<String>,
|
||||||
|
/// Upload only: save the dirty buffers under `paths` first (default
|
||||||
|
/// true). Ignored by download.
|
||||||
|
#[serde(default)]
|
||||||
|
save_first: Option<bool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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.
|
/// Turns client paths into project-relative ones.
|
||||||
fn relative_paths(
|
pub(super) fn relative_paths(
|
||||||
state: &State,
|
state: &State,
|
||||||
command: &str,
|
command: &str,
|
||||||
given: &[String],
|
given: &[String],
|
||||||
|
|
@ -1097,7 +1209,7 @@ impl Command for Upload {
|
||||||
label: "Deployment: Upload to Server",
|
label: "Deployment: Upload to Server",
|
||||||
menu_path: None,
|
menu_path: None,
|
||||||
default_shortcut: 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 command = self.spec().id;
|
||||||
let p: TransferParams = parse(command, params)?;
|
let p: TransferParams = parse(command, params)?;
|
||||||
let paths = relative_paths(state, command, &p.paths)?;
|
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))
|
start(state, command, p.id.as_deref(), Work::Upload(paths))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
413
crates/engine/src/cmd/deploy_remote.rs
Normal file
413
crates/engine/src/cmd/deploy_remote.rs
Normal file
|
|
@ -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<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `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<Outcome, EngineError> {
|
||||||
|
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<String>,
|
||||||
|
/// A browser path, relative to the server's root.
|
||||||
|
#[serde(default)]
|
||||||
|
remote_path: Option<String>,
|
||||||
|
/// The server's id; the default server when absent.
|
||||||
|
#[serde(default)]
|
||||||
|
id: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `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<Outcome, EngineError> {
|
||||||
|
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<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `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<Outcome, EngineError> {
|
||||||
|
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<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `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<Outcome, EngineError> {
|
||||||
|
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<Outcome, EngineError> {
|
||||||
|
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<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `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<Outcome, EngineError> {
|
||||||
|
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<String>,
|
||||||
|
/// The server's id; the default server when absent.
|
||||||
|
#[serde(default)]
|
||||||
|
id: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `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<Outcome, EngineError> {
|
||||||
|
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<String>,
|
||||||
|
/// Project-relative files to delete on the server.
|
||||||
|
#[serde(default)]
|
||||||
|
delete: Vec<String>,
|
||||||
|
/// The user confirmed the deletions.
|
||||||
|
#[serde(default)]
|
||||||
|
confirm_delete: bool,
|
||||||
|
/// The server's id; the default server when absent.
|
||||||
|
#[serde(default)]
|
||||||
|
id: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `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<Outcome, EngineError> {
|
||||||
|
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))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -112,6 +112,19 @@ fn save(state: &mut State, command: &str, id: BufferId) -> Result<u64, EngineErr
|
||||||
Ok(version)
|
Ok(version)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Writes buffer `id` to disk like `file.save`, for other commands (such as
|
||||||
|
/// `deploy.upload`, which saves before it uploads).
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// Like `file.save`.
|
||||||
|
pub(super) fn save_buffer(
|
||||||
|
state: &mut State,
|
||||||
|
command: &str,
|
||||||
|
id: BufferId,
|
||||||
|
) -> Result<u64, EngineError> {
|
||||||
|
save(state, command, id)
|
||||||
|
}
|
||||||
|
|
||||||
/// Params of `file.save`.
|
/// Params of `file.save`.
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
#[serde(deny_unknown_fields)]
|
#[serde(deny_unknown_fields)]
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@
|
||||||
mod app;
|
mod app;
|
||||||
mod buffer;
|
mod buffer;
|
||||||
pub mod deploy;
|
pub mod deploy;
|
||||||
|
mod deploy_remote;
|
||||||
mod file;
|
mod file;
|
||||||
pub mod git;
|
pub mod git;
|
||||||
pub mod git_blame;
|
pub mod git_blame;
|
||||||
|
|
@ -98,6 +99,7 @@ pub(crate) const BUILTIN_COMMAND_IDS: &[&[&str]] = &[
|
||||||
app::COMMAND_IDS,
|
app::COMMAND_IDS,
|
||||||
buffer::COMMAND_IDS,
|
buffer::COMMAND_IDS,
|
||||||
deploy::COMMAND_IDS,
|
deploy::COMMAND_IDS,
|
||||||
|
deploy_remote::COMMAND_IDS,
|
||||||
file::COMMAND_IDS,
|
file::COMMAND_IDS,
|
||||||
git::COMMAND_IDS,
|
git::COMMAND_IDS,
|
||||||
git_blame::COMMAND_IDS,
|
git_blame::COMMAND_IDS,
|
||||||
|
|
|
||||||
|
|
@ -384,3 +384,122 @@ fn bad_params_and_no_project() {
|
||||||
Err(EngineError::Disabled(_))
|
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"), "<?php // old").unwrap();
|
||||||
|
let ftp = FtpServer::start(&remote, "deploy", PASSWORD).unwrap();
|
||||||
|
let host = Host::new(tmp.path());
|
||||||
|
let proj = project(tmp.path());
|
||||||
|
host.run("project.open", json!({"path": proj})).unwrap();
|
||||||
|
host.run(
|
||||||
|
"deploy.saveServer",
|
||||||
|
json!({"server": {
|
||||||
|
"name": "Shared", "kind": "ftp", "host": "127.0.0.1", "port": ftp.addr.port(),
|
||||||
|
"user": "deploy", "root": "/www", "excluded": ["composer.json"],
|
||||||
|
}, "secret": PASSWORD}),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let listed = host
|
||||||
|
.run("deploy.browse", json!({"path": "public"}))
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(listed["entries"][0]["name"], "old.php");
|
||||||
|
assert_eq!(listed["entries"][0]["isDir"], false);
|
||||||
|
let bad = host
|
||||||
|
.run("deploy.browse", json!({"path": "../.."}))
|
||||||
|
.unwrap_err();
|
||||||
|
assert_eq!(bad.code(), "invalid_params", "{bad}");
|
||||||
|
|
||||||
|
host.run(
|
||||||
|
"deploy.writeRemote",
|
||||||
|
json!({"remotePath": "notes/n.txt", "text": "hi"}),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(remote.join("www/notes/n.txt")).unwrap(),
|
||||||
|
"hi"
|
||||||
|
);
|
||||||
|
let read = host
|
||||||
|
.run("deploy.readRemote", json!({"remotePath": "notes/n.txt"}))
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(read["text"], "hi");
|
||||||
|
let missing = host
|
||||||
|
.run("deploy.readRemote", json!({"path": "public/index.php"}))
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(missing["text"], Value::Null);
|
||||||
|
host.run(
|
||||||
|
"deploy.renameRemote",
|
||||||
|
json!({"from": "notes/n.txt", "to": "notes/m.txt"}),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
host.run("deploy.mkdirRemote", json!({"path": "empty/dir"}))
|
||||||
|
.unwrap();
|
||||||
|
assert!(remote.join("www/empty/dir").is_dir());
|
||||||
|
let refused = host
|
||||||
|
.run("deploy.deleteRemote", json!({"path": "notes"}))
|
||||||
|
.unwrap_err();
|
||||||
|
assert_eq!(refused.code(), "invalid_params");
|
||||||
|
assert!(
|
||||||
|
remote.join("www/notes/m.txt").exists(),
|
||||||
|
"nothing is deleted without confirm"
|
||||||
|
);
|
||||||
|
let deleted = host
|
||||||
|
.run(
|
||||||
|
"deploy.deleteRemote",
|
||||||
|
json!({"path": "notes", "confirm": true}),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(deleted["deleted"], 2);
|
||||||
|
|
||||||
|
let diffs = host
|
||||||
|
.run("deploy.compare", json!({"paths": ["public"]}))
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
diffs["differences"],
|
||||||
|
json!([
|
||||||
|
{"path": "public/index.php", "status": "localOnly", "localSize": 13},
|
||||||
|
{"path": "public/old.php", "status": "remoteOnly", "remoteSize": 12},
|
||||||
|
])
|
||||||
|
);
|
||||||
|
let unconfirmed = host
|
||||||
|
.run(
|
||||||
|
"deploy.sync",
|
||||||
|
json!({"upload": ["public/index.php"], "delete": ["public/old.php"]}),
|
||||||
|
)
|
||||||
|
.unwrap_err();
|
||||||
|
assert_eq!(unconfirmed.code(), "invalid_params");
|
||||||
|
assert!(remote.join("www/public/old.php").exists());
|
||||||
|
let synced = host
|
||||||
|
.run(
|
||||||
|
"deploy.sync",
|
||||||
|
json!({"upload": ["public/index.php"], "delete": ["public/old.php"], "confirmDelete": true}),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
(synced["files"].clone(), synced["deleted"].clone()),
|
||||||
|
(json!(1), json!(1))
|
||||||
|
);
|
||||||
|
assert!(!remote.join("www/public/old.php").exists());
|
||||||
|
|
||||||
|
let opened = host
|
||||||
|
.run("file.open", json!({"path": "public/index.php"}))
|
||||||
|
.unwrap();
|
||||||
|
let id = opened["id"].as_u64().unwrap();
|
||||||
|
host.run(
|
||||||
|
"buffer.edit",
|
||||||
|
json!({"id": id, "baseVersion": 1, "edits": [{"from": 0, "to": 0, "insert": "// unsaved\n"}]}),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
host.run("deploy.upload", json!({"paths": ["public"]}))
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(remote.join("www/public/index.php")).unwrap(),
|
||||||
|
"// unsaved\n<?php echo 1;",
|
||||||
|
"the upload saved the buffer first"
|
||||||
|
);
|
||||||
|
assert!(!host.transcript().contains(PASSWORD));
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -762,6 +762,13 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
|
||||||
- **UI (`ui/src/components/deploy/`):** `deploy.ts` store, `DeployStatusItem.vue` (progress, Cancel, the `deployment.*` UI commands), `DeploymentDialog.vue` (exclusive modal `deployment`; write-only secret field; host-key question), `DeploymentLogToolWindow.vue` (bottom panel). The project tree's context menu gains Upload/Download for files and folders.
|
- **UI (`ui/src/components/deploy/`):** `deploy.ts` store, `DeployStatusItem.vue` (progress, Cancel, the `deployment.*` UI commands), `DeploymentDialog.vue` (exclusive modal `deployment`; write-only secret field; host-key question), `DeploymentLogToolWindow.vue` (bottom panel). The project tree's context menu gains Upload/Download for files and folders.
|
||||||
- **Tests:** `crates/deploy/tests/transfer.rs` (7: host key first use and mismatch, password and key sign-in, upload, download, cancel, FTP, unreachable), `crates/engine/tests/deploy.rs` (4, including a grep of every event, value, error and the config and data directories for the test password), `ui/tests/deploy/Deploy.test.ts` (12).
|
- **Tests:** `crates/deploy/tests/transfer.rs` (7: host key first use and mismatch, password and key sign-in, upload, download, cancel, FTP, unreachable), `crates/engine/tests/deploy.rs` (4, including a grep of every event, value, error and the config and data directories for the test password), `ui/tests/deploy/Deploy.test.ts` (12).
|
||||||
|
|
||||||
|
### Remote browser, compare and sync (C9 D2)
|
||||||
|
|
||||||
|
- **Crate:** `Remote` gains `remove_file`, `remove_dir`, `rename` (SFTP, FTP, folder; the test servers too: SFTP `rename`, FTP `RMD`, `DELE`, `RNFR`/`RNTO`). `browse`: browser paths relative to the root (absolute and `..` refused); `list` (folders first), `read` (`Target::Mapped` project path or `Target::Browser` path; at most 4 MiB, NUL or invalid UTF-8 → binary, missing → `text: None`), `write` (creates the folder), `rename`, `mkdir`, `delete` (recursive, never the root). `job::compare` walks the local tree and the remote listings (sizes from the server; `walk_remote_tree` also serves downloads now) and reports `localOnly`, `remoteOnly`, `different` (size, then contents up to 8 MiB); `job::sync` uploads files and deletes listed files in one connection; `Summary.deleted`.
|
||||||
|
- **Engine (`cmd/deploy_remote.rs`):** `deploy.browse {path?, id?}`, `deploy.readRemote {path | remotePath, id?}` (answers like `git.show`: `{text, binary, tooLarge}`), `deploy.writeRemote {remotePath, text, id?}`, `deploy.renameRemote {from, to, id?}`, `deploy.mkdirRemote {path, id?}`, `deploy.deleteRemote {path, confirm: true, id?}`, `deploy.compare {paths, id?}`, `deploy.sync {upload?, delete?, confirmDelete, id?}`. Same job slot and events as D1. Missing confirmations are `invalid_params` before any connection. `deploy.upload {saveFirst?}` (default true) saves the dirty buffers under its paths through `file::save_buffer` while `DeployState.saving` keeps those saves from queueing uploads on save.
|
||||||
|
- **UI:** `remoteBrowser.ts` store; `RemoteBrowserToolWindow.vue` (bottom panel tab `remote`: server select, tree, inline rename / new folder / delete question, read-only viewer with Edit and Upload); `SyncDialog.vue` (exclusive modal `deploySync`); the diff store's server tabs (`DiffTab.remote`, `openRemote`, left side from `deploy.readRemote`). UI commands `deployment.browse`, `deployment.compare {path?, kind?}`, `deployment.sync`; the tree menu adds Compare with Server.
|
||||||
|
- **Tests:** `crates/deploy/tests/remote.rs` (2: the whole browser, compare and sync scenario over SFTP and over FTP), `crates/engine/tests/deploy.rs` (+1: commands, refused unconfirmed deletes, sync, save before upload), `ui/tests/deploy/RemoteBrowser.test.ts` (6).
|
||||||
|
|
||||||
## Decisions (M0)
|
## Decisions (M0)
|
||||||
|
|
||||||
| Question | Decision | Why |
|
| Question | Decision | Why |
|
||||||
|
|
@ -782,6 +789,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
|
||||||
|
|
||||||
| Date | Change | Summary |
|
| Date | Change | Summary |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
|
| 2026-11-06 | minor | C9 D2: remote browser, compare and sync; save before upload |
|
||||||
| 2026-11-06 | minor | C9 D1: `crates/deploy` (L3), `deploy.*` commands, deployment events and UI |
|
| 2026-11-06 | minor | C9 D1: `crates/deploy` (L3), `deploy.*` commands, deployment events and UI |
|
||||||
| 2026-11-02 | minor | C9 F1: `Kind::Path` and `check_path` (one validator for `settings.set` and the dialog, `path` in `settings.list`), `lutra_proc::spawn_detached` for the CLI's desktop start |
|
| 2026-11-02 | minor | C9 F1: `Kind::Path` and `check_path` (one validator for `settings.set` and the dialog, `path` in `settings.list`), `lutra_proc::spawn_detached` for the CLI's desktop start |
|
||||||
| 2026-10-31 | minor | C7 B1: app identifier `com.tyrveil.lutra` with the one-time copy from `dev.lutra.desktop`, NSIS and DMG installers, `cargo xtask bundle` |
|
| 2026-10-31 | minor | C7 B1: app identifier `com.tyrveil.lutra` with the one-time copy from `dev.lutra.desktop`, NSIS and DMG installers, `cargo xtask bundle` |
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
# Deployment
|
# Deployment
|
||||||
|
|
||||||
> **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.
|
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).
|
- **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.
|
- **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.
|
- 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.
|
- 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.
|
- 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
|
## 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.
|
||||||
|
|
|
||||||
|
|
@ -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 |
|
| 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 |
|
| G15 | Database tools, HTTP client, Docker and remote | later | ~430 h |
|
||||||
| G16 | Plug-ins and ecosystem | later | ~120 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 | 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-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) |
|
| 2026-11-01 | patch | G8: chunk staging, unstaging and revert from the gutter and the diff viewer (C8 C3) |
|
||||||
|
|
|
||||||
|
|
@ -21,7 +21,7 @@
|
||||||
* are exclusive modals too. So is the branches popup (M4.5), and so are
|
* are exclusive modals too. So is the branches popup (M4.5), and so are
|
||||||
* "Clone Repository…" and "Manage Remotes…" (M4.10), the merge
|
* "Clone Repository…" and "Manage Remotes…" (M4.10), the merge
|
||||||
* dialog (M4.8) and the stash dialog (M4.9), the deployment servers
|
* 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 { defineStore } from "pinia";
|
||||||
import { ref, watch } from "vue";
|
import { ref, watch } from "vue";
|
||||||
|
|
@ -40,6 +40,7 @@ export type ModalId =
|
||||||
| "clone"
|
| "clone"
|
||||||
| "remotes"
|
| "remotes"
|
||||||
| "deployment"
|
| "deployment"
|
||||||
|
| "deploySync"
|
||||||
| "merge"
|
| "merge"
|
||||||
| "stash"
|
| "stash"
|
||||||
| "themes";
|
| "themes";
|
||||||
|
|
|
||||||
|
|
@ -21,6 +21,9 @@ export interface UiCommandSpec {
|
||||||
|
|
||||||
/** The frontend's UI commands. */
|
/** The frontend's UI commands. */
|
||||||
export const UI_COMMANDS: readonly UiCommandSpec[] = [
|
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.download", labelKey: "command.deployment.download", menuPath: "Tools/Deployment/Download Current File" },
|
||||||
{ id: "deployment.servers", labelKey: "command.deployment.servers", menuPath: "Tools/Deployment/Servers…" },
|
{ id: "deployment.servers", labelKey: "command.deployment.servers", menuPath: "Tools/Deployment/Servers…" },
|
||||||
{ id: "deployment.showLog", labelKey: "command.deployment.showLog", menuPath: "Tools/Deployment/Deployment Log" },
|
{ id: "deployment.showLog", labelKey: "command.deployment.showLog", menuPath: "Tools/Deployment/Deployment Log" },
|
||||||
|
|
|
||||||
|
|
@ -14,25 +14,43 @@
|
||||||
* - `deployment.uploadProject`: the whole project;
|
* - `deployment.uploadProject`: the whole project;
|
||||||
* - `deployment.testConnection`: opens the servers dialog and tests the
|
* - `deployment.testConnection`: opens the servers dialog and tests the
|
||||||
* default server, so a host key can be checked there;
|
* 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
|
* 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 { LoaderCircle, X } from "@lucide/vue";
|
||||||
import { computed, onBeforeUnmount, onMounted } from "vue";
|
import { computed, onBeforeUnmount, onMounted, watch } from "vue";
|
||||||
import { useCommandsStore } from "../../commands/store";
|
import { useCommandsStore } from "../../commands/store";
|
||||||
import { t } from "../../i18n";
|
import { t } from "../../i18n";
|
||||||
import { useEditorStore } from "../../stores/editor";
|
import { useEditorStore } from "../../stores/editor";
|
||||||
import { useNotificationsStore } from "../../stores/notifications";
|
import { useNotificationsStore } from "../../stores/notifications";
|
||||||
import { useProjectStore } from "../../stores/project";
|
import { useProjectStore } from "../../stores/project";
|
||||||
import DeploymentDialog from "./DeploymentDialog.vue";
|
import DeploymentDialog from "./DeploymentDialog.vue";
|
||||||
|
import SyncDialog from "./SyncDialog.vue";
|
||||||
import { useDeployStore } from "./deploy";
|
import { useDeployStore } from "./deploy";
|
||||||
|
import { useRemoteBrowserStore } from "./remoteBrowser";
|
||||||
|
|
||||||
const deploy = useDeployStore();
|
const deploy = useDeployStore();
|
||||||
const commands = useCommandsStore();
|
const commands = useCommandsStore();
|
||||||
const editor = useEditorStore();
|
const editor = useEditorStore();
|
||||||
const project = useProjectStore();
|
const project = useProjectStore();
|
||||||
const notifications = useNotificationsStore();
|
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. */
|
/** The running job's text, or null while none runs. */
|
||||||
const progressText = computed(() => {
|
const progressText = computed(() => {
|
||||||
|
|
@ -130,6 +148,23 @@ onMounted(() => {
|
||||||
},
|
},
|
||||||
enabled: idle,
|
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", {
|
commands.provide("deployment.servers", {
|
||||||
run: () => deploy.showDialog(),
|
run: () => deploy.showDialog(),
|
||||||
enabled: () => project.root !== null,
|
enabled: () => project.root !== null,
|
||||||
|
|
@ -175,6 +210,7 @@ onBeforeUnmount(() => {
|
||||||
</button>
|
</button>
|
||||||
</span>
|
</span>
|
||||||
<DeploymentDialog />
|
<DeploymentDialog />
|
||||||
|
<SyncDialog />
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
|
|
|
||||||
561
ui/src/components/deploy/RemoteBrowserToolWindow.vue
Normal file
561
ui/src/components/deploy/RemoteBrowserToolWindow.vue
Normal file
|
|
@ -0,0 +1,561 @@
|
||||||
|
<script setup lang="ts">
|
||||||
|
/**
|
||||||
|
* The Remote Host tool window (C9 D2), shown in the bottom panel: the
|
||||||
|
* chosen deployment server's folders as a tree on the left, the opened
|
||||||
|
* file on the right.
|
||||||
|
*
|
||||||
|
* - **Toolbar:** the server (default first), Refresh, New Folder (in the
|
||||||
|
* selected folder, else the root), and Compare Project (the sync
|
||||||
|
* preview).
|
||||||
|
* - **Rows:** a click expands a folder or opens a file. Each row offers
|
||||||
|
* Rename and Delete; both show their own inline form, and Delete runs
|
||||||
|
* only after its question was answered with the red button.
|
||||||
|
* - **Viewer:** read-only first; Edit makes it editable, Upload writes it
|
||||||
|
* back, Close drops it. Binary, missing and too large files show a
|
||||||
|
* notice instead.
|
||||||
|
* State lives in the remote browser store (`remoteBrowser.ts`).
|
||||||
|
*/
|
||||||
|
import { ChevronDown, ChevronRight, File, Folder, Pencil, RefreshCw, Trash2 } from "@lucide/vue";
|
||||||
|
import { computed, nextTick, ref } from "vue";
|
||||||
|
import { t } from "../../i18n";
|
||||||
|
import { useDeployStore } from "./deploy";
|
||||||
|
import { childPath, parentPath, useRemoteBrowserStore, type RemoteEntry } from "./remoteBrowser";
|
||||||
|
|
||||||
|
const browser = useRemoteBrowserStore();
|
||||||
|
const deploy = useDeployStore();
|
||||||
|
|
||||||
|
/** One visible row of the tree. */
|
||||||
|
interface Row {
|
||||||
|
/** Browser path. */
|
||||||
|
path: string;
|
||||||
|
/** The entry. */
|
||||||
|
entry: RemoteEntry;
|
||||||
|
/** Nesting depth. */
|
||||||
|
depth: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The open inline form: rename, new folder or the delete question. */
|
||||||
|
const form = ref<{ kind: "rename" | "newFolder" | "delete"; path: string; name: string } | null>(null);
|
||||||
|
/** The inline name field. */
|
||||||
|
const nameInput = ref<HTMLInputElement | null>(null);
|
||||||
|
|
||||||
|
/** The tree's rows in display order. */
|
||||||
|
const rows = computed<Row[]>(() => {
|
||||||
|
const out: Row[] = [];
|
||||||
|
const walk = (dir: string, depth: number): void => {
|
||||||
|
for (const entry of browser.dirs[dir]?.entries ?? []) {
|
||||||
|
const path = childPath(dir, entry.name);
|
||||||
|
out.push({ path, entry, depth });
|
||||||
|
if (entry.isDir && browser.open.includes(path)) {
|
||||||
|
walk(path, depth + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
walk("", 0);
|
||||||
|
return out;
|
||||||
|
});
|
||||||
|
|
||||||
|
/** The root's listing state. */
|
||||||
|
const root = computed(() => browser.dirs[""]);
|
||||||
|
|
||||||
|
/** The viewer's notice text, or null. */
|
||||||
|
const notice = computed(() => {
|
||||||
|
switch (browser.file?.notice) {
|
||||||
|
case "binary":
|
||||||
|
return t("deploy.remote.binary");
|
||||||
|
case "tooLarge":
|
||||||
|
return t("deploy.remote.tooLarge");
|
||||||
|
case "missing":
|
||||||
|
return t("deploy.remote.missing");
|
||||||
|
default:
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Opens an inline form.
|
||||||
|
*
|
||||||
|
* @param kind - which form.
|
||||||
|
* @param path - the row (or, for a new folder, the parent folder).
|
||||||
|
* @param name - the starting name.
|
||||||
|
*/
|
||||||
|
async function startForm(kind: "rename" | "newFolder" | "delete", path: string, name: string): Promise<void> {
|
||||||
|
form.value = { kind, path, name };
|
||||||
|
await nextTick();
|
||||||
|
nameInput.value?.focus();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The folder a new folder goes in: the selected folder, else the root. */
|
||||||
|
function newFolderParent(): string {
|
||||||
|
const sel = browser.selected;
|
||||||
|
if (sel === null) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
const row = rows.value.find((r) => r.path === sel);
|
||||||
|
return row?.entry.isDir ? sel : parentPath(sel);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Submits the open form. */
|
||||||
|
async function submit(): Promise<void> {
|
||||||
|
const f = form.value;
|
||||||
|
if (f === null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const done =
|
||||||
|
f.kind === "rename"
|
||||||
|
? await browser.rename(f.path, f.name)
|
||||||
|
: f.kind === "newFolder"
|
||||||
|
? await browser.newFolder(f.path, f.name)
|
||||||
|
: await browser.remove(f.path);
|
||||||
|
if (done) {
|
||||||
|
form.value = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Activates a row: expands a folder or opens a file.
|
||||||
|
*
|
||||||
|
* @param row - the row.
|
||||||
|
*/
|
||||||
|
async function activate(row: Row): Promise<void> {
|
||||||
|
if (row.entry.isDir) {
|
||||||
|
await browser.toggle(row.path);
|
||||||
|
} else {
|
||||||
|
await browser.openFile(row.path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Chooses the server from the select.
|
||||||
|
*
|
||||||
|
* @param event - the change event.
|
||||||
|
*/
|
||||||
|
async function chooseServer(event: Event): Promise<void> {
|
||||||
|
const value = (event.target as HTMLSelectElement).value;
|
||||||
|
await browser.setServer(value === "" ? null : value);
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<section
|
||||||
|
class="remote"
|
||||||
|
:aria-label="t('deploy.remote.title')"
|
||||||
|
data-test="remote-browser"
|
||||||
|
>
|
||||||
|
<header class="remote__toolbar">
|
||||||
|
<select
|
||||||
|
class="remote__select"
|
||||||
|
:value="browser.serverId ?? ''"
|
||||||
|
:aria-label="t('deploy.remote.server')"
|
||||||
|
data-test="remote-server"
|
||||||
|
@change="chooseServer"
|
||||||
|
>
|
||||||
|
<option value="">
|
||||||
|
{{ t("deploy.remote.defaultServer", { name: deploy.target?.name ?? "" }) }}
|
||||||
|
</option>
|
||||||
|
<option
|
||||||
|
v-for="server in deploy.servers"
|
||||||
|
:key="server.id"
|
||||||
|
:value="server.id"
|
||||||
|
>
|
||||||
|
{{ server.name }}
|
||||||
|
</option>
|
||||||
|
</select>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="remote__button"
|
||||||
|
:title="t('deploy.remote.refresh')"
|
||||||
|
:aria-label="t('deploy.remote.refresh')"
|
||||||
|
data-test="remote-refresh"
|
||||||
|
@click="browser.refresh()"
|
||||||
|
>
|
||||||
|
<RefreshCw
|
||||||
|
:size="12"
|
||||||
|
aria-hidden="true"
|
||||||
|
/>
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="remote__button"
|
||||||
|
data-test="remote-new-folder"
|
||||||
|
@click="startForm('newFolder', newFolderParent(), '')"
|
||||||
|
>
|
||||||
|
{{ t("deploy.remote.newFolder") }}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="remote__button"
|
||||||
|
data-test="remote-compare"
|
||||||
|
@click="browser.compareFolders([''])"
|
||||||
|
>
|
||||||
|
{{ t("deploy.remote.compareProject") }}
|
||||||
|
</button>
|
||||||
|
</header>
|
||||||
|
<p
|
||||||
|
v-if="browser.error !== null"
|
||||||
|
class="remote__error"
|
||||||
|
role="alert"
|
||||||
|
data-test="remote-error"
|
||||||
|
>
|
||||||
|
{{ browser.error }}
|
||||||
|
</p>
|
||||||
|
<form
|
||||||
|
v-if="form !== null"
|
||||||
|
class="remote__form"
|
||||||
|
:class="{ 'remote__form--danger': form.kind === 'delete' }"
|
||||||
|
data-test="remote-form"
|
||||||
|
@submit.prevent="submit"
|
||||||
|
>
|
||||||
|
<template v-if="form.kind === 'delete'">
|
||||||
|
<span>{{ t("deploy.remote.deleteQuestion", { path: form.path }) }}</span>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
class="remote__button remote__button--danger"
|
||||||
|
data-test="remote-delete-confirm"
|
||||||
|
>
|
||||||
|
{{ t("deploy.remote.delete") }}
|
||||||
|
</button>
|
||||||
|
</template>
|
||||||
|
<template v-else>
|
||||||
|
<span>{{ form.kind === "rename" ? t("deploy.remote.renameTo") : t("deploy.remote.newFolderIn", { path: form.path || "/" }) }}</span>
|
||||||
|
<input
|
||||||
|
ref="nameInput"
|
||||||
|
v-model="form.name"
|
||||||
|
class="remote__input"
|
||||||
|
type="text"
|
||||||
|
spellcheck="false"
|
||||||
|
data-test="remote-form-name"
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
class="remote__button"
|
||||||
|
data-test="remote-form-ok"
|
||||||
|
>
|
||||||
|
{{ t("deploy.remote.ok") }}
|
||||||
|
</button>
|
||||||
|
</template>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="remote__button"
|
||||||
|
@click="form = null"
|
||||||
|
>
|
||||||
|
{{ t("deploy.remote.cancel") }}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
<div class="remote__body">
|
||||||
|
<ul
|
||||||
|
class="remote__tree"
|
||||||
|
role="tree"
|
||||||
|
:aria-label="browser.serverName"
|
||||||
|
>
|
||||||
|
<li
|
||||||
|
v-if="root?.loading"
|
||||||
|
class="remote__note"
|
||||||
|
>
|
||||||
|
{{ t("deploy.remote.loading") }}
|
||||||
|
</li>
|
||||||
|
<li
|
||||||
|
v-else-if="root?.error"
|
||||||
|
class="remote__note remote__note--error"
|
||||||
|
>
|
||||||
|
{{ root.error }}
|
||||||
|
</li>
|
||||||
|
<li
|
||||||
|
v-for="row in rows"
|
||||||
|
:key="row.path"
|
||||||
|
class="remote__row"
|
||||||
|
:class="{ 'remote__row--selected': browser.selected === row.path }"
|
||||||
|
role="treeitem"
|
||||||
|
:aria-expanded="row.entry.isDir ? browser.open.includes(row.path) : undefined"
|
||||||
|
:style="{ '--remote-depth': row.depth }"
|
||||||
|
:data-path="row.path"
|
||||||
|
data-test="remote-row"
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="remote__name"
|
||||||
|
@click="activate(row)"
|
||||||
|
>
|
||||||
|
<template v-if="row.entry.isDir">
|
||||||
|
<ChevronDown
|
||||||
|
v-if="browser.open.includes(row.path)"
|
||||||
|
:size="12"
|
||||||
|
aria-hidden="true"
|
||||||
|
/>
|
||||||
|
<ChevronRight
|
||||||
|
v-else
|
||||||
|
:size="12"
|
||||||
|
aria-hidden="true"
|
||||||
|
/>
|
||||||
|
<Folder
|
||||||
|
:size="12"
|
||||||
|
aria-hidden="true"
|
||||||
|
/>
|
||||||
|
</template>
|
||||||
|
<File
|
||||||
|
v-else
|
||||||
|
:size="12"
|
||||||
|
aria-hidden="true"
|
||||||
|
/>
|
||||||
|
<span>{{ row.entry.name }}</span>
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="remote__action"
|
||||||
|
:title="t('deploy.remote.rename')"
|
||||||
|
:aria-label="t('deploy.remote.rename')"
|
||||||
|
data-test="remote-rename"
|
||||||
|
@click="startForm('rename', row.path, row.entry.name)"
|
||||||
|
>
|
||||||
|
<Pencil
|
||||||
|
:size="12"
|
||||||
|
aria-hidden="true"
|
||||||
|
/>
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="remote__action"
|
||||||
|
:title="t('deploy.remote.delete')"
|
||||||
|
:aria-label="t('deploy.remote.delete')"
|
||||||
|
data-test="remote-delete"
|
||||||
|
@click="startForm('delete', row.path, '')"
|
||||||
|
>
|
||||||
|
<Trash2
|
||||||
|
:size="12"
|
||||||
|
aria-hidden="true"
|
||||||
|
/>
|
||||||
|
</button>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<div
|
||||||
|
v-if="browser.file !== null"
|
||||||
|
class="remote__viewer"
|
||||||
|
data-test="remote-viewer"
|
||||||
|
>
|
||||||
|
<header class="remote__viewer-head">
|
||||||
|
<span class="remote__viewer-path">{{ browser.file.path }}</span>
|
||||||
|
<span
|
||||||
|
v-if="!browser.file.editing"
|
||||||
|
class="remote__badge"
|
||||||
|
>{{ t("deploy.remote.readOnly") }}</span>
|
||||||
|
<button
|
||||||
|
v-if="!browser.file.editing && notice === null"
|
||||||
|
type="button"
|
||||||
|
class="remote__button"
|
||||||
|
data-test="remote-edit"
|
||||||
|
@click="browser.edit()"
|
||||||
|
>
|
||||||
|
{{ t("deploy.remote.edit") }}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
v-if="browser.file.editing"
|
||||||
|
type="button"
|
||||||
|
class="remote__button remote__button--primary"
|
||||||
|
:disabled="browser.file.text === browser.file.original"
|
||||||
|
data-test="remote-upload"
|
||||||
|
@click="browser.upload()"
|
||||||
|
>
|
||||||
|
{{ t("deploy.remote.upload") }}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="remote__button"
|
||||||
|
data-test="remote-close-file"
|
||||||
|
@click="browser.closeFile()"
|
||||||
|
>
|
||||||
|
{{ t("deploy.remote.close") }}
|
||||||
|
</button>
|
||||||
|
</header>
|
||||||
|
<p
|
||||||
|
v-if="notice !== null"
|
||||||
|
class="remote__note"
|
||||||
|
>
|
||||||
|
{{ notice }}
|
||||||
|
</p>
|
||||||
|
<textarea
|
||||||
|
v-else
|
||||||
|
class="remote__text"
|
||||||
|
:value="browser.file.text"
|
||||||
|
:readonly="!browser.file.editing"
|
||||||
|
spellcheck="false"
|
||||||
|
:aria-label="browser.file.path"
|
||||||
|
data-test="remote-text"
|
||||||
|
@input="browser.setText(($event.target as HTMLTextAreaElement).value)"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.remote {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
height: 100%;
|
||||||
|
min-height: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.remote__toolbar,
|
||||||
|
.remote__form {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
flex: none;
|
||||||
|
padding: 2px 8px;
|
||||||
|
border-bottom: 1px solid var(--lt-border);
|
||||||
|
}
|
||||||
|
|
||||||
|
.remote__form--danger {
|
||||||
|
color: var(--lt-error);
|
||||||
|
}
|
||||||
|
|
||||||
|
.remote__select,
|
||||||
|
.remote__input {
|
||||||
|
min-width: 0;
|
||||||
|
padding: 1px 4px;
|
||||||
|
font: inherit;
|
||||||
|
color: var(--lt-fg);
|
||||||
|
background: var(--lt-editor-bg);
|
||||||
|
border: 1px solid var(--lt-border);
|
||||||
|
border-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.remote__button,
|
||||||
|
.remote__action {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 4px;
|
||||||
|
padding: 1px 8px;
|
||||||
|
font: inherit;
|
||||||
|
color: var(--lt-fg);
|
||||||
|
background: transparent;
|
||||||
|
border: 1px solid var(--lt-border);
|
||||||
|
border-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.remote__button--primary {
|
||||||
|
border-color: var(--lt-accent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.remote__button--danger {
|
||||||
|
color: var(--lt-error);
|
||||||
|
border-color: var(--lt-error);
|
||||||
|
}
|
||||||
|
|
||||||
|
.remote__button:disabled {
|
||||||
|
color: var(--lt-fg-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.remote__action {
|
||||||
|
padding: 1px 4px;
|
||||||
|
border-color: transparent;
|
||||||
|
visibility: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.remote__row:hover .remote__action,
|
||||||
|
.remote__row--selected .remote__action,
|
||||||
|
.remote__action:focus-visible {
|
||||||
|
visibility: visible;
|
||||||
|
}
|
||||||
|
|
||||||
|
.remote__button:focus-visible,
|
||||||
|
.remote__action:focus-visible,
|
||||||
|
.remote__name:focus-visible {
|
||||||
|
outline: 1px solid var(--lt-accent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.remote__error,
|
||||||
|
.remote__note--error {
|
||||||
|
margin: 0;
|
||||||
|
padding: 2px 8px;
|
||||||
|
color: var(--lt-error);
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
|
||||||
|
.remote__body {
|
||||||
|
display: flex;
|
||||||
|
flex: 1;
|
||||||
|
min-height: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.remote__tree {
|
||||||
|
flex: 0 0 40%;
|
||||||
|
margin: 0;
|
||||||
|
padding: 2px 0;
|
||||||
|
list-style: none;
|
||||||
|
overflow-y: auto;
|
||||||
|
border-right: 1px solid var(--lt-border);
|
||||||
|
}
|
||||||
|
|
||||||
|
.remote__row {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
padding-left: calc(var(--remote-depth) * 14px + 4px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.remote__row--selected {
|
||||||
|
background: var(--lt-editor-selection-bg);
|
||||||
|
}
|
||||||
|
|
||||||
|
.remote__name {
|
||||||
|
display: inline-flex;
|
||||||
|
flex: 1;
|
||||||
|
align-items: center;
|
||||||
|
gap: 4px;
|
||||||
|
min-width: 0;
|
||||||
|
padding: 1px 4px;
|
||||||
|
font: inherit;
|
||||||
|
text-align: left;
|
||||||
|
color: var(--lt-fg);
|
||||||
|
background: transparent;
|
||||||
|
border: none;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.remote__note {
|
||||||
|
margin: 0;
|
||||||
|
padding: 2px 8px;
|
||||||
|
color: var(--lt-fg-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.remote__viewer {
|
||||||
|
display: flex;
|
||||||
|
flex: 1;
|
||||||
|
flex-direction: column;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.remote__viewer-head {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
padding: 2px 8px;
|
||||||
|
border-bottom: 1px solid var(--lt-border);
|
||||||
|
}
|
||||||
|
|
||||||
|
.remote__viewer-path {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.remote__badge {
|
||||||
|
color: var(--lt-fg-muted);
|
||||||
|
font-size: var(--lt-font-size-small);
|
||||||
|
}
|
||||||
|
|
||||||
|
.remote__text {
|
||||||
|
flex: 1;
|
||||||
|
margin: 0;
|
||||||
|
padding: 4px 8px;
|
||||||
|
resize: none;
|
||||||
|
font-family: var(--lt-font-mono);
|
||||||
|
font-size: var(--lt-font-size-editor);
|
||||||
|
color: var(--lt-fg);
|
||||||
|
background: var(--lt-editor-bg);
|
||||||
|
border: none;
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
295
ui/src/components/deploy/SyncDialog.vue
Normal file
295
ui/src/components/deploy/SyncDialog.vue
Normal file
|
|
@ -0,0 +1,295 @@
|
||||||
|
<script setup lang="ts">
|
||||||
|
/**
|
||||||
|
* The sync preview (C9 D2): every file that differs between the compared
|
||||||
|
* project folders and the server, with what Sync would do.
|
||||||
|
*
|
||||||
|
* - Only in the project, or different: upload; selected by default.
|
||||||
|
* Different files offer Show Diff (a server tab in the diff viewer).
|
||||||
|
* - Only on the server: delete on the server; never selected by default.
|
||||||
|
* As soon as one is selected, a red confirmation checkbox appears and
|
||||||
|
* Sync stays disabled until it is ticked.
|
||||||
|
* - Escape or Close closes the preview. The dialog is an exclusive modal
|
||||||
|
* (`deploySync`).
|
||||||
|
*/
|
||||||
|
import { computed, watch } from "vue";
|
||||||
|
import { useModalsStore } from "../../commands/modals";
|
||||||
|
import { t } from "../../i18n";
|
||||||
|
import { useRemoteBrowserStore, type SyncItem } from "./remoteBrowser";
|
||||||
|
|
||||||
|
const browser = useRemoteBrowserStore();
|
||||||
|
const modals = useModalsStore();
|
||||||
|
|
||||||
|
/** Whether the preview is open. */
|
||||||
|
const isOpen = computed(() => browser.syncItems !== null);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What Sync does with an item, for people.
|
||||||
|
*
|
||||||
|
* @param item - the item.
|
||||||
|
*/
|
||||||
|
function action(item: SyncItem): string {
|
||||||
|
return item.status === "localOnly"
|
||||||
|
? t("deploy.sync.uploadNew")
|
||||||
|
: item.status === "different"
|
||||||
|
? t("deploy.sync.uploadChanged")
|
||||||
|
: t("deploy.sync.deleteOnServer");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Selects or clears an item.
|
||||||
|
*
|
||||||
|
* @param item - the item.
|
||||||
|
* @param event - the checkbox change.
|
||||||
|
*/
|
||||||
|
function toggle(item: SyncItem, event: Event): void {
|
||||||
|
item.selected = (event.target as HTMLInputElement).checked;
|
||||||
|
if (browser.deletions.length === 0) {
|
||||||
|
browser.confirmDelete = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Closes the preview. */
|
||||||
|
function close(): void {
|
||||||
|
browser.closeSync();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Escape closes.
|
||||||
|
*
|
||||||
|
* @param event - the key.
|
||||||
|
*/
|
||||||
|
function onKeydown(event: KeyboardEvent): void {
|
||||||
|
if (event.key === "Escape") {
|
||||||
|
event.preventDefault();
|
||||||
|
close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(isOpen, (open) => {
|
||||||
|
if (open) {
|
||||||
|
modals.opened("deploySync", close);
|
||||||
|
} else {
|
||||||
|
modals.closed("deploySync");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div
|
||||||
|
v-if="isOpen"
|
||||||
|
class="sync-dialog"
|
||||||
|
data-test="sync-dialog"
|
||||||
|
@mousedown.self="close"
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
class="sync-dialog__box"
|
||||||
|
role="dialog"
|
||||||
|
aria-modal="true"
|
||||||
|
aria-labelledby="lt-sync-title"
|
||||||
|
@keydown="onKeydown"
|
||||||
|
>
|
||||||
|
<h2
|
||||||
|
id="lt-sync-title"
|
||||||
|
class="sync-dialog__title"
|
||||||
|
>
|
||||||
|
{{ t("deploy.sync.title", { server: browser.serverName }) }}
|
||||||
|
</h2>
|
||||||
|
<p
|
||||||
|
v-if="browser.syncing && (browser.syncItems ?? []).length === 0"
|
||||||
|
class="sync-dialog__note"
|
||||||
|
>
|
||||||
|
{{ t("deploy.sync.comparing") }}
|
||||||
|
</p>
|
||||||
|
<p
|
||||||
|
v-else-if="(browser.syncItems ?? []).length === 0 && browser.error === null"
|
||||||
|
class="sync-dialog__note"
|
||||||
|
data-test="sync-equal"
|
||||||
|
>
|
||||||
|
{{ t("deploy.sync.equal") }}
|
||||||
|
</p>
|
||||||
|
<ul
|
||||||
|
v-else
|
||||||
|
class="sync-dialog__list"
|
||||||
|
>
|
||||||
|
<li
|
||||||
|
v-for="item in browser.syncItems ?? []"
|
||||||
|
:key="item.path"
|
||||||
|
class="sync-dialog__item"
|
||||||
|
:class="{ 'sync-dialog__item--delete': item.status === 'remoteOnly' }"
|
||||||
|
data-test="sync-item"
|
||||||
|
>
|
||||||
|
<label class="sync-dialog__check">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
:checked="item.selected"
|
||||||
|
:data-path="item.path"
|
||||||
|
@change="toggle(item, $event)"
|
||||||
|
>
|
||||||
|
<span class="sync-dialog__path">{{ item.path }}</span>
|
||||||
|
</label>
|
||||||
|
<span class="sync-dialog__action">{{ action(item) }}</span>
|
||||||
|
<button
|
||||||
|
v-if="item.status === 'different'"
|
||||||
|
type="button"
|
||||||
|
class="sync-dialog__button"
|
||||||
|
data-test="sync-diff"
|
||||||
|
@click="browser.compareFile(item.path)"
|
||||||
|
>
|
||||||
|
{{ t("deploy.sync.showDiff") }}
|
||||||
|
</button>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<label
|
||||||
|
v-if="browser.deletions.length > 0"
|
||||||
|
class="sync-dialog__confirm"
|
||||||
|
data-test="sync-confirm"
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
v-model="browser.confirmDelete"
|
||||||
|
type="checkbox"
|
||||||
|
>
|
||||||
|
{{ t("deploy.sync.confirmDelete", { count: browser.deletions.length }) }}
|
||||||
|
</label>
|
||||||
|
<p
|
||||||
|
v-if="browser.error !== null"
|
||||||
|
class="sync-dialog__error"
|
||||||
|
role="alert"
|
||||||
|
>
|
||||||
|
{{ browser.error }}
|
||||||
|
</p>
|
||||||
|
<div class="sync-dialog__buttons">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="sync-dialog__button sync-dialog__button--primary"
|
||||||
|
:disabled="!browser.canSync"
|
||||||
|
data-test="sync-run"
|
||||||
|
@click="browser.runSync()"
|
||||||
|
>
|
||||||
|
{{ t("deploy.sync.run") }}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="sync-dialog__button"
|
||||||
|
data-test="sync-close"
|
||||||
|
@click="close"
|
||||||
|
>
|
||||||
|
{{ t("deploy.dialog.close") }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.sync-dialog {
|
||||||
|
position: fixed;
|
||||||
|
inset: 0;
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-start;
|
||||||
|
justify-content: center;
|
||||||
|
padding-top: 8vh;
|
||||||
|
background: color-mix(in srgb, var(--lt-bg) 50%, transparent);
|
||||||
|
z-index: 20;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sync-dialog__box {
|
||||||
|
width: min(720px, 92vw);
|
||||||
|
max-height: 80vh;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 10px;
|
||||||
|
padding: 16px;
|
||||||
|
color: var(--lt-fg);
|
||||||
|
background: var(--lt-bg);
|
||||||
|
border: 1px solid var(--lt-border);
|
||||||
|
border-radius: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sync-dialog__title {
|
||||||
|
margin: 0;
|
||||||
|
font-size: var(--lt-font-size-ui);
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sync-dialog__note {
|
||||||
|
margin: 0;
|
||||||
|
color: var(--lt-fg-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.sync-dialog__list {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
list-style: none;
|
||||||
|
overflow-y: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sync-dialog__item {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
padding: 3px 0;
|
||||||
|
border-bottom: 1px solid var(--lt-border);
|
||||||
|
}
|
||||||
|
|
||||||
|
.sync-dialog__item--delete .sync-dialog__action {
|
||||||
|
color: var(--lt-error);
|
||||||
|
}
|
||||||
|
|
||||||
|
.sync-dialog__check {
|
||||||
|
display: flex;
|
||||||
|
flex: 1;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sync-dialog__path {
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
font-family: var(--lt-font-mono);
|
||||||
|
}
|
||||||
|
|
||||||
|
.sync-dialog__action {
|
||||||
|
color: var(--lt-fg-muted);
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sync-dialog__confirm {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
color: var(--lt-error);
|
||||||
|
}
|
||||||
|
|
||||||
|
.sync-dialog__error {
|
||||||
|
margin: 0;
|
||||||
|
color: var(--lt-error);
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sync-dialog__buttons {
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-end;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sync-dialog__button {
|
||||||
|
padding: 4px 12px;
|
||||||
|
font: inherit;
|
||||||
|
color: var(--lt-fg);
|
||||||
|
background: var(--lt-editor-bg);
|
||||||
|
border: 1px solid var(--lt-border);
|
||||||
|
border-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sync-dialog__button--primary {
|
||||||
|
border-color: var(--lt-accent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.sync-dialog__button:disabled {
|
||||||
|
color: var(--lt-fg-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.sync-dialog__button:focus-visible {
|
||||||
|
outline: 1px solid var(--lt-accent);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
549
ui/src/components/deploy/remoteBrowser.ts
Normal file
549
ui/src/components/deploy/remoteBrowser.ts
Normal file
|
|
@ -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<string, unknown>).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<string, unknown>) : {};
|
||||||
|
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<string, unknown>).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<string, unknown>) : {};
|
||||||
|
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<string | null>(null);
|
||||||
|
/** Loaded folders by browser path. */
|
||||||
|
const dirs = ref<Record<string, DirState>>({});
|
||||||
|
/** Expanded folders. */
|
||||||
|
const open = ref<string[]>([]);
|
||||||
|
/** The selected path, or null. */
|
||||||
|
const selected = ref<string | null>(null);
|
||||||
|
/** The file in the viewer, or null. */
|
||||||
|
const file = shallowRef<RemoteFile | null>(null);
|
||||||
|
/** The sync preview's items; null while the preview is closed. */
|
||||||
|
const syncItems = ref<SyncItem[] | null>(null);
|
||||||
|
/** The paths the preview compared. */
|
||||||
|
const syncPaths = ref<string[]>([]);
|
||||||
|
/** 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<string | null>(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<string, JsonValue> {
|
||||||
|
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<string, JsonValue>): Promise<JsonValue | null> {
|
||||||
|
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<void> {
|
||||||
|
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<void> {
|
||||||
|
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<void> {
|
||||||
|
serverId.value = id;
|
||||||
|
dirs.value = {};
|
||||||
|
open.value = [];
|
||||||
|
file.value = null;
|
||||||
|
selected.value = null;
|
||||||
|
await loadDir("");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Reads every loaded folder again. */
|
||||||
|
async function refresh(): Promise<void> {
|
||||||
|
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<void> {
|
||||||
|
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<void> {
|
||||||
|
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<boolean> {
|
||||||
|
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<boolean> {
|
||||||
|
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<boolean> {
|
||||||
|
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<boolean> {
|
||||||
|
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<void> {
|
||||||
|
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<void> {
|
||||||
|
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<boolean> {
|
||||||
|
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<string, JsonValue> = { 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,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
@ -17,7 +17,8 @@
|
||||||
*
|
*
|
||||||
* The bottom panel ({@link BottomPanel}) holds the Find, Terminal and
|
* The bottom panel ({@link BottomPanel}) holds the Find, Terminal and
|
||||||
* Problems tool windows (and the Deployment log, G17, which appears with
|
* 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`),
|
* shown. Find appears with the UI command `find.open` (`Mod+Alt+F`),
|
||||||
* Terminal with `terminal.open` (`Mod+Shift+T`, M3.6), Problems with
|
* 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
|
* `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 { SHOW_HISTORY_COMMAND, SHOW_LOG_COMMAND, useLogStore } from "../vcs/log/log";
|
||||||
import StashDialog from "../vcs/stash/StashDialog.vue";
|
import StashDialog from "../vcs/stash/StashDialog.vue";
|
||||||
import DeploymentLogToolWindow from "../deploy/DeploymentLogToolWindow.vue";
|
import DeploymentLogToolWindow from "../deploy/DeploymentLogToolWindow.vue";
|
||||||
|
import RemoteBrowserToolWindow from "../deploy/RemoteBrowserToolWindow.vue";
|
||||||
|
import { useRemoteBrowserStore } from "../deploy/remoteBrowser";
|
||||||
import { useDeployStore } from "../deploy/deploy";
|
import { useDeployStore } from "../deploy/deploy";
|
||||||
import { SHOW_COMMIT_COMMAND, TOGGLE_BLAME_COMMAND, setCommitOpener, toggleBlame } from "../editor/blame";
|
import { SHOW_COMMIT_COMMAND, TOGGLE_BLAME_COMMAND, setCommitOpener, toggleBlame } from "../editor/blame";
|
||||||
import { SHOW_CHUNK_COMMAND, openChunkPopup } from "../editor/chunkPopup";
|
import { SHOW_CHUNK_COMMAND, openChunkPopup } from "../editor/chunkPopup";
|
||||||
|
|
@ -117,11 +120,12 @@ const nav = useNavStore();
|
||||||
const changes = useChangesStore();
|
const changes = useChangesStore();
|
||||||
const vcsLog = useLogStore();
|
const vcsLog = useLogStore();
|
||||||
const deploy = useDeployStore();
|
const deploy = useDeployStore();
|
||||||
|
const remoteBrowser = useRemoteBrowserStore();
|
||||||
const editor = useEditorStore();
|
const editor = useEditorStore();
|
||||||
const project = useProjectStore();
|
const project = useProjectStore();
|
||||||
|
|
||||||
/** Tool windows of the bottom panel. */
|
/** 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. */
|
/** The bottom tool window last chosen. */
|
||||||
const bottomTool = ref<BottomTool>("find");
|
const bottomTool = ref<BottomTool>("find");
|
||||||
/** Bottom tool windows that are shown, in tab order. */
|
/** 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 (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 (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 (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;
|
return tools;
|
||||||
});
|
});
|
||||||
/** The active bottom tool window: the chosen one if shown, else the first. */
|
/** The active bottom tool window: the chosen one if shown, else the first. */
|
||||||
|
|
@ -155,7 +160,9 @@ const bottomStore = computed(() =>
|
||||||
? vcsLog
|
? vcsLog
|
||||||
: bottomActive.value === "deployment"
|
: bottomActive.value === "deployment"
|
||||||
? deploy
|
? deploy
|
||||||
: find,
|
: bottomActive.value === "remote"
|
||||||
|
? remoteBrowser
|
||||||
|
: find,
|
||||||
);
|
);
|
||||||
/** Expansion of the panel, kept per tool window by its store. */
|
/** Expansion of the panel, kept per tool window by its store. */
|
||||||
const bottomOpen = computed({
|
const bottomOpen = computed({
|
||||||
|
|
@ -178,7 +185,8 @@ function chooseBottom(id: string): void {
|
||||||
id === "references" ||
|
id === "references" ||
|
||||||
id === "changes" ||
|
id === "changes" ||
|
||||||
id === "log" ||
|
id === "log" ||
|
||||||
id === "deployment"
|
id === "deployment" ||
|
||||||
|
id === "remote"
|
||||||
) {
|
) {
|
||||||
bottomTool.value = id;
|
bottomTool.value = id;
|
||||||
}
|
}
|
||||||
|
|
@ -288,6 +296,13 @@ onMounted(() => {
|
||||||
},
|
},
|
||||||
enabled: () => project.root !== null && activeView() !== null,
|
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", {
|
commands.provide("deployment.showLog", {
|
||||||
run: () => {
|
run: () => {
|
||||||
bottomTool.value = "deployment";
|
bottomTool.value = "deployment";
|
||||||
|
|
@ -395,6 +410,10 @@ onBeforeUnmount(() => {
|
||||||
v-if="deploy.visible"
|
v-if="deploy.visible"
|
||||||
v-show="bottomActive === 'deployment'"
|
v-show="bottomActive === 'deployment'"
|
||||||
/>
|
/>
|
||||||
|
<RemoteBrowserToolWindow
|
||||||
|
v-if="remoteBrowser.visible"
|
||||||
|
v-show="bottomActive === 'remote'"
|
||||||
|
/>
|
||||||
</BottomPanel>
|
</BottomPanel>
|
||||||
<StatusBar />
|
<StatusBar />
|
||||||
<StashDialog />
|
<StashDialog />
|
||||||
|
|
|
||||||
|
|
@ -3,8 +3,10 @@
|
||||||
* The project tree's context menu (M4.3). For a file: Open, Show Diff
|
* The project tree's context menu (M4.3). For a file: Open, Show Diff
|
||||||
* (`vcs.showDiff {path}`) and Show History (`vcs.showHistory {path}`,
|
* (`vcs.showDiff {path}`) and Show History (`vcs.showHistory {path}`,
|
||||||
* M4.6), the Git items dimmed while their command is disabled. For a file
|
* M4.6), the Git items dimmed while their command is disabled. For a file
|
||||||
* and a folder: Upload to Server and Download from Server
|
* and a folder: Upload to Server, Compare with Server (a diff for a file,
|
||||||
* (`deployment.upload` / `deployment.download {path}`, G17), dimmed while
|
* 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.
|
* no project is open or a deployment job runs.
|
||||||
*
|
*
|
||||||
* Follows the WAI-ARIA menu pattern: it takes the focus when it opens,
|
* Follows the WAI-ARIA menu pattern: it takes the focus when it opens,
|
||||||
|
|
@ -65,6 +67,12 @@ const deployItems = computed<MenuItem[]>(() => [
|
||||||
enabled: commands.isEnabled("deployment.upload"),
|
enabled: commands.isEnabled("deployment.upload"),
|
||||||
run: () => commands.execute("deployment.upload", { path: props.path }),
|
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",
|
id: "download",
|
||||||
label: t("project.tree.menu.download"),
|
label: t("project.tree.menu.download"),
|
||||||
|
|
|
||||||
|
|
@ -99,6 +99,9 @@ const caption = computed(() => {
|
||||||
if (tab.commit) {
|
if (tab.commit) {
|
||||||
return t("vcs.diff.captionCommit", { path: tab.path, hash: tab.commit.hash.slice(0, SHORT_HASH) });
|
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"
|
return refFor(tab.staged) === "HEAD"
|
||||||
? t("vcs.diff.captionHead", { path: tab.path })
|
? t("vcs.diff.captionHead", { path: tab.path })
|
||||||
: t("vcs.diff.captionIndex", { path: tab.path });
|
: t("vcs.diff.captionIndex", { path: tab.path });
|
||||||
|
|
@ -275,7 +278,7 @@ onBeforeUnmount(() => {
|
||||||
{{ caption }}
|
{{ caption }}
|
||||||
</div>
|
</div>
|
||||||
<div
|
<div
|
||||||
v-if="diff.activeTab && !diff.activeTab.commit && diff.activeContent?.phase === 'ready' && diff.activeContent.bufferId !== null"
|
v-if="diff.activeTab && !diff.activeTab.commit && !diff.activeTab.remote && diff.activeContent?.phase === 'ready' && diff.activeContent.bufferId !== null"
|
||||||
class="diff-view__hint"
|
class="diff-view__hint"
|
||||||
data-test="diff-chunk-hint"
|
data-test="diff-chunk-hint"
|
||||||
>
|
>
|
||||||
|
|
|
||||||
|
|
@ -31,6 +31,11 @@
|
||||||
* (right, `git.showAt {path, rev: hash}`) with its first parent (left, the
|
* (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
|
* old path of a rename). Both sides are read-only texts; nothing is
|
||||||
* re-read on `gitChanged` (commits do not change).
|
* 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.
|
* - **Untrusted input:** `git.show` results are checked field by field.
|
||||||
*/
|
*/
|
||||||
import { defineStore } from "pinia";
|
import { defineStore } from "pinia";
|
||||||
|
|
@ -83,6 +88,26 @@ export interface DiffTab {
|
||||||
name: string;
|
name: string;
|
||||||
/** For a commit tab: what it compares; absent for working-copy diffs. */
|
/** For a commit tab: what it compares; absent for working-copy diffs. */
|
||||||
commit?: DiffCommit;
|
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. */
|
/** What a diff tab shows. */
|
||||||
|
|
@ -282,6 +307,17 @@ export const useDiffStore = defineStore("diff", () => {
|
||||||
* @returns the checked result, or the error text.
|
* @returns the checked result, or the error text.
|
||||||
*/
|
*/
|
||||||
async function readLeft(tab: DiffTab): Promise<ShowResult | string> {
|
async function readLeft(tab: DiffTab): Promise<ShowResult | string> {
|
||||||
|
if (tab.remote) {
|
||||||
|
const params: Record<string, JsonValue> = { 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) });
|
const result = await runWaiting("git.show", { path: tab.path, ref: refFor(tab.staged) });
|
||||||
if (!result.ok) {
|
if (!result.ok) {
|
||||||
return result.error.message;
|
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<void> {
|
||||||
|
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
|
* Re-reads the left side of every loaded text tab; a changed text
|
||||||
* replaces the left document (`gitChanged`).
|
* replaces the left document (`gitChanged`).
|
||||||
|
|
@ -456,7 +510,7 @@ export const useDiffStore = defineStore("diff", () => {
|
||||||
await Promise.all(
|
await Promise.all(
|
||||||
tabs.value.map(async (tab) => {
|
tabs.value.map(async (tab) => {
|
||||||
const before = contents.value[tab.key];
|
const before = contents.value[tab.key];
|
||||||
if (before?.phase !== "ready" || tab.commit) {
|
if (before?.phase !== "ready" || tab.commit || tab.remote) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const generation = generations.get(tab.key);
|
const generation = generations.get(tab.key);
|
||||||
|
|
@ -569,6 +623,7 @@ export const useDiffStore = defineStore("diff", () => {
|
||||||
deactivate,
|
deactivate,
|
||||||
open,
|
open,
|
||||||
openAtCommit,
|
openAtCommit,
|
||||||
|
openRemote,
|
||||||
showDiff,
|
showDiff,
|
||||||
refreshLeft,
|
refreshLeft,
|
||||||
close,
|
close,
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,11 @@
|
||||||
{
|
{
|
||||||
"app.statusBar.version": "{name} {version}",
|
"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.download": "Download Current File from Server",
|
||||||
"command.deployment.servers": "Deployment Servers…",
|
"command.deployment.servers": "Deployment Servers…",
|
||||||
"command.deployment.showLog": "Deployment Log",
|
"command.deployment.showLog": "Deployment Log",
|
||||||
|
"command.deployment.sync": "Sync Project with Server…",
|
||||||
"command.deployment.testConnection": "Test Deployment Connection",
|
"command.deployment.testConnection": "Test Deployment Connection",
|
||||||
"command.deployment.upload": "Upload Current File to Server",
|
"command.deployment.upload": "Upload Current File to Server",
|
||||||
"command.deployment.uploadProject": "Upload Project to Server",
|
"command.deployment.uploadProject": "Upload Project to Server",
|
||||||
|
|
@ -135,6 +138,36 @@
|
||||||
"deploy.operation.upload": "Uploading",
|
"deploy.operation.upload": "Uploading",
|
||||||
"deploy.progress.files": "{operation} {done}/{total} · {server}",
|
"deploy.progress.files": "{operation} {done}/{total} · {server}",
|
||||||
"deploy.progress.short": "{operation} · {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.class": "Class",
|
||||||
"editor.assist.kind.color": "Colour",
|
"editor.assist.kind.color": "Colour",
|
||||||
"editor.assist.kind.constant": "Constant",
|
"editor.assist.kind.constant": "Constant",
|
||||||
|
|
@ -258,6 +291,8 @@
|
||||||
"notification.deploy.downloaded": "Downloaded {files} from {server}.",
|
"notification.deploy.downloaded": "Downloaded {files} from {server}.",
|
||||||
"notification.deploy.noServer": "No default deployment server yet. Add one, or choose the default.",
|
"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.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.uploadFailed": "Upload failed: {reason}",
|
||||||
"notification.deploy.uploadOnSaveFailed": "Upload on save to {server} failed: {error}",
|
"notification.deploy.uploadOnSaveFailed": "Upload on save to {server} failed: {error}",
|
||||||
"notification.deploy.uploaded": "Uploaded {files} to {server}.",
|
"notification.deploy.uploaded": "Uploaded {files} to {server}.",
|
||||||
|
|
@ -344,6 +379,7 @@
|
||||||
"project.openFolder": "Open Folder…",
|
"project.openFolder": "Open Folder…",
|
||||||
"project.toolWindow.title": "Project",
|
"project.toolWindow.title": "Project",
|
||||||
"project.tree.loading": "Loading…",
|
"project.tree.loading": "Loading…",
|
||||||
|
"project.tree.menu.compareServer": "Compare with Server",
|
||||||
"project.tree.menu.download": "Download from Server",
|
"project.tree.menu.download": "Download from Server",
|
||||||
"project.tree.menu.label": "Actions for {name}",
|
"project.tree.menu.label": "Actions for {name}",
|
||||||
"project.tree.menu.open": "Open",
|
"project.tree.menu.open": "Open",
|
||||||
|
|
@ -521,6 +557,7 @@
|
||||||
"vcs.diff.captionCommit": "{path}: before (left) and after (right) commit {hash}",
|
"vcs.diff.captionCommit": "{path}: before (left) and after (right) commit {hash}",
|
||||||
"vcs.diff.captionHead": "{path}: last commit (left) and working copy (right)",
|
"vcs.diff.captionHead": "{path}: last commit (left) and working copy (right)",
|
||||||
"vcs.diff.captionIndex": "{path}: staged version (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.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.closeTab": "Close the diff of {name}",
|
||||||
"vcs.diff.failed": "The diff cannot be shown: {reason}",
|
"vcs.diff.failed": "The diff cannot be shown: {reason}",
|
||||||
|
|
|
||||||
203
ui/tests/deploy/RemoteBrowser.test.ts
Normal file
203
ui/tests/deploy/RemoteBrowser.test.ts
Normal file
|
|
@ -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<string, unknown>;
|
||||||
|
}
|
||||||
|
|
||||||
|
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<string, unknown> }) => {
|
||||||
|
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: "<?php // server", binary: false, tooLarge: false });
|
||||||
|
case "deploy.compare":
|
||||||
|
return Promise.resolve({
|
||||||
|
differences: [
|
||||||
|
{ path: "a.php", status: "different", localSize: 1, remoteSize: 2 },
|
||||||
|
{ path: "new.php", status: "localOnly", localSize: 1 },
|
||||||
|
{ path: "old.php", status: "remoteOnly", remoteSize: 1 },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
case "deploy.sync":
|
||||||
|
return Promise.resolve({ files: 2, deleted: 1, failed: 0, skipped: 0, bytes: 2 });
|
||||||
|
default:
|
||||||
|
return Promise.resolve({});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
for (const wrapper of mounted) {
|
||||||
|
wrapper.unmount();
|
||||||
|
}
|
||||||
|
document.body.innerHTML = "";
|
||||||
|
});
|
||||||
|
|
||||||
|
async function mountBrowser(): Promise<VueWrapper> {
|
||||||
|
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<HTMLTextAreaElement>("[data-test='remote-text']");
|
||||||
|
expect(text.element.readOnly).toBe(true);
|
||||||
|
await wrapper.find("[data-test='remote-edit']").trigger("click");
|
||||||
|
await text.setValue("<?php // edited");
|
||||||
|
await wrapper.find("[data-test='remote-upload']").trigger("click");
|
||||||
|
await flushPromises();
|
||||||
|
expect(callsOf("deploy.writeRemote")[0]?.params).toEqual({ remotePath: "index.php", text: "<?php // edited" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("renames, creates a folder and deletes only after the question", async () => {
|
||||||
|
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");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -475,7 +475,7 @@ describe("project tree context menu", () => {
|
||||||
await tree.find("[data-path='a.php']").trigger("contextmenu", { clientX: 40, clientY: 50 });
|
await tree.find("[data-path='a.php']").trigger("contextmenu", { clientX: 40, clientY: 50 });
|
||||||
const menu = document.querySelector("[data-test=tree-menu]");
|
const menu = document.querySelector("[data-test=tree-menu]");
|
||||||
expect(menu).not.toBeNull();
|
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();
|
(document.querySelector("[data-item=showDiff]") as HTMLElement).click();
|
||||||
await flushPromises();
|
await flushPromises();
|
||||||
await flushPromises();
|
await flushPromises();
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue