Файли
openidea/crates/ide-svn/tests/process.rs
T
LU XIANGRUIтаwildcatDownstairs adf5701e16 fix(svn): data loss and mixed-project Git fixes from a second review of #7131 (#7266)
Fixes from a second review of the built-in Subversion support: rollback keeps moved and needs-lock files intact, a failed commit staging step undoes only the schedules it made, mixed Git/SVN Commit All no longer pulls in unstaged Git edits, status refreshes keep failed roots' rows without resurrecting cleaned ones, BASE image sizes follow copy history, logins say whether the user asked, Windows passwords are sent in the console code page, and background Log refreshes share one SVN branch lookup so a cancelled login is not re-prompted.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 15:48:23 +08:00

423 рядки
17 KiB
Rust

//! How svn runs as a process (plan §8 group 6): a cancelled command leaves no working-copy
//! lock behind, and a locale that is not UTF-8 does not garble paths. Against a throwaway
//! `svnserve`; skipped locally without svn, required in CI.
mod common;
use common::*;
use ide_core::CancellationToken;
use ide_core::error::ErrorKind;
use ide_vcs::Backend;
use std::net::{TcpListener, TcpStream};
use std::path::Path;
use std::process::Command;
use std::time::{Duration, Instant};
/// `svnserve` on a free port, open to anyone, serving the test repository.
#[cfg(unix)]
fn serve(repo: &Path) -> (Svnserve, String) {
std::fs::write(repo.join("conf/svnserve.conf"), "[general]\nanon-access = write\n").unwrap();
svnserve(repo)
}
/// svnserve stopped (`SIGSTOP`) for as long as this lives; resumed when dropped, also when an
/// assertion fails, and then `cancel` is cancelled too, so no test waits on a stopped server.
#[cfg(unix)]
struct Paused<'a> {
pid: String,
cancel: &'a CancellationToken,
}
#[cfg(unix)]
impl<'a> Paused<'a> {
fn new(server: &Svnserve, cancel: &'a CancellationToken) -> Self {
let pid = server.0.id().to_string();
assert!(Command::new("kill").args(["-STOP", &pid]).status().unwrap().success());
Paused { pid, cancel }
}
}
#[cfg(unix)]
impl Drop for Paused<'_> {
fn drop(&mut self) {
if std::thread::panicking() {
self.cancel.cancel();
}
let _ = Command::new("kill").args(["-CONT", &self.pid]).status();
}
}
/// Waits until a command holds the working copy's lock (`L`), instead of guessing how long
/// svn takes to get there.
#[cfg(unix)]
fn until_locked(repo: &Repo, wc: &ide_svn::WorkingCopy) {
let started = Instant::now();
while !repo.svn(wc.root(), &["status", "--depth", "empty"]).lines().any(|l| l.as_bytes().get(2) == Some(&b'L')) {
assert!(started.elapsed() < Duration::from_secs(30), "the update never took the lock");
std::thread::sleep(Duration::from_millis(50));
}
}
/// Cancel during an update that hangs on the server: the command stops at once, and the
/// working copy is not left locked (no Cleanup needed). IntelliJ SvnCommandLineStabilityTest
/// for the many quick commands after it.
#[cfg(unix)]
#[test]
fn a_cancelled_update_leaves_no_lock() {
if !have(&["svnserve"]) {
return;
}
let Some(repo) = repo() else { return };
let (server, url) = serve(&repo.base.join("repo"));
let dest = repo.base.join("wc");
let ctx = ctx();
let wc = ide_svn::WorkingCopy::checkout(
&format!("{url}/trunk"),
None,
&dest,
ide_svn::Depth::Infinity,
ctx.clone(),
&CancellationToken::new(),
)
.unwrap();
let other = repo.checkout("other");
write(&other, "a.txt", "a\n");
other.files_added(&[other.root().join("a.txt")]).unwrap();
commit(&other, &[], "a");
// The server stops answering mid-way.
let cancel = CancellationToken::new();
let (err, took) = std::thread::scope(|s| {
let paused = Paused::new(&server, &cancel);
let update = s.spawn(|| wc.update(&[], None, &cancel));
until_locked(&repo, &wc);
let started = Instant::now();
cancel.cancel();
let result = update.join().unwrap();
drop(paused);
(result, started.elapsed())
});
let err = err.unwrap_err();
assert_eq!(err.kind, ErrorKind::Cancelled, "{err:?}");
assert!(took < Duration::from_secs(10), "{took:?}");
let status = repo.svn(wc.root(), &["status"]);
assert!(!status.lines().any(|l| l.as_bytes().get(2) == Some(&b'L')), "locked:\n{status}");
assert_eq!(wc.update(&[], None, &CancellationToken::new()).unwrap(), 2);
assert!(wc.root().join("a.txt").exists());
// Many quick commands in a row all answer.
for _ in 0..50 {
assert!(wc.status().unwrap().is_empty());
}
}
/// `LC_ALL` set to a locale that is not UTF-8 (`C`): paths with other scripts still come
/// through, as svn runs with a UTF-8 `LC_CTYPE` of its own.
#[test]
fn a_locale_that_is_not_utf8() {
let Some(repo) = repo() else { return };
let wc = repo.checkout("wc");
let name = named("中文 ünïcode.txt", "ünïcode.txt");
write(&wc, name, "x\n");
// SAFETY: the variables are read by the svn processes this test starts; the other tests
// of this binary set the same values or none.
unsafe {
std::env::set_var("LC_ALL", "C");
std::env::set_var("LANG", "C");
}
wc.files_added(&[wc.root().join(name)]).unwrap();
assert_eq!(rows(&wc), [format!("{name}:Added")]);
commit(&wc, &[], "中文说明");
assert!(wc.status().unwrap().is_empty());
assert_eq!(
wc.log(&ide_vcs::LogQuery { limit: 1, ..Default::default() }, &CancellationToken::new()).unwrap()[0].summary,
"中文说明"
);
}
/// While a long update runs (the server is slow), a refresh of the Changes view still
/// answers, and a second command that writes says plainly that the working copy is busy.
/// commit_tests.py (commit_with_lock), IntelliJ SvnTestCase's E155004 retry.
#[cfg(unix)]
#[test]
fn commands_during_a_long_update() {
if !have(&["svnserve"]) {
return;
}
let Some(repo) = repo() else { return };
let (server, url) = serve(&repo.base.join("repo"));
let dest = repo.base.join("wc");
let wc = ide_svn::WorkingCopy::checkout(
&format!("{url}/trunk"),
None,
&dest,
ide_svn::Depth::Infinity,
ctx(),
&CancellationToken::new(),
)
.unwrap();
write(&wc, "mine.txt", "m\n");
let other = repo.checkout("other");
write(&other, "a.txt", "a\n");
other.files_added(&[other.root().join("a.txt")]).unwrap();
commit(&other, &[], "a");
let cancel = CancellationToken::new();
std::thread::scope(|s| {
let paused = Paused::new(&server, &cancel);
let update = s.spawn(|| wc.update(&[], None, &cancel));
until_locked(&repo, &wc);
// The file watcher's refresh.
assert_eq!(rows(&wc), ["mine.txt:Untracked"]);
// A second writer.
let err = wc.files_added(&[wc.root().join("mine.txt")]).unwrap_err();
assert!(err.message.starts_with("the working copy is locked: another svn command is using it"), "{err:?}");
drop(paused);
assert_eq!(update.join().unwrap().unwrap(), 2);
});
wc.files_added(&[wc.root().join("mine.txt")]).unwrap();
assert_eq!(rows(&wc), ["mine.txt:Added"]);
}
/// Records every prompt and answers with the next of `answers` (`None`: cancel).
struct Answers {
answers: parking_lot::Mutex<Vec<Option<String>>>,
asked: parking_lot::Mutex<Vec<ide_svn::Prompt>>,
}
impl Answers {
fn new(answers: &[Option<&str>]) -> std::sync::Arc<Self> {
std::sync::Arc::new(Self {
answers: parking_lot::Mutex::new(answers.iter().rev().map(|a| a.map(str::to_owned)).collect()),
asked: Default::default(),
})
}
}
impl ide_svn::PromptHandler for Answers {
fn answer(&self, prompt: &ide_svn::Prompt) -> Option<String> {
self.asked.lock().push(prompt.clone());
self.answers.lock().pop().flatten()
}
}
fn context(config: &Path, handler: std::sync::Arc<Answers>) -> std::sync::Arc<ide_svn::SvnContext> {
std::fs::create_dir_all(config).unwrap();
std::fs::write(config.join("config"), "[auth]\npassword-stores =\n").unwrap();
let ctx = std::sync::Arc::new(ide_svn::SvnContext::new(ide_svn::Settings {
config_dir: Some(config.to_path_buf()),
..ide_svn::Settings::default()
}));
ctx.set_prompt_handler(Some(handler));
ctx
}
/// A self-signed HTTPS server (`openssl s_server`, closing each connection after the
/// handshake): svn asks whether to trust its certificate, and each answer does what svn
/// says. IntelliJ SvnNativeClientAuthTest (testCertificateRejectedThen…, testMixedSSLCommit).
#[test]
#[cfg_attr(windows, ignore = "svn's own prompts: interactive mode is not available on Windows")]
fn server_certificate_prompts() {
// openssl is a helper here: skipped without it locally, required in CI (`have`).
if !have(&["svn", "openssl"]) {
return;
}
let dir = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(dir.path()).unwrap();
let made = Command::new("openssl")
.args(["req", "-x509", "-newkey", "rsa:2048", "-nodes", "-days", "1", "-subj", "/CN=localhost", "-keyout"])
.arg(base.join("key.pem"))
.arg("-out")
.arg(base.join("cert.pem"))
.output()
.unwrap();
assert!(made.status.success(), "{}", String::from_utf8_lossy(&made.stderr));
let port = TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
let server = Command::new("openssl")
.args(["s_server", "-quiet", "-accept", &port.to_string(), "-cert"])
.arg(base.join("cert.pem"))
.arg("-key")
.arg(base.join("key.pem"))
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
.unwrap();
let _server = Svnserve(server);
let started = Instant::now();
while TcpStream::connect(("127.0.0.1", port)).is_err() {
assert!(started.elapsed() < Duration::from_secs(10), "openssl s_server did not start");
std::thread::sleep(Duration::from_millis(50));
}
let url = format!("https://localhost:{port}/repo");
let config = base.join("config");
let checkout = |answers: &[Option<&str>], name: &str| {
let handler = Answers::new(answers);
let err = ide_svn::WorkingCopy::checkout(
&url,
None,
&base.join(name),
ide_svn::Depth::Infinity,
context(&config, handler.clone()),
&CancellationToken::new(),
)
.expect_err("the server closes every connection");
(err, handler.asked.lock().clone())
};
// Reject: svn says the certificate is not trusted.
let (err, asked) = checkout(&[Some("R")], "r");
assert!(matches!(&asked[..], [ide_svn::Prompt::ServerCertificate { permanent: true, .. }]), "{asked:?}");
let ide_svn::Prompt::ServerCertificate { url: asked_url, details, .. } = &asked[0] else { unreachable!() };
assert_eq!(asked_url, &format!("https://localhost:{port}"));
assert!(details.contains("Fingerprint:"), "{details}");
assert!(err.message.contains("certificate"), "{err:?}");
// Cancel: the command is cancelled.
let (err, _) = checkout(&[None], "c");
assert_eq!(err.kind, ErrorKind::Cancelled, "{err:?}");
// Accept for now: svn goes on past the certificate, and asks again next time.
let (err, _) = checkout(&[Some("t")], "t");
assert!(!err.message.contains("certificate"), "{err:?}");
let (_, asked) = checkout(&[Some("t")], "t2");
assert_eq!(asked.len(), 1);
// Accept for good: never asked again.
checkout(&[Some("p")], "p");
let (err, asked) = checkout(&[], "p2");
assert!(asked.is_empty(), "{asked:?}");
assert!(!err.message.contains("certificate"), "{err:?}");
}
/// The prompts no local server here can bring (a client certificate's file and passphrase,
/// and Linux's "Store password unencrypted"), from a stand-in for svn that asks them in
/// svn's own words: each reaches the handler, and the answer reaches svn.
#[cfg(unix)]
#[test]
fn client_certificate_and_plaintext_prompts() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(dir.path()).unwrap();
let fake = base.join("svn");
let script = r#"#!/bin/sh
if [ "$1" = "--version" ]; then echo 1.14.0; exit 0; fi
printf "Authentication realm: https://example.test:443\nClient certificate filename: " >&2
read file
printf "Authentication realm: https://example.test:443\nPassphrase for '%s': " "$file" >&2
read pass
printf "\n-----------------------------------------------------------------------\nATTENTION! Your password for authentication realm:\n\n <https://example.test:443> Test\n\ncan only be stored to disk unencrypted!\n-----------------------------------------------------------------------\nStore password unencrypted (yes/no)? " >&2
read store
printf '<?xml version="1.0"?><info><entry kind="dir" path="." revision="1"><url>https://example.test/trunk</url><relative-url>^/trunk</relative-url><repository><root>https://example.test</root><uuid>u</uuid></repository><wc-info><wcroot-abspath>%s</wcroot-abspath></wc-info></entry></info>' "$PWD"
echo "$file|$pass|$store" > answers.txt
"#;
std::fs::write(&fake, script).unwrap();
std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
std::fs::create_dir(base.join(".svn")).unwrap();
let handler = Answers::new(&[Some("/certs/me.p12"), Some("pass phrase"), Some("no")]);
let ctx = std::sync::Arc::new(ide_svn::SvnContext::new(ide_svn::Settings {
executable: Some(fake),
..Default::default()
}));
ctx.set_prompt_handler(Some(handler.clone()));
let found = ide_svn::WorkingCopy::discover(&base, ctx).unwrap();
assert!(found.is_some());
let asked = handler.asked.lock().clone();
assert!(
matches!(
&asked[..],
[
ide_svn::Prompt::ClientCertificate { .. },
ide_svn::Prompt::ClientCertificatePassphrase { .. },
ide_svn::Prompt::StorePlaintext { .. }
]
),
"{asked:?}"
);
let ide_svn::Prompt::ClientCertificatePassphrase { file, .. } = &asked[1] else { unreachable!() };
assert_eq!(file, "/certs/me.p12");
// What svn read on its standard input.
assert_eq!(std::fs::read_to_string(base.join("answers.txt")).unwrap(), "/certs/me.p12|pass phrase|no\n");
}
/// `svn+ssh://`: svn starts the ssh of `SVN_SSH` with the environment of the settings, and
/// that ssh asks the app's `SSH_ASKPASS` for the password (no terminal: svn runs in a
/// session of its own). The stand-in ssh checks the password, then runs svnserve in tunnel
/// mode as sshd would.
#[cfg(unix)]
#[test]
fn svn_over_ssh_asks_the_askpass_program() {
use std::os::unix::fs::PermissionsExt;
if !have(&["svnserve"]) {
return;
}
let Some(repo) = repo() else { return };
let exe = |name: &str, text: String| {
let path = repo.base.join(name);
std::fs::write(&path, text).unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
path
};
let asked = repo.base.join("asked.txt");
let askpass = exe("askpass", format!("#!/bin/sh\necho \"$1\" >> '{}'\necho secret\n", asked.display()));
let ssh = exe(
"ssh",
format!(
"#!/bin/sh\nanswer=$(\"$SSH_ASKPASS\" \"alice@localhost's password: \" </dev/null)\n[ \"$answer\" = secret ] || {{ echo 'Permission denied' >&2; exit 255; }}\nexec svnserve -t -r '{}'\n",
repo.base.join("repo").display()
),
);
let env = vec![
("SVN_SSH".to_owned(), ssh.to_string_lossy().into_owned()),
("SSH_ASKPASS".to_owned(), askpass.to_string_lossy().into_owned()),
("SSH_ASKPASS_REQUIRE".to_owned(), "force".to_owned()),
];
let ctx = std::sync::Arc::new(ide_svn::SvnContext::new(ide_svn::Settings {
config_dir: Some(config_dir().to_path_buf()),
env,
..ide_svn::Settings::default()
}));
let dest = repo.base.join("wc");
let wc = ide_svn::WorkingCopy::checkout(
"svn+ssh://localhost/trunk",
None,
&dest,
ide_svn::Depth::Infinity,
ctx,
&CancellationToken::new(),
)
.unwrap();
write(&wc, "a.txt", "a\n");
wc.files_added(&[wc.root().join("a.txt")]).unwrap();
assert_eq!(commit(&wc, &[], "over ssh"), "2");
let asked = std::fs::read_to_string(&asked).unwrap();
assert!(asked.lines().all(|l| l == "alice@localhost's password: ") && asked.lines().count() >= 2, "{asked}");
}
/// An svn older than OpenIDEA needs, or none at the configured path: every command says so,
/// and nothing runs.
#[cfg(unix)]
#[test]
fn an_old_or_missing_svn() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(dir.path()).unwrap();
let old = base.join("svn");
let ran = base.join("ran.txt");
std::fs::write(
&old,
format!(
"#!/bin/sh\nif [ \"$1\" = \"--version\" ]; then echo 1.7.22; exit 0; fi\necho \"$*\" >> '{}'\n",
ran.display()
),
)
.unwrap();
std::fs::set_permissions(&old, std::fs::Permissions::from_mode(0o755)).unwrap();
std::fs::create_dir(base.join(".svn")).unwrap();
let with = |exe: std::path::PathBuf| {
std::sync::Arc::new(ide_svn::SvnContext::new(ide_svn::Settings { executable: Some(exe), ..Default::default() }))
};
let err = ide_svn::WorkingCopy::discover(&base, with(old)).unwrap_err();
assert!(err.message.contains("Subversion 1.7 is too old; OpenIDEA needs 1.8 or later"), "{err:?}");
assert!(!ran.exists(), "no command ran");
let err = ide_svn::WorkingCopy::discover(&base, with(base.join("nowhere/svn"))).unwrap_err();
assert!(err.data.is_some(), "a missing tool: {err:?}");
}