Порівняти коміти

..
Автор SHA1 Повідомлення Дата
l0ng-ai 6d3a0d83c0 fix(database): include identity, generated, partition and unlogged clauses in PostgreSQL DDL
Go to DDL on PostgreSQL dropped identity columns (generated by default / always as
identity), stored generated columns, partition by on partitioned tables, the
partition of ... for values form of partitions, and unlogged. They are now rendered;
a partition lists only its local overrides, constraints, indexes and triggers. The DDL
of ordinary tables is unchanged (compared byte for byte on PostgreSQL 17).
2026-12-01 16:58:08 +08:00
85 змінених файлів з 463 додано та 3682 видалено

No files matched your search

+38 -75
Переглянути файл
@@ -2050,63 +2050,46 @@ impl AgentManager {
return Err(IdeError::invalid("wait until the agent is done"));
}
let epoch = self.shared.shutdown_epoch();
// A Codex fork must be opened by its own task: the creating app-server owns its writer.
// It can also fork a recorded thread whose writer is held by another process.
let codex_source = {
let s = source.state.lock();
(s.task.provider == "codex").then(|| s.session_id.clone()).flatten()
};
let live = if codex_source.is_none() {
Some(source.ensure_session(epoch).await.map_err(IdeError::internal)?)
} else {
None
};
let live = source.ensure_session(epoch).await.map_err(IdeError::internal)?;
let total = turn_starts(&source.state.lock().history.conversation.main.entries).len() as u32;
let keep = turns.unwrap_or(total).min(total);
let capabilities = live.as_ref().map(|l| l.capabilities).unwrap_or(source.state.lock().task.capabilities);
if !capabilities.fork || (keep < total && !capabilities.rollback) {
if !live.capabilities.fork || (keep < total && !live.capabilities.rollback) {
return Err(IdeError::invalid("this agent can't copy a conversation from there"));
}
let session = if let Some(live) = &live {
let (cwd, provider_id, mcp_overrides, project_root) = {
let s = source.state.lock();
let t = &s.task;
(t.cwd.0.clone(), t.provider.clone(), t.mcp_overrides.clone(), t.project_root.clone().map(|p| p.0))
};
let mcp_servers = source.shared.mcp_servers_for_session(&provider_id, &live.init, &mcp_overrides);
let roots = source.shared.additional_directories(&live.init, &cwd, project_root.as_deref());
let skills_delivery = source.stage_skills(stage_key(live.driver), &cwd).await;
let memory_delivery = source.stage_memory(&provider_id, &cwd).await;
let cwd_s = dunce::canonicalize(&cwd).unwrap_or(cwd).to_string_lossy().into_owned();
let reply: Value = live
.peer
.request(
"session/fork",
{
let mut params = session_params(
&cwd_s,
&mcp_servers,
skills_delivery.as_ref(),
memory_delivery.as_ref(),
&roots,
);
params["sessionId"] = json!(live.session);
params
},
None,
)
.await
.map_err(|e| IdeError::internal(source.describe(e)))?;
Some(
reply
.get("sessionId")
.and_then(Value::as_str)
.ok_or_else(|| IdeError::internal("the agent returned no session"))?
.to_owned(),
)
} else {
None
let (cwd, provider_id, mcp_overrides, project_root) = {
let s = source.state.lock();
let t = &s.task;
(t.cwd.0.clone(), t.provider.clone(), t.mcp_overrides.clone(), t.project_root.clone().map(|p| p.0))
};
let mcp_servers = source.shared.mcp_servers_for_session(&provider_id, &live.init, &mcp_overrides);
let roots = source.shared.additional_directories(&live.init, &cwd, project_root.as_deref());
let skills_delivery = source.stage_skills(stage_key(live.driver), &cwd).await;
let memory_delivery = source.stage_memory(&provider_id, &cwd).await;
let cwd_s = dunce::canonicalize(&cwd).unwrap_or(cwd).to_string_lossy().into_owned();
let reply: Value = live
.peer
.request(
"session/fork",
{
let mut params = session_params(
&cwd_s,
&mcp_servers,
skills_delivery.as_ref(),
memory_delivery.as_ref(),
&roots,
);
params["sessionId"] = json!(live.session);
params
},
None,
)
.await
.map_err(|e| IdeError::internal(source.describe(e)))?;
let session = reply
.get("sessionId")
.and_then(Value::as_str)
.ok_or_else(|| IdeError::internal("the agent returned no session"))?
.to_owned();
let file = {
let s = source.state.lock();
let mut entries = s.history.conversation.main.entries.clone();
@@ -2132,7 +2115,7 @@ impl AgentManager {
};
TaskFile {
task,
session_id: session,
session_id: Some(session),
entries,
wanted: s.wanted.clone(),
pending_model: None,
@@ -2147,19 +2130,12 @@ impl AgentManager {
pending_rollback: total - keep,
title_renamed: s.title_renamed,
ephemeral: s.ephemeral,
pending_native_fork: codex_source.map(|source| ForkStart { source, target: None }),
pending_native_fork: None,
}
};
// Copying may have started the source's agent: it stops again once idle.
if live.is_some() {
source.release_when_idle();
}
source.release_when_idle();
let task = Task::restore(file, self.shared.clone());
if live.is_none() {
// Establish the fork before returning so its snapshot cannot drift while the source continues.
task.ensure_session(epoch).await.map_err(IdeError::internal)?;
task.release_when_idle();
}
self.tasks.write().insert(task.id.clone(), task.clone());
task.persist();
task.emit_task();
@@ -4973,19 +4949,6 @@ impl Task {
if let Some(message) = self.sign_in_error(&e, Some(&sign_in_message)) {
return Err(SessionOpenError { message, allow_acp_fallback: false });
}
// A writer conflict is temporary: retrying must retain the original session ID.
if spec.driver == provider::Driver::Codex
&& matches!(&e, RpcError::Server { message, .. } if message.contains("already has an active writer"))
{
return Err(SessionOpenError {
message: format!(
"Couldn't reopen this conversation's {} session: {}",
spec.name,
self.describe(e)
),
allow_acp_fallback: false,
});
}
if pending_model.is_some() {
return Err(SessionOpenError {
message: format!(
-35
Переглянути файл
@@ -2191,41 +2191,6 @@ async fn a_session_that_fails_to_load_is_reported_and_replaced_only_when_sent_ag
assert_eq!(calls(&agent), ["session/load", "session/new", "session/prompt"]);
}
/// A locked Codex recording can be forked without resuming it or moving its writer between tasks.
#[tokio::test(flavor = "multi_thread")]
async fn codex_writer_conflict_can_retry_or_fork_on_a_new_connection() {
let tmp = tempfile::tempdir().unwrap();
let task = {
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask { prompt: text("again"), provider: "codex".into(), ..Default::default() })
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
mgr.shutdown();
task
};
let agent = Arc::new(FakeAgent {
load_error: Some((codes::INVALID_PARAMS, "thread s1 already has an active writer".into())),
..Default::default()
});
let mgr = manager(tmp.path(), agent.clone());
for _ in 0..2 {
mgr.prompt(&task.id, text("again"), false).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Failed).await;
}
assert!(!agent.calls.lock().iter().any(|c| c == "session/new"));
let copy = mgr.fork(&task.id, None).await.unwrap();
assert_eq!(agent.forks.lock().last().unwrap()["sessionId"], "s1");
let copy_handle = mgr.task(&copy.id).unwrap();
assert_eq!(copy_handle.live.lock().as_ref().unwrap().session, "s2");
let loads = agent.calls.lock().iter().filter(|c| *c == "session/load").count();
mgr.prompt(&copy.id, text("again"), false).await.unwrap();
wait_for(&mgr, &copy.id, AgentStatus::Ready).await;
assert_eq!(agent.calls.lock().iter().filter(|c| *c == "session/load").count(), loads);
mgr.shutdown();
}
fn text(t: &str) -> AgentPrompt {
AgentPrompt { text: t.into(), ..AgentPrompt::default() }
}
+3 -3
Переглянути файл
@@ -17,8 +17,8 @@ pub use launch_resources::process_launch_resources;
pub use modules::record_module_build;
pub use single::{
SingleFileTarget, compile_file_plan, compile_file_plan_cancellable, find_javac, gradle_compile_file_plan,
has_gradle_file_target, javac_step, maven_system_classpath, module_classpath, module_classpath_without_build,
module_classpaths, single_file_classpath, single_file_target,
has_gradle_file_target, javac_step, module_classpath, module_classpath_without_build, module_classpaths,
single_file_classpath, single_file_target,
};
pub use structure::{
StructureJdk, StructureRoots, artifact_file, artifact_output, language_release, structure_compile_file_plan,
@@ -986,7 +986,7 @@ fn maven_launch_projects<'a>(
}
projects.push(p);
for dep in &p.dependencies {
if !dep.resolved() || dep.scope == "system" || (dep.scope == "test" && (!test || p.pom != start.pom)) {
if !dep.resolved() || (dep.scope == "test" && (!test || p.pom != start.pom)) {
continue;
}
if let Some(upstream) = reactor.iter().find(|u| {
+4 -87
Переглянути файл
@@ -180,30 +180,6 @@ pub fn find_javac(env: &BTreeMap<String, String>) -> String {
exe.to_owned()
}
/// Existing system-scope dependencies of this module. Maven resolves these from
/// their local files and does not pass them transitively to reactor dependents.
pub fn maven_system_classpath(root: &Path, model: &BuildModel, module: &Path) -> Vec<PathBuf> {
let Some(maven) = &model.maven else { return Vec::new() };
let module = root.join(module);
maven
.projects
.iter()
.find(|p| root.join(&p.dir) == module)
.into_iter()
.flat_map(|p| &p.system_paths)
.filter(|p| p.is_file())
.cloned()
.collect()
}
fn with_system_classpath(root: &Path, model: &BuildModel, module: &Path, classpath: String) -> String {
let system = maven_system_classpath(root, model, module);
if system.is_empty() {
return classpath;
}
join_classpath(std::env::split_paths(&classpath).chain(system).map(|p| p.to_string_lossy().into_owned()))
}
/// Dependency classpath of the module: existing reactor class directories plus
/// `mvn dependency:build-classpath` (which resolves without compiling anything,
/// so `-am` stays cheap). Entries are platform-separated (`;` on Windows).
@@ -257,7 +233,7 @@ pub fn module_classpath_without_build(
&& cached.version == CLASSPATH_CACHE_VERSION
&& classpath_entries_exist(root, &cached.classpath)
{
return Ok(with_system_classpath(root, model, &target.module, cached.classpath));
return Ok(cached.classpath);
}
classpath(root, model, &target, if test { "test" } else { "runtime" }, false, cancel)
}
@@ -294,7 +270,7 @@ pub fn module_classpaths(
&& classpath_entries_exist(root, &cached.classpath)
{
if i == 0 {
return Ok(with_system_classpath(root, model, &target.module, cached.classpath));
return Ok(cached.classpath);
}
continue;
}
@@ -322,7 +298,7 @@ pub fn module_classpaths(
}
}
}
Ok(with_system_classpath(root, model, &modules[0], classpaths.into_iter().next().unwrap()))
Ok(classpaths.into_iter().next().unwrap())
}
/// A module whose classpath the Maven probe resolves, with its cache key and file.
@@ -370,8 +346,7 @@ fn classpath(
compile_first: bool,
cancel: &CancellationToken,
) -> IdeResult<String> {
let classpath = classpaths(root, model, &[target], scope, compile_first, cancel)?.pop().unwrap();
Ok(with_system_classpath(root, model, &target.module, classpath))
Ok(classpaths(root, model, &[target], scope, compile_first, cancel)?.pop().unwrap())
}
/// The classpath of each of `targets` (modules of one reactor) from one Maven probe.
@@ -937,64 +912,6 @@ mod tests {
assert!(args.lines().any(|a| a == "-Dmdep.includeScope=test"), "{args}");
}
#[cfg(unix)]
#[test]
fn system_jars_augment_maven_javac_and_launch_classpaths() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap();
write(
&root,
"pom.xml",
r#"<project><groupId>demo</groupId><artifactId>parent</artifactId><version>1</version>
<packaging>pom</packaging><modules><module>app</module></modules>
<properties><lib.dir>src/main/resources/lib</lib.dir></properties></project>"#,
);
write(
&root,
"app/pom.xml",
r#"<project><parent><groupId>demo</groupId><artifactId>parent</artifactId><version>1</version></parent>
<artifactId>app</artifactId>
<properties><lib.file>${lib.dir}/offline.jar</lib.file></properties>
<dependencies>
<dependency><groupId>local</groupId><artifactId>offline</artifactId><version>1</version>
<scope>system</scope><systemPath>${pom.basedir}/${lib.file}</systemPath></dependency>
<dependency><groupId>local</groupId><artifactId>late</artifactId><version>1</version>
<scope>system</scope><systemPath>${project.basedir}/${lib.dir}/late.jar</systemPath></dependency>
<dependency><groupId>local</groupId><artifactId>directory</artifactId><version>1</version>
<scope>system</scope><systemPath>${project.basedir}/${lib.dir}</systemPath></dependency>
</dependencies></project>"#,
);
let jars = "app/src/main/resources/lib";
write(&root, &format!("{jars}/offline.jar"), "");
write(&root, "app/src/main/java/demo/Main.java", "class Main {}");
// The scope-filtered Maven classpath can contain no dependencies.
write(&root, "mvnw", "#!/bin/sh\nmkdir -p app/target\n: > app/target/ide-compile-cp.txt\n");
fs::set_permissions(root.join("mvnw"), fs::Permissions::from_mode(0o755)).unwrap();
let cache = root.join("cache");
let model = crate::load(&root, &cache, None);
let module = root.join("app");
let file = module.join("src/main/java/demo/Main.java");
let jar = root.join(jars).join("offline.jar");
let plan = compile_file_plan(&root, &model, &file).unwrap();
assert!(plan.steps[0].args.windows(2).any(|arg| arg[0] == "-cp" && Path::new(&arg[1]) == jar));
let cancel = CancellationToken::new();
let cp = module_classpath(&root, &model, &module, false, None, &cache, &cancel).unwrap();
let paths: Vec<_> = std::env::split_paths(&cp).collect();
assert_eq!(paths, [module.join("target/classes"), jar.clone()]);
assert!(maven_system_classpath(&root, &model, &root).is_empty());
// Adding a previously absent jar or deleting an old one updates a no-build launch.
fs::remove_file(jar).unwrap();
write(&root, &format!("{jars}/late.jar"), "");
fs::remove_file(root.join("mvnw")).unwrap();
let cp = module_classpath_without_build(&root, &model, &module, false, &cache, &cancel).unwrap();
let paths: Vec<_> = std::env::split_paths(&cp).collect();
assert_eq!(paths, [module.join("target/classes"), root.join(jars).join("late.jar")]);
}
/// Modules launched together resolve their classpaths in one Maven probe and leave
/// the others' cached; a probe another module breaks still resolves the first one.
#[cfg(unix)]
+4 -19
Переглянути файл
@@ -234,7 +234,9 @@ fn members(r: &mut Bytes, pool: &Pool, refs: &mut BTreeSet<String>) -> Option<Ve
Some(out)
}
fn read_pool(r: &mut Bytes<'_>) -> Option<Pool> {
/// Parses a class file; `None` when it isn't a well-formed one.
pub fn parse(data: &[u8]) -> Option<ClassFile> {
let mut r = Bytes { data, pos: 0 };
if r.u4()? != 0xCAFE_BABE {
return None;
}
@@ -281,28 +283,11 @@ fn read_pool(r: &mut Bytes<'_>) -> Option<Pool> {
entries.push(entry);
i += 1;
if wide {
if i == count {
return None;
}
entries.push(Entry::Empty);
i += 1;
}
}
Some(Pool(entries))
}
/// Reads the internal class name (e.g. `com/acme/Order$Line`) from `this_class`.
pub fn class_file_name(data: &[u8]) -> Option<String> {
let mut r = Bytes { data, pos: 0 };
let pool = read_pool(&mut r)?;
r.u2()?; // access_flags
Some(pool.class(r.u2()?)?.to_owned())
}
/// Parses a class file; `None` when it isn't a well-formed one.
pub fn parse(data: &[u8]) -> Option<ClassFile> {
let mut r = Bytes { data, pos: 0 };
let pool = read_pool(&mut r)?;
let pool = Pool(entries);
let mut refs = BTreeSet::new();
for entry in &pool.0 {
match entry {
+1 -1
Переглянути файл
@@ -22,7 +22,7 @@ mod incremental;
mod javac;
mod model;
pub use classfile::{ClassFile, class_file_name};
pub use classfile::ClassFile;
pub use javac::{JavacPool, Reply, ServerKey};
use incremental::{ClassRecord, SetStamp, SetState};
+2 -27
Переглянути файл
@@ -69,9 +69,6 @@ pub struct MavenProject {
pub aggregated: bool,
pub plugins: Vec<MavenPlugin>,
pub dependencies: Vec<MavenDependency>,
/// Local classpath entries from the POM. The synced dependency tree has coordinates only.
#[serde(skip)]
pub system_paths: Vec<PathBuf>,
/// Profile ids declared in this POM.
pub profiles: Vec<String>,
/// Java feature version the project compiles for (`maven.compiler.release`, `java.version`…).
@@ -179,7 +176,6 @@ struct RawDep {
kind: Option<String>,
classifier: Option<String>,
scope: Option<String>,
system_path: Option<String>,
optional: bool,
}
@@ -252,7 +248,6 @@ fn read_dep(e: &Element) -> Option<RawDep> {
kind: e.text_of("type"),
classifier: e.text_of("classifier"),
scope: e.text_of("scope"),
system_path: e.text_of("systemPath"),
optional: e.text_of("optional").is_some_and(|o| o == "true"),
})
}
@@ -1524,13 +1519,7 @@ pub fn load_with_linked_jdk(
let packaging = i(pom.packaging.as_deref().unwrap_or("jar"));
let managed: HashMap<String, &RawDep> = ctx.managed.iter().map(|m| (m.key(), m)).collect();
let managed_version = |d: &RawDep| managed.get(&d.key()).and_then(|m| m.version.clone());
let scope = |d: &RawDep| {
d.scope
.as_deref()
.or_else(|| managed.get(&d.key()).and_then(|m| m.scope.as_deref()))
.map(i)
.unwrap_or_else(|| "compile".into())
};
let managed_scope = |d: &RawDep| managed.get(&d.key()).and_then(|m| m.scope.clone());
let dependencies = ctx
.deps
.iter()
@@ -1540,24 +1529,11 @@ pub fn load_with_linked_jdk(
version: d.version.clone().or_else(|| managed_version(d)).map(|v| i(&v)),
kind: d.kind.clone().unwrap_or_else(|| "jar".into()),
classifier: d.classifier.clone(),
scope: scope(d),
scope: d.scope.clone().or_else(|| managed_scope(d)).unwrap_or_else(|| "compile".into()),
optional: d.optional,
..MavenDependency::default()
})
.collect();
let system_paths = ctx
.deps
.iter()
.filter(|d| scope(d) == "system")
.filter_map(|d| {
let path = d
.system_path
.as_deref()
.or_else(|| managed.get(&d.key()).and_then(|m| m.system_path.as_deref()))?;
let path = i(path);
(!path.contains("${") && Path::new(&path).is_absolute()).then(|| PathBuf::from(path))
})
.collect();
let mut plugins: Vec<RawPlugin> = ctx.plugins.clone();
for a in lifecycle_plugins(&packaging) {
@@ -1616,7 +1592,6 @@ pub fn load_with_linked_jdk(
aggregated,
plugins,
dependencies,
system_paths,
profiles: ctx.profiles.iter().map(|(id, _)| id.clone()).collect(),
java_version: jv,
command: wrapper(&canonical_root, &dir_canon),
-23
Переглянути файл
@@ -530,7 +530,6 @@ pub struct DebuggerSettings {
/// Java: whether to reload changed classes into running debug sessions after compilation.
pub hot_swap_after_compile: HotSwapPolicy,
pub python: PythonDebuggerSettings,
pub cpp: CppDebuggerSettings,
}
impl Default for DebuggerSettings {
@@ -553,7 +552,6 @@ impl Default for DebuggerSettings {
flutter_hot_reload_on_save: true,
hot_swap_after_compile: HotSwapPolicy::Ask,
python: PythonDebuggerSettings::default(),
cpp: CppDebuggerSettings::default(),
}
}
}
@@ -572,14 +570,6 @@ impl Default for PythonDebuggerSettings {
}
}
/// C/C++ debugger executables. Empty paths use automatic discovery.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct CppDebuggerSettings {
pub gdb_executable: String,
pub lldb_dap_executable: String,
}
/// Run/Debug configuration behaviour.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
@@ -813,17 +803,4 @@ mod tests {
assert_eq!(serialized["hotSwapAfterCompile"], raw);
}
}
#[test]
fn cpp_debugger_paths_default_to_empty_and_roundtrip() {
let missing: DebuggerSettings = serde_json::from_str("{}").unwrap();
assert!(missing.cpp.gdb_executable.is_empty());
assert!(missing.cpp.lldb_dap_executable.is_empty());
let cpp = serde_json::json!({"gdbExecutable": "tools/gdb-16", "lldbDapExecutable": "/opt/llvm/bin/lldb-dap"});
let settings: DebuggerSettings = serde_json::from_value(serde_json::json!({"cpp": cpp})).unwrap();
assert_eq!(settings.cpp.gdb_executable, "tools/gdb-16");
assert_eq!(settings.cpp.lldb_dap_executable, "/opt/llvm/bin/lldb-dap");
assert_eq!(serde_json::to_value(&settings).unwrap()["cpp"], cpp);
}
}
+2 -23
Переглянути файл
@@ -585,9 +585,8 @@ async fn prepare_gdb(spec: &AdapterSpec, binary: &Path) -> IdeResult<bool> {
return Ok(major == 15);
}
let mut msg = format!(
"debugging with GDB needs GDB {GDB_MIN_MAJOR} or newer (found {major}.{minor} at {}): \
this one has no DAP interpreter (`gdb -i dap`)",
binary.display(),
"debugging with GDB needs GDB {GDB_MIN_MAJOR} or newer (found {major}.{minor}): \
this one has no DAP interpreter (`gdb -i dap`)"
);
if let Some(hint) = &spec.install_hint {
msg.push_str(". ");
@@ -1069,26 +1068,6 @@ mod tests {
assert!(builtin("nope").is_none());
}
#[cfg(unix)]
#[tokio::test]
async fn gdb_version_check_probes_the_adapter_command() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let binary = dir.path().join("custom gdb");
std::fs::write(&binary, "#!/bin/sh\n[ \"$1\" = --version ] && echo 'GNU gdb (GDB) 13.2'\n").unwrap();
std::fs::set_permissions(&binary, std::fs::Permissions::from_mode(0o755)).unwrap();
let mut spec = resolve(&builtin("gdb").unwrap(), dir.path().to_path_buf());
spec.command = binary.to_str().unwrap().to_owned();
let Err(error) = ProcessLauncher.launch(spec, None).await else {
panic!("GDB 13 was started as a DAP adapter");
};
assert_eq!(error.kind, ide_core::error::ErrorKind::Unavailable);
assert!(error.message.contains("needs GDB 14 or newer (found 13.2 at "), "{}", error.message);
assert!(error.message.contains(binary.to_str().unwrap()), "{}", error.message);
}
/// Debian/Ubuntu's versioned lldb-dap (and lldb-vscode before LLVM 18): the newest LLVM wins.
#[cfg(unix)]
#[test]
+9 -10
Переглянути файл
@@ -6,7 +6,7 @@ use crate::LaunchConfig;
use crate::adapter::{GDB_MIN_MAJOR, probe_gdb_version};
use ide_core::{IdeError, IdeResult};
use serde_json::{Map, Value, json};
use std::path::{Path, PathBuf};
use std::path::PathBuf;
/// Prefix of the error when none of them is there; the UI offers to install CodeLLDB on it.
pub const NO_NATIVE_DEBUGGER: &str = "No C/C++ debugger found";
@@ -36,7 +36,7 @@ pub async fn choose(
Found::LldbDap => {}
Found::CodeLldb => convert(&mut config, "codelldb")?,
Found::Gdb(gdb) => match probe_gdb_version(&gdb, &cwd, &[]).await {
Some((major, minor)) if major < GDB_MIN_MAJOR => return Err(missing(Some((&gdb, major, minor)))),
Some((major, minor)) if major < GDB_MIN_MAJOR => return Err(missing(Some((major, minor)))),
// Unknown versions are left to GDB itself, as a GDB launch does.
_ => convert(&mut config, "gdb")?,
},
@@ -52,12 +52,11 @@ enum Found {
Nothing,
}
fn missing(gdb: Option<(&Path, u32, u32)>) -> IdeError {
fn missing(gdb: Option<(u32, u32)>) -> IdeError {
let found = match gdb {
Some((path, major, minor)) => format!(
"lldb-dap and CodeLLDB are not installed, and GDB {major}.{minor} at {} cannot debug through DAP \
(it needs GDB {GDB_MIN_MAJOR} or newer)",
path.display(),
Some((major, minor)) => format!(
"lldb-dap and CodeLLDB are not installed, and GDB {major}.{minor} cannot debug through DAP \
(it needs GDB {GDB_MIN_MAJOR} or newer)"
),
None => "lldb-dap, CodeLLDB and GDB are not installed".to_owned(),
};
@@ -104,6 +103,8 @@ fn convert(config: &mut LaunchConfig, to: &str) -> IdeResult<()> {
mod tests {
use super::*;
use std::collections::BTreeMap;
#[cfg(unix)]
use std::path::Path;
fn cmake_launch() -> LaunchConfig {
LaunchConfig {
@@ -187,11 +188,9 @@ mod tests {
async fn an_old_gdb_is_named_in_the_error() {
let dir = tempfile::tempdir().unwrap();
let gdb = fake_gdb(dir.path(), "GNU gdb (Ubuntu 12.1-0ubuntu1~22.04.2) 12.1");
let path = gdb.clone();
let e = choose(cmake_launch(), move |c| (c == "gdb").then(|| path.clone())).await.unwrap_err();
let e = choose(cmake_launch(), move |c| (c == "gdb").then(|| gdb.clone())).await.unwrap_err();
assert!(e.message.starts_with(NO_NATIVE_DEBUGGER), "{}", e.message);
assert!(e.message.contains("GDB 12.1"), "{}", e.message);
assert!(e.message.contains(gdb.to_str().unwrap()), "{}", e.message);
}
#[cfg(unix)]
-10
Переглянути файл
@@ -90,8 +90,6 @@ impl HostConfig {
pub struct Host {
local_database_tunnels: bool,
/// Finders of non-Git working copies ([`Host::with_vcs_provider`]); Git is built in.
pub(crate) vcs_providers: Vec<Arc<dyn ide_vcs::BackendProvider>>,
pub(crate) mcp_executable: Arc<RwLock<Option<PathBuf>>>,
pub mcp: mcp::McpService,
plugin_host: RwLock<std::sync::Weak<plugins::PluginHost>>,
@@ -211,13 +209,6 @@ impl Host {
self
}
/// Adds a version control system besides Git: projects opened afterwards look for its
/// working copies (when trusted) and route the Changes view, status and log to them.
pub fn with_vcs_provider(mut self, provider: Arc<dyn ide_vcs::BackendProvider>) -> Self {
self.vcs_providers.push(provider);
self
}
/// User home directory used by agent memory discovery.
pub fn home_dir(&self) -> Option<PathBuf> {
self.home_dir.clone()
@@ -246,7 +237,6 @@ impl Host {
let host = Self {
plugin_host: RwLock::default(),
local_database_tunnels: false,
vcs_providers: Vec::new(),
mcp_executable: Arc::default(),
mcp: Default::default(),
diagnostics,
+3 -22
Переглянути файл
@@ -1,15 +1,13 @@
mod kotlin;
#[cfg(test)]
mod kotlin_tests;
#[cfg(test)]
mod native_tests;
mod output;
use crate::Host;
use ide_command::command;
use ide_core::{DebugSessionId, IdeResult};
use ide_dap::*;
use std::path::{Path, PathBuf};
use std::path::PathBuf;
/// Starts a session owned by this window: its events (and those of child sessions) go here only.
#[command(trust = trusted)]
@@ -145,10 +143,8 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
// No lldb-dap on this host (most Linux hosts): CodeLLDB, else GDB 14+.
if config.adapter == "lldb-dap" {
let (root, settings) = (root.clone(), settings.clone());
let project_root = project.root.clone();
config = ide_dap::native::choose(config, move |command| {
native_debugger_command(&project_root, &settings.debugger.cpp, command)
.or_else(|| ide_sdk::apply::tool_command(&root, &settings, command))
ide_sdk::apply::tool_command(&root, &settings, command)
.or_else(|| ide_dap::adapter::resolve_binary(command, &root))
})
.await?;
@@ -165,13 +161,11 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
.await?;
}
let java_analyzer = java_analyzer_command(host, window, &config)?;
let native = native_debugger_command(&project.root, &settings.debugger.cpp, &config.adapter);
let custom = |command: &str| {
if let Some(binary) = java_analyzer {
return Some(binary.to_string_lossy().into_owned());
}
let path = native
.or_else(|| ide_sdk::apply::tool_command(&root, &settings, command))
let path = ide_sdk::apply::tool_command(&root, &settings, command)
.or_else(|| ruby_tools.into_iter().find(|(name, _)| *name == command).map(|(_, path)| path))?;
Some(path.to_string_lossy().into_owned())
};
@@ -203,19 +197,6 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
result
}
fn native_debugger_command(
root: &Path,
settings: &ide_core::settings::CppDebuggerSettings,
adapter: &str,
) -> Option<PathBuf> {
let path = match adapter {
"gdb" => &settings.gdb_executable,
"lldb-dap" => &settings.lldb_dap_executable,
_ => return None,
};
ide_sdk::apply::setting_path(root, path)
}
/// For java-analyzer's debugger, the executable of the java-analyzer serving the module
/// (`projectRoot`, else the working directory), so the session debugs with the server that
/// analyzes the code.
-63
Переглянути файл
@@ -1,63 +0,0 @@
use super::*;
use ide_core::IdeError;
use ide_dap::adapter::{AdapterLauncher, AdapterSpec, LaunchFuture};
use ide_workspace::SettingsScope;
use parking_lot::Mutex;
use std::sync::Arc;
#[derive(Default)]
struct CaptureAdapter(Mutex<Option<AdapterSpec>>);
impl AdapterLauncher for CaptureAdapter {
fn launch(&self, spec: AdapterSpec, _: Option<u16>) -> LaunchFuture {
*self.0.lock() = Some(spec);
Box::pin(async { Err(IdeError::cancelled()) })
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn cpp_debugger_paths_override_adapter_commands() {
let dir = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(dir.path()).unwrap();
let root = base.join("project");
let cwd = root.join("build");
std::fs::create_dir_all(&cwd).unwrap();
let capture = Arc::new(CaptureAdapter::default());
let mut host = Host::new(crate::HostConfig::for_test(&base));
host.debugger = DebugManager::with_launcher(host.languages.clone(), capture.clone());
host.open_project("main", &root).unwrap();
host.set_project_trust(&root, true, false).await.unwrap();
let project = host.project("main").unwrap();
for (adapter, key, configured) in [
("gdb", "gdbExecutable", root.join("custom gdb").to_str().unwrap().to_owned()),
("lldb-dap", "lldbDapExecutable", "tools/lldb-dap-custom".into()),
] {
let config = LaunchConfig {
name: "C++".into(),
adapter: adapter.into(),
request: "attach".into(),
program: None,
args: vec![],
cwd: Some(cwd.clone().into()),
env: Default::default(),
extra_json: Some(r#"{"pid":1}"#.into()),
};
let _ = debug_start(&host, "main", config.clone()).await.unwrap_err();
assert_eq!(capture.0.lock().take().unwrap().command, adapter);
project
.settings
.set(SettingsScope::Project, &format!("debugger.cpp.{key}"), serde_json::json!(configured))
.unwrap();
let mut config = config;
config.request = "launch".into();
config.program = Some(cwd.join("app").to_str().unwrap().to_owned());
config.extra_json = None;
let _ = debug_start(&host, "main", config).await.unwrap_err();
let spec = capture.0.lock().take().unwrap();
assert_eq!(spec.adapter, adapter);
assert_eq!(Path::new(&spec.command), root.join(configured));
assert_eq!(spec.cwd, cwd);
}
}
+1 -11
Переглянути файл
@@ -246,17 +246,7 @@ pub fn fs_scratches_dir(host: &Host) -> IdeResult<ide_core::IpcPath> {
#[command(trust = always)]
pub fn fs_set_writable(host: &Host, window: &str, path: PathBuf, writable: bool) -> IdeResult<bool> {
match host.project(window) {
Ok(p) => {
// A checkout backend keeps files read-only until opened for edit (`p4 edit`), so
// its server learns about the change to come. `backend_of` is empty unless trusted.
if writable
&& let Some(backend) = p.backend_of(&path)
&& backend.open_for_edit(std::slice::from_ref(&path))?
{
p.vcs_changed();
}
p.documents.set_writable(&path, writable)
}
Ok(p) => p.documents.set_writable(&path, writable),
Err(_) => ide_vfs::set_writable(&path, writable).map(|()| !writable),
}
}
-41
Переглянути файл
@@ -246,7 +246,6 @@ pub(crate) async fn resolve_launch(
append_unique_class_paths(&mut class_paths, std::mem::take(&mut info.class_paths));
}
info.class_paths = class_paths;
apply_maven_system_classpath(&mut info, root, &model, &module);
apply_library_classpath(&mut info, root, &settings.project_structure.libraries, test);
if build && !delegated {
match compile::process_launch_resources(root, &model, cache, &info.class_paths, &cancel) {
@@ -564,9 +563,6 @@ async fn resolve_launch_without_jdtls(
},
)?;
info.class_paths = class_paths;
if !by_service {
apply_maven_system_classpath(&mut info, root, &model, &module);
}
apply_library_classpath(&mut info, root, &settings.project_structure.libraries, test);
finish_launch(&mut info, root, &module, settings, &model, &data_dir);
if cancel.is_cancelled() {
@@ -685,15 +681,6 @@ fn entry_key(path: &str, windows: bool) -> String {
if windows { key.to_lowercase() } else { key }
}
fn apply_maven_system_classpath(info: &mut JavaLaunchInfo, root: &Path, model: &BuildModel, module: &Path) {
for path in compile::maven_system_classpath(root, model, module) {
let path = path.to_string_lossy();
if !info.class_paths.iter().chain(&info.module_paths).any(|entry| same_entry(entry, &path, cfg!(windows))) {
info.class_paths.push(path.into_owned());
}
}
}
fn apply_library_classpath(
info: &mut JavaLaunchInfo,
root: &std::path::Path,
@@ -1288,34 +1275,6 @@ mod tests {
assert!(info.hints[0].contains("offline dependency"), "{:?}", info.hints);
}
#[test]
fn java_server_launch_classpath_includes_local_maven_system_jars() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
let jar = root.join("src/main/resources/lib/offline.jar");
std::fs::create_dir_all(jar.parent().unwrap()).unwrap();
std::fs::write(&jar, "").unwrap();
std::fs::write(
root.join("pom.xml"),
r#"<project><groupId>demo</groupId><artifactId>app</artifactId><version>1</version>
<dependencies><dependency><groupId>local</groupId><artifactId>offline</artifactId><version>1</version>
<scope>system</scope><systemPath>${pom.basedir}/src/main/resources/lib/offline.jar</systemPath>
</dependency></dependencies></project>"#,
)
.unwrap();
let model = ide_build::load(&root, &root.join("cache"), None);
let jar = jar.to_string_lossy().into_owned();
let mut info = JavaLaunchInfo { class_paths: vec!["classes".into()], ..Default::default() };
apply_maven_system_classpath(&mut info, &root, &model, &root);
apply_maven_system_classpath(&mut info, &root, &model, &root);
assert_eq!(info.class_paths, ["classes", &jar]);
info.class_paths.pop();
info.module_paths.push(jar);
apply_maven_system_classpath(&mut info, &root, &model, &root);
assert_eq!(info.class_paths, ["classes"]);
}
/// Maven's launch classpath lists the module's and its reactor siblings' outputs, which
/// the launch already runs from a snapshot: listed twice, MyBatis loads each mapper XML
/// twice and fails with "XML fragments parsed from previous mappers already contains value".
+2 -19
Переглянути файл
@@ -929,14 +929,9 @@ pub async fn lsp_library_sources(
#[command(trust = trusted)]
pub async fn lsp_resolve_class_file(host: &Host, window: &str, path: std::path::PathBuf) -> IdeResult<String> {
// Opens compiled classes through JDT as decompiled class documents.
let archive = ide_vfs::split_archive_path(&path);
host.project(window)?.lsp.java_class_file(&path, archive, read_internal_class_name(&path)).await
}
async fn read_internal_class_name(path: &Path) -> IdeResult<String> {
let bytes = tokio::fs::read(path).await?;
ide_build::jbuild::class_file_name(&bytes)
.ok_or_else(|| IdeError::not_found(format!("invalid class file: {}", path.display())))
host.project(window)?.lsp.java_class_file(&path, archive).await
}
/// References of the symbol at `pos`. `project_wide` also searches project files
@@ -2497,18 +2492,6 @@ pub fn plugin_formatters() -> IdeResult<Vec<crate::plugins::language_features::F
#[cfg(test)]
mod tests {
#[tokio::test]
async fn disk_class_name_comes_from_bytecode() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("moved.class");
// Class header, UTF-8 and Class constants, then access_flags and this_class.
let bytes = b"\xca\xfe\xba\xbe\0\0\0\x3d\0\x03\x01\0\x0d\x70/Outer$Inner\x07\0\x01\0\x21\0\x02";
std::fs::write(&path, bytes).unwrap();
assert_eq!(read_internal_class_name(&path).await.unwrap(), "p/Outer$Inner");
std::fs::write(&path, b"invalid").unwrap();
assert_eq!(read_internal_class_name(&path).await.unwrap_err().kind, ErrorKind::NotFound);
}
#[test]
fn a_plugin_offering_ghost_text_keeps_the_editor_asking() {
use super::*;
+4 -4
Переглянути файл
@@ -552,19 +552,19 @@ async fn start_inner(
.then(|| xcode_container(&config).map(|c| run_dir.join(c)))
.flatten();
if config.kind == "xcode" {
let dir = run_dir.clone();
let (dir, cache) = (run_dir.clone(), project.cache_dir.clone());
config = host
.blocking(move || {
ide_run::xcode::prepare(&dir, &mut config)?;
ide_run::xcode::prepare(&dir, &cache, &mut config)?;
Ok(config)
})
.await?;
}
if config.kind == ide_run::xcode_clean::KIND {
let dir = run_dir.clone();
let (dir, cache) = (run_dir.clone(), project.cache_dir.clone());
config = host
.blocking(move || {
ide_run::xcode_clean::prepare(&dir, &mut config)?;
ide_run::xcode_clean::prepare(&dir, &cache, &mut config)?;
Ok(config)
})
.await?;
+24 -60
Переглянути файл
@@ -7,7 +7,19 @@ use ide_vcs::FileStatus;
#[command(trust = always)]
pub async fn vcs_status(host: &Host, window: &str) -> IdeResult<Vec<FileStatus>> {
let project = host.project(window)?;
host.blocking(move || merged_status(&project, None)).await
host.blocking(move || {
let settings = project.settings.effective();
let repos = project.repos();
if repos.is_empty() {
return Err(ide_core::IdeError::unavailable("project is not a git repository"));
}
for r in repos.all() {
r.set_ignored_names(settings.ignored_names());
r.set_cli_status(settings.vcs.git.cli_status);
}
repos.status()
})
.await
}
#[command(trust = always)]
@@ -30,67 +42,19 @@ pub async fn vcs_ignored_files(host: &Host, window: &str) -> IdeResult<Vec<FileS
pub async fn vcs_status_paths(host: &Host, window: &str, paths: Vec<std::path::PathBuf>) -> IdeResult<Vec<FileStatus>> {
// `paths` that belong to no repository are ignored, and an empty list is the full status.
let project = host.project(window)?;
host.blocking(move || merged_status(&project, Some(&paths))).await
}
/// The Git repositories' changes and those of the non-Git working copies, each file reported
/// by the backend [`crate::Project::backend_of`] routes it to. `paths` narrows them (empty:
/// everything). A working copy that cannot answer (an unreachable server) is logged and
/// skipped while another backend answered, so it never hides the Git changes.
fn merged_status(project: &crate::Project, paths: Option<&[std::path::PathBuf]>) -> IdeResult<Vec<FileStatus>> {
let settings = project.settings.effective();
let repos = project.repos();
let backends = project.backends();
if repos.is_empty() && backends.is_empty() {
return Err(ide_core::IdeError::unavailable("project is not a git repository"));
}
for r in repos.all() {
r.set_ignored_names(settings.ignored_names());
r.set_cli_status(settings.vcs.git.cli_status);
}
let mut status = if repos.is_empty() {
Vec::new()
} else {
match paths {
Some(paths) => repos.status_paths(paths)?,
None => repos.status()?,
host.blocking(move || {
let settings = project.settings.effective();
let repos = project.repos();
if repos.is_empty() {
return Err(ide_core::IdeError::unavailable("project is not a git repository"));
}
};
if backends.is_empty() {
return Ok(status);
}
// Routed from these snapshots: one lookup per entry, no locks taken again.
let owner = |f: &FileStatus| crate::project::backend_for(&backends, &repos, &f.path).map(|b| b.root());
status.retain(|f| owner(f).is_none());
let mut answered = !repos.is_empty();
let mut failure = None;
for backend in &backends {
let changes = match paths.filter(|p| !p.is_empty()) {
Some(paths) => {
let mine: Vec<_> = paths.iter().filter(|p| p.starts_with(backend.root())).cloned().collect();
if mine.is_empty() {
answered = true;
continue;
}
backend.status_paths(&mine)
}
None => backend.status(),
};
match changes {
Ok(changes) => {
answered = true;
status.extend(changes.into_iter().filter(|f| owner(f) == Some(backend.root())));
}
Err(e) => {
tracing::warn!("status of {}: {e}", backend.root().display());
failure = Some(e);
}
for r in repos.all() {
r.set_ignored_names(settings.ignored_names());
r.set_cli_status(settings.vcs.git.cli_status);
}
}
match failure {
Some(e) if !answered => Err(e),
_ => Ok(status),
}
repos.status_paths(&paths)
})
.await
}
pub mod commands;
+14 -213
Переглянути файл
@@ -94,14 +94,13 @@ async fn revision_text(
project: &Option<std::sync::Arc<Project>>,
external: &Option<std::sync::Arc<ide_vcs::Repo>>,
path: &Path,
f: impl FnOnce(&dyn Backend) -> IdeResult<T>,
f: impl FnOnce(&ide_vcs::Repo) -> IdeResult<T>,
) -> IdeResult<T> {
match project {
Some(project) => project.with_log_backend_of(path, f),
Some(project) => project.with_log_repo_of(path, f),
None => f(external
.as_ref()
.ok_or_else(|| ide_core::IdeError::unavailable("external Git log is not open"))?
.as_ref()),
.ok_or_else(|| ide_core::IdeError::unavailable("external Git log is not open"))?),
}
}
let (text_encoding, charset) = match &encoding {
@@ -149,46 +148,20 @@ impl LogAccess {
.with_log_repo_at(at, f)
}
/// The non-Git working copy `at` names (see [`Project::backend_at`]).
fn backend(&self, at: Option<&Path>) -> Option<std::sync::Arc<dyn Backend>> {
if self.external.is_some() {
return None;
}
self.project.as_ref().and_then(|p| p.backend_at(at))
}
/// `with_log_repo_at` through the backend-agnostic Changes-view surface.
fn with_log_backend_at<T>(&self, at: Option<&Path>, f: impl FnOnce(&dyn Backend) -> IdeResult<T>) -> IdeResult<T> {
if let Some(backend) = self.backend(at) {
return f(backend.as_ref());
}
self.with_log_repo_at(at, |r| f(r as &dyn Backend))
}
/// `with_log_repo_at` for a Git-only read: a non-Git working copy answers `T::default()`
/// (no refs, users, branches) so its log and branch widget still work.
fn with_git_log_or_default<T: Default>(
&self,
at: Option<&Path>,
f: impl FnOnce(&Repo) -> IdeResult<T>,
) -> IdeResult<T> {
if self.backend(at).is_some() {
return Ok(T::default());
}
self.with_log_repo_at(at, f)
}
}
/// A repository of the project (IDEA's VCS root).
#[derive(Default, Serialize, Deserialize, Type)]
#[derive(Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct VcsRoot {
/// Worktree root.
pub root: ide_core::IpcPath,
/// Root representing all mapped worktrees of the same Git repository in branch lists.
pub branch_root: ide_core::IpcPath,
/// The version control system holding it.
pub kind: VcsKind,
/// Merge / rebase / cherry-pick / revert in progress.
pub operation: Option<String>,
/// The current rebase uses Git's interactive mode.
@@ -453,32 +426,14 @@ fn per_repo(
Ok(())
}
/// `per_repo` through the backend-agnostic Changes-view surface: the paths of a non-Git
/// working copy go to it, the rest to the Git repositories as before.
/// `per_repo` through the backend-agnostic Changes-view surface.
fn per_backend(
project: &Project,
paths: &[PathBuf],
recorded: Option<&str>,
f: impl Fn(&dyn Backend, &[PathBuf]) -> IdeResult<()>,
) -> IdeResult<()> {
let mut git: Vec<PathBuf> = Vec::new();
let mut groups: Vec<(std::sync::Arc<dyn Backend>, Vec<PathBuf>)> = Vec::new();
for path in paths {
match project.backend_of(path) {
Some(backend) => match groups.iter_mut().find(|(b, _)| b.root() == backend.root()) {
Some((_, mine)) => mine.push(path.clone()),
None => groups.push((backend, vec![path.clone()])),
},
None => git.push(path.clone()),
}
}
for (backend, mine) in &groups {
project.backend_recorded(backend.as_ref(), recorded, |b| f(b, mine))?;
}
if git.is_empty() && !groups.is_empty() {
return Ok(());
}
per_repo(project, &git, recorded, |r, paths| f(r as &dyn Backend, paths))
per_repo(project, paths, recorded, |r, paths| f(r as &dyn Backend, paths))
}
fn with_shelf_batch<T>(project: &Project, batch: Option<String>, operation: impl FnOnce() -> T) -> T {
@@ -584,7 +539,6 @@ fn unavailable_vcs_root(root: &Path) -> VcsRoot {
VcsRoot {
root: root.into(),
branch_root: root.into(),
kind: VcsKind::Git,
operation: None,
interactive_rebase: false,
head: None,
@@ -603,7 +557,6 @@ fn unavailable_vcs_root(root: &Path) -> VcsRoot {
pub async fn vcs_roots(host: &Host, window: &str) -> IdeResult<Vec<VcsRoot>> {
let project = host.project(window)?;
let repos = project.repos();
let backends = project.backends();
let trusted = project.is_trusted();
blocking(move || {
let primary = repos.primary().map(|r| r.root().to_path_buf());
@@ -626,7 +579,7 @@ pub async fn vcs_roots(host: &Host, window: &str) -> IdeResult<Vec<VcsRoot>> {
}
}
}
let mut roots: Vec<VcsRoot> = roots
Ok(roots
.iter()
.map(|(r, available, dirs)| {
if !available {
@@ -651,7 +604,6 @@ pub async fn vcs_roots(host: &Host, window: &str) -> IdeResult<Vec<VcsRoot>> {
VcsRoot {
root: r.root().into(),
branch_root: branch_root.copied().unwrap_or_else(|| r.root()).into(),
kind: VcsKind::Git,
operation,
interactive_rebase,
head,
@@ -669,16 +621,7 @@ pub async fn vcs_roots(host: &Host, window: &str) -> IdeResult<Vec<VcsRoot>> {
unavailable: false,
}
})
.collect();
// A non-Git working copy shows its own head (a stream, `trunk`) where Git shows the branch.
roots.extend(backends.iter().map(|b| VcsRoot {
root: b.root().into(),
branch_root: b.root().into(),
kind: b.kind(),
head: b.head_label(),
..VcsRoot::default()
}));
Ok(roots)
.collect())
})
.await
}
@@ -686,13 +629,7 @@ pub async fn vcs_roots(host: &Host, window: &str) -> IdeResult<Vec<VcsRoot>> {
#[command(trust = always)]
pub async fn vcs_branch_info(host: &Host, window: &str, repo: Option<PathBuf>) -> IdeResult<BranchInfo> {
let project = LogAccess::new(host, window, repo.as_deref());
blocking(move || {
if let Some(backend) = project.backend(repo.as_deref()) {
return Ok(BranchInfo { head: backend.head_label(), ..BranchInfo::default() });
}
project.with_log_repo_at(repo.as_deref(), |r| r.branch_info())
})
.await
blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.branch_info())).await
}
#[command(trust = trusted)]
@@ -963,9 +900,6 @@ pub async fn vcs_log(host: &Host, window: &str, repo: Option<PathBuf>, query: Lo
let cancel =
request.map_or_else(ide_core::CancellationToken::new, |id| host.begin_project_read_request(window, id));
let result = blocking(move || {
if let Some(backend) = project.backend(repo.as_deref()) {
return backend.log(&query, &cancel);
}
project.with_log_repo_at(repo.as_deref(), |r| {
r.enable_log_index(&project.cache);
(r as &dyn Backend).log(&query, &cancel)
@@ -1003,13 +937,13 @@ pub async fn vcs_log_refs(
repo: Option<PathBuf>,
) -> IdeResult<std::collections::BTreeMap<String, String>> {
let project = LogAccess::new(host, window, repo.as_deref());
blocking(move || project.with_git_log_or_default(repo.as_deref(), |r| r.log_refs())).await
blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.log_refs())).await
}
#[command(trust = always)]
pub async fn vcs_log_users(host: &Host, window: &str, repo: Option<PathBuf>) -> IdeResult<Vec<String>> {
let project = LogAccess::new(host, window, repo.as_deref());
blocking(move || project.with_git_log_or_default(repo.as_deref(), |r| r.log_users())).await
blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.log_users())).await
}
#[command(trust = always)]
@@ -1039,7 +973,7 @@ pub async fn vcs_log_details(
revision: String,
) -> IdeResult<LogDetails> {
let project = LogAccess::new(host, window, repo.as_deref());
blocking(move || project.with_log_backend_at(repo.as_deref(), |b| b.log_details(&revision))).await
blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.log_details(&revision))).await
}
#[command(trust = always)]
@@ -1053,9 +987,6 @@ pub async fn vcs_log_details_batch(
let project = LogAccess::new(host, window, repo.as_deref());
let cancel = host.begin_project_read_request(window, request);
let result = blocking(move || {
if let Some(backend) = project.backend(repo.as_deref()) {
return revisions.iter().map(|revision| backend.log_details(revision)).collect();
}
project.with_log_repo_at(repo.as_deref(), |r| {
r.enable_log_index(&project.cache);
r.log_details_batch_cancellable(&revisions, &cancel)
@@ -1199,23 +1130,13 @@ pub async fn vcs_commit_selection_changes(
#[command(trust = always)]
pub async fn vcs_branches(host: &Host, window: &str, repo: Option<PathBuf>) -> IdeResult<Vec<Branch>> {
let project = LogAccess::new(host, window, repo.as_deref());
blocking(move || match project.backend(repo.as_deref()) {
Some(backend) => backend.branches(),
None => project.with_log_repo_at(repo.as_deref(), |r| r.branches()),
})
.await
blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.branches())).await
}
#[command(trust = always)]
pub async fn vcs_stashes(host: &Host, window: &str, repo: Option<PathBuf>) -> IdeResult<Vec<Stash>> {
let project = host.project(window)?;
blocking(move || {
if project.backend_at(repo.as_deref()).is_some() {
return Ok(Vec::new());
}
project.with_repo_at(repo.as_deref(), |r| r.stashes())
})
.await
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.stashes())).await
}
#[command(trust = trusted)]
@@ -1419,15 +1340,6 @@ pub async fn vcs_checkout(
let options = options.unwrap_or_default();
blocking(move || {
with_shelf_batch(&project, shelf_batch, || {
// A non-Git working copy switches to another line of development (`svn switch`).
if project.backend_at(repo.as_deref()).is_some() {
if create {
return Err(ide_core::IdeError::unavailable("creating a branch is not supported here"));
}
return project.with_backend_recorded(repo.as_deref(), Some("Switch"), |b| {
b.switch_to(&branch).map(|()| CheckoutOutcome::Done)
});
}
project.with_repo_recorded(repo.as_deref(), Some("Git checkout"), |r| {
r.checkout_with(&branch, create, &options)
})
@@ -1927,15 +1839,6 @@ pub async fn vcs_remote(
RemoteOp::PullLfs => Some("Git LFS pull"),
_ => None,
};
// Update Project on a non-Git working copy is its own update (`svn update`, `p4 sync`).
if matches!(op, RemoteOp::Pull { .. } | RemoteOp::UpdateProjectBranch { .. })
&& project.backend_at(repo.as_deref()).is_some()
{
return with_shelf_batch(&project, shelf_batch, || {
project
.with_backend_recorded(repo.as_deref(), Some("Update"), |b| b.update(&cancel, &out).map(|()| None))
});
}
with_shelf_batch(&project, shelf_batch, || {
project.with_repo_recorded(repo.as_deref(), recorded, |r| match op {
RemoteOp::Fetch { background: true, report, skip_remotes } => {
@@ -3370,103 +3273,6 @@ pub async fn vcs_shelf_import(
.await
}
/// The changelists the non-Git working copy at `repo` keeps itself; `None` when the root
/// (Git) leaves them to the IDE's lists ([`vcs_changelists_load`]).
#[command(trust = trusted)]
pub async fn vcs_backend_changelists(
host: &Host,
window: &str,
repo: Option<PathBuf>,
) -> IdeResult<Option<Vec<BackendChangelist>>> {
host.require_trust(window)?;
let project = host.project(window)?;
blocking(move || match project.backend_at(repo.as_deref()) {
Some(backend) => backend.changelists(),
None => Ok(None),
})
.await
}
/// Creates a changelist of the working copy at `repo`; returns its id.
#[command(trust = trusted)]
pub async fn vcs_backend_changelist_create(
host: &Host,
window: &str,
repo: Option<PathBuf>,
name: String,
comment: String,
) -> IdeResult<String> {
host.require_trust(window)?;
let project = host.project(window)?;
blocking(move || {
let id = project.with_backend_at(repo.as_deref(), |b| b.create_changelist(&name, &comment))?;
project.vcs_changed();
Ok(id)
})
.await
}
#[command(trust = trusted)]
pub async fn vcs_backend_changelist_edit(
host: &Host,
window: &str,
repo: Option<PathBuf>,
id: String,
name: String,
comment: String,
) -> IdeResult<()> {
host.require_trust(window)?;
let project = host.project(window)?;
blocking(move || {
project.with_backend_at(repo.as_deref(), |b| b.edit_changelist(&id, &name, &comment))?;
project.vcs_changed();
Ok(())
})
.await
}
#[command(trust = trusted)]
pub async fn vcs_backend_changelist_delete(
host: &Host,
window: &str,
repo: Option<PathBuf>,
id: String,
) -> IdeResult<()> {
host.require_trust(window)?;
let project = host.project(window)?;
blocking(move || {
project.with_backend_at(repo.as_deref(), |b| b.delete_changelist(&id))?;
project.vcs_changed();
Ok(())
})
.await
}
/// Moves `paths` to changelist `id` of the working copy each belongs to.
#[command(trust = trusted)]
pub async fn vcs_backend_changelist_move(host: &Host, window: &str, paths: Vec<PathBuf>, id: String) -> IdeResult<()> {
host.require_trust(window)?;
let project = host.project(window)?;
blocking(move || {
let mut groups: Vec<(std::sync::Arc<dyn Backend>, Vec<PathBuf>)> = Vec::new();
for path in paths {
let backend = project.backend_of(&path).ok_or_else(|| {
ide_core::IdeError::invalid(format!("{} is not in a working copy with changelists", path.display()))
})?;
match groups.iter_mut().find(|(b, _)| b.root() == backend.root()) {
Some((_, mine)) => mine.push(path),
None => groups.push((backend, vec![path])),
}
}
for (backend, mine) in &groups {
backend.move_to_changelist(mine, &id)?;
}
project.vcs_changed();
Ok(())
})
.await
}
#[command(trust = always)]
pub async fn vcs_changelists_load(host: &Host, window: &str) -> IdeResult<ChangelistState> {
let project = host.project(window)?;
@@ -3550,11 +3356,6 @@ ide_command::domain!(
vcs_branch_info,
vcs_check_incoming,
vcs_branches,
vcs_backend_changelists,
vcs_backend_changelist_create,
vcs_backend_changelist_edit,
vcs_backend_changelist_delete,
vcs_backend_changelist_move,
vcs_changelists_load,
vcs_changelists_save,
vcs_checkout,
+4 -117
Переглянути файл
@@ -1,9 +1,8 @@
//! Code insight for Xcode projects: sourcekit-lsp doesn't read `.xcodeproj` / `.xcworkspace`
//! files, it gets their build settings from a Build Server Protocol server named in
//! `.bsp/*.json` or the legacy `buildServer.json`. The IDE neither bundles nor installs a BSP
//! server: when a trusted project has none, it runs the one on `PATH` (xcode-build-server,
//! sourcekit-xcode-bsp) to write the config, keeps the config out of Git through
//! `.git/info/exclude`, then restarts sourcekit-lsp.
//! server: it offers to run the one on `PATH` (xcode-build-server, sourcekit-xcode-bsp) to write
//! the config, then restarts sourcekit-lsp.
use crate::Host;
use ide_command::command;
use ide_core::{IdeError, IdeResult};
@@ -25,39 +24,6 @@ fn tool_args(tool: &str, container: &str) -> Vec<String> {
vec!["config".into(), flag.into(), container.into()]
}
/// The config `tool` writes at the project root.
fn config_name(tool: &str) -> &'static str {
if tool == "sourcekit-xcode-bsp" { ".bsp" } else { "buildServer.json" }
}
fn git(root: &Path, args: &[&str]) -> Option<std::process::Output> {
let mut cmd = Command::new("git");
ide_core::process::prepare(&mut cmd).arg("-C").arg(root).args(args).stdin(Stdio::null());
cmd.output().ok()
}
/// Adds `name` (a file or folder at `root`) to the repository's `info/exclude`, so a generated
/// machine-specific config doesn't show up as a change. Nothing when `root` isn't in a Git
/// repository or `name` is already tracked or ignored. Returns whether it added the line.
fn exclude_from_git(root: &Path, name: &str) -> std::io::Result<bool> {
let ok = |args: &[&str]| git(root, args).filter(|o| o.status.success());
let text = |o: std::process::Output| String::from_utf8_lossy(&o.stdout).trim_end_matches('\n').to_owned();
let Some(exclude) = ok(&["rev-parse", "--git-path", "info/exclude"]).map(text) else { return Ok(false) };
let prefix = ok(&["rev-parse", "--show-prefix"]).map(text).unwrap_or_default();
if ok(&["ls-files", "--error-unmatch", "--", name]).is_some() || ok(&["check-ignore", "-q", "--", name]).is_some() {
return Ok(false);
}
let exclude = root.join(exclude);
if let Some(dir) = exclude.parent() {
std::fs::create_dir_all(dir)?;
}
let before = std::fs::read_to_string(&exclude).unwrap_or_default();
let sep = if before.is_empty() || before.ends_with('\n') { "" } else { "\n" };
let mut file = std::fs::OpenOptions::new().create(true).append(true).open(&exclude)?;
std::io::Write::write_all(&mut file, format!("{sep}/{prefix}{name}\n").as_bytes())?;
Ok(true)
}
/// An Xcode project without a BSP config, at the project root.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Type)]
#[serde(rename_all = "camelCase")]
@@ -103,8 +69,8 @@ pub fn xcode_bsp_setup(host: &Host, window: &str) -> IdeResult<Option<XcodeBspSe
Ok(Some(XcodeBspSetup { container, tool }))
}
/// Writes the BSP config at the project root with `tool`, adds it to `.git/info/exclude`
/// ([`exclude_from_git`]), then restarts the project's sourcekit-lsp so it reads it.
/// Writes the BSP config at the project root with `tool`, then restarts the project's
/// sourcekit-lsp so it reads it.
#[command(trust = trusted)]
pub async fn xcode_bsp_generate(host: &Host, window: &str, tool: String, container: String) -> IdeResult<()> {
if !TOOLS.contains(&tool.as_str()) {
@@ -127,10 +93,6 @@ pub async fn xcode_bsp_generate(host: &Host, window: &str, tool: String, contain
.stdin(Stdio::null());
let out = cmd.output().map_err(|e| IdeError::unavailable(format!("{tool}: {e}")))?;
if out.status.success() {
// Best effort: a config that shows up in `git status` is a nuisance, not a failure.
if let Err(e) = exclude_from_git(&root, config_name(&tool)) {
tracing::warn!("could not add {} to .git/info/exclude: {e}", config_name(&tool));
}
return Ok(());
}
let stderr = String::from_utf8_lossy(&out.stderr);
@@ -174,81 +136,6 @@ mod tests {
assert_eq!(tool_args("sourcekit-xcode-bsp", "A.xcodeproj"), ["init"]);
}
fn git_in(dir: &Path, args: &[&str]) {
let out = Command::new("git").arg("-C").arg(dir).args(args).output().unwrap();
assert!(out.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&out.stderr));
}
fn exclude_file(repo: &Path) -> String {
std::fs::read_to_string(repo.join(".git/info/exclude")).unwrap_or_default()
}
#[test]
fn excludes_the_generated_config_from_git_once() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path();
git_in(repo, &["init", "-q"]);
std::fs::write(repo.join("buildServer.json"), "{}").unwrap();
assert!(exclude_from_git(repo, "buildServer.json").unwrap());
assert!(exclude_file(repo).ends_with("\n/buildServer.json\n"), "{}", exclude_file(repo));
// Now ignored: not added twice.
assert!(!exclude_from_git(repo, "buildServer.json").unwrap());
assert_eq!(exclude_file(repo).matches("buildServer.json").count(), 1);
// sourcekit-xcode-bsp's folder.
std::fs::create_dir(repo.join(".bsp")).unwrap();
std::fs::write(repo.join(".bsp/x.json"), "{}").unwrap();
assert!(exclude_from_git(repo, config_name("sourcekit-xcode-bsp")).unwrap());
assert!(exclude_file(repo).ends_with("/buildServer.json\n/.bsp\n"));
}
#[test]
fn leaves_tracked_and_ignored_configs_and_non_repos_alone() {
let tmp = tempfile::tempdir().unwrap();
// Not a Git repository: nothing to do, no `.git` created.
let plain = tmp.path().join("plain");
std::fs::create_dir(&plain).unwrap();
assert!(!exclude_from_git(&plain, "buildServer.json").unwrap());
assert!(!plain.join(".git").exists());
let repo = tmp.path().join("repo");
std::fs::create_dir(&repo).unwrap();
git_in(&repo, &["init", "-q"]);
let before = exclude_file(&repo);
// Tracked: the team shares it.
std::fs::write(repo.join("buildServer.json"), "{}").unwrap();
git_in(&repo, &["add", "buildServer.json"]);
assert!(!exclude_from_git(&repo, "buildServer.json").unwrap());
// Already in .gitignore.
git_in(&repo, &["rm", "-q", "--cached", "buildServer.json"]);
std::fs::write(repo.join(".gitignore"), "buildServer.json\n").unwrap();
assert!(!exclude_from_git(&repo, "buildServer.json").unwrap());
assert_eq!(exclude_file(&repo), before);
}
#[test]
fn excludes_the_config_of_a_project_in_a_subfolder_of_the_repository() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path();
git_in(repo, &["init", "-q"]);
let ios = repo.join("apps/ios");
std::fs::create_dir_all(&ios).unwrap();
assert!(exclude_from_git(&ios, "buildServer.json").unwrap());
assert!(exclude_file(repo).ends_with("/apps/ios/buildServer.json\n"));
std::fs::write(ios.join("buildServer.json"), "{}").unwrap();
// The line matches the file in the subfolder only.
git_in(&ios, &["check-ignore", "-q", "buildServer.json"]);
assert!(
Command::new("git")
.arg("-C")
.arg(repo)
.args(["check-ignore", "-q", "buildServer.json"])
.status()
.unwrap()
.code()
== Some(1)
);
}
#[test]
fn accepts_only_bundle_names_in_the_root() {
assert!(is_container_name("App.xcworkspace") && is_container_name("App.xcodeproj"));
+5 -10
Переглянути файл
@@ -3008,16 +3008,11 @@ impl PluginHost {
{
let mut plugins = self.plugins.write();
if let Some(existing) = plugins.get(&id) {
// Every rescan meets the same duplicate again: say it once per directory, not on each scan.
static WARNED: std::sync::LazyLock<Mutex<std::collections::HashSet<(String, PathBuf)>>> =
std::sync::LazyLock::new(Default::default);
if WARNED.lock().insert((id.clone(), dir.to_path_buf())) {
tracing::warn!(
"plugin {id:?} at {} ignored: already loaded from {}",
dir.display(),
existing.dir().display()
);
}
tracing::warn!(
"plugin {id:?} at {} ignored: already loaded from {}",
dir.display(),
existing.dir().display()
);
return (id, None);
}
plugins.insert(id.clone(), plugin.clone());
+12 -251
Переглянути файл
@@ -9,7 +9,7 @@ use ide_language::{FileTypes, LanguageRegistry, SyntaxCache};
use ide_lsp::LspManager;
use ide_syntax::StructureService;
use ide_text::{AppliedChange, ByteEdit};
use ide_vcs::{Backend, BackendProvider, FileStatus, Repo, Repos};
use ide_vcs::{Backend, Repo, Repos};
use ide_vfs::Watcher;
use ide_workspace::documents::DocumentObserver;
use ide_workspace::{DocumentInfo, Documents, FileMoves, LocalHistory, ProjectRoots, SettingsStore, SourceFolder};
@@ -41,14 +41,6 @@ pub struct Project {
pub lsp: Arc<LspManager>,
/// Git repositories: the one containing the project root and those nested below it.
pub repos: Arc<RwLock<Repos>>,
/// Working copies of the other version control systems ([`Host::with_vcs_provider`]) holding
/// the project root or a content root. Found in a trusted project only: answering may run
/// the system's client, and a `P4CONFIG` can name a program as its server.
pub backends: Arc<RwLock<Vec<Arc<dyn Backend>>>>,
pub(crate) vcs_providers: Arc<[Arc<dyn BackendProvider>]>,
/// Held for a whole scan of `backends`, so overlapping scans (project open, trust change)
/// finish in turn and the last one reads the current trust.
backend_scan: Arc<Mutex<()>>,
/// Explicitly opened external logs remain read-only and outside project indexing.
pub(crate) external_log_repos: RwLock<Vec<Arc<Repo>>>,
/// Incrementally maintained syntax trees of the open documents.
@@ -394,12 +386,8 @@ impl Host {
}));
}
{
// Weak: `documents` keeps `lsp` alive through its observers, so a strong handle here would be
// a cycle that leaks every closed project's documents, registry and language manager.
let documents = Arc::downgrade(&documents);
lsp.set_apply_edit_hook(Box::new(move |edit| {
documents.upgrade().is_some_and(|documents| documents.apply_workspace_edit(&edit).is_ok())
}));
let documents = documents.clone();
lsp.set_apply_edit_hook(Box::new(move |edit| documents.apply_workspace_edit(&edit).is_ok()));
}
let syntax = Arc::new(SyntaxCache::new(self.syntax()));
documents.add_observer(Arc::new(SyntaxObserver(syntax.clone())));
@@ -437,9 +425,6 @@ impl Host {
let tsc_watch = crate::tsc_watch::TscWatch::new(root.clone(), settings.clone(), sink.clone(), trusted.clone());
documents.add_observer(tsc_watch.clone());
let repos = Arc::new(RwLock::new(Repos::enclosing(&root)?));
let backends: Arc<RwLock<Vec<Arc<dyn Backend>>>> = Arc::default();
let vcs_providers: Arc<[Arc<dyn BackendProvider>]> = self.vcs_providers.clone().into();
let backend_scan: Arc<Mutex<()>> = Arc::default();
for repo in repos.read().all() {
repo.set_execution_allowed(trusted.load(Ordering::Acquire));
}
@@ -478,9 +463,6 @@ impl Host {
let build_cache = build_cache.clone();
let notify_watch_exhausted = notify_watch_exhausted.clone();
let watcher_weak = watcher_weak.clone();
let (backends, vcs_providers, backend_scan) =
(backends.clone(), vcs_providers.clone(), backend_scan.clone());
let markers: Vec<String> = vcs_providers.iter().filter_map(|p| p.marker().map(str::to_owned)).collect();
Watcher::start(
&root.clone(),
excludes.clone(),
@@ -618,41 +600,6 @@ impl Host {
if git_dirs || vcs_moved {
sink.emit(IdeEvent::VcsChanged { root: root.clone().into() });
}
// A working copy appeared below the project (a checkout made inside it, a
// folder moved in) or one went: its marker is the signal, as `.git` is above.
// The marker itself may be an ignored name, so the folders of created paths
// are checked for it. The scan asks providers, so it runs off this thread.
if !markers.is_empty() && trusted.load(Ordering::Acquire) {
let known: Vec<PathBuf> = backends.read().iter().map(|b| b.root().to_path_buf()).collect();
let mut folders: HashSet<&Path> = HashSet::new();
for p in &batch.created {
let is_marker = p.file_name().is_some_and(|n| markers.iter().any(|m| n == m.as_str()));
folders.extend(if !is_marker && p.is_dir() { Some(p.as_path()) } else { p.parent() });
}
let appeared = folders
.iter()
.any(|d| !known.iter().any(|r| r == d) && markers.iter().any(|m| d.join(m).exists()));
let gone = batch.removed.iter().any(|p| known.iter().any(|r| r.starts_with(p)));
if appeared || gone {
let (backends, providers, lock, trust) =
(backends.clone(), vcs_providers.clone(), backend_scan.clone(), trusted.clone());
let (root, settings, sink, cache) =
(root.clone(), settings.clone(), sink.clone(), build_cache.clone());
let rescan = move || {
let scan = BackendScan {
backends: &backends,
providers: &providers,
lock: &lock,
trusted: &trust,
};
scan.run(&root, &settings, &sink, &cache);
};
if let Err(e) = std::thread::Builder::new().name("openidea-vcs-roots".into()).spawn(rescan)
{
tracing::warn!("looking for working copies again: {e}");
}
}
}
// A watch limit hit after startup (per-directory mode, Linux):
// folders past the limit never sync — surface it once, like
// the polling fallback below (#1915). The check itself is
@@ -734,14 +681,9 @@ impl Host {
{
let (root, repos, settings, sink) = (root.clone(), repos.clone(), settings.clone(), sink.clone());
let (build_cache, git_metadata) = (build_cache.clone(), git_metadata.clone());
let (backends, providers, trust) = (backends.clone(), vcs_providers.clone(), trusted.clone());
let scan = backend_scan.clone();
let trusted = trusted.load(Ordering::Acquire);
std::thread::Builder::new().name("openidea-vcs-roots".into()).spawn(move || {
scan_repositories(&root, &repos, git_metadata.as_deref(), &settings, &sink, &build_cache, trusted);
let backend_scan =
BackendScan { backends: &backends, providers: &providers, lock: &scan, trusted: &trust };
backend_scan.run(&root, &settings, &sink, &build_cache);
scan_repositories(&root, &repos, git_metadata.as_deref(), &settings, &sink, &build_cache, trusted)
})?;
}
mark("git");
@@ -782,9 +724,6 @@ impl Host {
index,
lsp,
repos,
backends,
vcs_providers,
backend_scan,
external_log_repos: RwLock::default(),
structure: Arc::new(StructureService::new(syntax.clone())),
syntax,
@@ -1086,9 +1025,6 @@ impl Host {
index,
lsp,
repos: Arc::default(),
backends: Arc::default(),
vcs_providers: Arc::new([]),
backend_scan: Arc::default(),
external_log_repos: RwLock::default(),
structure: Arc::new(StructureService::new(syntax.clone())),
syntax,
@@ -1294,94 +1230,6 @@ fn repository_searched(root: &Path, dir: &Path, settings: &ide_core::settings::S
&& Repos::searched(root, dir, &repository_scan_skips(settings))
}
/// Asks `providers` in order about `folder`; the first to answer adds its working copy to
/// `found`, unless one with the same root is there already.
fn ask_providers<'a>(
folder: &Path,
providers: impl IntoIterator<Item = &'a Arc<dyn BackendProvider>>,
found: &mut Vec<Arc<dyn Backend>>,
) {
for provider in providers {
match provider.discover(folder) {
Ok(Some(backend)) => {
if !found.iter().any(|b| b.root() == backend.root()) {
found.push(backend);
}
return;
}
Ok(None) => {}
Err(e) => tracing::warn!("looking for a working copy in {}: {e}", folder.display()),
}
}
}
/// The working copy among `backends` that `path` belongs to ([`Project::backend_of`]): the
/// deepest one holding it, unless a Git repository at or below its root holds the path.
pub(crate) fn backend_for<'a>(
backends: &'a [Arc<dyn Backend>],
repos: &Repos,
path: &Path,
) -> Option<&'a Arc<dyn Backend>> {
let backend =
backends.iter().filter(|b| path.starts_with(b.root())).max_by_key(|b| b.root().components().count())?;
let nested_git = repos.for_path(path).is_some_and(|r| r.root().starts_with(backend.root()));
(!nested_git).then_some(backend)
}
/// What a scan of the non-Git working copies works on: the list it replaces, the providers
/// asked, the lock that serialises scans and the project's trust, read under that lock.
struct BackendScan<'a> {
backends: &'a RwLock<Vec<Arc<dyn Backend>>>,
providers: &'a [Arc<dyn BackendProvider>],
lock: &'a Mutex<()>,
trusted: &'a AtomicBool,
}
impl BackendScan<'_> {
/// Asks the providers for the working copies holding the project root and its content
/// roots; emits `VcsChanged` when the set changed. An untrusted project gets none and runs
/// nothing. Scans run one at a time, each reading the trust when it starts, so a scan
/// started before a trust change can't overwrite the one after it. Providers are asked in
/// registration order and the first to answer for a folder wins it.
fn run(&self, root: &Path, settings: &SettingsStore, sink: &SharedSink, build_cache: &Path) {
let _scan = self.lock.lock();
let trusted = self.trusted.load(Ordering::Acquire);
let mut found: Vec<Arc<dyn Backend>> = Vec::new();
if trusted && !self.providers.is_empty() {
let settings = settings.effective();
let mut folders = vec![root.to_path_buf()];
folders.extend(content_roots(&settings, root, build_cache, trusted));
let markers: Vec<&str> = self.providers.iter().filter_map(|p| p.marker()).collect();
let skip = repository_scan_skips(&settings);
for folder in &folders {
// The folder itself (its working copy may start above it): every provider.
if !found.iter().any(|b| folder.starts_with(b.root())) {
ask_providers(folder, self.providers, &mut found);
}
// Working copies nested below it, like nested Git repositories: a separate
// checkout or a directory external inside a working copy, or one inside a Git
// repository. Only the providers whose marker the folder holds are asked.
if markers.is_empty() {
continue;
}
for nested in ide_vcs::marked_folders(folder, &markers, &skip) {
if found.iter().any(|b| b.root() == nested) {
continue;
}
let marked = self.providers.iter().filter(|p| p.marker().is_some_and(|m| nested.join(m).exists()));
ask_providers(&nested, marked, &mut found);
}
}
}
let roots =
|list: &[Arc<dyn Backend>]| list.iter().map(|b| (b.kind(), b.root().to_path_buf())).collect::<Vec<_>>();
if roots(&found) != roots(&self.backends.read()) {
*self.backends.write() = found;
sink.emit(IdeEvent::VcsChanged { root: root.to_path_buf().into() });
}
}
}
impl Project {
/// The repository roots detection finds, before Directory Mappings exclude or add any.
pub fn detected_repository_roots(&self) -> IdeResult<Vec<PathBuf>> {
@@ -1399,53 +1247,6 @@ impl Project {
&self.build_cache_dir(),
self.is_trusted(),
);
self.refresh_backends();
}
/// Looks for the non-Git working copies again: they are found in a trusted project only,
/// so trusting it (or restricting it) changes the answer.
pub fn refresh_backends(&self) {
let scan = BackendScan {
backends: &self.backends,
providers: &self.vcs_providers,
lock: &self.backend_scan,
trusted: &self.trusted,
};
scan.run(&self.root, &self.settings, &self.sink, &self.build_cache_dir());
}
/// Tells the UI that what version control reports changed without a file event (a file
/// was opened for edit).
pub fn vcs_changed(&self) {
self.sink.emit(IdeEvent::VcsChanged { root: self.root.clone().into() });
}
/// The project's non-Git working copies; none while it is in Restricted Mode. A working
/// copy rooted where a Git repository is (a folder with both `.git` and `.svn`) is left to
/// Git, so each root is reported once.
pub fn backends(&self) -> Vec<Arc<dyn Backend>> {
if !self.is_trusted() {
return Vec::new();
}
let repos = self.repos.read();
self.backends.read().iter().filter(|b| repos.at_root(b.root()).is_none()).cloned().collect()
}
/// The non-Git working copy `path` belongs to: the deepest one holding it, unless a Git
/// repository at or below that working copy's root holds the path (a Git checkout inside
/// a Perforce workspace stays Git's).
pub fn backend_of(&self, path: &Path) -> Option<Arc<dyn Backend>> {
backend_for(&self.backends(), &self.repos.read(), path).cloned()
}
/// The non-Git working copy rooted at `at`; without `at`, the first one of a project that
/// has no Git repository, where Git would use its primary repository.
pub fn backend_at(&self, at: Option<&Path>) -> Option<Arc<dyn Backend>> {
match at {
Some(root) => self.backends().into_iter().find(|b| b.root() == root),
None if self.repos.read().is_empty() => self.backends().into_iter().next(),
None => None,
}
}
/// Settings › Version Control › Git › Enable Git integration (effective value).
@@ -1547,12 +1348,8 @@ impl Project {
}
}
/// Runs `f` with the backend `path` belongs to: its non-Git working copy, else its Git
/// repository.
/// `with_repo_of` through the backend-agnostic Changes-view surface.
pub fn with_backend_of<T>(&self, path: &Path, f: impl FnOnce(&dyn Backend) -> IdeResult<T>) -> IdeResult<T> {
if let Some(backend) = self.backend_of(path) {
return f(backend.as_ref());
}
self.with_repo_of(path, |r| f(r as &dyn Backend))
}
@@ -1568,12 +1365,8 @@ impl Project {
f(repo)
}
/// `with_repo_at` through the backend-agnostic Changes-view surface; `at` may name a
/// non-Git working copy ([`Self::backend_at`]).
/// `with_repo_at` through the backend-agnostic Changes-view surface.
pub fn with_backend_at<T>(&self, at: Option<&Path>, f: impl FnOnce(&dyn Backend) -> IdeResult<T>) -> IdeResult<T> {
if let Some(backend) = self.backend_at(at) {
return f(backend.as_ref());
}
self.with_repo_at(at, |r| f(r as &dyn Backend))
}
@@ -1583,43 +1376,22 @@ impl Project {
at: Option<&Path>,
f: impl FnOnce(&dyn Backend) -> IdeResult<T>,
) -> IdeResult<T> {
if let Some(backend) = self.backend_at(at) {
return f(backend.as_ref());
}
self.with_log_repo_at(at, |r| f(r as &dyn Backend))
}
/// `with_log_repo_of` through the backend-agnostic Changes-view surface.
pub fn with_log_backend_of<T>(&self, path: &Path, f: impl FnOnce(&dyn Backend) -> IdeResult<T>) -> IdeResult<T> {
if let Some(backend) = self.backend_of(path) {
return f(backend.as_ref());
}
self.with_log_repo_of(path, |r| f(r as &dyn Backend))
}
/// `with_repo_recorded` through the backend-agnostic Changes-view surface: a non-Git
/// working copy's operation (update, revert…) gets the same Local History labels and
/// snapshots.
/// `with_repo_recorded` through the backend-agnostic Changes-view surface.
pub fn with_backend_recorded<T>(
&self,
at: Option<&Path>,
operation: Option<&str>,
f: impl FnOnce(&dyn Backend) -> IdeResult<T>,
) -> IdeResult<T> {
match self.backend_at(at) {
Some(backend) => self.backend_recorded(backend.as_ref(), operation, f),
None => self.with_repo_recorded(at, operation, |r| f(r as &dyn Backend)),
}
}
/// [`Self::with_backend_recorded`] for a working copy already looked up.
pub fn backend_recorded<T>(
&self,
backend: &dyn Backend,
operation: Option<&str>,
f: impl FnOnce(&dyn Backend) -> IdeResult<T>,
) -> IdeResult<T> {
self.recorded(operation, || backend.status(), || f(backend))
self.with_repo_recorded(at, operation, |r| f(r as &dyn Backend))
}
/// Runs `f` with the project's primary git repository, or fails when the project is not under git.
@@ -1644,27 +1416,16 @@ impl Project {
operation: Option<&str>,
f: impl FnOnce(&Repo) -> IdeResult<T>,
) -> IdeResult<T> {
self.recorded(operation, || self.with_repo_at(at, Backend::status), || self.with_repo_at(at, f))
}
/// Runs `run` with the Local History labels and snapshots of [`Self::with_repo_recorded`]:
/// `changed` lists the files to snapshot.
fn recorded<T>(
&self,
operation: Option<&str>,
changed: impl FnOnce() -> IdeResult<Vec<FileStatus>>,
run: impl FnOnce() -> IdeResult<T>,
) -> IdeResult<T> {
let Some(name) = operation else { return self.with_disk_sync(run) };
let Some(name) = operation else { return self.with_disk_sync(|| self.with_repo_at(at, f)) };
self.history_label(&format!("Before {name}"));
if let Ok(changed) = changed() {
if let Ok(changed) = self.with_backend_at(at, |r| r.status()) {
for file in changed.iter().take(HISTORY_BATCH_LIMIT) {
if let Err(e) = self.history.record_file(&file.path, &format!("Before {name}"), false) {
tracing::debug!("local history: {e}");
}
}
}
let result = self.with_disk_sync(run);
let result = self.with_disk_sync(|| self.with_repo_at(at, f));
self.history_label(&format!("After {name}"));
result
}
@@ -1896,7 +1657,7 @@ impl Project {
return encoding_rs::Encoding::for_label(loaded.encoding.as_bytes())
.ok_or_else(|| ide_core::IdeError::invalid("unknown file encoding"));
}
let bytes = self.with_log_backend_of(path, |b| b.file_bytes_at(path, rev))?.unwrap_or_default();
let bytes = self.with_log_repo_of(path, |r| r.file_bytes_at(path, rev))?.unwrap_or_default();
Ok(self.documents.detect_encoding(path, &bytes))
}
-4
Переглянути файл
@@ -260,10 +260,6 @@ impl crate::Host {
let p = project.clone();
tokio::task::spawn_blocking(move || p.refresh_repositories());
project.sink.emit(ide_core::IdeEvent::ProjectRootsChanged { root: project.root.clone().into() });
} else if !project.vcs_providers.is_empty() {
// Non-Git working copies are found in a trusted project only: they show up (or go) now.
let p = project.clone();
tokio::task::spawn_blocking(move || p.refresh_backends());
}
if let Some(bridge) = &project.kotlin_bridge {
bridge.schedule();
-43
Переглянути файл
@@ -87,46 +87,3 @@ fn detached_close_returns_while_runtime_workers_wait_for_the_closing_thread() {
host.shutdown_notebooks_on_exit();
assert!(started.elapsed() < Duration::from_secs(5), "exit joined the finished close instead of timing out");
}
/// `Documents` keeps the language manager alive through its observers and the manager once held the
/// documents back, so a closed project's documents (and everything they reference) were never freed.
/// Checked for the synchronous close and for the detached close that a window uses.
#[test]
fn closing_a_project_frees_its_documents() {
for detached in [false, true] {
assert_close_frees_documents(detached);
}
}
fn assert_close_frees_documents(detached: bool) {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap().join("project");
std::fs::create_dir_all(&root).unwrap();
let runtime = tokio::runtime::Builder::new_multi_thread().worker_threads(2).enable_all().build().unwrap();
let _guard = runtime.enter();
let host = Arc::new(Host::new(common::host_config(tmp.path())));
host.trust.decide(&root, true, false).unwrap();
host.open_project("main", &root).unwrap();
let (documents, languages) = {
let project = host.project("main").unwrap();
(Arc::downgrade(&project.documents), Arc::downgrade(&project.languages))
};
assert!(documents.upgrade().is_some(), "the open project owns its documents");
if detached {
host.close_project_detached("main");
} else {
host.close_project("main");
}
// The detached close drops the project on its own thread.
let deadline = Instant::now() + Duration::from_secs(5);
while documents.upgrade().is_some() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(10));
}
assert!(documents.upgrade().is_none(), "detached={detached}: the documents of a closed project are still alive");
assert!(
languages.upgrade().is_none(),
"detached={detached}: the language registry of a closed project is still alive"
);
}
-607
Переглянути файл
@@ -1,607 +0,0 @@
//! A version control system besides Git plugs in through `BackendProvider`, the way
//! Perforce and Subversion do: an in-memory fake here, so nothing but `git` has to be
//! installed.
mod common;
use ide_core::{CancellationToken, IdeError, IdeResult};
use ide_host::{
Host,
ops::{fs, vcs},
};
use ide_vcs::{
Backend, BackendChangelist, BackendProvider, BlameLine, BlockHistory, Branch, ChangeKind, ChangedFile, Commit,
CommitOptions, FileStatus, LineHunk, LogDetails, LogQuery, PendingChange, RevisionChange, TextEncoding, VcsKind,
};
use parking_lot::Mutex;
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::time::Duration;
/// A working copy whose root holds a `.fake-vcs` file. Its changes are whatever the test
/// says; it remembers what it was asked to stage and open for edit.
struct Fake {
root: PathBuf,
changed: Mutex<Vec<PathBuf>>,
unreachable: AtomicBool,
staged: Mutex<Vec<PathBuf>>,
opened: Mutex<Vec<PathBuf>>,
/// The line of development checked out (`trunk` until switched).
head: Mutex<String>,
/// Its own changelists, named lists like Subversion's.
lists: Mutex<Vec<BackendChangelist>>,
}
impl Backend for Fake {
fn root(&self) -> &Path {
&self.root
}
fn kind(&self) -> VcsKind {
VcsKind::Perforce
}
fn head_label(&self) -> Option<String> {
Some(self.head.lock().clone())
}
fn update(&self, _: &CancellationToken, output: &dyn Fn(String)) -> IdeResult<()> {
std::fs::write(self.root.join("a.txt"), "updated\n")?;
output("Updated to revision 8.".into());
Ok(())
}
fn branches(&self) -> IdeResult<Vec<Branch>> {
let head = self.head.lock().clone();
Ok(["trunk", "branches/x"]
.map(|name| Branch {
name: name.into(),
remote: false,
current: name == head,
upstream: None,
tracked_tip: None,
ahead: 0,
behind: 0,
outgoing: None,
last_commit_ms: 0.0,
commit: String::new(),
})
.into())
}
fn switch_to(&self, branch: &str) -> IdeResult<()> {
*self.head.lock() = branch.into();
Ok(())
}
fn changelists(&self) -> IdeResult<Option<Vec<BackendChangelist>>> {
Ok(Some(self.lists.lock().clone()))
}
fn create_changelist(&self, name: &str, comment: &str) -> IdeResult<String> {
let list = BackendChangelist { id: name.into(), name: name.into(), comment: comment.into(), files: Vec::new() };
self.lists.lock().push(list);
Ok(name.into())
}
fn edit_changelist(&self, id: &str, name: &str, comment: &str) -> IdeResult<()> {
let mut lists = self.lists.lock();
let list = lists.iter_mut().find(|l| l.id == id).ok_or_else(|| IdeError::not_found(id))?;
(list.name, list.comment) = (name.into(), comment.into());
Ok(())
}
fn delete_changelist(&self, id: &str) -> IdeResult<()> {
self.lists.lock().retain(|l| l.id != id);
Ok(())
}
fn move_to_changelist(&self, paths: &[PathBuf], id: &str) -> IdeResult<()> {
let mut lists = self.lists.lock();
for list in lists.iter_mut() {
list.files.retain(|f| !paths.contains(&f.0));
}
if let Some(list) = lists.iter_mut().find(|l| l.id == id) {
list.files.extend(paths.iter().map(|p| p.clone().into()));
}
Ok(())
}
fn status(&self) -> IdeResult<Vec<FileStatus>> {
if self.unreachable.load(Ordering::Acquire) {
return Err(IdeError::unavailable("server unreachable"));
}
Ok(self
.changed
.lock()
.iter()
.map(|p| FileStatus {
path: p.clone().into(),
rel_path: p.strip_prefix(&self.root).unwrap().to_string_lossy().into_owned(),
staged: None,
unstaged: Some(ChangeKind::Modified),
renamed_from: None,
})
.collect())
}
fn file_bytes_at(&self, _: &Path, _: Option<&str>) -> IdeResult<Option<Vec<u8>>> {
Ok(None)
}
fn file_at(&self, _: &Path, _: Option<&str>, _: TextEncoding) -> IdeResult<Option<String>> {
Ok(None)
}
fn file_mode_at(&self, _: &Path, _: Option<&str>) -> IdeResult<Option<String>> {
Ok(None)
}
fn diff_text(&self, _: &Path, _: bool, _: TextEncoding) -> IdeResult<String> {
Ok(String::new())
}
fn working_tree_patch(
&self,
_: Option<&Path>,
_: Option<&str>,
_: usize,
_: &CancellationToken,
) -> IdeResult<String> {
Ok(String::new())
}
fn line_hunks(&self, _: &Path, _: &str, _: bool, _: TextEncoding) -> IdeResult<Vec<LineHunk>> {
Ok(Vec::new())
}
fn blame(&self, _: &Path, _: Option<&str>, _: Option<&str>, _: TextEncoding) -> IdeResult<Vec<BlameLine>> {
Ok(Vec::new())
}
fn block_history(
&self,
_: &Path,
_: Option<&str>,
_: (u32, u32),
_: TextEncoding,
_: &CancellationToken,
) -> IdeResult<BlockHistory> {
Err(IdeError::unavailable("no block history"))
}
fn log(&self, _: &LogQuery, _: &CancellationToken) -> IdeResult<Vec<Commit>> {
Ok(Vec::new())
}
fn log_details(&self, revision: &str) -> IdeResult<LogDetails> {
Ok(LogDetails {
message: format!("change {revision}"),
containing_branches: Vec::new(),
signature: "N".into(),
signer: String::new(),
key: String::new(),
fingerprint: String::new(),
})
}
fn commit_files(&self, _: &str) -> IdeResult<Vec<ChangedFile>> {
Ok(Vec::new())
}
fn commits_changes(&self, _: &[String]) -> IdeResult<Vec<RevisionChange>> {
Ok(Vec::new())
}
fn diff_revisions(&self, _: &str, _: &str) -> IdeResult<Vec<ChangedFile>> {
Ok(Vec::new())
}
fn diff_with_worktree(&self, _: &str) -> IdeResult<Vec<ChangedFile>> {
Ok(Vec::new())
}
fn numstat_with_worktree(&self, _: &str) -> IdeResult<Vec<(String, u32, u32)>> {
Ok(Vec::new())
}
fn stage(&self, paths: &[PathBuf]) -> IdeResult<()> {
self.staged.lock().extend_from_slice(paths);
Ok(())
}
fn unstage(&self, _: &[PathBuf]) -> IdeResult<()> {
Ok(())
}
/// Reverts: the file gets its depot text back.
fn discard(&self, paths: &[PathBuf]) -> IdeResult<()> {
for path in paths {
std::fs::write(path, "depot\n")?;
}
self.changed.lock().retain(|p| !paths.contains(p));
Ok(())
}
fn commit(&self, _: &str, _: &CommitOptions, _: &dyn Fn(&Path) -> IdeResult<TextEncoding>) -> IdeResult<String> {
Err(IdeError::unavailable("no submit"))
}
fn pending_changes(
&self,
_: &CommitOptions,
_: usize,
_: &dyn Fn(&Path) -> IdeResult<TextEncoding>,
) -> IdeResult<Vec<PendingChange>> {
Ok(Vec::new())
}
fn open_for_edit(&self, paths: &[PathBuf]) -> IdeResult<bool> {
self.opened.lock().extend_from_slice(paths);
Ok(true)
}
}
/// Finds the folder holding `.fake-vcs` at or above the one asked about; counts the questions.
#[derive(Default)]
struct Provider {
asked: AtomicUsize,
/// While set, `discover` waits (a slow client); `answered` counts the answers given.
hold: AtomicBool,
answered: AtomicUsize,
found: Mutex<Vec<Arc<Fake>>>,
}
impl Provider {
fn fake(&self) -> Arc<Fake> {
self.found.lock().first().cloned().expect("a working copy was discovered")
}
fn fake_at(&self, root: &Path) -> Arc<Fake> {
self.found.lock().iter().find(|f| f.root == root).cloned().expect("a working copy at that root")
}
}
impl BackendProvider for Provider {
fn marker(&self) -> Option<&str> {
Some(".fake-vcs")
}
fn discover(&self, folder: &Path) -> IdeResult<Option<Arc<dyn Backend>>> {
self.asked.fetch_add(1, Ordering::AcqRel);
while self.hold.load(Ordering::Acquire) {
std::thread::sleep(Duration::from_millis(5));
}
let _answered = Answered(&self.answered);
let Some(root) = folder.ancestors().find(|dir| dir.join(".fake-vcs").is_file()) else { return Ok(None) };
let mut found = self.found.lock();
let fake = match found.iter().find(|f| f.root == root) {
Some(fake) => fake.clone(),
None => {
let fake = Arc::new(Fake {
root: root.to_path_buf(),
changed: Mutex::default(),
unreachable: AtomicBool::new(false),
staged: Mutex::default(),
opened: Mutex::default(),
head: Mutex::new("trunk".into()),
lists: Mutex::default(),
});
found.push(fake.clone());
fake
}
};
Ok(Some(fake))
}
}
/// Counts an answer when `discover` returns, whichever way.
struct Answered<'a>(&'a AtomicUsize);
impl Drop for Answered<'_> {
fn drop(&mut self) {
self.0.fetch_add(1, Ordering::AcqRel);
}
}
fn git(root: &Path, args: &[&str]) -> String {
let output = Command::new("git").current_dir(root).args(args).output().unwrap();
assert!(output.status.success(), "{args:?}: {}", String::from_utf8_lossy(&output.stderr));
String::from_utf8(output.stdout).unwrap().trim().to_owned()
}
fn host(base: &Path, provider: &Arc<Provider>) -> Host {
Host::new(common::host_config(base)).with_vcs_provider(provider.clone())
}
async fn until(what: &str, done: impl Fn() -> bool) {
for _ in 0..500 {
if done() {
return;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
panic!("timed out waiting for {what}");
}
fn paths(status: &[FileStatus]) -> BTreeSet<PathBuf> {
status.iter().map(|f| f.path.0.clone()).collect()
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_working_copy_answers_the_shared_vcs_commands() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
std::fs::create_dir_all(&root).unwrap();
std::fs::write(root.join(".fake-vcs"), "").unwrap();
let file = root.join("a.txt");
std::fs::write(&file, "edited\n").unwrap();
let provider = Arc::new(Provider::default());
let host = host(&base, &provider);
host.trust.decide(&root, true, false).unwrap();
let project = host.open_project("main", &root).unwrap();
until("the working copy", || !project.backends().is_empty()).await;
let fake = provider.fake();
fake.changed.lock().push(file.clone());
assert_eq!(paths(&vcs::vcs_status(&host, "main").await.unwrap()), BTreeSet::from([file.clone()]));
assert_eq!(paths(&vcs::vcs_status_paths(&host, "main", vec![file.clone()]).await.unwrap()).len(), 1);
let roots = vcs::vcs_roots(&host, "main").await.unwrap();
assert_eq!(roots.len(), 1);
assert_eq!((roots[0].root.0.as_path(), roots[0].kind), (root.as_path(), VcsKind::Perforce));
assert_eq!(roots[0].head.as_deref(), Some("trunk"));
let info = vcs::vcs_branch_info(&host, "main", None).await.unwrap();
assert_eq!(info.head.as_deref(), Some("trunk"));
// The log comes from the working copy; Git-only reads (refs, stashes) answer nothing.
assert!(vcs::vcs_log(&host, "main", None, LogQuery::default()).await.unwrap().is_empty());
assert_eq!(vcs::vcs_log_details(&host, "main", None, "7".into()).await.unwrap().message, "change 7");
assert!(vcs::vcs_log_refs(&host, "main", Some(root.clone())).await.unwrap().is_empty());
assert!(vcs::vcs_stashes(&host, "main", None).await.unwrap().is_empty());
vcs::vcs_stage(&host, "main", vec![file.clone()]).await.unwrap();
assert_eq!(*fake.staged.lock(), std::slice::from_ref(&file));
fs::fs_set_writable(&host, "main", file.clone(), true).unwrap();
assert_eq!(*fake.opened.lock(), std::slice::from_ref(&file));
// Rollback rewrites the file: Local History keeps the text from before, between labels.
vcs::vcs_discard(&host, "main", vec![file.clone()]).await.unwrap();
assert_eq!(std::fs::read_to_string(&file).unwrap(), "depot\n");
let history = project.history.list(&file).unwrap();
let labels: Vec<&str> = history.iter().map(|e| e.label.as_str()).collect();
assert!(labels.contains(&"After Rollback") && labels.contains(&"Before Rollback"), "{labels:?}");
let snapshot = history.iter().find(|e| !e.id.is_empty() && e.label == "Before Rollback").expect("a snapshot");
assert_eq!(project.history.content(&snapshot.id).unwrap(), "edited\n");
// Update Project and the branch widget use the shared commands too.
let output = Arc::new(Mutex::new(Vec::new()));
let lines = output.clone();
let channel = ide_host::ops::Channel::new(move |line: String| lines.lock().push(line));
let op = vcs::RemoteOp::UpdateProjectBranch { rebase: false };
let report = vcs::vcs_remote(&host, "main", None, ide_core::RequestId::next(), op, channel, None).await.unwrap();
assert!(report.is_none());
assert_eq!(*output.lock(), ["Updated to revision 8."]);
assert_eq!(std::fs::read_to_string(&file).unwrap(), "updated\n");
let labels: Vec<String> = project.history.list(&file).unwrap().into_iter().map(|e| e.label).collect();
assert!(labels.iter().any(|l| l == "Before Update") && labels.iter().any(|l| l == "After Update"), "{labels:?}");
let branches = vcs::vcs_branches(&host, "main", None).await.unwrap();
assert_eq!(
branches.iter().map(|b| (b.name.as_str(), b.current)).collect::<Vec<_>>(),
[("trunk", true), ("branches/x", false)]
);
let outcome = vcs::vcs_checkout(&host, "main", None, "branches/x".into(), false, None, None).await.unwrap();
assert_eq!(outcome, ide_vcs::CheckoutOutcome::Done);
assert_eq!(vcs::vcs_branch_info(&host, "main", None).await.unwrap().head.as_deref(), Some("branches/x"));
assert!(vcs::vcs_checkout(&host, "main", None, "branches/y".into(), true, None, None).await.is_err());
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn git_inside_a_working_copy_keeps_its_files_and_its_changes() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
let lib = root.join("lib");
std::fs::create_dir_all(&lib).unwrap();
std::fs::write(root.join(".fake-vcs"), "").unwrap();
git(&lib, &["init", "-q", "-b", "main"]);
git(&lib, &["config", "user.name", "Test"]);
git(&lib, &["config", "user.email", "[email protected]"]);
std::fs::write(lib.join("tracked.txt"), "one\n").unwrap();
git(&lib, &["add", "."]);
git(&lib, &["commit", "-qm", "first"]);
let (outside, tracked, untracked) = (root.join("a.txt"), lib.join("tracked.txt"), lib.join("new.txt"));
std::fs::write(&outside, "edited\n").unwrap();
std::fs::write(&untracked, "new\n").unwrap();
let provider = Arc::new(Provider::default());
let host = host(&base, &provider);
host.trust.decide(&root, true, false).unwrap();
let project = host.open_project("main", &root).unwrap();
until("Git and the working copy", || !project.backends().is_empty() && !project.repos().is_empty()).await;
let fake = provider.fake();
// The working copy claims a file of the nested Git repository too: Git keeps it.
fake.changed.lock().extend([outside.clone(), tracked.clone()]);
assert!(project.backend_of(&outside).is_some());
assert!(project.backend_of(&tracked).is_none() && project.backend_of(&lib).is_none());
let status = vcs::vcs_status(&host, "main").await.unwrap();
assert_eq!(paths(&status), BTreeSet::from([outside.clone(), untracked.clone()]));
let kinds: Vec<VcsKind> = vcs::vcs_roots(&host, "main").await.unwrap().iter().map(|r| r.kind).collect();
assert_eq!(kinds, [VcsKind::Git, VcsKind::Perforce]);
// Each path goes to its own backend.
vcs::vcs_stage(&host, "main", vec![outside.clone(), untracked.clone()]).await.unwrap();
assert_eq!(*fake.staged.lock(), std::slice::from_ref(&outside));
assert_eq!(git(&lib, &["status", "--porcelain", "new.txt"]), "A new.txt");
// The working copy's own changelists; the Git root keeps the IDE's lists.
assert_eq!(vcs::vcs_backend_changelists(&host, "main", Some(lib.clone())).await.unwrap(), None);
let id = vcs::vcs_backend_changelist_create(&host, "main", Some(root.clone()), "ui".into(), String::new())
.await
.unwrap();
vcs::vcs_backend_changelist_move(&host, "main", vec![outside.clone()], id.clone()).await.unwrap();
assert!(vcs::vcs_backend_changelist_move(&host, "main", vec![untracked.clone()], id.clone()).await.is_err());
// A list with a path in no working copy is refused whole: nothing moves, not even the
// paths that would have been valid on their own.
vcs::vcs_backend_changelist_move(&host, "main", vec![outside.clone()], "default".into()).await.unwrap();
let mixed = vec![outside.clone(), untracked.clone()];
assert!(vcs::vcs_backend_changelist_move(&host, "main", mixed, id.clone()).await.is_err());
let lists = vcs::vcs_backend_changelists(&host, "main", Some(root.clone())).await.unwrap().unwrap();
assert!(lists.iter().all(|l| l.files.is_empty()), "{lists:?}");
vcs::vcs_backend_changelist_move(&host, "main", vec![outside.clone()], id.clone()).await.unwrap();
vcs::vcs_backend_changelist_edit(&host, "main", Some(root.clone()), id.clone(), "UI".into(), "menus".into())
.await
.unwrap();
let lists = vcs::vcs_backend_changelists(&host, "main", Some(root.clone())).await.unwrap().unwrap();
assert_eq!(lists.len(), 1);
assert_eq!((lists[0].name.as_str(), lists[0].comment.as_str()), ("UI", "menus"));
assert_eq!(lists[0].files.iter().map(|f| f.0.clone()).collect::<Vec<_>>(), std::slice::from_ref(&outside));
vcs::vcs_backend_changelist_delete(&host, "main", Some(root.clone()), id).await.unwrap();
assert_eq!(vcs::vcs_backend_changelists(&host, "main", Some(root.clone())).await.unwrap(), Some(Vec::new()));
assert!(
vcs::vcs_backend_changelist_create(&host, "main", Some(lib.clone()), "x".into(), String::new()).await.is_err()
);
// A server that cannot be reached leaves the Git changes visible.
fake.unreachable.store(true, Ordering::Release);
let status = vcs::vcs_status(&host, "main").await.unwrap();
assert_eq!(paths(&status), BTreeSet::from([untracked.clone()]));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_working_copy_at_a_git_root_is_left_to_git() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
std::fs::create_dir_all(&root).unwrap();
std::fs::write(root.join(".fake-vcs"), "").unwrap();
git(&root, &["init", "-q", "-b", "main"]);
let untracked = root.join("new.txt");
std::fs::write(&untracked, "new\n").unwrap();
let provider = Arc::new(Provider::default());
let host = host(&base, &provider);
host.trust.decide(&root, true, false).unwrap();
let project = host.open_project("main", &root).unwrap();
until("the working copy", || !project.backends.read().is_empty()).await;
provider.fake().changed.lock().push(untracked.clone());
// Found, but shadowed: the root is reported once, as Git's, and Git answers for it.
assert!(project.backends().is_empty() && project.backend_at(Some(&root)).is_none());
let roots = vcs::vcs_roots(&host, "main").await.unwrap();
let roots: Vec<_> = roots.iter().map(|r| (r.root.0.clone(), r.kind)).collect();
assert_eq!(roots, [(root.clone(), VcsKind::Git)]);
let status = vcs::vcs_status(&host, "main").await.unwrap();
assert_eq!(paths(&status), BTreeSet::from([root.join(".fake-vcs"), untracked.clone()]));
assert!(status.iter().all(|f| f.unstaged == Some(ChangeKind::Untracked)));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn restricted_mode_asks_no_provider_until_the_project_is_trusted() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
std::fs::create_dir_all(&root).unwrap();
std::fs::write(root.join(".fake-vcs"), "").unwrap();
std::fs::create_dir_all(root.join("inner")).unwrap();
std::fs::write(root.join("inner/.fake-vcs"), "").unwrap();
let provider = Arc::new(Provider::default());
let host = host(&base, &provider);
let project = host.open_project("main", &root).unwrap();
tokio::time::sleep(Duration::from_millis(200)).await;
project.refresh_backends();
assert_eq!(provider.asked.load(Ordering::Acquire), 0);
assert!(project.backends().is_empty() && project.backend_of(&root.join("a.txt")).is_none());
assert!(vcs::vcs_status(&host, "main").await.is_err());
host.set_project_trust(&root, true, false).await.unwrap();
until("both working copies", || project.backends().len() == 2).await;
assert!(provider.asked.load(Ordering::Acquire) > 0);
assert!(vcs::vcs_status(&host, "main").await.unwrap().is_empty());
host.set_project_trust(&root, false, false).await.unwrap();
assert!(project.backends().is_empty());
until("the working copy to go", || project.backends.read().is_empty()).await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_slow_scan_started_before_restricting_does_not_bring_the_working_copy_back() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
std::fs::create_dir_all(&root).unwrap();
std::fs::write(root.join(".fake-vcs"), "").unwrap();
let provider = Arc::new(Provider::default());
provider.hold.store(true, Ordering::Release);
let host = host(&base, &provider);
host.trust.decide(&root, true, false).unwrap();
let project = host.open_project("main", &root).unwrap();
until("the opening scan to ask", || provider.asked.load(Ordering::Acquire) > 0).await;
// Restricted while the opening scan still waits for its answer: the rescan this starts
// must come after it, not before.
host.set_project_trust(&root, false, false).await.unwrap();
tokio::time::sleep(Duration::from_millis(100)).await;
provider.hold.store(false, Ordering::Release);
until("the opening scan's answer", || provider.answered.load(Ordering::Acquire) > 0).await;
tokio::time::sleep(Duration::from_millis(300)).await;
assert!(project.backends.read().is_empty());
}
fn roots_of(project: &ide_host::Project) -> BTreeSet<PathBuf> {
project.backends().iter().map(|b| b.root().to_path_buf()).collect()
}
fn marked(dir: &Path) {
std::fs::create_dir_all(dir).unwrap();
std::fs::write(dir.join(".fake-vcs"), "").unwrap();
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn working_copies_nested_in_a_working_copy_are_found_like_nested_git_repositories() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
// A separate checkout inside the working copy, a directory external two levels down, and
// one in a dependency folder that is never searched.
let (inner, external) = (root.join("inner"), root.join("ext/lib"));
for dir in [&root, &inner, &external, &root.join("node_modules/pkg")] {
marked(dir);
}
let provider = Arc::new(Provider::default());
let host = host(&base, &provider);
host.trust.decide(&root, true, false).unwrap();
let project = host.open_project("main", &root).unwrap();
until("the nested working copies", || project.backends().len() == 3).await;
assert_eq!(roots_of(&project), BTreeSet::from([root.clone(), inner.clone(), external.clone()]));
// The deepest working copy owns a path.
let owner = |path: &Path| project.backend_of(path).map(|b| b.root().to_path_buf());
assert_eq!(owner(&inner.join("b.txt")), Some(inner.clone()));
assert_eq!(owner(&external.join("x.txt")), Some(external.clone()));
assert_eq!(owner(&root.join("ext/y.txt")), Some(root.clone()));
assert_eq!(owner(&root.join("node_modules/pkg/z.txt")), Some(root.clone()));
// Each changed file is listed once, by its own working copy.
let (outer_file, inner_file) = (root.join("a.txt"), inner.join("b.txt"));
provider.fake_at(&root).changed.lock().extend([outer_file.clone(), inner_file.clone()]);
provider.fake_at(&inner).changed.lock().push(inner_file.clone());
let status = vcs::vcs_status(&host, "main").await.unwrap();
assert_eq!(status.len(), 2, "{status:?}");
assert_eq!(paths(&status), BTreeSet::from([outer_file, inner_file]));
let kinds: Vec<VcsKind> = vcs::vcs_roots(&host, "main").await.unwrap().iter().map(|r| r.kind).collect();
assert_eq!(kinds, [VcsKind::Perforce; 3]);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_working_copy_inside_a_git_project_is_found() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
let wc = root.join("vendor-src/wc");
std::fs::create_dir_all(&root).unwrap();
git(&root, &["init", "-q", "-b", "main"]);
marked(&wc);
let provider = Arc::new(Provider::default());
let host = host(&base, &provider);
host.trust.decide(&root, true, false).unwrap();
let project = host.open_project("main", &root).unwrap();
until("Git and the working copy", || !project.repos().is_empty() && !project.backends().is_empty()).await;
assert_eq!(roots_of(&project), BTreeSet::from([wc.clone()]));
assert!(project.backend_of(&wc.join("a.txt")).is_some());
assert!(project.backend_of(&root.join("a.txt")).is_none());
let roots: Vec<_> =
vcs::vcs_roots(&host, "main").await.unwrap().iter().map(|r| (r.root.0.clone(), r.kind)).collect();
assert_eq!(roots, [(root.clone(), VcsKind::Git), (wc.clone(), VcsKind::Perforce)]);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_working_copy_checked_out_in_the_open_project_shows_up_and_goes() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
std::fs::create_dir_all(root.join("src")).unwrap();
std::fs::write(root.join("src/main.txt"), "x\n").unwrap();
let provider = Arc::new(Provider::default());
let host = host(&base, &provider);
host.trust.decide(&root, true, false).unwrap();
let project = host.open_project("main", &root).unwrap();
until("the opening scan", || provider.answered.load(Ordering::Acquire) > 0).await;
assert!(project.backends().is_empty());
// A checkout writes its folder, the marker, then the files.
let checkout = root.join("checkout");
marked(&checkout);
std::fs::write(checkout.join("a.txt"), "a\n").unwrap();
until("the new working copy", || roots_of(&project) == BTreeSet::from([checkout.clone()])).await;
std::fs::remove_dir_all(&checkout).unwrap();
until("the removed working copy to go", || project.backends().is_empty()).await;
}
-71
Переглянути файл
@@ -530,77 +530,6 @@ src/local/
assert!(listed[0].ignored);
}
#[test]
fn root_anchored_gitignore_is_honoured_and_does_not_match_nested_names() {
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap();
for f in ["src/a.rs", "build/gen.rs", "build/nested/out.rs", "packages/foo/build/x.rs", "tmp/scratch.rs"] {
touch(&root, f);
}
std::fs::write(
root.join(".gitignore"),
"# Flutter-style root build output
/build/
tmp/
",
)
.unwrap();
let filter = PathFilter::new(&root, &vec![].into(), &[]);
let mut found: Vec<(String, bool)> = filter
.walk(&root, &AtomicBool::new(false))
.iter()
.filter_map(|f| Some((filter.rel(&f.path)?, f.ignored)))
.collect();
found.sort();
// Root-anchored `/build/` ignores only the root `build/` tree. Unanchored
// `tmp/` is also filename-only. A nested directory named `build` is kept.
assert_eq!(
found,
[
(".gitignore", false),
("build/gen.rs", true),
("build/nested/out.rs", true),
("packages/foo/build/x.rs", false),
("src/a.rs", false),
("tmp/scratch.rs", true),
]
.map(|(p, i)| (p.to_owned(), i))
);
for rel in ["build/gen.rs", "build/nested/out.rs", "packages/foo/build/x.rs", "tmp/scratch.rs", "src/a.rs"] {
assert!(!filter.is_excluded(&root.join(rel)), "{rel}");
}
let mut listed: Vec<(String, bool)> = filter
.list_dir(&root.join("build"))
.iter()
.filter_map(|f| Some((filter.rel(&f.path)?, f.ignored)))
.collect();
listed.sort();
assert_eq!(listed, [("build/gen.rs", true)].map(|(p, i)| (p.to_owned(), i)));
}
#[test]
fn root_anchored_exclude_file_is_honoured() {
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap();
touch(&root, "src/a.rs");
touch(&root, "build/gen.rs");
std::fs::create_dir_all(root.join(".git/info")).unwrap();
std::fs::write(
root.join(".git/info/exclude"),
"/build/
",
)
.unwrap();
let filter = PathFilter::new(&root, &vec![].into(), &[]);
let mut found: Vec<(String, bool)> = filter
.walk(&root, &AtomicBool::new(false))
.iter()
.filter_map(|f| Some((filter.rel(&f.path)?, f.ignored)))
.collect();
found.sort();
assert_eq!(found, [("build/gen.rs", true), ("src/a.rs", false)].map(|(p, i)| (p.to_owned(), i)));
}
#[test]
fn a_nested_repository_is_not_hidden_by_the_outer_repositorys_gitignore() {
let dir = tempfile::tempdir().unwrap();
-4
Переглянути файл
@@ -390,10 +390,6 @@ impl Store {
})
}
pub(crate) fn snapshot_exists(&self) -> bool {
self.snapshot.is_file()
}
fn open_db(&self) -> Result<Database> {
let file = self.snapshot.with_file_name("index.redb");
let db = match Database::builder().set_cache_size(DB_CACHE_BYTES).create(&file) {
+8 -51
Переглянути файл
@@ -601,11 +601,8 @@ impl Shared {
d.remove(path);
}
}
let index_changed = !stale.is_empty() || !todo.is_empty();
let stale: Vec<String> = stale.iter().filter_map(|p| filter.store_key(p)).collect();
if !stale.is_empty() {
self.persist(&[], &stale, false);
}
self.persist(&[], &stale, false);
let total = todo.len();
if task.is_none() && total >= QUIET_SCAN_FILES {
@@ -677,31 +674,25 @@ impl Shared {
return None;
}
let durable_started = Instant::now();
if index_changed {
self.persist(&[], &[], true);
}
self.persist(&[], &[], true);
let durable = durable_started.elapsed();
let update_elapsed = update_started.elapsed();
let snapshot_started = Instant::now();
if let Some(store) = &self.store {
let recent: Vec<String> = self.recent.lock().iter().filter_map(|p| filter.recent_key(p)).collect();
// process() may already have applied the change and deleted the snapshot;
// a follow-up reconcile scan can have scheduled=0 and still need to write it.
if index_changed || !store.snapshot_exists() {
let d = self.data.read();
let snapshot_started = Instant::now();
if let Err(e) = store.save_snapshot(&d, &filter, guard) {
tracing::warn!("index snapshot: {e}");
}
tracing::info!("index snapshot: written in {:?}", snapshot_started.elapsed());
*self.snapshot_saved.lock() = Some(Instant::now());
let d = self.data.read();
let snapshot_started = Instant::now();
if let Err(e) = store.save_snapshot(&d, &filter, guard) {
tracing::warn!("index snapshot: {e}");
}
tracing::info!("index snapshot: written in {:?}", snapshot_started.elapsed());
if let Err(e) = store.save_recent_file(&recent) {
tracing::warn!("index recent snapshot: {e}");
}
}
let snapshot_elapsed = snapshot_started.elapsed();
*self.snapshot_due.lock() = None;
*self.snapshot_saved.lock() = Some(Instant::now());
if let Some(task) = task {
self.indexing.store(false, Ordering::SeqCst);
self.sink.emit(IdeEvent::Task {
@@ -1452,40 +1443,6 @@ mod metric_tests {
assert_eq!(shared.data.read().symbol_count, 1);
}
#[test]
fn no_change_scan_skips_snapshot_rewrite() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("project");
std::fs::create_dir(&root).unwrap();
let root = dunce::canonicalize(root).unwrap();
std::fs::write(root.join("main.rs"), "fn main() {}\n").unwrap();
let cache = dir.path().join("cache");
let mut index = shared(&root);
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
// A guard after every write, so save_snapshot does not discard the file
// when a directory mtime lands on the same instant as the scan start.
let guard = || SystemTime::now() + std::time::Duration::from_secs(2);
let cold = index.scan(None, &[], None, guard()).unwrap();
assert_eq!(cold.scheduled, 1);
let snapshot = cache.join("index.snapshot");
assert!(snapshot.exists());
let before = std::fs::metadata(&snapshot).unwrap();
// A rewrite would bump mtime; give the filesystem a distinct timestamp.
std::thread::sleep(std::time::Duration::from_millis(20));
let hot = index.scan(None, &[], None, guard()).unwrap();
assert_eq!((hot.discovered, hot.metadata_reused, hot.scheduled), (1, 1, 0));
let after = std::fs::metadata(&snapshot).unwrap();
assert_eq!(after.len(), before.len(), "a no-change scan must not rewrite the snapshot");
assert_eq!(after.modified().unwrap(), before.modified().unwrap());
std::fs::write(root.join("main.rs"), "fn renamed() {}\n").unwrap();
std::thread::sleep(std::time::Duration::from_millis(20));
let changed = index.scan(None, &[], None, guard()).unwrap();
assert_eq!(changed.scheduled, 1);
let rewritten = std::fs::metadata(&snapshot).unwrap();
assert!(rewritten.modified().unwrap() > after.modified().unwrap(), "a changed scan must refresh the snapshot");
}
#[test]
fn extraction_outcomes_are_exclusive_and_forced_parsing_is_counted() {
let dir = tempfile::tempdir().unwrap();
+3 -70
Переглянути файл
@@ -1,16 +1,15 @@
//! Java project queries and class-file navigation for servers other than jdtls.
//! Java project queries for launches when jdtls does not serve the module: another Java
//! language server (java-analyzer) answers the classpath and JDK, if it supports it.
use crate::LspManager;
use crate::jdtls::{JavaClasspath, SERVER as JDTLS};
use crate::{ErrorKind, LspManager, Target, uri};
use ide_core::{CancellationToken, IdeError, IdeResult, LanguageId};
use serde_json::{Value, json};
use std::future::Future;
use std::path::{Path, PathBuf};
use std::time::Duration;
/// `{ uri, scope: "runtime" | "test" }` → `{ projectRoot, classPaths, modulePaths, jdkHome }`.
const CLASSPATH: &str = "java-analyzer/projectClasspath";
const CLASS_FILE: &str = "java-analyzer/classFile";
/// Waiting for the server to start and import the project.
const READY_TIMEOUT: Duration = Duration::from_secs(120);
const REQUEST_TIMEOUT: Duration = Duration::from_secs(120);
@@ -38,54 +37,6 @@ impl LspManager {
})
}
/// Resolve a compiled class to the document that the project's Java server opens.
/// The internal name is only read for disk classes handled by a server other than jdtls.
pub async fn java_class_file(
&self,
path: &Path,
archive: Option<(PathBuf, String)>,
internal_name: impl Future<Output = IdeResult<String>>,
) -> IdeResult<String> {
if self.java_served_by_jdtls(&self.project_root) {
let result = self.jdtls_class_file(path, archive.clone()).await;
// Starting jdtls can expose a configured fallback.
if result.is_ok() || self.java_served_by_jdtls(&self.project_root) {
return result;
}
}
// Use the workspace's server for archives, which can live outside the project.
let route = if archive.is_some() { &self.project_root } else { path };
let servers: Vec<_> = self
.servers_for(&LanguageId::new("java"), route)
.into_iter()
.filter(|s| s.name != JDTLS && !s.gave_up())
.collect();
if servers.is_empty() {
return self.jdtls_class_file(path, archive).await;
}
for server in &servers {
self.ensure_started(server);
let Some(run) = server.wait_ready(READY_TIMEOUT).await else { continue };
if run.caps.read().raw["experimental"][CLASS_FILE] != true {
continue;
}
let params = match archive {
Some((jar, entry)) => json!({ "archive": uri::path_to_uri_string(&jar), "entry": entry }),
None => disk_class_params(path, &internal_name.await?),
};
let target = Target { server: server.clone(), run };
let result: Option<ClassFileDocument> =
self.call(&target, CLASS_FILE, params, None, REQUEST_TIMEOUT).await?;
let doc = result
.ok_or_else(|| IdeError::not_found(format!("{} could not resolve {}", server.name, path.display())))?;
// Go-to-definition also opens these materialized file URIs as ordinary editor paths.
return uri::uri_to_path(&doc.uri)
.map(|path| path.to_string_lossy().into_owned())
.ok_or_else(|| IdeError::new(ErrorKind::Protocol, format!("{CLASS_FILE}: expected a file URI")));
}
Err(crate::unsupported(&servers, "Java class-file resolution"))
}
/// Runtime (`test == false`) or test classpath of the module at `path` from the first
/// Java server other than jdtls. `None` when there is none or it doesn't support the query.
pub async fn java_server_classpath(
@@ -126,24 +77,6 @@ impl LspManager {
}
}
#[derive(serde::Deserialize)]
struct ClassFileDocument {
uri: String,
}
fn disk_class_params(path: &Path, name: &str) -> Value {
let entry = format!("{name}.class");
// Supplying the output directory disambiguates classes with the same name in different modules.
if path.ends_with(&entry)
&& let Some(output) = path.ancestors().nth(Path::new(&entry).components().count())
&& !output.as_os_str().is_empty()
{
json!({ "archive": uri::path_to_uri_string(output), "entry": entry })
} else {
json!({ "binaryName": name.replace('/', ".") })
}
}
/// `None` for a `null` answer (the server has no module for the path).
fn parse(v: &Value) -> Option<ServerClasspath> {
if v.is_null() {
+1 -1
Переглянути файл
@@ -1257,7 +1257,7 @@ impl LspManager {
/// Archive URIs must come from JDT's Java model: fabricated handles cannot map debug lines.
/// A class in an output directory opens as itself even when its project source exists:
/// the user asked for the compiled class, not the file it was built from.
pub(crate) async fn jdtls_class_file(&self, path: &Path, archive: Option<(PathBuf, String)>) -> IdeResult<String> {
pub async fn java_class_file(&self, path: &Path, archive: Option<(PathBuf, String)>) -> IdeResult<String> {
if let Some((jar, entry)) = archive {
return self.archive_class(jar, entry, false).await;
}
+5 -70
Переглянути файл
@@ -5770,12 +5770,7 @@ async fn jar_library_sources_reload_with_another_encoding() {
async fn class_file_opening_routes_archive_and_output_classes() {
let mut caps = incremental_caps();
caps["workspaceSymbolProvider"] = json!(true);
let h = harness_for(
"java",
"java",
&[("jdtls", caps), ("java-analyzer", json!({"experimental":{"java-analyzer/classFile":true}}))],
&[],
);
let h = harness_for("java", "java", &[("jdtls", caps)], &[]);
h.open("App.java", "class App {}\n");
h.wait_status("jdtls", ServerStatus::Ready).await;
let s = h.launcher.state("jdtls");
@@ -5784,17 +5779,12 @@ async fn class_file_opening_routes_archive_and_output_classes() {
{"name":"Outer", "kind":5, "location":{"uri":jdt,"range":{"start":{"line":0,"character":0},"end":{"line":0,"character":0}}}}
]));
let archive = Some((PathBuf::from("/m2/lib.jar"), "p/Outer$1.class".into()));
let unused_name = || async { panic!("jdtls does not need the internal class name") };
assert_eq!(
h.mgr.java_class_file(Path::new("/m2/lib.jar!/p/Outer$1.class"), archive, unused_name()).await.unwrap(),
jdt
);
assert_eq!(h.mgr.java_class_file(Path::new("/m2/lib.jar!/p/Outer$1.class"), archive).await.unwrap(), jdt);
assert!(
h.mgr
.java_class_file(
Path::new("/other/lib.jar!/p/Outer.class"),
Some(("/other/lib.jar".into(), "p/Outer.class".into())),
unused_name(),
Some(("/other/lib.jar".into(), "p/Outer.class".into()))
)
.await
.is_err()
@@ -5807,71 +5797,16 @@ async fn class_file_opening_routes_archive_and_output_classes() {
s.respond("java/classFileContents", json!("// Source code is decompiled from a .class file using FernFlower decompiler (from Intellij IDEA).\npackage p;\npublic class Outer {}"));
for class in ["Outer", "Outer$Nested", "Outer$1"] {
let path = h.root.join(format!("target/classes/p/{class}.class"));
assert_eq!(h.mgr.java_class_file(&path, None, unused_name()).await.unwrap(), uri_of(&path));
assert_eq!(h.mgr.java_class_file(&path, None).await.unwrap(), uri_of(&path));
}
let path = h.root.join("build/classes/java/main/p/Missing.class");
let uri = uri_of(&path);
assert_eq!(h.mgr.java_class_file(&path, None, unused_name()).await.unwrap(), uri);
assert_eq!(h.mgr.java_class_file(&path, None).await.unwrap(), uri);
let vd = h.mgr.virtual_document(&uri).await.unwrap();
assert!(vd.decompiled);
assert_eq!(vd.language_id.as_str(), "java");
assert_eq!(vd.title, "Missing.class");
assert!(s.requested("java/classFileContents").iter().any(|p| p["uri"] == uri));
assert!(h.launcher.state("java-analyzer").requested("java-analyzer/classFile").is_empty());
}
#[tokio::test(flavor = "multi_thread")]
async fn class_file_opening_starts_java_analyzer_for_archive_classes() {
const METHOD: &str = "java-analyzer/classFile";
for with_jdtls in [false, true] {
let mut servers = vec![("java-analyzer", json!({"experimental":{METHOD:true}}))];
if with_jdtls {
servers.insert(0, ("jdtls", incremental_caps()));
}
let h = harness_for("java", "java", &servers, &["java-analyzer"]);
h.launcher.state("jdtls").missing.store(true, Ordering::SeqCst);
let server = h.launcher.state("java-analyzer");
let source = h.root.join("cache with spaces/p/Outer.java");
server.respond(METHOD, json!({"uri":uri_of(&source)}));
let archive = h.root.join("external Maven cache/lib.jar");
let entry = "META-INF/versions/17/p/Outer$Inner.class";
let path = PathBuf::from(format!("{}!/{entry}", archive.display()));
let opened = h
.mgr
.java_class_file(&path, Some((archive.clone(), entry.into())), async {
panic!("archive entries do not need the internal class name")
})
.await
.unwrap();
assert_eq!(Path::new(&opened), source);
assert_eq!(server.requested(METHOD), [json!({"archive":uri_of(&archive), "entry":entry})]);
assert!(server.requested("workspace/textDocumentContent").is_empty());
}
}
#[tokio::test(flavor = "multi_thread")]
async fn class_file_opening_routes_disk_classes_by_internal_name() {
const METHOD: &str = "java-analyzer/classFile";
let h = harness_for("java", "java", &[("java-analyzer", json!({"experimental":{METHOD:true}}))], &[]);
let server = h.launcher.state("java-analyzer");
let source = h.root.join("src/main/java/p/Outer.java");
server.respond(METHOD, json!({"uri":uri_of(&source)}));
let output = h.root.join("target/classes");
let class = output.join("p/Outer$Inner.class");
let moved = h.root.join("moved.class");
let internal_name = || async { Ok("p/Outer$Inner".into()) };
for path in [&class, &moved] {
assert_eq!(Path::new(&h.mgr.java_class_file(path, None, internal_name()).await.unwrap()), source);
}
assert_eq!(
server.requested(METHOD),
[json!({"archive":uri_of(&output), "entry":"p/Outer$Inner.class"}), json!({"binaryName":"p.Outer$Inner"})]
);
server.respond(METHOD, Value::Null);
assert_eq!(
h.mgr.java_class_file(&class, None, internal_name()).await.unwrap_err().kind,
ide_core::error::ErrorKind::NotFound
);
}
#[tokio::test(flavor = "multi_thread")]
+8 -87
Переглянути файл
@@ -1,7 +1,6 @@
//! Xcode schemes: one configuration per scheme that builds its app and runs it on the iOS
//! Simulator or the Mac (see [`crate::xcode::prepare`]). A workspace next to the projects builds them all
//! and links what they depend on (CocoaPods, Tuist, a SwiftPM workspace), so its schemes and theirs
//! are built through it, even when it has no schemes of its own.
//! Simulator or the Mac (see [`crate::xcode::prepare`]). A workspace next to the projects builds them all,
//! so its schemes and theirs are built through it, as is the workspace of a CocoaPods project.
use super::{ConfigExt, config};
use crate::RunConfig;
@@ -26,7 +25,7 @@ pub(super) fn detect(dir: &Path, out: &mut Vec<RunConfig>) {
.iter()
.map(|s| s.container.clone())
.find(|c| c.extension().is_some_and(|x| x == "xcworkspace"))
.or_else(|| crate::xcode::root_workspace(dir));
.or_else(|| crate::xcode::pods_workspace(dir));
for scheme in &found {
let container = workspace.as_ref().unwrap_or(&scheme.container);
let container = container.strip_prefix(dir).unwrap_or(container).to_string_lossy().into_owned();
@@ -99,15 +98,13 @@ mod tests {
std::fs::create_dir_all(&schemes).unwrap();
std::fs::write(schemes.join("App.xcscheme"), &scheme).unwrap();
}
// `pod install`'s workspace has no schemes of its own.
std::fs::create_dir(root.join("App.xcworkspace")).unwrap();
let args = |out: &[RunConfig]| out.iter().map(|c| c.args.join(" ")).collect::<Vec<_>>();
// Project only.
std::fs::rename(root.join("Pods"), root.join("Pods.off")).unwrap();
let mut out = Vec::new();
detect(root, &mut out);
assert_eq!(args(&out), ["-project App.xcodeproj -scheme App -configuration Staging"]);
std::fs::rename(root.join("Pods.off"), root.join("Pods")).unwrap();
// `pod install`'s (or Tuist's) workspace has no schemes of its own.
std::fs::create_dir(root.join("App.xcworkspace")).unwrap();
// Without a Podfile, a `Pods/` folder is just another project.
assert!(is_project(&root.join("Pods")));
@@ -125,86 +122,10 @@ mod tests {
let mut out = Vec::new();
detect(root, &mut out);
assert_eq!(args(&out), ["-workspace App.xcworkspace -scheme App -configuration Staging"]);
assert_eq!(crate::xcode::root_workspace(root), Some(root.join("App.xcworkspace")));
assert_eq!(crate::xcode::pods_workspace(root), Some(root.join("App.xcworkspace")));
// Without a workspace named after a project, the first by name.
std::fs::remove_dir(root.join("App.xcworkspace")).unwrap();
std::fs::create_dir(root.join("Old.xcworkspace")).unwrap();
assert_eq!(crate::xcode::root_workspace(root), Some(root.join("Aardvark.xcworkspace")));
}
fn project_with_scheme(root: &Path) {
let scheme = std::fs::read_to_string(
Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/fixtures/xcode/App.xcodeproj/xcshareddata/xcschemes/App.xcscheme"),
)
.unwrap();
let schemes = root.join("App.xcodeproj/xcshareddata/xcschemes");
std::fs::create_dir_all(&schemes).unwrap();
std::fs::write(schemes.join("App.xcscheme"), &scheme).unwrap();
}
fn workspace(root: &Path, name: &str, location: &str) {
std::fs::create_dir(root.join(name)).unwrap();
let data = format!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Workspace\n version = \"1.0\">\n <FileRef\n location = \"{location}\">\n </FileRef>\n</Workspace>\n"
);
std::fs::write(root.join(name).join("contents.xcworkspacedata"), data).unwrap();
}
fn run_and_test_args(root: &Path) -> (Vec<String>, Vec<String>) {
let args = |out: &[RunConfig]| out.iter().map(|c| c.args.join(" ")).collect::<Vec<_>>();
let (mut out, mut tests) = (Vec::new(), Vec::new());
detect(root, &mut out);
super::super::xcode_test::detect(root, &mut tests);
(args(&out), args(&tests))
}
#[test]
fn an_unrelated_workspace_beside_the_project_is_not_built() {
// No Podfile: a leftover or playground workspace that doesn't name the project.
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
project_with_scheme(root);
workspace(root, "Playground.xcworkspace", "group:Playground.playground");
std::fs::create_dir(root.join("Old.xcworkspace")).unwrap();
assert_eq!(crate::xcode::root_workspace(root), None);
let (run, test) = run_and_test_args(root);
assert_eq!(run, ["-project App.xcodeproj -scheme App -configuration Staging"]);
assert_eq!(test, ["test -project App.xcodeproj -scheme App"]);
// A project in a subfolder with the same name is not this one.
workspace(root, "Sub.xcworkspace", "group:Sub/App.xcodeproj");
assert_eq!(crate::xcode::root_workspace(root), None);
}
#[test]
fn a_tuist_workspace_that_references_the_project_is_built() {
// Tuist names the workspace after the manifest, not after the project.
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
project_with_scheme(root);
workspace(root, "Wasai.xcworkspace", "container:App.xcodeproj");
let (run, test) = run_and_test_args(root);
assert_eq!(run, ["-workspace Wasai.xcworkspace -scheme App -configuration Staging"]);
assert_eq!(test, ["test -workspace Wasai.xcworkspace -scheme App"]);
std::fs::remove_dir_all(root.join("Wasai.xcworkspace")).unwrap();
workspace(root, "Other.xcworkspace", "group:./App.xcodeproj");
assert_eq!(crate::xcode::root_workspace(root), Some(root.join("Other.xcworkspace")));
}
#[test]
fn a_workspace_without_schemes_builds_the_projects_schemes() {
// A hand-made workspace named after the project, with no Podfile and no schemes.
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
project_with_scheme(root);
std::fs::create_dir(root.join("App.xcworkspace")).unwrap();
let (run, test) = run_and_test_args(root);
assert_eq!(run, ["-workspace App.xcworkspace -scheme App -configuration Staging"]);
assert_eq!(test, ["test -workspace App.xcworkspace -scheme App"]);
// Workspace only: nothing to build without a scheme.
std::fs::remove_dir_all(root.join("App.xcodeproj")).unwrap();
let mut out = Vec::new();
detect(root, &mut out);
assert!(out.is_empty());
assert_eq!(crate::xcode::pods_workspace(root), Some(root.join("Aardvark.xcworkspace")));
}
}
+6 -7
Переглянути файл
@@ -1,5 +1,5 @@
//! Xcode test configurations: `xcodebuild test` for each scheme whose `TestAction` has tests,
//! through the workspace beside the project when there is one (CocoaPods, Tuist).
//! through the CocoaPods workspace when the project has one.
//! The simulator destination and the result bundle are added at launch (`xcode::prepare_test`).
use super::{ConfigExt, config};
@@ -7,14 +7,14 @@ use crate::RunConfig;
use std::path::Path;
pub(super) fn detect(root: &Path, out: &mut Vec<RunConfig>) {
// Every scheme is built through the workspace beside the projects, assuming it links their
// targets, as the one `pod install` or Tuist writes does.
let workspace = crate::xcode::root_workspace(root);
// With a Podfile every scheme is built through the Pods workspace, assuming one app project
// per folder: the workspace `pod install` writes links that project's targets.
let pods = crate::xcode::pods_workspace(root);
for scheme in crate::xcode::schemes(root) {
if !scheme.has_tests {
continue;
}
let path = workspace.as_ref().unwrap_or(&scheme.container);
let path = pods.as_ref().unwrap_or(&scheme.container);
let Some(container) = path.file_name().and_then(|n| n.to_str()) else { continue };
let flag = if container.ends_with(".xcworkspace") { "-workspace" } else { "-project" };
out.push(
@@ -41,8 +41,7 @@ mod tests {
assert_eq!(
found,
[
// Built through the workspace beside the project, as its run configuration is.
("xcode:test:App.xcworkspace:App", "test -workspace App.xcworkspace -scheme App".to_owned(), true),
("xcode:test:App.xcodeproj:App", "test -project App.xcodeproj -scheme App".to_owned(), true),
(
"xcode:test:App.xcworkspace:Everything",
"test -workspace App.xcworkspace -scheme Everything".to_owned(),
+61 -46
Переглянути файл
@@ -47,35 +47,22 @@ pub fn schemes(root: &Path) -> Vec<XcodeScheme> {
containers.iter().flat_map(|c| container_schemes(c)).collect()
}
/// The `.xcworkspace` in `root` that its projects are built through. CocoaPods, Tuist and
/// SwiftPM-workspace projects link their dependencies only in the workspace, which often has no
/// schemes of its own, so the projects' schemes are built through it too. Without a `Podfile`
/// only a workspace that is named after an `.xcodeproj` in `root`, or that references one
/// ([`references_project`]), counts: a leftover or unrelated workspace would lack the schemes.
/// With a `Podfile` it is the one `pod install` wrote: named after a project, else the first by
/// name (the frontend's `podsWorkspace` in `src/features/run/cocoapodsActions.ts`).
pub fn root_workspace(root: &Path) -> Option<PathBuf> {
/// The `.xcworkspace` `pod install` wrote next to the app's project, when `root` has a `Podfile`:
/// the one named after an `.xcodeproj` in `root`, else the first by name (a leftover workspace
/// may sit beside it). The project alone doesn't link the pods, so its schemes are built through
/// this workspace, which usually has no schemes of its own. The frontend picks the same one
/// (`podsWorkspace` in `src/features/run/cocoapodsActions.ts`).
pub fn pods_workspace(root: &Path) -> Option<PathBuf> {
if !root.join("Podfile").is_file() {
return None;
}
let mut dirs: Vec<PathBuf> = fs::read_dir(root).ok()?.flatten().map(|e| e.path()).filter(|p| p.is_dir()).collect();
dirs.sort();
let has_ext = |p: &Path, ext: &str| p.extension().is_some_and(|e| e == ext);
let projects: Vec<&PathBuf> = dirs.iter().filter(|p| has_ext(p, "xcodeproj")).collect();
let projects: Vec<_> = dirs.iter().filter(|p| has_ext(p, "xcodeproj")).filter_map(|p| p.file_stem()).collect();
let workspaces: Vec<&PathBuf> = dirs.iter().filter(|p| has_ext(p, "xcworkspace")).collect();
let named = workspaces.iter().find(|w| projects.iter().any(|p| p.file_stem() == w.file_stem()));
if root.join("Podfile").is_file() {
return named.or(workspaces.first()).map(|w| (*w).clone());
}
let names: Vec<&str> = projects.iter().filter_map(|p| p.file_name()?.to_str()).collect();
named.or_else(|| workspaces.iter().find(|w| references_project(w, &names))).map(|w| (*w).clone())
}
/// Whether the workspace's `contents.xcworkspacedata` has a `FileRef` to one of `projects` (bundle
/// names in the workspace's own folder), as `group:App.xcodeproj` or `container:App.xcodeproj`.
fn references_project(workspace: &Path, projects: &[&str]) -> bool {
let Ok(data) = fs::read_to_string(workspace.join("contents.xcworkspacedata")) else { return false };
data.split("location").skip(1).filter_map(|rest| rest.split('"').nth(1)).any(|location| {
let path = location.strip_prefix("group:").or_else(|| location.strip_prefix("container:"));
path.map(|p| p.trim_start_matches("./")).is_some_and(|p| projects.contains(&p))
})
let named = workspaces.iter().find(|w| w.file_stem().is_some_and(|s| projects.contains(&s)));
named.or(workspaces.first()).map(|w| (*w).clone())
}
/// The `Pods/` folder of a CocoaPods project: its `Pods.xcodeproj` is generated, not the app.
@@ -266,10 +253,12 @@ pub const MAC: &str = "macos";
/// The `xcodebuild` arguments that pick what is built, and where, for a `kind = "xcode"`
/// configuration: its `container`, `scheme` and `configuration` params and the `-destination`
/// (`id=<udid>`, `platform=macOS`; None leaves it to the scheme). There is no `-derivedDataPath`:
/// a run builds where Xcode does, so Xcode's builds and the IDE's share one build folder, and the
/// build log that xcode-build-server's `build_root` reads (`buildServer.json`) is the latest of either.
pub fn build_args(params: &BTreeMap<String, String>, destination: Option<&str>) -> Result<Vec<String>, String> {
/// (`id=<udid>`, `platform=macOS`; None leaves it to the scheme).
pub fn build_args(
params: &BTreeMap<String, String>,
destination: Option<&str>,
derived_data: &Path,
) -> Result<Vec<String>, String> {
let param = |key: &str| params.get(key).map(|v| v.trim()).filter(|v| !v.is_empty());
let container = param("container").ok_or("No Xcode project or workspace is set")?;
let scheme = param("scheme").ok_or("No scheme is set")?;
@@ -281,6 +270,7 @@ pub fn build_args(params: &BTreeMap<String, String>, destination: Option<&str>)
if let Some(destination) = destination {
args.extend(["-destination".to_owned(), destination.to_owned()]);
}
args.extend(["-derivedDataPath".to_owned(), derived_data.to_string_lossy().into_owned()]);
Ok(args)
}
@@ -468,11 +458,13 @@ fn output(dir: &Path, program: &str, args: &[String]) -> IdeResult<String> {
/// Where a run of `params` builds: [`MAC_DESTINATION`] when the scheme's app runs on the Mac
/// ([`runs_on_mac`]), else `id=<udid>` of the configured simulator or the default one. A Clean
/// Build Folder of the configuration uses the same destination.
pub fn destination(dir: &Path, params: &BTreeMap<String, String>) -> IdeResult<String> {
pub fn destination(dir: &Path, params: &BTreeMap<String, String>, derived_data: &Path) -> IdeResult<String> {
let simulator = params.get(SIMULATOR_PARAM).map_or("", String::as_str);
let args =
[build_args(params, None).map_err(IdeError::invalid)?, vec!["-showBuildSettings".into(), "-json".into()]]
.concat();
let args = [
build_args(params, None, derived_data).map_err(IdeError::invalid)?,
vec!["-showBuildSettings".into(), "-json".into()],
]
.concat();
if runs_on_mac(&output(dir, "xcodebuild", &args)?, simulator).map_err(IdeError::invalid)? {
return Ok(MAC_DESTINATION.to_owned());
}
@@ -484,19 +476,20 @@ pub fn destination(dir: &Path, params: &BTreeMap<String, String>) -> IdeResult<S
}
/// Turns a `kind = "xcode"` configuration into the process that builds, installs and launches
/// its scheme on the simulator, or on the physical device whose UDID [`SIMULATOR_PARAM`] holds. `dir` is the run's working directory; it builds in Xcode's
/// DerivedData location ([`build_args`]). The configuration's environment reaches a simulator app as `SIMCTL_CHILD_*`.
/// its scheme on the simulator, or on the physical device whose UDID [`SIMULATOR_PARAM`] holds. `dir` is the run's working directory; DerivedData goes under
/// `cache_dir`. The configuration's environment reaches a simulator app as `SIMCTL_CHILD_*`.
/// A macOS app ([`runs_on_mac`]) is built for `platform=macOS` and run directly, with no simulator.
pub fn prepare(dir: &Path, config: &mut crate::RunConfig) -> IdeResult<()> {
pub fn prepare(dir: &Path, cache_dir: &Path, config: &mut crate::RunConfig) -> IdeResult<()> {
if !cfg!(target_os = "macos") {
return Err(IdeError::unavailable("Xcode schemes run on macOS only"));
}
let params = &config.extras.params;
let derived_data = crate::xcode_clean::ide_derived_data(cache_dir);
let show =
|args: &[String]| output(dir, "xcodebuild", &[args, &["-showBuildSettings".into(), "-json".into()]].concat());
let destination = destination(dir, params)?;
let destination = destination(dir, params, &derived_data)?;
if destination == MAC_DESTINATION {
let args = build_args(params, Some(MAC_DESTINATION)).map_err(IdeError::invalid)?;
let args = build_args(params, Some(MAC_DESTINATION), &derived_data).map_err(IdeError::invalid)?;
let executable = mac_executable(&show(&args)?).map_err(IdeError::invalid)?;
let app_args = crate::import::split_args(params.get("arguments").map_or("", String::as_str));
config.command = "/bin/sh".into();
@@ -513,7 +506,7 @@ pub fn prepare(dir: &Path, config: &mut crate::RunConfig) -> IdeResult<()> {
if let Some(reason) = device.as_ref().and_then(device_unready) {
return Err(IdeError::unavailable(reason));
}
let args = build_args(params, Some(&destination)).map_err(IdeError::invalid)?;
let args = build_args(params, Some(&destination), &derived_data).map_err(IdeError::invalid)?;
let settings = show(&args)?;
let (app, bundle_id) = built_app(&settings, device.is_some()).map_err(IdeError::invalid)?;
let app_args = crate::import::split_args(params.get("arguments").map_or("", String::as_str));
@@ -673,18 +666,30 @@ mod tests {
[("container", "App.xcworkspace"), ("scheme", "App"), ("configuration", "Staging")]
.map(|(k, v)| (k.to_owned(), v.to_owned()))
.into();
let dd = Path::new("/cache/DerivedData");
assert_eq!(
build_args(&params, Some("id=U1")).unwrap(),
["-workspace", "App.xcworkspace", "-scheme", "App", "-configuration", "Staging", "-destination", "id=U1"]
build_args(&params, Some("id=U1"), dd).unwrap(),
[
"-workspace",
"App.xcworkspace",
"-scheme",
"App",
"-configuration",
"Staging",
"-destination",
"id=U1",
"-derivedDataPath",
"/cache/DerivedData"
]
);
params.insert("container".into(), "App.xcodeproj".into());
params.remove("configuration");
assert_eq!(
build_args(&params, Some("id=U1")).unwrap()[..5],
build_args(&params, Some("id=U1"), dd).unwrap()[..5],
["-project", "App.xcodeproj", "-scheme", "App", "-destination"]
);
params.remove("scheme");
assert_eq!(build_args(&params, Some("id=U1")).unwrap_err(), "No scheme is set");
assert_eq!(build_args(&params, Some("id=U1"), dd).unwrap_err(), "No scheme is set");
}
#[test]
@@ -785,13 +790,23 @@ mod tests {
PathBuf::from("/dd/Build/Products/Debug/My App.app/Contents/MacOS/My App")
);
assert_eq!(mac_executable(&settings("macosx")).unwrap_err(), "The scheme builds no macOS application");
let dd = Path::new("/dd");
let params: BTreeMap<String, String> =
[("container", "App.xcodeproj"), ("scheme", "App")].map(|(k, v)| (k.to_owned(), v.to_owned())).into();
assert_eq!(
build_args(&params, Some("platform=macOS")).unwrap(),
["-project", "App.xcodeproj", "-scheme", "App", "-destination", "platform=macOS"]
build_args(&params, Some("platform=macOS"), dd).unwrap(),
[
"-project",
"App.xcodeproj",
"-scheme",
"App",
"-destination",
"platform=macOS",
"-derivedDataPath",
"/dd"
]
);
assert!(!build_args(&params, None).unwrap().iter().any(|a| a == "-destination"));
assert!(!build_args(&params, None, dd).unwrap().iter().any(|a| a == "-destination"));
}
/// The script builds, then runs the executable in its place: the stub app logs its arguments
+16 -11
Переглянути файл
@@ -8,25 +8,29 @@ use std::path::{Path, PathBuf};
/// The configuration kind of a Clean Build Folder run; its params are an `xcode` configuration's.
pub const KIND: &str = "xcode-clean";
/// Where the IDE's runs of a project built before they built in Xcode's DerivedData location
/// (`xcodebuild -derivedDataPath`, under the project's cache): still deleted with the rest.
/// Where the IDE's runs of a project build: `xcodebuild -derivedDataPath`, under the project's cache.
pub fn ide_derived_data(cache_dir: &Path) -> PathBuf {
cache_dir.join("xcode/DerivedData")
}
/// Turns a [`KIND`] configuration into `xcodebuild clean` of the build its `xcode` configuration
/// runs: the same container, scheme, configuration, destination (the simulator, or the Mac for a
/// macOS app). `dir` is the configuration's working directory.
pub fn prepare(dir: &Path, config: &mut crate::RunConfig) -> IdeResult<()> {
/// macOS app) and DerivedData. `dir` is the configuration's working directory.
pub fn prepare(dir: &Path, cache_dir: &Path, config: &mut crate::RunConfig) -> IdeResult<()> {
let params = &config.extras.params;
let destination = destination(dir, params)?;
config.args = clean_args(params, &destination).map_err(IdeError::invalid)?;
let derived_data = ide_derived_data(cache_dir);
let destination = destination(dir, params, &derived_data)?;
config.args = clean_args(params, &destination, &derived_data).map_err(IdeError::invalid)?;
config.command = "xcodebuild".into();
Ok(())
}
fn clean_args(params: &BTreeMap<String, String>, destination: &str) -> Result<Vec<String>, String> {
let mut args = build_args(params, Some(destination))?;
fn clean_args(
params: &BTreeMap<String, String>,
destination: &str,
derived_data: &Path,
) -> Result<Vec<String>, String> {
let mut args = build_args(params, Some(destination), derived_data)?;
args.push("clean".into());
Ok(args)
}
@@ -62,8 +66,7 @@ pub fn derived_data_of(settings: &str) -> Option<PathBuf> {
}
/// The existing DerivedData folders of an `xcode` configuration's project: Xcode's
/// `<Name>-<hash>` one (Xcode's builds, and the IDE's runs and tests) and the one older IDE
/// runs left in the project's cache.
/// `<Name>-<hash>` one (Xcode's own builds and the scheme's tests) and the IDE's runs' one.
/// `dir` is the configuration's working directory.
pub fn derived_data_dirs(dir: &Path, cache_dir: &Path, params: &BTreeMap<String, String>) -> IdeResult<Vec<PathBuf>> {
let args = settings_args(params).map_err(IdeError::invalid)?;
@@ -92,7 +95,7 @@ mod tests {
fn clean_cleans_the_build_a_run_makes() {
let p = params(&[("container", "App.xcworkspace"), ("scheme", "App"), ("configuration", "Debug")]);
assert_eq!(
clean_args(&p, "id=UDID").unwrap(),
clean_args(&p, "id=UDID", Path::new("/cache/xcode/DerivedData")).unwrap(),
[
"-workspace",
"App.xcworkspace",
@@ -102,6 +105,8 @@ mod tests {
"Debug",
"-destination",
"id=UDID",
"-derivedDataPath",
"/cache/xcode/DerivedData",
"clean"
]
);
-16
Переглянути файл
@@ -62,22 +62,6 @@ fn round_trip() {
assert!(!loaded[0].detected);
}
#[test]
fn docker_detach_round_trips_in_project_params() {
let dir = tempfile::tempdir().unwrap();
let mut configs = sample();
for (config, (kind, detach)) in configs.iter_mut().zip([("docker-dockerfile", "true"), ("docker-image", "false")]) {
config.kind = kind.into();
config.extras.params.insert("detach".into(), detach.into());
}
save_user_configs(dir.path(), &configs).unwrap();
let project = fs::read_to_string(user_configs_path(dir.path())).unwrap();
assert!(project.contains("params = { detach = \"true\" }"), "{project}");
assert!(project.contains("params = { detach = \"false\" }"), "{project}");
assert_eq!(load_user_configs(dir.path()).unwrap(), configs);
}
#[test]
fn preserves_unrelated_content() {
let dir = tempfile::tempdir().unwrap();
+4 -130
Переглянути файл
@@ -16,42 +16,13 @@
//! Mode. A caller that needs them downcasts through [`Backend::as_git`]; a
//! caller that must work for every backend uses only the trait. As Perforce
//! support lands, methods that turn out to be needed generically move here.
//!
//! Git repositories stay where they are (`ide-host`'s `Repos`). Every other
//! backend comes from a [`BackendProvider`] registered with the host, which
//! finds its working copies in a trusted project; the host then routes the
//! Changes view, status, log and the IDE's file operations to them. A
//! backend's own commands (changelists, locks…) reach its concrete type by
//! upcasting to `&dyn Any` and downcasting.
use crate::{
BackendChangelist, BlameLine, BlockHistory, Branch, ChangedFile, Commit, CommitOptions, FileStatus, LineHunk,
LogDetails, LogQuery, PendingChange, Repo, RevisionChange, TextEncoding, VcsKind,
BlameLine, BlockHistory, ChangedFile, Commit, CommitOptions, FileStatus, LineHunk, LogQuery, PendingChange, Repo,
RevisionChange, TextEncoding,
};
use ide_core::{CancellationToken, IdeError, IdeResult};
use std::any::Any;
use ide_core::{CancellationToken, IdeResult};
use std::path::{Path, PathBuf};
use std::sync::Arc;
/// Finds the working copies of one non-Git version control system. Registered
/// once at host startup; the host asks it about the project root and each
/// content root of a trusted project only, because answering may run the
/// system's client (a `P4CONFIG` can name a program as its server).
pub trait BackendProvider: Send + Sync {
/// The working copy holding `folder` (at it or above it), `None` when
/// there is none. An unreachable server or a missing client is `Ok(None)`
/// or an error the host logs; either way the folder gets no backend.
fn discover(&self, folder: &Path) -> IdeResult<Option<Arc<dyn Backend>>>;
/// A file or folder a working copy's root holds (Subversion's `.svn`, also in each
/// directory external). The host looks for it below the project root and content roots,
/// as it looks for nested `.git`, asks [`discover`](Self::discover) about each folder
/// holding it, and rescans when one appears. `None` (Perforce, which has no marker): only
/// the project root and content roots are asked.
fn marker(&self) -> Option<&str> {
None
}
}
/// The version-control surface the Changes view, diff viewer, annotate and log
/// need from a repository. Implemented by every supported backend; today that
@@ -61,20 +32,10 @@ pub trait BackendProvider: Send + Sync {
/// `:0` for the index, ids, `<id>^`…) for the Git backend; a Perforce backend
/// takes `#have`, `@label` or a change number, and its "index" side is the
/// opened-file state.
pub trait Backend: Send + Sync + Any {
pub trait Backend: Send + Sync {
/// The repository's working root.
fn root(&self) -> &Path;
/// The version control system this is.
fn kind(&self) -> VcsKind;
/// What the branch widget shows where Git shows the current branch: a
/// Perforce stream or client, Subversion's `trunk` or `branches/x`.
/// `None` shows nothing; Git's own branch comes from `Repo::branch_info`.
fn head_label(&self) -> Option<String> {
None
}
/// Working-area changes, in the same shape `git status` gives: staged and
/// unstaged kinds per path. A backend without an index reports everything
/// as `unstaged`.
@@ -88,10 +49,6 @@ pub trait Backend: Send + Sync + Any {
self.status()
}
/// Raw bytes of `path` at `rev` (the encoding detection of a file that
/// is not on disk reads them); `None` when absent there.
fn file_bytes_at(&self, path: &Path, rev: Option<&str>) -> IdeResult<Option<Vec<u8>>>;
/// Text of `path` at `rev`; `None` when absent there.
fn file_at(&self, path: &Path, rev: Option<&str>, encoding: TextEncoding) -> IdeResult<Option<String>>;
@@ -150,10 +107,6 @@ pub trait Backend: Send + Sync + Any {
/// The change log, newest first.
fn log(&self, query: &LogQuery, cancel: &CancellationToken) -> IdeResult<Vec<Commit>>;
/// The full description of a change in the log (its message, and for Git
/// the containing branches and signature).
fn log_details(&self, revision: &str) -> IdeResult<LogDetails>;
/// Files `commit` changed.
fn commit_files(&self, commit: &str) -> IdeResult<Vec<ChangedFile>>;
@@ -201,71 +154,8 @@ pub trait Backend: Send + Sync + Any {
encoding: &dyn Fn(&Path) -> IdeResult<TextEncoding>,
) -> IdeResult<Vec<PendingChange>>;
// ---- shared actions a backend may support ----
/// Update Project (`vcs.update`): brings the working copy up to date with the
/// server (`svn update`, `p4 sync`), sending output lines to `output`. Git's
/// pull stays on [`Repo`].
fn update(&self, _cancel: &CancellationToken, _output: &dyn Fn(String)) -> IdeResult<()> {
Err(IdeError::unavailable("this version control system cannot update the working copy"))
}
/// The branch widget's list: what the working copy can switch to
/// (Subversion's `trunk`, `branches/*`, `tags/*`; Perforce streams), the
/// current one marked. Empty when there is nothing to switch to.
fn branches(&self) -> IdeResult<Vec<Branch>> {
Ok(Vec::new())
}
/// Switches the working copy to one of [`branches`](Self::branches)
/// (`svn switch`, `p4 switch`).
fn switch_to(&self, _branch: &str) -> IdeResult<()> {
Err(IdeError::unavailable("this version control system cannot switch branches"))
}
// ---- changelists the system keeps itself ----
/// The working copy's own changelists (`svn changelist`, Perforce pending
/// changes), which the Commit window shows for this root instead of the
/// IDE's lists. `None` (Git) leaves the grouping to the IDE
/// (`.openidea/changelists.json`).
fn changelists(&self) -> IdeResult<Option<Vec<BackendChangelist>>> {
Ok(None)
}
/// Creates an empty changelist and returns its id (`p4 change`; a
/// Subversion list is its name, and exists once a file is moved to it).
fn create_changelist(&self, _name: &str, _comment: &str) -> IdeResult<String> {
Err(no_changelists())
}
/// Renames or re-describes changelist `id`.
fn edit_changelist(&self, _id: &str, _name: &str, _comment: &str) -> IdeResult<()> {
Err(no_changelists())
}
/// Deletes changelist `id`; its files go to the default list.
fn delete_changelist(&self, _id: &str) -> IdeResult<()> {
Err(no_changelists())
}
/// Moves `paths` to changelist `id` ([`crate::changelists::DEFAULT_ID`] is
/// the default list): `svn changelist` / `--remove`, `p4 reopen -c`.
fn move_to_changelist(&self, _paths: &[PathBuf], _id: &str) -> IdeResult<()> {
Err(no_changelists())
}
// ---- IDE file operations ----
/// The editor is about to make read-only `paths` writable (Make File
/// Writable, or typing into a read-only file). A checkout backend opens
/// them for edit (`p4 edit`, `svn lock` for `svn:needs-lock`) first.
/// Returns whether that changed what [`status`](Self::status) reports.
/// Git keeps files writable, so this is a no-op.
fn open_for_edit(&self, _paths: &[PathBuf]) -> IdeResult<bool> {
Ok(false)
}
/// Files or folders the IDE created (project tree New File, refactorings).
/// A checkout backend opens them for add (`p4 add`); Git tracks new files
/// by content, so this is a no-op. Called after the files exist on disk;
@@ -298,27 +188,11 @@ pub trait Backend: Send + Sync + Any {
}
}
fn no_changelists() -> IdeError {
IdeError::unavailable("this version control system keeps no changelists; the IDE does")
}
impl Backend for Repo {
fn root(&self) -> &Path {
Repo::root(self)
}
fn kind(&self) -> VcsKind {
VcsKind::Git
}
fn file_bytes_at(&self, path: &Path, rev: Option<&str>) -> IdeResult<Option<Vec<u8>>> {
Repo::file_bytes_at(self, path, rev)
}
fn log_details(&self, revision: &str) -> IdeResult<LogDetails> {
Repo::log_details(self, revision)
}
fn status(&self) -> IdeResult<Vec<FileStatus>> {
Repo::status(self)
}
+3 -25
Переглянути файл
@@ -52,17 +52,7 @@ pub struct StagingPatchEntry {
pub side: StagingPatchSide,
}
/// The version control system holding a root.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum VcsKind {
#[default]
Git,
Perforce,
Subversion,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct BranchInfo {
/// `None` when HEAD is detached.
@@ -974,18 +964,6 @@ pub struct Changelist {
pub applied_commit: Option<CommitApplySource>,
}
/// A changelist a version control system keeps itself (`svn changelist`, a Perforce
/// pending change), with its files. Id [`changelists::DEFAULT_ID`] is the default list.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct BackendChangelist {
pub id: String,
pub name: String,
#[serde(default)]
pub comment: String,
pub files: Vec<ide_core::IpcPath>,
}
/// User change lists of a project and which list each changed file belongs to.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
@@ -1051,7 +1029,7 @@ pub use submodules::SubmoduleRollbackSource;
mod text_encoding;
mod write;
pub use backend::{Backend, BackendProvider};
pub use backend::Backend;
pub use cherry_pick_plan::CherryPickOptions;
pub use cli::{
GitCommandObserver, detected_git_executable, filter_overrides_from, git_version, restrict, set_askpass_env,
@@ -1074,7 +1052,7 @@ pub use rebase_editor::{
RebaseEdit, RebaseEditKind, RebaseEditorOperation, RebaseEditorReply, RebaseFixupMessage, RebaseTodoRow,
};
pub use remotes::{FetchReport, Remote};
pub use roots::{ProjectUpdateTarget, Repos, marked_folders};
pub use roots::{ProjectUpdateTarget, Repos};
pub use signing::{GitSigningConfig, GitSigningEdit, GpgSigningKey, SshSigningKey};
pub use staged_text::{StagedText, StagedTextEdit, StagingLineHunk, StagingLineHunks};
+22 -44
Переглянути файл
@@ -21,42 +21,6 @@ fn not_searched(path: &Path, skip: &dyn Fn(&Path) -> bool) -> bool {
name.starts_with('.') || SKIPPED.contains(&name.as_ref()) || skip(path)
}
/// Calls `visit` with every folder below `root` that nested repositories are looked for in:
/// up to [`MAX_DEPTH`] levels, skipping hidden and dependency folders and those `skip` rejects.
fn walk_nested(root: &Path, skip: &dyn Fn(&Path) -> bool, mut visit: impl FnMut(&Path)) {
let mut stack: Vec<(PathBuf, usize)> = vec![(root.to_path_buf(), 0)];
while let Some((dir, depth)) = stack.pop() {
let Ok(entries) = std::fs::read_dir(&dir) else { continue };
for entry in entries.flatten() {
if !entry.file_type().is_ok_and(|t| t.is_dir()) {
continue;
}
let path = entry.path();
if not_searched(&path, skip) {
continue;
}
visit(&path);
if depth + 1 < MAX_DEPTH {
stack.push((path, depth + 1));
}
}
}
}
/// Folders below `root` holding one of `markers` (a working copy's `.svn`), searched like
/// nested Git repositories are: the same depth, and the same hidden, dependency and `skip`
/// folders left out. `root` itself is not included. Sorted.
pub fn marked_folders(root: &Path, markers: &[&str], skip: &dyn Fn(&Path) -> bool) -> Vec<PathBuf> {
let mut found = Vec::new();
walk_nested(root, skip, |path| {
if markers.iter().any(|m| path.join(m).exists()) {
found.push(path.to_path_buf());
}
});
found.sort();
found
}
/// The repositories of a project, sorted by root; lookups pick the innermost one.
#[derive(Clone, Default)]
pub struct Repos {
@@ -108,15 +72,29 @@ impl Repos {
if let Some(r) = Repo::discover(project_root)? {
repos.push(r);
}
walk_nested(project_root, skip, |path| {
if path.join(".git").exists()
&& let Ok(Some(r)) = Repo::discover(path)
&& r.root() == path
&& !repos.iter().any(|x| x.root() == r.root())
{
repos.push(r);
let mut stack: Vec<(PathBuf, usize)> = vec![(project_root.to_path_buf(), 0)];
while let Some((dir, depth)) = stack.pop() {
let Ok(entries) = std::fs::read_dir(&dir) else { continue };
for entry in entries.flatten() {
if !entry.file_type().is_ok_and(|t| t.is_dir()) {
continue;
}
let path = entry.path();
if not_searched(&path, skip) {
continue;
}
if path.join(".git").exists()
&& let Ok(Some(r)) = Repo::discover(&path)
&& r.root() == path
&& !repos.iter().any(|x| x.root() == r.root())
{
repos.push(r);
}
if depth + 1 < MAX_DEPTH {
stack.push((path, depth + 1));
}
}
});
}
// Declared submodules remain Git roots under ignored folders or beyond the
// filesystem scan's depth. An uninitialized submodule has no Git worktree.
let mut next = 0;
+8 -32
Переглянути файл
@@ -215,20 +215,20 @@ impl GitignoreStack {
{
let mut nested = self.nested.lock();
let target = if dir.file_name().is_some_and(|n| n == ".git") { dir.parent().unwrap_or(dir) } else { dir };
// Always drop descendant keys. Requiring `target` itself to be a key
// misses a repository created after the watch started: lookups then
// stop at the new `.git`, so the filesystem root is never recorded,
// and `reload_ignore_rules` from that root would leave a stale
// "no rules" cache behind.
nested.by_dir.retain(|k, _| !k.starts_with(target));
nested.by_root.retain(|k, _| !k.starts_with(target));
if nested.by_dir.contains_key(target) || nested.by_root.contains_key(target) {
nested.by_dir.retain(|k, _| !k.starts_with(target));
nested.by_root.retain(|k, _| !k.starts_with(target));
}
for stack in nested.by_root.values() {
stack.invalidate_tree(dir);
}
}
let mut cache = self.cache.lock();
self.generation.fetch_add(1, Ordering::Relaxed);
cache.retain(|k, _| !k.starts_with(dir));
// Lookups always populate every ancestor, so no key below `dir` exists without `dir`.
if cache.contains_key(dir) {
cache.retain(|k, _| !k.starts_with(dir));
}
}
pub fn repo_root(&self) -> Option<&Path> {
@@ -545,28 +545,4 @@ mod tests {
stack.invalidate_tree(&workspace.join("sub/.git"));
assert!(stack.is_ignored(&workspace.join("sub/deep/a.tmp"), false));
}
#[test]
fn git_init_after_the_first_listing_is_picked_up_from_the_filesystem_root() {
// The project was opened before `git init`. A listing after the repository
// appears, but before any ignore file is written, caches a nested stack whose
// keys stop at the new `.git` and never include the filesystem root. Reloading
// from that root must still drop those stale "no rules" entries.
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
std::fs::write(root.join("shared.ignore-me"), "x").unwrap();
std::fs::write(root.join("private.ignore-me"), "x").unwrap();
let stack = GitignoreStack::new(&root);
assert_eq!(stack.repo_root(), None);
std::fs::create_dir_all(root.join(".git/info")).unwrap();
assert!(!stack.is_ignored(&root.join("shared.ignore-me"), false));
assert!(!stack.is_ignored(&root.join("private.ignore-me"), false));
std::fs::write(root.join(".gitignore"), "/shared.ignore-me\n").unwrap();
std::fs::write(root.join(".git/info/exclude"), "/private.ignore-me\n").unwrap();
stack.reload_repo_level();
let top = root.ancestors().last().unwrap();
stack.invalidate_tree(top);
assert!(stack.is_ignored(&root.join("shared.ignore-me"), false));
assert!(stack.is_ignored(&root.join("private.ignore-me"), false));
}
}
+1 -8
Переглянути файл
@@ -146,14 +146,7 @@ impl Watcher {
// `.git` that now exists (`git init`). `/` is no ancestor of `C:\…` on Windows, so take
// the watch root's own topmost ancestor.
let top = self.root.ancestors().last().unwrap_or(&self.root);
let origin = self.rules.repo_root().unwrap_or(top);
self.rules.invalidate_tree(origin);
// After `git init`, a listing may have cached a nested stack whose keys
// stop at the new `.git` and never include `top`. Drop the watched tree
// itself too, which also covers a Windows `C:\` vs `\\?\C:\` mismatch.
if origin != self.root.as_path() {
self.rules.invalidate_tree(&self.root);
}
self.rules.invalidate_tree(self.rules.repo_root().unwrap_or(top));
}
/// The watched directory (canonical).
-22
Переглянути файл
@@ -371,28 +371,6 @@ fn watcher_read_dir_sees_a_repository_made_after_it_started() {
assert_eq!(ignored, BTreeSet::from(["private.ignore-me".to_string(), "shared.ignore-me".to_string()]));
}
/// Same as above, but the first listing happens after `git init` and before the
/// ignore files exist. That caches a nested stack that never recorded the
/// filesystem root as a key — the case `reload_ignore_rules` hits when the
/// watcher has already seen the new `.git`.
#[test]
fn watcher_read_dir_sees_ignore_files_written_after_a_post_init_listing() {
let (_t, r) = root();
write(&r.join("shared.ignore-me"), "x");
write(&r.join("private.ignore-me"), "x");
let sink: SharedSink = Arc::new(|_| {});
let watcher = Watcher::start(&r, vec![], sink, Box::new(|_| {})).unwrap();
assert_eq!(watcher.repo_root(), None);
write(&r.join(".git/HEAD"), "ref: refs/heads/main\n");
assert!(watcher.read_dir(&r, &[]).unwrap().iter().all(|e| !e.ignored));
write(&r.join(".gitignore"), "/shared.ignore-me\n");
write(&r.join(".git/info/exclude"), "/private.ignore-me\n");
watcher.reload_ignore_rules();
let ignored: BTreeSet<String> =
watcher.read_dir(&r, &[]).unwrap().into_iter().filter(|e| e.ignored).map(|e| e.name).collect();
assert_eq!(ignored, BTreeSet::from(["private.ignore-me".to_string(), "shared.ignore-me".to_string()]));
}
#[test]
fn watcher_reports_changes() {
let (_t, r) = root();
-11
Переглянути файл
@@ -386,18 +386,7 @@ test("a click in the User filter shows only that user's commits, without check m
const item = (name: string) => page.getByRole("menuitem", { name, exact: true });
const logAuthors = () => page.evaluate(() => (window as { logAuthors?: unknown }).logAuthors);
// The menu opens with the users known so far and fetches the list in the background.
await user.click();
await page.keyboard.press("Escape");
await expect(async () => {
await user.click();
try {
await expect(item(alice)).toBeVisible({ timeout: 1000 });
} catch (e) {
await page.keyboard.press("Escape");
throw e;
}
}).toPass();
await item(alice).click();
await expect(user).toHaveText(`User: ${alice}`);
await expect.poll(logAuthors).toEqual([alice]);
+1 -7
Переглянути файл
@@ -15,8 +15,6 @@ use tracing_subscriber::{EnvFilter, Layer};
const PREFIX: &str = "openidea";
const SUFFIX: &str = "log";
/// Lines waiting for the log writer thread before new ones are dropped.
const LOG_QUEUE_LINES: usize = 16_384;
static LOG_DIR: OnceLock<PathBuf> = OnceLock::new();
static GUARD: OnceLock<WorkerGuard> = OnceLock::new();
@@ -40,11 +38,7 @@ pub fn init(identifier: &str) {
.max_log_files(7)
.build(&dir)
.ok()?;
// The default queue holds 128 000 lines and is filled when it is created: 4 MB of memory for a
// backlog the writer thread never builds.
let (writer, guard) = tracing_appender::non_blocking::NonBlockingBuilder::default()
.buffered_lines_limit(LOG_QUEUE_LINES)
.finish(appender);
let (writer, guard) = tracing_appender::non_blocking(appender);
let _ = GUARD.set(guard);
log_panics(dir.clone());
let _ = LOG_DIR.set(dir);
-5
Переглянути файл
@@ -778,11 +778,6 @@ vcs_add_worktree trusted project_host bin
vcs_apply_mapped_patch trusted project_host bindings async
vcs_apply_patch trusted project_host bindings async
vcs_apply_project_patch trusted project_host bindings async
vcs_backend_changelist_create trusted project_host bindings async
vcs_backend_changelist_delete trusted project_host bindings async
vcs_backend_changelist_edit trusted project_host bindings async
vcs_backend_changelist_move trusted project_host bindings async
vcs_backend_changelists trusted project_host bindings async
vcs_blame always project_host bindings async
vcs_block_history always project_host bindings async
vcs_block_history_revisions always project_host bindings async
+2 -36
Переглянути файл
@@ -2330,17 +2330,6 @@ export const commands = {
vcsApplyMappedPatch: (repo: string | null, base: string | null, patch: string, paths: string[] | null, mappings: PatchPathMapping[]) => typedError<ProjectPatchOutcome, IdeError>(__TAURI_INVOKE("vcs_apply_mapped_patch", { repo, base, patch, paths, mappings })),
vcsApplyPatch: (repo: string | null, patch: string, paths: string[] | null) => typedError<ApplyOutcome, IdeError>(__TAURI_INVOKE("vcs_apply_patch", { repo, patch, paths })),
vcsApplyProjectPatch: (base: string, patch: string, paths: string[] | null) => typedError<ProjectPatchOutcome, IdeError>(__TAURI_INVOKE("vcs_apply_project_patch", { base, patch, paths })),
/** Creates a changelist of the working copy at `repo`; returns its id. */
vcsBackendChangelistCreate: (repo: string | null, name: string, comment: string) => typedError<string, IdeError>(__TAURI_INVOKE("vcs_backend_changelist_create", { repo, name, comment })),
vcsBackendChangelistDelete: (repo: string | null, id: string) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_backend_changelist_delete", { repo, id })),
vcsBackendChangelistEdit: (repo: string | null, id: string, name: string, comment: string) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_backend_changelist_edit", { repo, id, name, comment })),
/** Moves `paths` to changelist `id` of the working copy each belongs to. */
vcsBackendChangelistMove: (paths: string[], id: string) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_backend_changelist_move", { paths, id })),
/**
* The changelists the non-Git working copy at `repo` keeps itself; `None` when the root
* (Git) leaves them to the IDE's lists ([`vcs_changelists_load`]).
*/
vcsBackendChangelists: (repo: string | null) => typedError<BackendChangelist[] | null, IdeError>(__TAURI_INVOKE("vcs_backend_changelists", { repo })),
vcsBlame: (path: string, text: string | null, revision: string | null) => typedError<BlameLine_Serialize[], IdeError>(__TAURI_INVOKE("vcs_blame", { path, text, revision })),
/**
* History for Selection: commits that changed `lines` (0-based, inclusive) of `path`'s
@@ -2830,8 +2819,8 @@ export const commands = {
path: string,
} | null>("wsl_resolve", { path }),
/**
* Writes the BSP config at the project root with `tool`, adds it to `.git/info/exclude`
* ([`exclude_from_git`]), then restarts the project's sourcekit-lsp so it reads it.
* Writes the BSP config at the project root with `tool`, then restarts the project's
* sourcekit-lsp so it reads it.
*/
xcodeBspGenerate: (tool: string, container: string) => typedError<null, IdeError>(__TAURI_INVOKE("xcode_bsp_generate", { tool, container })),
/**
@@ -4615,17 +4604,6 @@ export type AutoUpload = "never" |
/** Every save, including autosave and external changes. */
"always";
/**
* A changelist a version control system keeps itself (`svn changelist`, a Perforce
* pending change), with its files. Id [`changelists::DEFAULT_ID`] is the default list.
*/
export type BackendChangelist = {
id: string,
name: string,
comment?: string,
files: IpcPath[],
};
/** Appearance › Background Image. An empty `path` shows no image. */
export type BackgroundImageSettings = {
path?: string,
@@ -5936,12 +5914,6 @@ export type CoverageSuite = {
files: FileCoverage[],
};
/** C/C++ debugger executables. Empty paths use automatic discovery. */
export type CppDebuggerSettings = {
gdbExecutable?: string,
lldbDapExecutable?: string,
};
/** Payload for creating a new instruction or rule file. */
export type CreateAgentMemoryInput = {
scope: McpScope,
@@ -6951,7 +6923,6 @@ export type DebuggerSettings = {
/** Java: whether to reload changed classes into running debug sessions after compilation. */
hotSwapAfterCompile?: HotSwapPolicy,
python?: PythonDebuggerSettings,
cpp?: CppDebuggerSettings,
};
/** An editor decoration. */
@@ -16316,9 +16287,6 @@ export type VcsConfirmationSettings = {
onPatchCreated?: string,
};
/** The version control system holding a root. */
export type VcsKind = "git" | "perforce" | "subversion";
/**
* Directory Mappings on top of repository detection. Paths are relative to the project
* root (`.` for the root itself) or absolute outside it.
@@ -16336,8 +16304,6 @@ export type VcsRoot = {
root: IpcPath,
/** Root representing all mapped worktrees of the same Git repository in branch lists. */
branchRoot: IpcPath,
/** The version control system holding it. */
kind: VcsKind,
/** Merge / rebase / cherry-pick / revert in progress. */
operation: string | null,
/** The current rebase uses Git's interactive mode. */
-21
Переглянути файл
@@ -457,27 +457,6 @@ describe("overwrite mode", () => {
type("XYZ");
expect(show(v)).toBe("abXYZ|\nx");
});
it("overwrites a whole surrogate pair after the caret", () => {
for (const [text, typed, after] of [
["|😀b", "A", "A|b"],
["|ab😀c", "XYZ", "XYZ|c"],
["|是\u200D全角", "非", "非|\u200D全角"],
// A DOM change from 😀 to 🨀 arrives as the new high surrogate alone.
["|😀b", "\ud83e", "\ud83e|\ude00b"],
]) {
const v = make(text!, overwriteField);
toggleOverwrite(v);
v.state.facet(EditorView.inputHandler).some((h) => h(v, 0, 0, typed!, () => v.state.update({})));
expect(show(v)).toBe(after);
}
// A caret between the halves of a pair (Go to Line:Column can put it there) replaces nothing on its own.
const v = make("|😀b", overwriteField);
toggleOverwrite(v);
v.dispatch({ selection: { anchor: 1 } });
v.state.facet(EditorView.inputHandler).some((h) => h(v, 1, 1, "", () => v.state.update({})));
expect(v.state.doc.toString()).toBe("😀b");
});
});
describe("smooth caret", () => {
-4
Переглянути файл
@@ -24,10 +24,6 @@ const overwriteInput = EditorView.inputHandler.of((view, _from, _to, text) => {
if (r.empty) {
const line = state.doc.lineAt(r.head);
to = Math.min(line.to, r.head + text.length);
// A range that ends between the halves of a surrogate pair takes the low half too, unless the
// typed text ends with a high surrogate that pairs with it.
const pair = state.doc.sliceString(to - 1, to + 1);
if (to > r.head && /^[\ud800-\udbff][\udc00-\udfff]$/.test(pair) && !/[\ud800-\udbff]$/.test(text)) to++;
}
return { changes: { from: r.from, to, insert: text }, range: EditorSelection.cursor(r.from + text.length) };
});
-20
Переглянути файл
@@ -98,26 +98,6 @@ describe("string clipboard", () => {
expect(view.state.doc.toString()).toBe('value = ""\\\n"');
});
it.each([
["JavaScript", "javascript", "https://example.test"],
["TypeScript", "typescript", "https://example.test"],
["Python", "python", "https:\\/\\/example.test"],
])("%s unescapes an escaped slash only where the language does", async (mode, language, expected) => {
const view = await make(mode, language, 'value = "«https:\\/\\/example.test»"');
expect(copiedText(view.state)).toBe(expected);
});
it("keeps an escaped slash in a string of a language embedded in JavaScript", async () => {
// The embedded mode loads lazily; load it first so the first parse mounts it.
await loadSupport(findLanguageDescription("SQL", "")!);
const views = await Promise.all(
["", "// filler\n".repeat(400)].map((before) =>
make("JavaScript", "javascript", before + "const q = sql`SELECT '«a\\/b»'`;"),
),
);
for (const view of views) expect(copiedText(view.state)).toBe("a\\/b");
});
it("disables both escaping and unescaping with the setting", async () => {
const settings = { smartKeys: { escapeOnPaste: false, reformatOnPaste: "none" } };
const view = await make("Java", "java", 'value = "«a\\nb»"', settings);
+6 -16
Переглянути файл
@@ -8,11 +8,9 @@ const JS = new Set(["javascript", "typescript"]);
interface PlainString {
quote: string;
language: string;
/** `\/` is an escape: a JavaScript string, not one of a language embedded in a template literal. */
slash: boolean;
}
function readEscape(text: string, at: number, language: string, slash = false): { end: number; value: string } {
function readEscape(text: string, at: number, language: string): { end: number; value: string } {
const rest = text.slice(at + 1);
const ch = rest[0];
const basic: Record<string, string> = { n: "\n", r: "\r", t: "\t", "\\": "\\", '"': '"', "'": "'" };
@@ -20,7 +18,6 @@ function readEscape(text: string, at: number, language: string, slash = false):
if (!["kotlin", "rust"].includes(language)) basic.f = "\f";
if (["python", "go", "c", "cpp"].includes(language)) basic.a = "\x07";
if (!["java", "kotlin", "rust"].includes(language)) basic.v = "\v";
if (slash) basic["/"] = "/";
if (language === "kotlin") basic.$ = "$";
if (language === "java") basic.s = " ";
if (language === "c" || language === "cpp") basic["?"] = "?";
@@ -88,9 +85,7 @@ function plainStringAt(state: EditorState, from: number, to: number, language: s
if ([from, to].some((pos) => pos > node.from + i && pos < node.from + end)) return null;
i = end - 1;
}
let embedded = false;
for (let n = node.parent; n; n = n.parent) if (n.type.isTop && n.parent) embedded = true;
return { quote, language, slash: JS.has(language) && !embedded };
return { quote, language };
}
if (!node.parent) return null;
node = node.parent;
@@ -114,12 +109,12 @@ function escapeText(text: string, literal: PlainString): string {
});
}
function unescapeText(text: string, literal: PlainString): string {
function unescapeText(text: string, language: string): string {
let out = "";
for (let i = 0; i < text.length; i++) {
if (text[i] !== "\\") out += text[i];
else {
const escape = readEscape(text, i, literal.language, literal.slash);
const escape = readEscape(text, i, language);
out += escape.value;
i = escape.end - 1;
}
@@ -156,15 +151,10 @@ export function stringClipboard(language: string | undefined): Extension {
),
EditorView.clipboardOutputFilter.of((text, state) => {
const ranges = state.selection.ranges;
const literals: PlainString[] = [];
for (const r of ranges) {
const literal = r.empty ? null : plainStringAt(state, r.from, r.to, language);
if (!literal) return text;
literals.push(literal);
}
if (ranges.some((r) => r.empty || !plainStringAt(state, r.from, r.to, language))) return text;
const selected = ranges.map((r) => state.sliceDoc(r.from, r.to));
if (text !== selected.join(state.lineBreak)) return text;
return selected.map((part, i) => unescapeText(part, literals[i]!)).join(state.lineBreak);
return selected.map((part) => unescapeText(part, language)).join(state.lineBreak);
}),
];
}
+3 -61
Переглянути файл
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vitest";
import type { CodeAction, WorkspaceEdit } from "@/bindings";
import { readyOrganizeImportsAction, unambiguousImport } from "./autoImport";
import { describe, expect, it } from "vitest";
import type { CodeAction } from "@/bindings";
import { unambiguousImport } from "./autoImport";
const action = (title: string, over: Partial<CodeAction> = {}): CodeAction => ({
title,
@@ -14,21 +14,6 @@ const action = (title: string, over: Partial<CodeAction> = {}): CodeAction => ({
...over,
});
const organizeEdit = (): WorkspaceEdit => ({
files: [
{
kind: "edit",
path: "/p/Sample.java",
edits: [
{
range: { start: { line: 3, col: 0 }, end: { line: 4, col: 0 } },
new_text: "",
},
],
},
],
});
describe("unambiguousImport", () => {
it("applies the one import fix among other quick fixes", () => {
const fix = action("Import 'ArrayList' (java.util)");
@@ -58,46 +43,3 @@ describe("unambiguousImport", () => {
expect(unambiguousImport([action("UnityEngine.SceneManagement.SceneManager")])).toBeNull();
});
});
describe("readyOrganizeImportsAction", () => {
const organize = (over: Partial<CodeAction> = {}) =>
action("Organize imports", { kind: "source.organizeImports", ...over });
it("resolves a lazy organize-imports action that has data but no edit", async () => {
const lazy = organize({ data: '{"id":"organize_imports"}' });
const resolved = { ...lazy, edit: organizeEdit() };
const resolve = vi.fn(async (a: CodeAction) => {
expect(a).toBe(lazy);
return resolved;
});
await expect(readyOrganizeImportsAction([lazy], resolve)).resolves.toBe(resolved);
expect(resolve).toHaveBeenCalledOnce();
});
it("uses an action that already has an edit without resolving", async () => {
const ready = organize({ edit: organizeEdit() });
const resolve = vi.fn(async (a: CodeAction) => a);
await expect(readyOrganizeImportsAction([ready], resolve)).resolves.toBe(ready);
expect(resolve).not.toHaveBeenCalled();
});
it("skips disabled actions and lazy actions that cannot be resolved to an edit", async () => {
const resolve = vi.fn(async (a: CodeAction) => a);
await expect(
readyOrganizeImportsAction(
[
organize({ disabledReason: "unavailable", edit: organizeEdit() }),
organize(),
action("Import 'HashMap' (java.util)", { data: "{}" }),
],
resolve,
),
).resolves.toBeUndefined();
expect(resolve).not.toHaveBeenCalled();
const lazy = organize({ data: '{"id":"organize_imports"}' });
const unresolved = vi.fn(async (a: CodeAction) => a);
await expect(readyOrganizeImportsAction([lazy], unresolved)).resolves.toBeUndefined();
expect(unresolved).toHaveBeenCalledOnce();
});
});
+1 -22
Переглянути файл
@@ -35,25 +35,6 @@ export function unambiguousImport(actions: readonly CodeAction[]): CodeAction |
return imports.length === 1 ? imports[0]! : null;
}
/**
* An organize-imports action the on-the-fly path can inspect.
* java-analyzer (and other servers) often return a lazy action with `data` and
* no `edit`; the workspace edit is only available after `codeAction/resolve`.
* Command-palette and optimize-on-save already resolve through
* `runInteractiveCodeAction` / `lspApplyCodeAction`.
*/
export async function readyOrganizeImportsAction(
actions: readonly CodeAction[],
resolve: (action: CodeAction) => Promise<CodeAction>,
): Promise<CodeAction | undefined> {
const action = actions.find((a) => a.kind?.startsWith("source.organizeImports") && !a.disabledReason);
if (!action) return undefined;
if (action.edit) return action;
if (action.data == null) return undefined;
const resolved = await resolve(action);
return resolved.edit && !resolved.disabledReason ? resolved : undefined;
}
/** Whether a workspace edit for `path` touches 0-based `line`. */
export function editTouchesLine(action: CodeAction, path: string, line: number): boolean {
for (const f of action.edit?.files ?? []) {
@@ -135,9 +116,7 @@ const autoImportPlugin = ViewPlugin.fromClass(
const doc = docOf(view)!;
const range = offsetsToRange(view.state.doc, 0, view.state.doc.length);
const actions = await lspRequest(() => commands.lspCodeActions(doc.doc, range, ["source.organizeImports"]));
const action = await readyOrganizeImportsAction(actions, (a) =>
lspRequest(() => commands.lspResolveCodeAction(doc.doc, a)),
);
const action = actions.find((a) => a.kind?.startsWith("source.organizeImports") && !a.disabledReason && a.edit);
if (!action || editTouchesLine(action, doc.path, caretLine)) return;
const edits = action.edit!.files.flatMap((f) => (f.kind === "edit" && f.path === doc.path ? f.edits : []));
const noop = edits.every((e) => {
+1 -149
Переглянути файл
@@ -39,7 +39,7 @@ vi.mock("@tauri-apps/api/core", async (orig) => ({
},
}));
const { lensTargets, skipInheritedLifecycleUsages, usagesLensExtension } = await import("./codeLens");
const { lensTargets, usagesLensExtension } = await import("./codeLens");
const { foregroundStarted } = await import("./foreground");
const { lspDoc } = await import("./lsp");
const { useProject } = await import("@/platform/project");
@@ -692,151 +692,3 @@ describe("file changes on disk", () => {
expect(ipc.lspReferences).toHaveBeenCalledTimes(80);
});
});
describe("inherited Dart lifecycle usages", () => {
const textOf = (src: string) => EditorState.create({ doc: src }).doc;
const src = [
"class _PageState extends State<Page> {",
" @override",
" void initState() { super.initState(); }",
"",
" @override",
" Widget build(BuildContext context) { return const SizedBox(); }",
"",
" @override",
" void dispose() { super.dispose(); }",
"",
" @override",
" void didUpdateWidget(Page oldWidget) { super.didUpdateWidget(oldWidget); }",
"",
" @override",
" void didChangeDependencies() { super.didChangeDependencies(); }",
"",
" Future<void> loadData() async {}",
"",
" Widget buildHelper() { return const SizedBox(); }",
"",
" @override Widget createState() => this;",
"",
" @override",
" String toString() => 'page';",
"",
" @override",
" int get hashCode => 1;",
"",
" @override",
" bool operator ==(Object other) => other is _PageState;",
"}",
].join("\n");
const doc = textOf(src);
const lineOf = (snippet: string) => src.split("\n").findIndex((l) => l.includes(snippet));
it("skips Flutter @override lifecycle methods, not other Dart names", () => {
expect(skipInheritedLifecycleUsages("dart", "initState", doc, lineOf("void initState"))).toBe(true);
expect(skipInheritedLifecycleUsages("dart", "build", doc, lineOf("Widget build(BuildContext"))).toBe(true);
expect(skipInheritedLifecycleUsages("dart", "dispose", doc, lineOf("void dispose"))).toBe(true);
expect(skipInheritedLifecycleUsages("dart", "didUpdateWidget", doc, lineOf("void didUpdateWidget"))).toBe(true);
expect(
skipInheritedLifecycleUsages("dart", "didChangeDependencies", doc, lineOf("void didChangeDependencies")),
).toBe(true);
expect(skipInheritedLifecycleUsages("dart", "createState", doc, lineOf("@override Widget createState"))).toBe(true);
expect(skipInheritedLifecycleUsages("dart", "toString", doc, lineOf("String toString"))).toBe(true);
expect(skipInheritedLifecycleUsages("dart", "hashCode", doc, lineOf("int get hashCode"))).toBe(true);
expect(skipInheritedLifecycleUsages("dart", "operator ==", doc, lineOf("bool operator"))).toBe(true);
expect(skipInheritedLifecycleUsages("dart", "==", doc, lineOf("bool operator"))).toBe(true);
expect(skipInheritedLifecycleUsages("dart", "loadData", doc, lineOf("Future<void> loadData"))).toBe(false);
expect(skipInheritedLifecycleUsages("dart", "buildHelper", doc, lineOf("Widget buildHelper"))).toBe(false);
expect(skipInheritedLifecycleUsages("dart", "_PageState", doc, 0)).toBe(false);
expect(skipInheritedLifecycleUsages("rust", "build", doc, lineOf("Widget build(BuildContext"))).toBe(false);
});
it("does not skip a lifecycle name that is not an override", () => {
const plain = textOf("void dispose() {}\nWidget build() { return const SizedBox(); }");
expect(skipInheritedLifecycleUsages("dart", "dispose", plain, 0)).toBe(false);
expect(skipInheritedLifecycleUsages("dart", "build", plain, 1)).toBe(false);
});
});
describe("Dart Code Vision references", () => {
const dart = { doc: 11, path: "/p/page.dart", language: "dart", uiMode: "Dart", readOnly: false };
const src = [
"class _PageState extends State<Page> {",
" @override",
" void initState() {}",
" @override",
" Widget build(BuildContext context) { return const SizedBox(); }",
" Future<void> loadData() async {}",
" void refresh() {}",
"}",
].join("\n");
it("does not query references for @override lifecycle methods", async () => {
ipc.docOutline.mockResolvedValue(
ok([
item("_PageState", "class", 0, [
item("initState", "method", 2),
item("build", "method", 4),
item("loadData", "method", 5),
item("refresh", "method", 6),
]),
]),
);
const view = new EditorView({
state: EditorState.create({
doc: src,
extensions: [lspDoc.of(dart), usagesLensExtension()],
}),
parent: document.body,
});
views.push(view);
await settle();
expect(ipc.lspReferences.mock.calls.map((c) => c[2])).toEqual([
{ line: 0, col: 0 },
{ line: 5, col: 0 },
{ line: 6, col: 0 },
]);
expect(titles(view)).toEqual(["2 usages", "2 usages", "2 usages"]);
});
it("asks Dart references one at a time", async () => {
const pending = deferred<ReturnType<typeof refs>>();
ipc.docOutline.mockResolvedValue(ok(Array.from({ length: 8 }, (_, i) => item(`f${i}`, "function", i))));
ipc.lspReferences.mockReturnValue(pending.promise);
const view = new EditorView({
state: EditorState.create({
doc: Array.from({ length: 8 }, (_, i) => `void f${i}() {}`).join("\n"),
extensions: [lspDoc.of(dart), usagesLensExtension()],
}),
parent: document.body,
});
views.push(view);
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(1);
pending.resolve(refs(1));
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(8);
});
it("does not start a new Dart references wave until a cancelled request has finished", async () => {
const first = deferred<ReturnType<typeof refs>>();
ipc.lspReferences.mockReturnValueOnce(first.promise).mockResolvedValue(refs(2));
ipc.docOutline.mockResolvedValue(ok([item("loadData", "function", 0)]));
const view = new EditorView({
state: EditorState.create({
doc: "void loadData() {}",
extensions: [lspDoc.of(dart), usagesLensExtension()],
}),
parent: document.body,
});
views.push(view);
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(1);
_emitEditorEvent({ type: "docChanged", doc: 9, path: "/p/b.dart", baseVersion: 1, version: 2, changes: [] });
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(1);
first.resolve(refs(1));
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(2);
expect(titles(view)).toEqual(["2 usages"]);
});
});
+4 -76
Переглянути файл
@@ -3,11 +3,7 @@
* construction: only declarations in (and near) the viewport are counted, one
* debounced pass after edits / scrolling, results cached per document text
* and symbol until the project's documents change, and at most a few reference
* requests in flight. Dart is the exception: inherited Flutter lifecycle methods
* (`@override build`, `initState`, …) resolve to the framework and a single
* isolate cannot cancel `textDocument/references` promptly, so those methods are
* skipped and remaining Dart counts run one at a time, never overlapping a
* request that has not finished. Counts run the same references query the Find Usages
* requests in flight. Counts run the same references query the Find Usages
* panel runs (including the plugin indexers' anchors), scoped to what the
* server analyses: opening candidate files or the libraries for every count
* would trigger expensive server analysis, so only an explicit Find Usages
@@ -58,8 +54,6 @@ const LENS_KINDS = new Set<SymbolKind>([
const MAX_PER_PASS = 40;
const CONCURRENCY = 4;
/** The Dart analyzer is a single isolate; overlapping references stall completion. */
const DART_CONCURRENCY = 1;
/** Lines above/below the viewport that are counted too, so scrolling feels instant. */
const MARGIN_LINES = 10;
/**
@@ -138,46 +132,6 @@ export function usagesLabel(n: number): string {
return n === 1 ? tx("1 usage") : tx`${n} usages`;
}
/**
* Flutter / Dart `@override` lifecycle and Object methods. A references query
* for any of them walks the framework (and the project) from the superclass.
*/
const DART_INHERITED_LIFECYCLE = new Set([
"build",
"createState",
"initState",
"dispose",
"didUpdateWidget",
"didChangeDependencies",
"deactivate",
"activate",
"reassemble",
"toString",
"hashCode",
"==",
]);
/** Outline names for `operator ==` (`==`, `operator ==`). */
function dartMethodName(name: string): string {
return name.replace(/^operator\s+/, "").trim();
}
/**
* Whether Code Vision should skip a usages query for this declaration: a Dart
* method whose name is a framework lifecycle / Object member, with `@override`
* on or just above the name. Exported for tests.
*/
export function skipInheritedLifecycleUsages(language: string, name: string, text: Text, line: number): boolean {
if (language !== "dart") return false;
if (!DART_INHERITED_LIFECYCLE.has(dartMethodName(name))) return false;
const from = Math.max(1, line + 1 - 4);
const to = Math.min(text.lines, line + 1);
for (let n = from; n <= to; n++) {
if (/@override\b/.test(text.line(n).text)) return true;
}
return false;
}
const setLenses = StateEffect.define<CodeLens[]>();
const lensField = StateField.define<CodeLens[]>({
@@ -232,11 +186,6 @@ class UsagesLensPlugin {
private skipped = false;
/** A pass was cut short or held back by a foreground request, and runs once it is done. */
private yielded = false;
/** Reference requests still running on the server, including ones already cancelled. */
private inflight = 0;
/** A Dart pass is waiting for `inflight` to reach 0 before asking again. */
private drain = false;
private closed = false;
constructor(private view: EditorView) {
this.refresh();
@@ -327,11 +276,6 @@ class UsagesLensPlugin {
this.yielded = true;
return;
}
// Dart's analyzer does not cancel promptly; a new wave on top of a cancelled one stalls it.
if (doc.language === "dart" && this.inflight > 0) {
this.drain = true;
return;
}
const gen = this.generation;
const usagesWanted = usagesEnabled() && !isLibrarySource(doc);
const usages = usagesWanted && !usagesBackoff.active(doc.doc);
@@ -363,30 +307,20 @@ class UsagesLensPlugin {
.filter((t) => t.line >= firstLine && t.line <= lastLine)
.slice(0, MAX_PER_PASS);
const key = (t: LensTarget) => `${t.line}:${t.col}:${t.name}`;
const todo = usages
? visible.filter(
(t) =>
!this.cache.has(key(t)) &&
!this.incomplete.has(key(t)) &&
!skipInheritedLifecycleUsages(doc.language, t.name, text, t.line),
)
: [];
const todo = usages ? visible.filter((t) => !this.cache.has(key(t)) && !this.incomplete.has(key(t))) : [];
let unavailable = false;
let retry = false;
// A base file is outlined once per pass, however many of its methods are overridden here.
const outlines: OutlineCache = new Map([[doc.path, Promise.resolve(this.outline.items)]]);
const concurrency = doc.language === "dart" ? DART_CONCURRENCY : CONCURRENCY;
for (let i = 0; i < todo.length && !unavailable; i += concurrency) {
for (let i = 0; i < todo.length && !unavailable; i += CONCURRENCY) {
if (inForeground()) {
this.yielded = true;
return;
}
if (!wanted()) return;
// oxlint-disable-next-line no-await-in-loop -- batched in groups of CONCURRENCY; a batch's flags decide whether the next batch runs
await Promise.all(
todo.slice(i, i + concurrency).map(async (t) => {
todo.slice(i, i + CONCURRENCY).map(async (t) => {
const request = nextRequestId();
this.inflight++;
try {
// Opening candidate files for each count triggers expensive server analysis.
// Only an explicit Find Usages should widen the server's scope.
@@ -417,11 +351,6 @@ class UsagesLensPlugin {
if (wanted() && isUnavailable(e)) unavailable = true;
} finally {
this.pending.delete(request);
this.inflight--;
if (this.inflight === 0 && this.drain && !this.closed) {
this.drain = false;
this.schedule();
}
}
}),
);
@@ -496,7 +425,6 @@ class UsagesLensPlugin {
}
destroy() {
this.closed = true;
this.schedule.cancel();
this.unsubscribe();
this.offReady();
+1 -62
Переглянути файл
@@ -20,17 +20,7 @@ import { formatDuration, formatSentAt, userMessageText } from "../conversation";
import { isSignInErrorMessage, useAgentErrorText } from "../loginHint";
import { isBusy, recoveryDividerLabel, type ReplyTimes, type ReplyTurn } from "../model";
import { useRevealedText } from "../reveal";
import {
composerDraft,
forkTask,
refreshProviders,
rerunFrom,
resendMessage,
retrySubmittedDraft,
submittedDraft,
updateComposer,
useAgents,
} from "../store";
import { forkTask, refreshProviders, rerunFrom, resendMessage, useAgents } from "../store";
import { PermissionLine, QuestionForm, type QuestionAnswer } from "./QuestionForm";
import { providerName, samePropsExcept, type UserEntry } from "./shared";
import { SubagentCard, ThoughtEntry, ToolEntry } from "./toolEntries";
@@ -252,68 +242,17 @@ export const Entry = memo(
}),
);
/** Offers recovery for the current writer conflict without replacing the saved conversation. */
function AgentErrorEntry({ task, message }: { task: AgentTask; message: string }) {
const [signingIn, setSigningIn] = useState(false);
const [recovering, setRecovering] = useState(false);
const text = useAgentErrorText(message);
const providerCanSignIn = useAgents((s) => s.providers.find((p) => p.id === task.provider)?.canSignIn ?? false);
const entries = useAgents((s) => s.entries.get(task.id));
const canSignIn = isTauri() && providerCanSignIn && isSignInErrorMessage(message);
const locked =
task.provider === "codex" &&
task.status === "failed" &&
task.error === message &&
message.includes("already has an active writer");
const lastUser = locked
? entries?.findLast((entry): entry is UserEntry => entry.type === "user" && !entry.steered)
: undefined;
const name = providerName(task.provider);
// Restore the unsent message alongside any text typed since the failed attempt.
const recover = async (fork: boolean) => {
setRecovering(true);
try {
const original =
(lastUser && submittedDraft(task.id, lastUser.text)) ??
(lastUser ? { text: lastUser.text, images: lastUser.images ?? [], files: [] } : undefined);
if (!fork) {
if (original) await retrySubmittedDraft(task.id, original);
return;
}
const target = await forkTask(task.id, null);
if (target && original) {
const draft = composerDraft(task.id);
updateComposer(target, {
text: [original.text, draft.text].filter(Boolean).join("\n"),
files: [...original.files, ...draft.files],
images: [...original.images, ...draft.images],
});
}
} catch (error) {
notifications().notify({
level: "error",
title: fork ? "Couldn't fork the task" : "Couldn't retry the message",
body: String(error),
});
} finally {
setRecovering(false);
}
};
return (
<div className={styles.error} role="alert">
<Icon name="error" size={14} />
<div className={styles.errorContent}>
<span>{text}</span>
{locked && (
<div>
<Button size="small" disabled={recovering || !lastUser} onClick={() => void recover(false)}>
<T>Retry</T>
</Button>
<Button size="small" disabled={recovering} onClick={() => void recover(true)}>
<T>Fork</T>
</Button>
</div>
)}
{canSignIn && (
<div>
<Button size="small" onClick={() => setSigningIn(true)}>
-25
Переглянути файл
@@ -59,8 +59,6 @@ const backend = vi.hoisted(() => ({
}>,
imported: [] as Array<[string, string]>,
forked: [] as Array<[string, string, string]>,
retryPrompt: vi.fn(),
forkTask: vi.fn(),
importError: null as string | null,
importErrors: new Map<string, string>(),
importWait: null as Promise<void> | null,
@@ -80,8 +78,6 @@ const backend = vi.hoisted(() => ({
vi.mock("@/platform/ipc", async (original) => ({
...(await original<typeof import("@/platform/ipc")>()),
commands: {
agentPrompt: backend.retryPrompt,
agentFork: backend.forkTask,
fsProbe: async () => ({
status: "ok",
data: { size: 1, binary: false, tooLarge: false },
@@ -288,8 +284,6 @@ beforeEach(() => {
useChangesOptions.setState({ groupByCommit: false, scope: "task" });
backend.imported = [];
backend.forked = [];
backend.retryPrompt.mockReset().mockResolvedValue({ status: "ok", data: null });
backend.forkTask.mockReset().mockResolvedValue({ status: "ok", data: task("forked") });
backend.importError = null;
backend.importErrors = new Map();
backend.importWait = null;
@@ -321,25 +315,6 @@ beforeEach(() => {
});
});
it("offers recovery for a Codex writer conflict and keeps the failed message in a fork", async () => {
const message = "thread s1 already has an active writer";
const failed: AgentTask = { ...task("A"), status: "failed", error: message };
const entries: AgentEntry[] = [
{ type: "user", text: "Please continue", attachments: [], images: [], steered: false, sentMs: null, doneMs: null },
{ type: "error", message },
];
backend.entries.set("A", entries);
useAgents.setState({ tasks: new Map([["A", failed]]), entries: new Map(backend.entries) });
render(<SessionEditor input={input("A")} />);
fireEvent.click(await screen.findByRole("button", { name: "Retry" }));
await waitFor(() =>
expect(backend.retryPrompt).toHaveBeenCalledWith("A", expect.objectContaining({ text: "Please continue" }), false),
);
fireEvent.click(screen.getByRole("button", { name: "Fork" }));
await waitFor(() => expect(backend.forkTask).toHaveBeenCalledWith("A", null));
await waitFor(() => expect(useAgents.getState().composers.get("forked")?.text).toBe("Please continue"));
});
describe("conversation rows", () => {
it("keeps authors above messages and their folded work with matching icon-only actions", async () => {
const user = (text: string): AgentEntry => ({
+2 -20
Переглянути файл
@@ -1729,21 +1729,6 @@ export function trackNetworkOnline(): () => void {
return () => window.removeEventListener("online", onOnline);
}
// A failed session open happens after submission; keep file paths for an explicit recovery.
const submittedDrafts = new Map<string, { draft: ComposerDraft; prompt: AgentPrompt }>();
/** Returns the latest submitted draft while this window is alive, including file paths. */
export function submittedDraft(task: string, text: string): ComposerDraft | undefined {
const submitted = submittedDrafts.get(task);
return submitted?.prompt.text === text ? submitted.draft : undefined;
}
/** Retries the original prompt without consuming a newer composer draft. */
export async function retrySubmittedDraft(task: string, draft: ComposerDraft): Promise<void> {
const submitted = submittedDrafts.get(task);
await call(commands.agentPrompt(task, submitted?.draft === draft ? submitted.prompt : promptOf(task, draft), false));
}
/** Sends the session composer's message: queued while the agent works, or with `now` interrupting it. */
export async function sendMessage(task: string, now: boolean): Promise<void> {
const composer = composerDraft(task);
@@ -1751,9 +1736,7 @@ export async function sendMessage(task: string, now: boolean): Promise<void> {
const command = shellCommand(composer);
if (command !== null) return runShell(task, composer, command);
const started = generation;
const prompt = promptOf(task, composer);
await call(commands.agentPrompt(task, prompt, now));
submittedDrafts.set(task, { draft: composer, prompt });
await call(commands.agentPrompt(task, promptOf(task, composer), now));
clearSubmittedComposer(task, composer, started);
}
@@ -1769,7 +1752,7 @@ export function quoteInComposer(task: string, text: string) {
}
/** Copies the task's conversation into a new task (up to its first `turns` turns) and opens it. */
export async function forkTask(task: string, turns: number | null): Promise<string | undefined> {
export async function forkTask(task: string, turns: number | null): Promise<void> {
const started = generation;
try {
const copy = await call(commands.agentFork(task, turns));
@@ -1778,7 +1761,6 @@ export async function forkTask(task: string, turns: number | null): Promise<stri
tasks: s.tasks.has(copy.id) ? s.tasks : new Map(s.tasks).set(copy.id, copy),
}));
openTask(copy.id);
return copy.id;
} catch (e) {
if (generation === started) throw e;
}
-19
Переглянути файл
@@ -8,10 +8,7 @@ import {
connect,
disconnect,
forkTask,
retrySubmittedDraft,
sendMessage,
startTask,
submittedDraft,
updateComposer,
updateDraft,
useAgents,
@@ -20,7 +17,6 @@ import {
const backend = vi.hoisted(() => ({
create: vi.fn(),
fork: vi.fn(),
prompt: vi.fn(),
subscribe: vi.fn(),
open: vi.fn(),
close: vi.fn(),
@@ -40,7 +36,6 @@ vi.mock("@/platform/ipc", async (original) => ({
commands: {
agentCreate: backend.create,
agentFork: backend.fork,
agentPrompt: backend.prompt,
agentSubscribe: backend.subscribe,
agentProviders: async () => ({ status: "ok", data: [] }),
},
@@ -117,20 +112,6 @@ beforeEach(() => {
});
afterEach(() => disconnect());
it("retains the submitted file paths for retry without consuming a newer draft", async () => {
backend.prompt.mockResolvedValue(ok(null));
updateComposer("source", { text: "inspect", files: [{ path: "/project-a/a.txt", rel: "a.txt", attached: true }] });
await sendMessage("source", false);
const sent = backend.prompt.mock.calls[0]![1];
const original = submittedDraft("source", sent.text)!;
expect(original.files[0]?.path).toBe("/project-a/a.txt");
updateComposer("source", { text: "new draft" });
await retrySubmittedDraft("source", original);
expect(backend.prompt.mock.calls[1]![1]).toEqual(sent);
expect(composerDraft("source").text).toBe("new draft");
expect(submittedDraft("source", "a different message")).toBeUndefined();
});
const transitions = [
"disconnect",
"reconnect",
+2 -13
Переглянути файл
@@ -52,19 +52,8 @@ export function editCommand(command: "undo" | "redo" | "cut" | "copy" | "paste"
}
if (command === "selectAll" && selectReadingPane(document.activeElement)) return;
if (command === "paste") {
const focused = document.activeElement;
const view = focused instanceof HTMLElement ? EditorView.findFromDOM(focused) : null;
const selection = view && view.contentDOM === focused ? view.state.selection : undefined;
return readClipboardPlainText().then((text) => {
if (view && selection?.ranges.some((range) => !range.empty)) {
// CodeMirror owns the selection, including Vim's Visual range. Replace it in
// one transaction so any cursor update sees the finished paste.
if (text && focused === document.activeElement && view.state.selection.eq(selection) && !view.state.readOnly)
view.dispatch(view.state.replaceSelection(text), { userEvent: "input.paste", scrollIntoView: true });
} else {
document.execCommand("insertText", false, text);
}
});
void readClipboardPlainText().then((text) => document.execCommand("insertText", false, text));
return;
}
document.execCommand(command);
};
+2 -2
Переглянути файл
@@ -3,7 +3,7 @@
* for the right-clicked or active `Podfile`, else the project root's; in Find Action, Build › Xcode
* and the Project view's context menu. The IDE doesn't install CocoaPods: without `pod` on PATH it
* says so. Afterwards the run configurations are detected again (they build through the workspace
* `pod install` writes, host: `ide_run::xcode::root_workspace`) and the build server config is
* `pod install` writes, host: `ide_run::xcode::pods_workspace`) and the build server config is
* pointed at that workspace. Opening a project whose `Pods/Manifest.lock` differs from
* `Podfile.lock` offers Pod Install.
*/
@@ -64,7 +64,7 @@ export function podsOutOfDate(podfileLock: string | null, manifestLock: string |
/**
* The workspace `pod install` wrote in a folder with these entries: the one named after an
* `.xcodeproj`, else the first by name. Same rule as `ide_run::xcode::root_workspace`.
* `.xcodeproj`, else the first by name. Same rule as `ide_run::xcode::pods_workspace`.
*/
export function podsWorkspace(names: readonly string[]): string | null {
const workspaces = names.filter((n) => n.endsWith(".xcworkspace")).sort();
-137
Переглянути файл
@@ -1,137 +0,0 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { formParams, withParams } from "@/features/run/types";
import { hostOs } from "@/platform/remote";
import { dockerfileType, dockerImageType, typedConfig } from "./runTypes";
vi.mock("@/platform/remote", async (original) => ({
...(await original<typeof import("@/platform/remote")>()),
hostOs: vi.fn(),
}));
const dockerfileParams = {
dockerfile: "docker files/Dockerfile",
tag: "sample/app:latest",
target: "production",
buildArgs: "MODE=production",
buildOptions: "--no-cache",
runImage: "true",
containerName: "sample-app",
ports: "8080:80",
volumes: "./app data:/data",
containerEnv: "MODE=production",
runOptions: "--network bridge",
command: 'serve --title "Sample app"',
};
const imageParams = {
image: "registry.example.com/team/postgres:16",
pull: "true",
ports: "5432:5432",
containerEnv: "APP_NAME=Local database",
};
const foregroundSettings: Record<string, string>[] = [{}, { detach: "false" }];
describe.each([
{
os: "linux" as const,
build:
"docker build -f 'docker files/Dockerfile' -t sample/app:latest --target production --build-arg MODE=production --no-cache 'docker files'",
buildOnly: "docker build -f 'docker files/Dockerfile' -t sample/app:latest 'docker files'",
remove: ">/dev/null 2>&1;",
appArgs: "-p 8080:80 -v './app data:/data' -e MODE=production --network bridge sample/app:latest",
imageArgs: "--pull always -p 5432:5432 -e 'APP_NAME=Local database' registry.example.com/team/postgres:16",
},
{
os: "windows" as const,
build:
'docker build -f "docker files/Dockerfile" -t sample/app:latest --target production --build-arg MODE=production --no-cache "docker files"',
buildOnly: 'docker build -f "docker files/Dockerfile" -t sample/app:latest "docker files"',
remove: ">nul 2>&1 &",
appArgs: '-p 8080:80 -v "./app data:/data" -e MODE=production --network bridge sample/app:latest',
imageArgs: '--pull always -p 5432:5432 -e "APP_NAME=Local database" registry.example.com/team/postgres:16',
},
])("Docker run command lines on $os", ({ os, build, buildOnly, remove, appArgs, imageArgs }) => {
beforeEach(() => vi.mocked(hostOs).mockReturnValue(os));
it.each(foregroundSettings)("runs a Dockerfile in the foreground with %j", (detach) => {
expect(dockerfileType.commandLine({ ...dockerfileParams, ...detach })).toEqual({
command: `${build} && (docker rm -f sample-app ${remove} docker run --name sample-app ${appArgs} serve --title "Sample app")`,
args: [],
cwd: null,
stop: "docker stop sample-app",
});
});
it.each(foregroundSettings)("runs a Docker Image in the foreground with %j", (detach) => {
expect(dockerImageType.commandLine({ ...imageParams, ...detach })).toEqual({
command: `(docker rm -f postgres ${remove} docker run --name postgres ${imageArgs})`,
args: [],
cwd: null,
stop: "docker stop postgres",
});
});
it("runs the built image in the background and follows its logs", () => {
expect(dockerfileType.commandLine({ ...dockerfileParams, detach: "true" })).toEqual({
command: `${build} && (docker rm -f sample-app ${remove} docker run -d --name sample-app ${appArgs} serve --title "Sample app") && docker logs --tail 500 -f sample-app`,
args: [],
cwd: null,
stop: null,
});
});
it("runs a Docker Image in the background and follows logs using its derived name", () => {
expect(dockerImageType.commandLine({ ...imageParams, containerName: " ", detach: "true" })).toEqual({
command: `(docker rm -f postgres ${remove} docker run -d --name postgres ${imageArgs}) && docker logs --tail 500 -f postgres`,
args: [],
cwd: null,
stop: null,
});
});
it("builds without starting a container when Run built image is off", () => {
expect(
dockerfileType.commandLine({
dockerfile: dockerfileParams.dockerfile,
tag: dockerfileParams.tag,
detach: "true",
}),
).toEqual({ command: buildOnly, args: [], cwd: null });
});
});
describe("Docker detach setting", () => {
beforeEach(() => vi.mocked(hostOs).mockReturnValue("linux"));
it("offers the checkbox only when the configuration starts a container", () => {
const dockerfile = dockerfileType.fields.find((field) => field.key === "detach");
const image = dockerImageType.fields.find((field) => field.key === "detach");
const checkbox = { label: "Run in the background (-d)", control: "checkbox" };
expect(dockerfile).toMatchObject(checkbox);
expect(dockerfile?.visible?.({ runImage: "true" })).toBe(true);
expect(dockerfile?.visible?.({ runImage: "false" })).toBe(false);
expect(image).toMatchObject(checkbox);
expect(image?.visible).toBeUndefined();
});
it.each([
{ type: dockerfileType, params: dockerfileParams, name: "sample-app" },
{ type: dockerImageType, params: imageParams, name: "postgres" },
])("round-trips detach through saved $type.label params and the run form", ({ type, params, name }) => {
const foreground = typedConfig(type, "user:docker", "Docker", params);
expect(foreground.stopCommand).toBe(`docker stop ${name}`);
const detached = withParams(foreground, { ...params, detach: "true" }, type);
expect(detached.params?.detach).toBe("true");
expect(detached.stopCommand).toBeUndefined();
const reopened = formParams(detached, type)!;
expect(reopened.detach).toBe("true");
expect(withParams(detached, reopened, type)).toEqual(detached);
expect(withParams(detached, { ...reopened, detach: "false" }, type)).toEqual({
...foreground,
params: { ...params, detach: "false" },
});
});
});
+10 -15
Переглянути файл
@@ -3,8 +3,8 @@
* Dockerfile (build the image, then run a container from it), Docker Image (run
* a container from an image) and Docker Compose (`up` the selected services).
* They launch docker command lines in the Run tool window against the Docker
* connection chosen from the Services tool window's connections. Stop stops the
* attached container or takes the Compose project down. Detached containers keep running.
* connection chosen from the Services tool window's connections; Stop stops the
* container (`docker stop`) or takes the Compose project down.
*/
import { splitCommandLine } from "@/platform/commandLine";
import { call, commands, type RunConfig } from "@/platform/ipc";
@@ -62,23 +62,21 @@ export function containerName(p: Readonly<Record<string, string>>, image: string
}
/**
* Redeploys a container of the same name. Detached runs follow the new container's logs.
* Removes a previous container of the same name (IDEA redeploys over it), then runs
* the new one attached, so its output is the run's output.
*/
function runContainer(name: string, image: string, p: Readonly<Record<string, string>>, windows: boolean): string {
const remove = `${line(["docker", "rm", "-f", name], windows)} ${windows ? ">nul 2>&1 &" : ">/dev/null 2>&1;"}`;
const detach = on(p.detach);
const run = [
"docker",
"run",
...(detach ? ["-d"] : []),
"--name",
name,
...(on(p.pull) ? ["--pull", "always"] : []),
...containerArgs(p),
image,
];
const redeploy = `(${remove} ${line(run, windows)}${p.command?.trim() ? ` ${p.command.trim()}` : ""})`;
return detach ? `${redeploy} && ${line(["docker", "logs", "--tail", "500", "-f", name], windows)}` : redeploy;
return `${remove} ${line([...run], windows)}${p.command?.trim() ? ` ${p.command.trim()}` : ""}`;
}
/** The servers the form offers: the saved connections, else the default daemon ("Docker"). */
@@ -99,11 +97,8 @@ const connectionField = {
},
};
const detachField = { key: "detach", label: "Run in the background (-d)", control: "checkbox" } as const;
const containerFields: RunConfigTypeContribution["fields"] = [
{ key: "containerName", label: "Container name", mono: true, placeholder: "Derived from the image" },
detachField,
{ key: "ports", label: "Bind ports", mono: true, placeholder: "8080:80, 5005:5005" },
{ key: "volumes", label: "Bind mounts", mono: true, placeholder: "./data:/data; cache:/root/.cache" },
{ key: "containerEnv", label: "Container environment", mono: true, placeholder: "KEY=value; OTHER=value" },
@@ -196,10 +191,10 @@ export const dockerfileType: RunConfigTypeContribution = {
if (!on(p.runImage)) return { command: line(build, windows), args: [], cwd: null };
const name = containerName(p, tag);
return {
command: `${line(build, windows)} && ${runContainer(name, tag, p, windows)}`,
command: `${line(build, windows)} && (${runContainer(name, tag, p, windows)})`,
args: [],
cwd: null,
stop: on(p.detach) ? null : line(["docker", "stop", name], windows),
stop: line(["docker", "stop", name], windows),
};
},
prepareLaunch: withConnection,
@@ -226,10 +221,10 @@ export const dockerImageType: RunConfigTypeContribution = {
const image = p.image?.trim() ?? "";
const name = containerName(p, image);
return {
command: runContainer(name, image, p, windows),
command: `(${runContainer(name, image, p, windows)})`,
args: [],
cwd: null,
stop: on(p.detach) ? null : line(["docker", "stop", name], windows),
stop: line(["docker", "stop", name], windows),
};
},
prepareLaunch: withConnection,
@@ -254,7 +249,7 @@ export const dockerComposeType: RunConfigTypeContribution = {
},
{ key: "services", label: "Services", mono: true, placeholder: "All services" },
{ key: "project", label: "Project name", mono: true, placeholder: "The folder name" },
detachField,
{ key: "detach", label: "Run in the background (-d)", control: "checkbox" },
{ key: "build", label: "Build images before starting (--build)", control: "checkbox" },
{ key: "upOptions", label: "Up options", mono: true, placeholder: "e.g. --force-recreate --remove-orphans" },
],
+49 -1
Переглянути файл
@@ -15,9 +15,57 @@ import { choosePath } from "@/platform/choosePath";
import { usePageContext, useSetting } from "../components/context";
import { SdkField, tildify, useDetected, useJdtlsJdk } from "./components";
import { isMavenThreadCount } from "./mavenThreads";
import { PathField, PathInput } from "./PathInput";
import styles from "./Sdk.module.css";
interface PathFieldProps {
k: string;
placeholder: string;
title: string;
id?: string;
"aria-label"?: string;
/** Browse for a file instead of a directory. */
file?: boolean;
}
function PathField({ k, placeholder, title, id, file, ...aria }: PathFieldProps) {
const [value, set] = useSetting<string>(k);
return (
<span className={styles.pathRow}>
<Input
id={id}
mono
className={styles.pathInput}
value={value}
placeholder={placeholder}
onChange={(e) => set(e.target.value.trim())}
aria-label={aria["aria-label"]}
/>
<IconButton
icon="folder-open"
size="small"
title="Browse…"
onClick={async () => {
const p = await choosePath({ directory: !file, title, defaultPath: value || undefined });
if (p) set(p);
}}
/>
</span>
);
}
function PathInput({
label,
hint,
...field
}: Omit<PathFieldProps, "id" | "aria-label"> & { label: string; hint?: string }) {
const id = useId();
return (
<Row label={label} htmlFor={id} hint={hint}>
<PathField {...field} id={id} />
</Row>
);
}
function SdkRow({
k,
label,
-57
Переглянути файл
@@ -1,57 +0,0 @@
import { useId } from "react";
import { choosePath } from "@/platform/choosePath";
import { useTx } from "@/platform/i18n";
import { IconButton, Input } from "@/ui";
import { Row } from "../components/Form";
import { useSetting } from "../components/context";
import styles from "./Sdk.module.css";
interface PathFieldProps {
k: string;
placeholder: string;
title: string;
id?: string;
"aria-label"?: string;
/** Browse for a file instead of a directory. */
file?: boolean;
}
export function PathField({ k, placeholder, title, id, file, ...aria }: PathFieldProps) {
const [value, set] = useSetting<string>(k);
const tx = useTx();
return (
<span className={styles.pathRow}>
<Input
id={id}
mono
className={styles.pathInput}
value={value}
placeholder={placeholder}
onChange={(e) => set(e.target.value.trim())}
aria-label={aria["aria-label"]}
/>
<IconButton
icon="folder-open"
size="small"
title="Browse…"
onClick={async () => {
const p = await choosePath({ directory: !file, title: tx(title), defaultPath: value || undefined });
if (p) set(p);
}}
/>
</span>
);
}
export function PathInput({
label,
hint,
...field
}: Omit<PathFieldProps, "id" | "aria-label"> & { label: string; hint?: string }) {
const id = useId();
return (
<Row label={label} htmlFor={id} hint={hint}>
<PathField {...field} id={id} />
</Row>
);
}
-37
Переглянути файл
@@ -11,7 +11,6 @@ import { useProject } from "@/platform/project";
import type { SelectOption } from "@/ui";
import { ColorSwatches, FormGroup, GlobListEditor, Row, SettingNumber, Toggle } from "../components/Form";
import { usePageContext, useSetting } from "../components/context";
import { PathInput } from "../languages/PathInput";
import { useSettingsDialog } from "../model/staging";
import { lazyPage } from "./lazyPage";
import type { PageSpec } from "./spec";
@@ -26,35 +25,6 @@ export const BUILD_GROUP = "Build, Execution, Deployment";
const L = WORKFLOW_LIMITS;
const gdbLabel = "GDB executable";
const lldbDapLabel = "LLDB DAP executable";
function GdbExecutable() {
return (
<PathInput
k="debugger.cpp.gdbExecutable"
label={gdbLabel}
title={gdbLabel}
placeholder="Auto"
hint="Requires GDB 14 or newer. Leave blank for automatic discovery."
file
/>
);
}
function LldbDapExecutable() {
return (
<PathInput
k="debugger.cpp.lldbDapExecutable"
label={lldbDapLabel}
title={lldbDapLabel}
placeholder="Auto"
hint="Leave blank for automatic discovery."
file
/>
);
}
export const CONSOLE_ENCODINGS: SelectOption[] = [
"UTF-8",
"UTF-16LE",
@@ -412,13 +382,6 @@ export const EXECUTION_PAGES: PageSpec[] = [
},
],
},
{
title: "C/C++",
options: [
{ kind: "custom", label: gdbLabel, component: GdbExecutable },
{ kind: "custom", label: lldbDapLabel, component: LldbDapExecutable },
],
},
],
},
{
-27
Переглянути файл
@@ -1,27 +0,0 @@
import { describe, expect, it } from "vitest";
import { bspStep } from "./xcodeBsp";
describe("Xcode build server config on project open", () => {
const tool = { tool: "xcode-build-server" };
const missing = { tool: null };
it("generates the config without asking when a generator is on PATH", () => {
expect(bspStep(true, tool, false, false)).toBe("generate");
});
it("hints how to install xcode-build-server when it is missing", () => {
expect(bspStep(true, missing, false, false)).toBe("hint");
});
it("runs nothing in an untrusted project", () => {
expect(bspStep(false, tool, false, false)).toBeNull();
expect(bspStep(false, missing, false, true)).toBeNull();
});
it("leaves a project that already has a config alone", () => {
// The backend reports no setup when buildServer.json or .bsp/ exists.
expect(bspStep(true, null, false, true)).toBeNull();
});
it("does not repeat a failed generation or the hint on every open, only when asked again", () => {
expect(bspStep(true, tool, true, false)).toBeNull();
expect(bspStep(true, missing, true, false)).toBeNull();
expect(bspStep(true, tool, true, true)).toBe("generate");
expect(bspStep(true, missing, true, true)).toBe("hint");
});
});
+32 -38
Переглянути файл
@@ -1,10 +1,9 @@
/**
* Xcode projects (#6787): sourcekit-lsp reads an `.xcodeproj` / `.xcworkspace` only through a
* Build Server Protocol config (`buildServer.json`, `.bsp/`). A trusted project root with an Xcode
* project and no config gets one, without asking, from xcode-build-server or sourcekit-xcode-bsp,
* whichever is on PATH; the backend keeps it out of Git (`.git/info/exclude`) and restarts
* sourcekit-lsp. A config that exists is never replaced. With neither tool installed it says,
* once per root, how to install one: the IDE does not install them itself.
* Build Server Protocol config (`buildServer.json`, `.bsp/`). A project root with an Xcode project
* and no config offers, once per root, to generate one with xcode-build-server or
* sourcekit-xcode-bsp, whichever is on PATH; the backend then restarts sourcekit-lsp. With
* neither installed it says how to install one: the IDE does not install them itself.
*/
import { registerActions } from "@/platform/actions";
import { tx } from "@/platform/i18n";
@@ -12,8 +11,7 @@ import { call, commands, isTauri } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { notifications } from "@/workbench/contributions";
// v2: v1 remembered every root it offered to generate for, which would now skip generating.
const STORE_KEY = "openidea.xcodeBsp.v2";
const STORE_KEY = "openidea.xcodeBsp.v1";
const hintKey = (root: string) => `xcode-bsp:${root}`;
function hinted(): string[] {
@@ -33,23 +31,9 @@ function rememberHint(root: string) {
}
}
/**
* What opening `project` does about its build server config: `generate` it with the tool on
* PATH, `hint` how to install one, or nothing. Untrusted projects run no tool; after a failed
* generation or a hint, the root is remembered so neither repeats on every open, unless `again`.
*/
export function bspStep(
trusted: boolean,
setup: { tool: string | null } | null,
remembered: boolean,
again: boolean,
): "generate" | "hint" | null {
if (!trusted || !setup || (remembered && !again)) return null;
return setup.tool ? "generate" : "hint";
}
async function generate(root: string, tool: string, container: string) {
const key = hintKey(root);
notifications().notify({ group: "tools", level: "info", key, title: tx`Running ${tool}…` });
try {
await call(commands.xcodeBspGenerate(tool, container));
notifications().notify({
@@ -57,10 +41,9 @@ async function generate(root: string, tool: string, container: string) {
level: "info",
key,
title: "Build server config generated",
body: tx`Code insight for ${container} reads its last build: Run, or a build in Xcode, refreshes it.`,
body: tx`sourcekit-lsp now reads the build settings of ${container}.`,
});
} catch (e) {
rememberHint(root);
notifications().notify({
group: "tools",
level: "error",
@@ -72,25 +55,36 @@ async function generate(root: string, tool: string, container: string) {
}
}
/** Generates the open project's config, or says how to install a generator ([`bspStep`]). */
/** Shows the hint for the open project's root; `again`: also when it was shown before. */
export async function checkXcodeBsp(again = false) {
const project = useProject.getState().project;
if (!project?.trusted || !isTauri() || (!again && hinted().includes(project.root))) return;
const setup = await call(commands.xcodeBspSetup());
if (useProject.getState().project?.root !== project.root) return;
const step = bspStep(project.trusted, setup, hinted().includes(project.root), again);
if (!setup || !step) return;
const { container, tool } = setup;
if (step === "generate" && tool) return generate(project.root, tool, container);
if (!setup || useProject.getState().project?.root !== project.root) return;
rememberHint(project.root);
notifications().notify({
group: "tools",
level: "info",
key: hintKey(project.root),
title: "Xcode project needs a build server config",
body: tx`Cross-file code insight for ${container} needs a Build Server Protocol config. Install xcode-build-server (brew install xcode-build-server) to generate one.`,
actions: [{ label: "Check Again", run: () => void checkXcodeBsp(true).catch(() => {}) }],
});
const { container, tool } = setup;
notifications().notify(
tool
? {
group: "tools",
level: "info",
key: hintKey(project.root),
title: "Xcode project needs a build server config",
body:
tool === "xcode-build-server"
? tx`Cross-file code insight for ${container} needs buildServer.json. Generate it with xcode-build-server? It reads the log of the last build, so build the scheme in Xcode once first.`
: tx`Cross-file code insight for ${container} needs buildServer.json. Generate it with ${tool}?`,
actions: [{ label: "Generate", run: () => void generate(project.root, tool, container) }],
}
: {
group: "tools",
level: "info",
key: hintKey(project.root),
title: "Xcode project needs a build server config",
body: tx`Cross-file code insight for ${container} needs a Build Server Protocol config. Install xcode-build-server (brew install xcode-build-server) to generate one.`,
actions: [{ label: "Check Again", run: () => void checkXcodeBsp(true).catch(() => {}) }],
},
);
}
export function installXcodeBspHint(): () => void {
-21
Переглянути файл
@@ -119,24 +119,3 @@ describe("Git toolbar repository", () => {
expect(useVcs.getState().repo).toBe(primary);
});
});
describe("a non-Git working copy", () => {
it("shows its head label without commits, upstream or counts", async () => {
const wc = "/svn";
const trunk: BranchInfo = { head: "trunk", headCommit: null, upstream: null, ahead: 0, behind: 0, operation: null };
ipc.branchInfo.mockReset().mockResolvedValue(result(trunk));
useVcs.setState({
root: wc,
roots: [wc],
repo: wc,
kinds: { [wc]: "subversion" },
heads: { [wc]: { head: "trunk", headCommit: null, shallow: false } },
branch: trunk,
branchRoot: wc,
});
render(<BranchWidget />);
expect(await screen.findByText("trunk")).toBeInTheDocument();
expect(screen.queryByText("No commits")).not.toBeInTheDocument();
expect(screen.queryByLabelText(/incoming commits|outgoing commits/)).not.toBeInTheDocument();
});
});
+5 -121
Переглянути файл
@@ -1,7 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { Branch, BranchInfo, FileStatus, ProjectInfo, VcsRoot } from "@/bindings";
import { commands, isTauri } from "@/platform/ipc";
import { getContext } from "@/platform/context";
import { useProject } from "@/platform/project";
import { deferred } from "@/test/deferred";
import { getFileDecoration } from "@/workbench/contributions";
@@ -13,11 +12,8 @@ import {
onConflictsCleared,
refreshNow,
refreshPathsNow,
selectRepo,
useVcs,
useVcsKind,
} from "./store";
import { renderHook } from "@testing-library/react";
vi.mock(import("@/platform/ipc"), async (original) => ({
...(await original()),
@@ -38,7 +34,6 @@ const roots: VcsRoot[] = [
{
root: git.root,
branchRoot: git.root,
kind: "git",
head: branch.head,
headCommit: branch.headCommit,
operation: "merge",
@@ -100,75 +95,6 @@ it("updates the notification as conflicts are resolved and reopened", () => {
expect(cleared).toHaveBeenCalledOnce();
});
it("tells each root's version control system and keys the selected one", async () => {
const depot: VcsRoot = {
root: "/a/depot",
branchRoot: "/a/depot",
kind: "perforce",
head: "//depot/main",
headCommit: null,
operation: null,
shallow: false,
};
vi.mocked(commands.vcsRoots).mockResolvedValue(ok([{ ...roots[0]!, operation: null }, depot]));
useProject.setState({ project: git });
await refreshNow();
const { result } = renderHook(() => useVcsKind());
expect(useVcs.getState().kinds).toEqual({ [git.root]: "git", [depot.root]: "perforce" });
expect(getContext()).toMatchObject({ vcsKind: "git", vcsAnyGit: true });
expect(result.current).toBe("git");
expect(renderHook(() => useVcsKind(depot.root)).result.current).toBe("perforce");
await selectRepo(depot.root);
expect(getContext().vcsKind).toBe("perforce");
await vi.waitFor(() => expect(result.current).toBe("perforce"));
vi.mocked(commands.vcsRoots).mockResolvedValue(ok([depot]));
await refreshNow();
expect(getContext()).toMatchObject({ vcsKind: "perforce", vcsAnyGit: false });
});
it("serves a Subversion-only project with a working copy's default root fields", async () => {
// What the host sends for a non-Git root: `VcsRoot::default()` plus kind, root and head.
const wc: VcsRoot = {
root: nonGit.root,
branchRoot: nonGit.root,
kind: "subversion",
operation: null,
interactiveRebase: false,
head: "trunk",
headCommit: null,
shallow: false,
lfs: false,
uninitializedSubmodules: [],
hasRemotes: null,
resolvedConflicts: [],
};
const edited: FileStatus = { ...modified, path: "/b/src/edited.ts" };
const trunk: BranchInfo = { head: "trunk", headCommit: null, upstream: null, ahead: 0, behind: 0, operation: null };
vi.mocked(commands.vcsRoots).mockResolvedValue(ok([wc]));
vi.mocked(commands.vcsStatus).mockResolvedValue(ok([edited]));
vi.mocked(commands.vcsBranchInfo).mockResolvedValue(ok(trunk));
vi.mocked(isTauri).mockReturnValue(true);
useProject.setState({ project: nonGit });
await vi.waitFor(() => expect(useVcs.getState().statusLoaded).toBe(true));
expect(useVcs.getState()).toMatchObject({
available: true,
roots: [nonGit.root],
repo: nonGit.root,
kinds: { [nonGit.root]: "subversion" },
heads: { [nonGit.root]: { head: "trunk", headCommit: null, shallow: false } },
operations: {},
hasRemotes: null,
branch: trunk,
error: null,
});
expect(useVcs.getState().byPath.get(edited.path)).toEqual(edited);
expect(getContext()).toMatchObject({ vcsAvailable: true, vcsKind: "subversion", vcsAnyGit: false });
expect(getContext()).toMatchObject({ vcsShallowRepositories: "", vcsLfsRepositories: false });
});
describe("VCS status ownership", () => {
it.each([
{ command: "status", reopen: false },
@@ -274,7 +200,6 @@ describe("VCS status ownership", () => {
{
root: nonGit.root,
branchRoot: nonGit.root,
kind: "git",
head: nextBranch.head,
headCommit: nextBranch.headCommit,
operation: null,
@@ -353,9 +278,7 @@ describe("VCS status ownership", () => {
};
const remainingStatus = { ...modified, path: remaining + "/src/edited.ts" };
vi.mocked(commands.vcsRoots).mockResolvedValue(
ok([
{ root: remaining, branchRoot: remaining, kind: "git", head: "main", headCommit: "def1234", operation: null },
]),
ok([{ root: remaining, branchRoot: remaining, head: "main", headCommit: "def1234", operation: null }]),
);
vi.mocked(commands.vcsStatus).mockResolvedValue(ok([remainingStatus]));
vi.mocked(commands.vcsBranchInfo).mockImplementation(async (repo) => {
@@ -395,17 +318,7 @@ describe("VCS status ownership", () => {
expect(getFileDecoration(modified.path)?.color).toBe("var(--vcs-modified)");
vi.mocked(commands.vcsRoots).mockResolvedValueOnce(
ok([
{
root: git.root,
branchRoot: git.root,
kind: "git",
head: null,
headCommit: null,
operation: null,
unavailable: true,
},
]),
ok([{ root: git.root, branchRoot: git.root, head: null, headCommit: null, operation: null, unavailable: true }]),
);
vi.mocked(commands.vcsStatus).mockRejectedValueOnce(new Error("git repository is no longer valid: /a"));
vi.mocked(commands.vcsBranchInfo).mockRejectedValueOnce(new Error("git repository is no longer valid: /a"));
@@ -471,7 +384,6 @@ describe("VCS status ownership", () => {
{
root: healthy,
branchRoot: healthy,
kind: "git",
head: "main",
headCommit: "def1234",
operation: null,
@@ -489,19 +401,10 @@ describe("VCS status ownership", () => {
vi.mocked(commands.vcsRoots).mockResolvedValue(
ok([
{
root: git.root,
branchRoot: git.root,
kind: "git",
head: null,
headCommit: null,
operation: null,
unavailable: true,
},
{ root: git.root, branchRoot: git.root, head: null, headCommit: null, operation: null, unavailable: true },
{
root: healthy,
branchRoot: healthy,
kind: "git",
head: "main",
headCommit: "def1234",
operation: null,
@@ -538,17 +441,7 @@ describe("VCS status ownership", () => {
it("preserves empty roots reference across repeated all-unavailable refreshes", async () => {
useProject.setState({ project: git });
vi.mocked(commands.vcsRoots).mockResolvedValue(
ok([
{
root: git.root,
branchRoot: git.root,
kind: "git",
head: null,
headCommit: null,
operation: null,
unavailable: true,
},
]),
ok([{ root: git.root, branchRoot: git.root, head: null, headCommit: null, operation: null, unavailable: true }]),
);
vi.mocked(commands.vcsStatus).mockRejectedValue(new Error("git repository is no longer valid"));
vi.mocked(commands.vcsBranchInfo).mockRejectedValue(new Error("git repository is no longer valid"));
@@ -573,15 +466,7 @@ describe("VCS status ownership", () => {
vi.mocked(commands.vcsRoots).mockResolvedValueOnce(
ok([
...roots,
{
root: sibling,
branchRoot: sibling,
kind: "git",
head: null,
headCommit: null,
operation: null,
unavailable: true,
},
{ root: sibling, branchRoot: sibling, head: null, headCommit: null, operation: null, unavailable: true },
]),
);
await refreshNow();
@@ -593,7 +478,6 @@ describe("VCS status ownership", () => {
{
root: sibling,
branchRoot: sibling,
kind: "git",
head: "main",
headCommit: "def1234",
operation: null,
+1 -29
Переглянути файл
@@ -10,7 +10,7 @@
*/
import { onWorkflowSettingsChange, workflowSettings } from "@/platform/workflowSettings";
import { create } from "zustand";
import type { Branch, BranchInfo, FileStatus, Stash, TrackedTip, UnfetchedBranch, VcsKind } from "@/bindings";
import type { Branch, BranchInfo, FileStatus, Stash, TrackedTip, UnfetchedBranch } from "@/bindings";
import { call, commands, isTauri, onIdeEvent } from "@/platform/ipc";
import { setContext } from "@/platform/context";
import { useProject } from "@/platform/project";
@@ -44,8 +44,6 @@ export interface VcsState {
operations: Record<string, string>;
/** Root → its current branch (`head` null when detached) and HEAD commit. */
heads: Record<string, RepoHead>;
/** Root → the version control system holding it (Git unless a non-Git backend found it). */
kinds: Record<string, VcsKind>;
/** The selected repository's root (branch widget, log, push…). */
repo: string | null;
status: FileStatus[];
@@ -80,7 +78,6 @@ const initial: VcsState = {
branchRoots: {},
operations: {},
heads: {},
kinds: {},
repo: null,
status: [],
resolvedConflicts: new Set(),
@@ -105,19 +102,6 @@ export function currentRepo(): string | null {
return useVcs.getState().repo;
}
/**
* Hook: the version control system of `root`, or of the selected repository (the `vcsKind`
* context key). Actions of the selected repository go by it; actions over every repository
* (Stash, Worktrees) by the `vcsAnyGit` key.
*/
export function useVcsKind(root?: string | null): VcsKind {
return useVcs((s) => kindOf(s, root ?? s.repo ?? s.roots[0]));
}
function kindOf(s: Pick<VcsState, "kinds">, root: string | null | undefined): VcsKind {
return (root && s.kinds[root]) || "git";
}
/** Root of the selected repository, which its log's and diffs' repository-relative paths are relative to. */
export function currentRepoRoot(): string | null {
const s = useVcs.getState();
@@ -191,7 +175,6 @@ export function localChangesMayBeAside(): boolean {
export function selectRepo(root: string): Promise<void> {
if (useVcs.getState().repo === root) return Promise.resolve();
useVcs.setState({ repo: root, branches: [], branchesLoaded: false, stashes: [], stashesLoaded: false });
setContext("vcsKind", kindOf(useVcs.getState(), root));
return refreshNow();
}
@@ -305,8 +288,6 @@ export function refreshNow(): Promise<void> {
if (!vcsRoots.length) {
useVcs.setState({ ...initial, root: s.root, version: s.version });
setContext("vcsAvailable", false);
setContext("vcsKind", "git");
setContext("vcsAnyGit", true);
setContext("vcsShallowRepositories", "");
setContext("vcsLfsRepositories", false);
setContext("vcsUninitializedSubmodules", false);
@@ -386,21 +367,14 @@ export function refreshNow(): Promise<void> {
const resolvedConflicts = new Set(activeRoots.flatMap((r) => r.resolvedConflicts ?? []));
const branchRoots = Object.fromEntries(activeRoots.map((r) => [r.root, r.branchRoot]));
const sameBranchRoots = sameRoots && roots.every((root) => branchRoots[root] === s.branchRoots[root]);
const kinds = Object.fromEntries(vcsRoots.map((r) => [r.root, r.kind]));
useVcs.setState({
unavailableRoots: nextUnavailable,
operations,
heads,
kinds,
resolvedConflicts,
branchRoots: sameBranchRoots ? s.branchRoots : branchRoots,
});
if (repo !== s.repo || !sameRoots) useVcs.setState({ roots: sameRoots ? s.roots : roots, repo });
setContext("vcsKind", kindOf({ kinds }, repo));
setContext(
"vcsAnyGit",
vcsRoots.some((r) => r.kind === "git"),
);
setContext(
"vcsLfsRepositories",
activeRoots.some((r) => r.lfs),
@@ -613,8 +587,6 @@ export function installVcsStore(): () => void {
pendingPaths.clear();
useVcs.setState({ ...initial, available, root, version: useVcs.getState().version + 1 });
setContext("vcsAvailable", available);
setContext("vcsKind", "git");
setContext("vcsAnyGit", true);
setContext("vcsShallowRepositories", "");
setContext("vcsLfsRepositories", false);
setContext("vcsUninitializedSubmodules", false);
+15 -87
Переглянути файл
@@ -13,7 +13,6 @@ import {
} from "@/editor/api";
import { executeAction, registerAction } from "@/platform/actions";
import { getContext } from "@/platform/context";
import { editCommand } from "../../app/appActions";
import { _handleEx, applyRcCommands, vimExtension } from "../engine";
import { activate } from "../index";
import { useVimMode } from "../mode";
@@ -35,18 +34,6 @@ function makeView(extra = vimExtension()) {
return new EditorView({ parent, state: EditorState.create({ doc: "one two\nthree", extensions: extra }) });
}
function pressCtrl(view: EditorView, key: string) {
const event = new KeyboardEvent("keydown", {
key,
code: `Key${key.toUpperCase()}`,
ctrlKey: true,
bubbles: true,
cancelable: true,
});
view.contentDOM.dispatchEvent(event);
return event;
}
describe("Vim mode toggle", () => {
let dispose = () => {};
beforeEach(() => {
@@ -103,21 +90,31 @@ describe("Vim engine", () => {
Vim.mapclear();
});
it("leaves IDE overrides to the editor for Select All and paste without a selection", () => {
it("leaves keys the user gave to the IDE to the editor: Select All, and the browser's cut and paste", () => {
const view = makeView([vimExtension(), keymap.of([{ key: "Ctrl-a", run: selectAll }])]);
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: "n 5" } });
const press = (key: string) => {
const e = new KeyboardEvent("keydown", {
key,
code: `Key${key.toUpperCase()}`,
ctrlKey: true,
bubbles: true,
cancelable: true,
});
view.contentDOM.dispatchEvent(e);
return e;
};
try {
useVimSettings.setState({ enabled: true, handlers: {} }, true);
pressCtrl(view, "a");
press("a");
expect(view.state.doc.toString()).toBe("n 6");
useVimSettings.setState({ enabled: true, handlers: { "Ctrl+A": "ide", "Ctrl+V": "ide" } }, true);
expect(pressCtrl(view, "a").defaultPrevented).toBe(true);
expect(press("a").defaultPrevented).toBe(true);
expect(view.state.doc.toString()).toBe("n 6");
expect(view.state.selection.main).toMatchObject({ from: 0, to: 3 });
view.dispatch({ selection: { anchor: 0 } });
const paste = pressCtrl(view, "v");
const paste = press("v");
expect(paste.defaultPrevented).toBe(false);
expect(getCM(view)!.state.vim!.visualBlock).toBeFalsy();
} finally {
@@ -583,75 +580,6 @@ describe("Vim engine", () => {
});
});
describe("Vim Ctrl+V", () => {
const pasted = "PASTED";
const readText = vi.fn<() => Promise<string>>();
let view: EditorView;
let unregisterPaste: () => void;
beforeEach(() => {
view = makeView();
view.focus();
unregisterPaste = registerAction({ id: "edit.paste", title: "Paste", run: editCommand("paste") });
readText.mockReset().mockResolvedValue(pasted);
vi.stubGlobal("navigator", { clipboard: { readText }, userAgent: navigator.userAgent });
// jsdom does not implement the native insertText command.
document.execCommand = (command, _showUI, value) => {
if (command !== "insertText" || value === undefined) return false;
view.dispatch(view.state.replaceSelection(value));
return true;
};
useVimSettings.setState({ enabled: true, handlers: {} }, true);
});
afterEach(() => {
unregisterPaste();
Reflect.deleteProperty(document, "execCommand");
vi.unstubAllGlobals();
useVimSettings.setState({ enabled: false, handlers: {} }, true);
view.destroy();
});
it("replaces a Visual selection with the IDE handler", async () => {
useVimSettings.setState({ enabled: true, handlers: { "Ctrl+V": "ide" } }, true);
const cm = getCM(view)!;
Vim.handleKey(cm, "v", "user");
Vim.handleKey(cm, "e", "user");
let finishRead = (_text: string) => {};
readText.mockReturnValueOnce(new Promise((resolve) => (finishRead = resolve)));
expect(pressCtrl(view, "v").defaultPrevented).toBe(true);
await tick();
expect(view.state.selection.main).toMatchObject({ from: 0, to: 3 });
expect(view.dom.getAttribute("data-vim-mode")).toBe("visual");
finishRead(pasted);
await tick();
expect(view.state.doc.toString()).toBe("PASTED two\nthree");
expect(view.dom.getAttribute("data-vim-mode")).toBe("normal");
});
it("keeps Vim's Visual block on a mouse selection with the default handler, as IdeaVim does", async () => {
view.dispatch({ selection: { anchor: 0, head: 3 }, userEvent: "select.pointer" });
expect(view.dom.getAttribute("data-vim-mode")).toBe("visual");
pressCtrl(view, "v");
await tick();
expect(view.state.doc.toString()).toBe("one two\nthree");
});
it("pastes in Insert mode and stays there", async () => {
Vim.handleKey(getCM(view)!, "i", "user");
expect(pressCtrl(view, "v").defaultPrevented).toBe(true);
await tick();
expect(view.state.doc.toString()).toBe("PASTEDone two\nthree");
expect(view.dom.getAttribute("data-vim-mode")).toBe("insert");
});
});
describe("line motions across editors", () => {
const key = (view: EditorView, k: string) =>
view.contentDOM.dispatchEvent(new KeyboardEvent("keydown", { key: k, bubbles: true }));
+1 -9
Переглянути файл
@@ -47,7 +47,7 @@ const byStroke = new Map(VIM_KEYS.map((k) => [normalizeBinding(k.stroke), k]));
/**
* IdeaVim hands these strokes to the IDE in one Vim mode only: an editing mode pastes,
* Visual mode copies. Every other mode keeps the stroke's Vim meaning, so Ctrl+V still
* starts a Visual block in Normal and Visual mode.
* starts a Visual block in Normal mode.
*/
const MODE_ACTIONS: Readonly<Record<string, Readonly<Record<string, string>>>> = {
"Ctrl+V": { insert: "edit.paste" },
@@ -55,14 +55,6 @@ const MODE_ACTIONS: Readonly<Record<string, Readonly<Record<string, string>>>> =
"Ctrl+C": { visual: "edit.copy" },
};
/** Paste strokes: given to the IDE in Visual mode, they replace the selection (IdeaVim's `ideaput`). */
const PASTE_STROKES = new Set(["Ctrl+V", "Shift+Insert"]);
/** The IDE action for a stroke the user gave to the IDE, in a mode where it acts on the selection. */
export function ideActionFor(stroke: string, mode: string | null | undefined): string | null {
return mode === "visual" && PASTE_STROKES.has(normalizeBinding(stroke)) ? "edit.paste" : modeAction(stroke, mode);
}
/** The IDE action that replaces Vim's meaning of `stroke` in `mode`, if the mode changes it. */
export function modeAction(stroke: string, mode: string | null | undefined): string | null {
if (!mode) return null;
+7 -24
Переглянути файл
@@ -12,15 +12,7 @@ import { strokeOf } from "@/platform/keymap";
import { executeAction, getAction } from "@/platform/actions";
import { showStatusInfo } from "@/workbench/contributions";
import { installClipboardHooks } from "./clipboard";
import {
ideActionFor,
modeAction,
modeMovedToIde,
movedToIde,
VIM_EDITOR_ATTR,
VIM_MODE_ATTR,
vimModeOf,
} from "./conflicts";
import { modeAction, modeMovedToIde, movedToIde, VIM_EDITOR_ATTR, VIM_MODE_ATTR, vimModeOf } from "./conflicts";
import { useVimMode, type VimModeState } from "./mode";
import { resolveActionId, type RcCommand, type SetOp } from "./rc";
import { useVimSettings } from "./settings";
@@ -296,26 +288,17 @@ const ideHandledKeys = EditorView.domEventHandlers({
if (!stroke) return false;
const settings = useVimSettings.getState();
const mode = vimModeOf(e.target);
const ideOverride = movedToIde(stroke, settings.handlers);
const action = modeMovedToIde(stroke, settings.handlers, mode)
? modeAction(stroke, mode)
: ideOverride && mode === "visual"
? ideActionFor(stroke, mode)
: null;
const visualPaste = action === "edit.paste" && mode === "visual";
if (action && (!visualPaste || view.state.selection.ranges.some((range) => !range.empty))) {
const action = modeMovedToIde(stroke, settings.handlers, mode) ? modeAction(stroke, mode) : null;
if (!movedToIde(stroke, settings.handlers) && !action) return false;
if (action) {
// The mode gives this stroke an IDE meaning: paste while inserting, copy a Visual selection.
// Before the editor keymap: its default Ctrl-v scrolls the page, not pastes.
e.preventDefault();
void executeAction(action);
// Paste reads the clipboard asynchronously. Vim leaves Visual mode when the paste
// replaces the selection and sets the caret, so only copy needs an explicit exit.
if (action === "edit.copy") {
const cm = getCM(view);
if (cm?.state.vim?.visualMode) Vim.exitVisualMode(cm as never);
}
const cm = getCM(view);
if (cm?.state.vim?.visualMode) Vim.exitVisualMode(cm as never);
return true;
}
if (!ideOverride) return false;
if (runScopeHandlers(view, e, "editor")) return true;
// Returning true would cancel the browser's cut or paste: skip Vim's handler for this event only.
const plugin = getCM(view)?.state.vimPlugin as { handleKey?: unknown } | undefined;
+4 -1
Переглянути файл
@@ -4604,12 +4604,15 @@
"Previous Match": "Previous Match",
"Next Match": "Next Match",
"Build server config generated": "Build server config generated",
"Code insight for {container} reads its last build: Run, or a build in Xcode, refreshes it.": "Code insight for {container} reads its last build: Run, or a build in Xcode, refreshes it.",
"sourcekit-lsp now reads the build settings of {container}.": "sourcekit-lsp now reads the build settings of {container}.",
"Could not generate a build server config": "Could not generate a build server config",
"Try Again": "Try Again",
"Xcode project needs a build server config": "Xcode project needs a build server config",
"Cross-file code insight for {container} needs buildServer.json. Generate it with xcode-build-server? It reads the log of the last build, so build the scheme in Xcode once first.": "Cross-file code insight for {container} needs buildServer.json. Generate it with xcode-build-server? It reads the log of the last build, so build the scheme in Xcode once first.",
"Cross-file code insight for {container} needs buildServer.json. Generate it with {tool}?": "Cross-file code insight for {container} needs buildServer.json. Generate it with {tool}?",
"Cross-file code insight for {container} needs a Build Server Protocol config. Install xcode-build-server (brew install xcode-build-server) to generate one.": "Cross-file code insight for {container} needs a Build Server Protocol config. Install xcode-build-server (brew install xcode-build-server) to generate one.",
"Check Again": "Check Again",
"Running {tool}…": "Running {tool}…",
"Flask server": "Flask server",
"Run a Flask application with flask run": "Run a Flask application with flask run",
"Set as FLASK_APP: a module or file, optionally with the app or factory (hello:create_app()); empty finds app.py or wsgi.py": "Set as FLASK_APP: a module or file, optionally with the app or factory (hello:create_app()); empty finds app.py or wsgi.py",
+4 -1
Переглянути файл
@@ -6220,12 +6220,15 @@
"Compact Conversation": "Compactar conversación",
"Premium requests": "Solicitudes premium",
"Build server config generated": "Configuración del servidor de compilación generada",
"Code insight for {container} reads its last build: Run, or a build in Xcode, refreshes it.": "La asistencia de código para {container} lee su última compilación: Ejecutar, o compilar en Xcode, la actualiza.",
"sourcekit-lsp now reads the build settings of {container}.": "sourcekit-lsp ahora lee la configuración de compilación de {container}.",
"Could not generate a build server config": "No se pudo generar la configuración del servidor de compilación",
"Try Again": "Reintentar",
"Xcode project needs a build server config": "El proyecto de Xcode necesita una configuración del servidor de compilación",
"Cross-file code insight for {container} needs buildServer.json. Generate it with xcode-build-server? It reads the log of the last build, so build the scheme in Xcode once first.": "La asistencia de código entre archivos para {container} necesita buildServer.json. ¿Generarlo con xcode-build-server? Lee el registro de la última compilación, así que compila el esquema en Xcode una vez antes.",
"Cross-file code insight for {container} needs buildServer.json. Generate it with {tool}?": "La asistencia de código entre archivos para {container} necesita buildServer.json. ¿Generarlo con {tool}?",
"Cross-file code insight for {container} needs a Build Server Protocol config. Install xcode-build-server (brew install xcode-build-server) to generate one.": "La asistencia de código entre archivos para {container} necesita una configuración de Build Server Protocol. Instala xcode-build-server (brew install xcode-build-server) para generarla.",
"Check Again": "Comprobar de nuevo",
"Running {tool}…": "Ejecutando {tool}…",
"Open Module Settings": "Abrir configuración del módulo",
"Add as Library…": "Añadir como biblioteca…",
"Open Library Settings": "Abrir configuración de biblioteca",
+4 -1
Переглянути файл
@@ -5865,12 +5865,15 @@
"Compact Conversation": "Compacter la conversation",
"Premium requests": "Requêtes premium",
"Build server config generated": "Configuration du serveur de build générée",
"Code insight for {container} reads its last build: Run, or a build in Xcode, refreshes it.": "L’assistance au code pour {container} lit sa dernière compilation : Exécuter, ou une compilation dans Xcode, la met à jour.",
"sourcekit-lsp now reads the build settings of {container}.": "sourcekit-lsp lit maintenant les réglages de build de {container}.",
"Could not generate a build server config": "Impossible de générer la configuration du serveur de build",
"Try Again": "Réessayer",
"Xcode project needs a build server config": "Le projet Xcode a besoin d’une configuration de serveur de build",
"Cross-file code insight for {container} needs buildServer.json. Generate it with xcode-build-server? It reads the log of the last build, so build the scheme in Xcode once first.": "L’assistance au code entre fichiers pour {container} nécessite buildServer.json. Le générer avec xcode-build-server ? Il lit le journal du dernier build : compilez d’abord le schéma une fois dans Xcode.",
"Cross-file code insight for {container} needs buildServer.json. Generate it with {tool}?": "L’assistance au code entre fichiers pour {container} nécessite buildServer.json. Le générer avec {tool} ?",
"Cross-file code insight for {container} needs a Build Server Protocol config. Install xcode-build-server (brew install xcode-build-server) to generate one.": "L’assistance au code entre fichiers pour {container} nécessite une configuration Build Server Protocol. Installez xcode-build-server (brew install xcode-build-server) pour en générer une.",
"Check Again": "Vérifier à nouveau",
"Running {tool}…": "Exécution de {tool}…",
"Open Module Settings": "Ouvrir les paramètres du module",
"Add as Library…": "Ajouter en tant que bibliothèque…",
"Open Library Settings": "Ouvrir les paramètres de la bibliothèque",
+4 -1
Переглянути файл
@@ -6330,12 +6330,15 @@
"Compact Conversation": "대화 압축",
"Premium requests": "프리미엄 요청",
"Build server config generated": "빌드 서버 설정을 생성했습니다",
"Code insight for {container} reads its last build: Run, or a build in Xcode, refreshes it.": "{container}의 코드 인사이트는 마지막 빌드를 읽습니다. 실행하거나 Xcode에서 빌드하면 갱신됩니다.",
"sourcekit-lsp now reads the build settings of {container}.": "이제 sourcekit-lsp가 {container}의 빌드 설정을 읽습니다.",
"Could not generate a build server config": "빌드 서버 설정을 생성할 수 없습니다",
"Try Again": "다시 시도",
"Xcode project needs a build server config": "Xcode 프로젝트에 빌드 서버 설정이 필요합니다",
"Cross-file code insight for {container} needs buildServer.json. Generate it with xcode-build-server? It reads the log of the last build, so build the scheme in Xcode once first.": "{container}의 파일 간 코드 인사이트에는 buildServer.json이 필요합니다. xcode-build-server로 생성할까요? 마지막 빌드 로그를 읽으므로 먼저 Xcode에서 스킴을 한 번 빌드하세요.",
"Cross-file code insight for {container} needs buildServer.json. Generate it with {tool}?": "{container}의 파일 간 코드 인사이트에는 buildServer.json이 필요합니다. {tool}(으)로 생성할까요?",
"Cross-file code insight for {container} needs a Build Server Protocol config. Install xcode-build-server (brew install xcode-build-server) to generate one.": "{container}의 파일 간 코드 인사이트에는 Build Server Protocol 설정이 필요합니다. xcode-build-server(brew install xcode-build-server)를 설치하면 생성할 수 있습니다.",
"Check Again": "다시 확인",
"Running {tool}…": "{tool} 실행 중…",
"Open Module Settings": "모듈 설정 열기",
"Add as Library…": "라이브러리로 추가…",
"Open Library Settings": "라이브러리 설정 열기",
+4 -1
Переглянути файл
@@ -6028,12 +6028,15 @@
"Compact Conversation": "Skompresuj rozmowę",
"Premium requests": "Żądania premium",
"Build server config generated": "Wygenerowano konfigurację serwera budowania",
"Code insight for {container} reads its last build: Run, or a build in Xcode, refreshes it.": "Analiza kodu dla {container} korzysta z ostatniej kompilacji: uruchomienie lub kompilacja w Xcode ją odświeża.",
"sourcekit-lsp now reads the build settings of {container}.": "sourcekit-lsp odczytuje teraz ustawienia budowania {container}.",
"Could not generate a build server config": "Nie można wygenerować konfiguracji serwera budowania",
"Try Again": "Spróbuj ponownie",
"Xcode project needs a build server config": "Projekt Xcode wymaga konfiguracji serwera budowania",
"Cross-file code insight for {container} needs buildServer.json. Generate it with xcode-build-server? It reads the log of the last build, so build the scheme in Xcode once first.": "Analiza kodu między plikami dla {container} wymaga buildServer.json. Wygenerować go za pomocą xcode-build-server? Odczytuje on dziennik ostatniego budowania, więc najpierw zbuduj schemat raz w Xcode.",
"Cross-file code insight for {container} needs buildServer.json. Generate it with {tool}?": "Analiza kodu między plikami dla {container} wymaga buildServer.json. Wygenerować go za pomocą {tool}?",
"Cross-file code insight for {container} needs a Build Server Protocol config. Install xcode-build-server (brew install xcode-build-server) to generate one.": "Analiza kodu między plikami dla {container} wymaga konfiguracji Build Server Protocol. Zainstaluj xcode-build-server (brew install xcode-build-server), aby ją wygenerować.",
"Check Again": "Sprawdź ponownie",
"Running {tool}…": "Uruchamianie {tool}…",
"Open Module Settings": "Otwórz ustawienia modułu",
"Add as Library…": "Dodaj jako bibliotekę…",
"Open Library Settings": "Otwórz ustawienia biblioteki",
+4 -1
Переглянути файл
@@ -6043,12 +6043,15 @@
"Compact Conversation": "Compactar conversa",
"Premium requests": "Solicitações premium",
"Build server config generated": "Configuração do servidor de build gerada",
"Code insight for {container} reads its last build: Run, or a build in Xcode, refreshes it.": "A inteligência de código para {container} lê a última compilação: Executar, ou compilar no Xcode, a atualiza.",
"sourcekit-lsp now reads the build settings of {container}.": "O sourcekit-lsp agora lê as configurações de build de {container}.",
"Could not generate a build server config": "Não foi possível gerar a configuração do servidor de build",
"Try Again": "Tentar novamente",
"Xcode project needs a build server config": "O projeto Xcode precisa de uma configuração de servidor de build",
"Cross-file code insight for {container} needs buildServer.json. Generate it with xcode-build-server? It reads the log of the last build, so build the scheme in Xcode once first.": "A inteligência de código entre arquivos para {container} precisa de buildServer.json. Gerá-lo com xcode-build-server? Ele lê o log do último build, então compile o esquema no Xcode uma vez antes.",
"Cross-file code insight for {container} needs buildServer.json. Generate it with {tool}?": "A inteligência de código entre arquivos para {container} precisa de buildServer.json. Gerá-lo com {tool}?",
"Cross-file code insight for {container} needs a Build Server Protocol config. Install xcode-build-server (brew install xcode-build-server) to generate one.": "A inteligência de código entre arquivos para {container} precisa de uma configuração do Build Server Protocol. Instale o xcode-build-server (brew install xcode-build-server) para gerá-la.",
"Check Again": "Verificar novamente",
"Running {tool}…": "Executando {tool}…",
"Open Module Settings": "Abrir configurações do módulo",
"Add as Library…": "Adicionar como biblioteca…",
"Open Library Settings": "Abrir configurações da biblioteca",
+4 -1
Переглянути файл
@@ -10265,12 +10265,15 @@
"Compact Conversation": "Сжать диалог",
"Premium requests": "Премиум-запросы",
"Build server config generated": "Конфигурация сервера сборки создана",
"Code insight for {container} reads its last build: Run, or a build in Xcode, refreshes it.": "Поддержка кода в {container} использует последнюю сборку: запуск или сборка в Xcode обновляют её.",
"sourcekit-lsp now reads the build settings of {container}.": "Теперь sourcekit-lsp читает настройки сборки {container}.",
"Could not generate a build server config": "Не удалось создать конфигурацию сервера сборки",
"Try Again": "Повторить",
"Xcode project needs a build server config": "Проекту Xcode нужна конфигурация сервера сборки",
"Cross-file code insight for {container} needs buildServer.json. Generate it with xcode-build-server? It reads the log of the last build, so build the scheme in Xcode once first.": "Для межфайловой поддержки кода в {container} нужен buildServer.json. Создать его с помощью xcode-build-server? Он читает журнал последней сборки, поэтому сначала один раз соберите схему в Xcode.",
"Cross-file code insight for {container} needs buildServer.json. Generate it with {tool}?": "Для межфайловой поддержки кода в {container} нужен buildServer.json. Создать его с помощью {tool}?",
"Cross-file code insight for {container} needs a Build Server Protocol config. Install xcode-build-server (brew install xcode-build-server) to generate one.": "Для межфайловой поддержки кода в {container} нужна конфигурация Build Server Protocol. Установите xcode-build-server (brew install xcode-build-server), чтобы создать её.",
"Check Again": "Проверить снова",
"Running {tool}…": "Выполняется {tool}…",
"Open Module Settings": "Открыть настройки модуля",
"Add as Library…": "Добавить как библиотеку…",
"Open Library Settings": "Открыть настройки библиотеки",
+4 -1
Переглянути файл
@@ -8884,12 +8884,15 @@
"Compact Conversation": "Konuşmayı Sıkıştır",
"Premium requests": "Premium istekler",
"Build server config generated": "Derleme sunucusu yapılandırması oluşturuldu",
"Code insight for {container} reads its last build: Run, or a build in Xcode, refreshes it.": "{container} için kod zekâsı son derlemeyi okur: Çalıştırmak ya da Xcode'da derlemek onu yeniler.",
"sourcekit-lsp now reads the build settings of {container}.": "sourcekit-lsp artık {container} derleme ayarlarını okuyor.",
"Could not generate a build server config": "Derleme sunucusu yapılandırması oluşturulamadı",
"Try Again": "Yeniden Dene",
"Xcode project needs a build server config": "Xcode projesinin bir derleme sunucusu yapılandırmasına ihtiyacı var",
"Cross-file code insight for {container} needs buildServer.json. Generate it with xcode-build-server? It reads the log of the last build, so build the scheme in Xcode once first.": "{container} için dosyalar arası kod zekâsı buildServer.json gerektirir. xcode-build-server ile oluşturulsun mu? Son derlemenin günlüğünü okur, bu yüzden önce şemayı Xcode'da bir kez derleyin.",
"Cross-file code insight for {container} needs buildServer.json. Generate it with {tool}?": "{container} için dosyalar arası kod zekâsı buildServer.json gerektirir. {tool} ile oluşturulsun mu?",
"Cross-file code insight for {container} needs a Build Server Protocol config. Install xcode-build-server (brew install xcode-build-server) to generate one.": "{container} için dosyalar arası kod zekâsı bir Build Server Protocol yapılandırması gerektirir. Oluşturmak için xcode-build-server'ı yükleyin (brew install xcode-build-server).",
"Check Again": "Yeniden Denetle",
"Running {tool}…": "{tool} çalıştırılıyor…",
"Open Module Settings": "Modül Ayarlarını Aç",
"Add as Library…": "Kitaplık Olarak Ekle…",
"Open Library Settings": "Kitaplık Ayarlarını Aç",
+4 -6
Переглянути файл
@@ -1344,10 +1344,6 @@
"Debug views": "偵錯檢視",
"Debuggable configurations": "可偵錯的組態",
"Debugger": "偵錯工具",
"GDB executable": "GDB 執行檔",
"LLDB DAP executable": "LLDB DAP 執行檔",
"Requires GDB 14 or newer. Leave blank for automatic discovery.": "需要 GDB 14 或更新版本。留空則自動尋找。",
"Leave blank for automatic discovery.": "留空則自動尋找。",
"Debugger actions": "偵錯工具操作",
"Debugger is not available": "偵錯工具不可用",
"Debugging": "正在偵錯",
@@ -7929,7 +7925,6 @@
"Install coding agents and configure how they launch, chat and connect to the IDE.": "安裝程式設計 Agent,並設定其啟動方式、聊天行為以及與 IDE 的連線。",
"Fork Agent Task": "Fork Agent 任務",
"Couldn't fork the task": "無法 Fork 任務",
"Couldn't retry the message": "無法重試該訊息",
"Fork": "Fork",
"Fork Conversation from Here": "從此處 Fork 對話",
"Whole project": "整個專案",
@@ -9538,12 +9533,15 @@
"Previous Match": "上一個相符項目",
"Next Match": "下一個相符項目",
"Build server config generated": "已產生建置伺服器設定",
"Code insight for {container} reads its last build: Run, or a build in Xcode, refreshes it.": "{container} 的程式碼智慧讀取最近一次建置:執行或在 Xcode 中建置都會更新它。",
"sourcekit-lsp now reads the build settings of {container}.": "sourcekit-lsp 現在會讀取 {container} 的建置設定。",
"Could not generate a build server config": "無法產生建置伺服器設定",
"Try Again": "重試",
"Xcode project needs a build server config": "Xcode 專案需要建置伺服器設定",
"Cross-file code insight for {container} needs buildServer.json. Generate it with xcode-build-server? It reads the log of the last build, so build the scheme in Xcode once first.": "{container} 的跨檔案程式碼智慧需要 buildServer.json。要用 xcode-build-server 產生嗎?它讀取最近一次建置的記錄,請先在 Xcode 中建置一次該 scheme。",
"Cross-file code insight for {container} needs buildServer.json. Generate it with {tool}?": "{container} 的跨檔案程式碼智慧需要 buildServer.json。要用 {tool} 產生嗎?",
"Cross-file code insight for {container} needs a Build Server Protocol config. Install xcode-build-server (brew install xcode-build-server) to generate one.": "{container} 的跨檔案程式碼智慧需要 Build Server Protocol 設定。安裝 xcode-build-server(brew install xcode-build-server)即可產生。",
"Check Again": "重新檢查",
"Running {tool}…": "正在執行 {tool}…",
"Open Module Settings": "開啟模組設定",
"Add as Library…": "新增為庫…",
"Open Library Settings": "開啟庫設定",
+4 -6
Переглянути файл
@@ -1849,10 +1849,6 @@
"Debug views": "调试视图",
"Debuggable configurations": "可调试的配置",
"Debugger": "调试器",
"GDB executable": "GDB 可执行文件",
"LLDB DAP executable": "LLDB DAP 可执行文件",
"Requires GDB 14 or newer. Leave blank for automatic discovery.": "需要 GDB 14 或更高版本。留空则自动查找。",
"Leave blank for automatic discovery.": "留空则自动查找。",
"Debugger actions": "调试器操作",
"Debugger is not available": "调试器不可用",
"Debugging": "正在调试",
@@ -8884,7 +8880,6 @@
"Install coding agents and configure how they launch, chat and connect to the IDE.": "安装编程 Agent,并配置其启动方式、聊天行为以及与 IDE 的连接。",
"Fork Agent Task": "Fork Agent 任务",
"Couldn't fork the task": "无法 Fork 任务",
"Couldn't retry the message": "无法重试该消息",
"Fork": "Fork",
"Fork Conversation from Here": "从此处 Fork 对话",
"Whole project": "整个项目",
@@ -11251,12 +11246,15 @@
"Previous Match": "上一个匹配项",
"Next Match": "下一个匹配项",
"Build server config generated": "已生成构建服务器配置",
"Code insight for {container} reads its last build: Run, or a build in Xcode, refreshes it.": "{container} 的代码智能读取最近一次构建:运行或在 Xcode 中构建都会刷新它。",
"sourcekit-lsp now reads the build settings of {container}.": "sourcekit-lsp 现在会读取 {container} 的构建设置。",
"Could not generate a build server config": "无法生成构建服务器配置",
"Try Again": "重试",
"Xcode project needs a build server config": "Xcode 项目需要构建服务器配置",
"Cross-file code insight for {container} needs buildServer.json. Generate it with xcode-build-server? It reads the log of the last build, so build the scheme in Xcode once first.": "{container} 的跨文件代码智能需要 buildServer.json。用 xcode-build-server 生成吗?它读取最近一次构建的日志,请先在 Xcode 中构建一次该 scheme。",
"Cross-file code insight for {container} needs buildServer.json. Generate it with {tool}?": "{container} 的跨文件代码智能需要 buildServer.json。用 {tool} 生成吗?",
"Cross-file code insight for {container} needs a Build Server Protocol config. Install xcode-build-server (brew install xcode-build-server) to generate one.": "{container} 的跨文件代码智能需要 Build Server Protocol 配置。安装 xcode-build-server(brew install xcode-build-server)即可生成。",
"Check Again": "重新检查",
"Running {tool}…": "正在运行 {tool}…",
"Flask server": "Flask 服务器",
"Run a Flask application with flask run": "使用 flask run 运行 Flask 应用",
"Set as FLASK_APP: a module or file, optionally with the app or factory (hello:create_app()); empty finds app.py or wsgi.py": "设为 FLASK_APP:模块或文件,可附带应用或工厂函数(hello:create_app());留空时查找 app.py 或 wsgi.py",
-10
Переглянути файл
@@ -130,16 +130,6 @@ describe("validateWorkflow", () => {
expect(validateWorkflow({ debugger: { hotSwapAfterCompile: "invalid" } }).debugger.hotSwapAfterCompile).toBe("ask");
});
it("defaults C/C++ debugger paths to empty and accepts absolute and relative paths", () => {
const defaults = { gdbExecutable: "", lldbDapExecutable: "" };
expect(validateWorkflow({}).debugger.cpp).toEqual(defaults);
expect(
validateWorkflow({ debugger: { cpp: { gdbExecutable: 14, lldbDapExecutable: null } } }).debugger.cpp,
).toEqual(defaults);
const cpp = { gdbExecutable: "tools/gdb-16", lldbDapExecutable: "/opt/LLVM Tools/lldb-dap" };
expect(validateWorkflow({ debugger: { cpp } }).debugger.cpp).toEqual(cpp);
});
it("falls back to defaults for missing or malformed values", () => {
expect(validateWorkflow(undefined)).toEqual(DEFAULT_WORKFLOW);
const v = validateWorkflow({
-7
Переглянути файл
@@ -161,7 +161,6 @@ export interface DebuggerSettingsValid {
flutterHotReloadOnSave: boolean;
hotSwapAfterCompile: HotSwapPolicy;
python: { attachSubprocess: boolean; gevent: boolean };
cpp: { gdbExecutable: string; lldbDapExecutable: string };
}
export interface RunSettingsValid {
@@ -425,7 +424,6 @@ export const DEFAULT_WORKFLOW: WorkflowSettings = {
debugServerPage: false,
flutterHotReloadOnSave: true,
hotSwapAfterCompile: "ask",
cpp: { gdbExecutable: "", lldbDapExecutable: "" },
python: { attachSubprocess: true, gevent: false },
},
run: {
@@ -626,7 +624,6 @@ export function validateDebugger(raw: unknown): DebuggerSettingsValid {
const d = DEFAULT_WORKFLOW.debugger;
const v = obj(raw);
const py = obj(v.python);
const cpp = obj(v.cpp);
return {
showOnBreakpoint: bool(v.showOnBreakpoint, d.showOnBreakpoint),
focusAppOnBreakpoint: bool(v.focusAppOnBreakpoint, d.focusAppOnBreakpoint),
@@ -648,10 +645,6 @@ export function validateDebugger(raw: unknown): DebuggerSettingsValid {
attachSubprocess: bool(py.attachSubprocess, d.python.attachSubprocess),
gevent: bool(py.gevent, d.python.gevent),
},
cpp: {
gdbExecutable: text(cpp.gdbExecutable, d.cpp.gdbExecutable),
lldbDapExecutable: text(cpp.lldbDapExecutable, d.cpp.lldbDapExecutable),
},
};
}