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

..
Автор SHA1 Повідомлення Дата
l0ng-ai b06c66a3c5 fix(ssh): report a failed backend upload instead of waiting forever
The IDE backend is uploaded by streaming it into `gzip -dc > file` on the
host. When that command exits early (no gzip, a folder it cannot write, a
full disk), it stops reading: once the channel window (about 2 MB) is
used up, the next write waited for window space forever, so Remote
Development stayed on "Installing the IDE backend on the host…" at a few
percent and never showed the host's error. Each write, and closing the
input, now races the command's exit; an early exit ends the upload with
the command's status and stderr.

Refs #1330
2026-11-05 02:38:59 +08:00
154 змінених файлів з 547 додано та 10427 видалено

No files matched your search

+4 -17
Переглянути файл
@@ -2,8 +2,6 @@ name: Language smoke
# Everyday code intelligence (completion, go to definition, Find Usages, hover, diagnostics
# with a quick fix, an intention, formatting, rename) per language, against the language
# server the app starts by default: crates/ide-host/tests/language_smoke.rs.
# Then running and testing each fixture through the run store and openidea-server
# (Run, Run tests, the test tree, Rerun Failed Tests): smoke/run.test.ts.
on:
push:
branches: [main]
@@ -16,18 +14,12 @@ on:
- "fixtures/**"
- "Cargo.toml"
- "Cargo.lock"
- "src/features/run/**"
- "src/platform/**"
- "smoke/**"
- "package.json"
- "pnpm-lock.yaml"
- ".github/workflows/language-smoke.yml"
workflow_dispatch:
concurrency:
group: language-smoke-${{ github.ref }}
# A new push supersedes a PR's run; on main every merge runs to the end (and saves the cache).
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
cancel-in-progress: true
env:
CARGO_TERM_COLOR: always
@@ -61,10 +53,9 @@ jobs:
shared-key: language-smoke
save-if: ${{ github.ref == 'refs/heads/main' && matrix.language == 'rust' }}
- uses: pnpm/action-setup@v4
with: { version: 11 }
- uses: actions/setup-node@v4
with: { node-version: 22, cache: pnpm }
- if: matrix.language == 'typescript'
uses: actions/setup-node@v4
with: { node-version: 22 }
- if: matrix.language == 'typescript'
run: npm install --global "@vtsls/language-server@$VTSLS" "typescript@$TYPESCRIPT"
@@ -104,7 +95,3 @@ jobs:
- run: cargo test --locked -p ide-host --test language_smoke --no-run
- run: cargo test --locked -p ide-host --test language_smoke -- --ignored --exact ${{ matrix.language }}
- run: pnpm install --frozen-lockfile
- run: cargo build --locked -p ide-host --bin openidea-server
- run: pnpm smoke smoke/run.test.ts -t "^${{ matrix.language }}$"
-2
Переглянути файл
@@ -69,8 +69,6 @@ Shared agent skills live in `.agents/skills/` (`.claude/skills/` links to them):
- `cargo nextest run --workspace` (or `cargo test`), `cargo clippy --workspace --all-targets -- -D warnings`, `cargo fmt --all`.
- `cargo test -p ide-host --test language_smoke -- --ignored --exact <language>` — code intelligence
on `fixtures/` with that language's real server installed (CI: `Language smoke`, pinned versions).
- `pnpm smoke smoke/run.test.ts -t <language>` — run and test that language's fixture through the
run store and a real `openidea-server` (build it first: `cargo build -p ide-host --bin openidea-server`).
- `pnpm test`, `pnpm e2e`, `pnpm lint`, `pnpm format:check`, `pnpm knip`, `pnpm typecheck`,
`pnpm gen:bindings`.
- `pnpm perf` (UI interaction latency / frames / leaks), `pnpm perf:rust` (criterion
-6
Переглянути файл
@@ -716,12 +716,6 @@ pub struct PhpSettings {
/// PHP version the language server checks the code against (`7.4`); empty = from
/// `composer.json` (`config.platform.php`, else the lowest version `require.php` allows).
pub language_level: String,
/// Folders outside the project whose code the language server indexes too (a platform a
/// module extends); absolute, `~/`, or relative to the project.
pub include_paths: Vec<String>,
/// Intelephense stub sets loaded on top of its defaults and the `ext-*` entries of
/// `composer.json` (`wordpress`).
pub stubs: Vec<String>,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
+6 -18
Переглянути файл
@@ -589,12 +589,11 @@ impl DebugManager {
if let Some(command) = custom_command(&spec.command) {
spec.command = command;
}
// debugpy: run the adapter with the debuggee's interpreter (venvs carry their own debugpy),
// or with the launcher's when the debuggee runs through a manager (`uv run python`).
// debugpy: run the adapter with the debuggee's interpreter (venvs carry their own debugpy).
if config.adapter == "debugpy" {
let python = match (arguments.get("debugLauncherPython"), arguments.get("python")) {
(Some(Value::String(p)), _) | (_, Some(Value::String(p))) => Some(p.clone()),
(_, Some(Value::Array(a))) => a.first().and_then(Value::as_str).map(str::to_owned),
let python = match arguments.get("python") {
Some(Value::String(p)) => Some(p.clone()),
Some(Value::Array(a)) => a.first().and_then(Value::as_str).map(str::to_owned),
_ => None,
};
if let Some(python) = python {
@@ -652,19 +651,8 @@ impl DebugManager {
{
arguments["project"] = json!(real);
}
if config.adapter == "codelldb" {
if arguments.get("sourceLanguages").is_none() {
arguments["sourceLanguages"] = json!(["rust"]);
}
// The Debug Console and Evaluate Expression take expressions, as with every other
// debugger; LLDB commands still run with a leading backtick.
match arguments.get_mut("_adapterSettings") {
None => arguments["_adapterSettings"] = json!({"consoleMode": "evaluate"}),
Some(Value::Object(settings)) => {
settings.entry("consoleMode").or_insert_with(|| json!("evaluate"));
}
Some(_) => {}
}
if config.adapter == "codelldb" && arguments.get("sourceLanguages").is_none() {
arguments["sourceLanguages"] = json!(["rust"]);
}
let port = debug_server.map(|s| s.port);
self.start_session(id, owner, config.name, config.adapter, None, config.request, arguments, spec, port).await
-31
Переглянути файл
@@ -698,37 +698,6 @@ async fn js_debug_launch_gets_port_and_workspace_folder() {
assert_eq!(launch["type"], "pwa-node");
}
/// CodeLLDB treats console input as LLDB commands unless told otherwise: Evaluate Expression
/// and the Debug Console send expressions, so its console evaluates them. A launch
/// configuration that picks a console mode keeps it.
#[tokio::test]
async fn codelldb_console_evaluates_expressions() {
let launch_with = |extra: Value| async move {
let h = harness(Script::default());
let config = LaunchConfig {
name: "demo".into(),
adapter: "codelldb".into(),
request: "launch".into(),
program: Some("/p/target/debug/demo".into()),
args: vec![],
cwd: Some("/p".into()),
env: BTreeMap::new(),
extra_json: Some(extra.to_string()),
};
h.start(config).await.unwrap();
h.request("launch")["arguments"].clone()
};
let launch = launch_with(json!({})).await;
assert_eq!(launch["_adapterSettings"]["consoleMode"], "evaluate");
assert_eq!(launch["sourceLanguages"], json!(["rust"]));
let launch =
launch_with(json!({"_adapterSettings": {"consoleMode": "commands", "showDisassembly": "never"}})).await;
assert_eq!(launch["_adapterSettings"], json!({"consoleMode": "commands", "showDisassembly": "never"}));
let launch = launch_with(json!({"_adapterSettings": {"showDisassembly": "never"}})).await;
assert_eq!(launch["_adapterSettings"], json!({"consoleMode": "evaluate", "showDisassembly": "never"}));
}
/// An adapter that is already listening (java-debug inside jdtls): the client
/// connects over TCP to the `debugServer` port instead of spawning anything.
#[tokio::test]
+1 -7
Переглянути файл
@@ -3,7 +3,7 @@ use crate::Host;
use crate::Project;
use crate::rpc::Dispatcher;
use ide_core::{DocId, IdeResult, IpcPath, Location, Pos};
use ide_index::{ExtensionCount, FileMatch, IndexStatus, SymbolFilter, SymbolMatch};
use ide_index::{FileMatch, IndexStatus, SymbolFilter, SymbolMatch};
use ide_language::{FileReference, WebReference};
use ide_workspace::file_refs::{self, PathCompletion};
use serde::{Deserialize, Serialize};
@@ -32,11 +32,6 @@ pub fn index_status(host: &Host, window: &str) -> IdeResult<IndexStatus> {
Ok(host.project(window)?.index.status())
}
/// The project's file extensions, most common first.
pub fn index_file_extensions(host: &Host, window: &str) -> IdeResult<Vec<ExtensionCount>> {
Ok(host.project(window)?.index.file_extensions())
}
pub fn find_files(host: &Host, window: &str, query: String, limit: u32) -> IdeResult<Vec<FileMatch>> {
Ok(host.project(window)?.index.find_files(&query, limit as usize))
}
@@ -165,7 +160,6 @@ pub async fn web_unresolved_references(host: &Host, window: &str, doc: DocId) ->
/// Commands of this module the remote server answers.
pub(crate) fn register(d: &mut Dispatcher) {
d.add("index_status", |c| async move { index_status(&c.host, &c.window) });
d.add("index_file_extensions", |c| async move { index_file_extensions(&c.host, &c.window) });
d.add("find_files", |c| async move { find_files(&c.host, &c.window, c.arg("query")?, c.arg("limit")?) });
d.add("find_dirs", |c| async move { find_dirs(&c.host, &c.window, c.arg("query")?, c.arg("limit")?) });
d.add("find_symbols", |c| async move {
-18
Переглянути файл
@@ -142,21 +142,6 @@ pub async fn run_gradle_jvm_args_script(_host: &Host, _window: &str, jvm_args: V
.map_err(|e| IdeError::internal(e.to_string()))?
}
/// Writes one of the IDE's Gradle init scripts (`text`; the file is named `<name>-<hash>`) on
/// the machine that runs the build, for `--init-script`, and returns its path.
pub async fn run_gradle_init_script(_host: &Host, _window: &str, name: String, text: String) -> IdeResult<String> {
if name.is_empty() || !name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') {
return Err(IdeError::invalid(format!("invalid init script name {name:?}")));
}
tokio::task::spawn_blocking(move || {
ide_run::gradle_jvm::write_script(&ide_run::gradle_jvm::default_dir(), &name, &text)
.map(|p| p.to_string_lossy().into_owned())
.map_err(|e| IdeError::internal(format!("cannot write the Gradle init script: {e}")))
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
}
/// Results from the JUnit XML reports (Surefire, Failsafe, Gradle) of the module at
/// `module` (relative to the project root) written since `since_ms` (Unix epoch, ms).
pub async fn run_test_reports(
@@ -323,9 +308,6 @@ pub(crate) fn register(d: &mut Dispatcher) {
d.add("run_gradle_jvm_args_script", |c| async move {
run_gradle_jvm_args_script(&c.host, &c.window, c.arg("jvmArgs")?).await
});
d.add("run_gradle_init_script", |c| async move {
run_gradle_init_script(&c.host, &c.window, c.arg("name")?, c.arg("text")?).await
});
d.add("run_test_reports", |c| async move {
run_test_reports(&c.host, &c.window, c.arg("module")?, c.arg("sinceMs")?).await
});
-40
Переглянути файл
@@ -34,42 +34,6 @@ pub fn sdk_python_effective(host: &Host, window: &str) -> IdeResult<Option<ide_c
Ok(ide_sdk::apply::python_interpreter(&project.root, &project.settings.effective()).map(Into::into))
}
/// The PHP language level of the project `path` belongs to (a workspace member, by path, as
/// the language server configuration picks it).
#[derive(Clone, Debug, serde::Serialize, specta::Type)]
#[serde(rename_all = "camelCase")]
pub struct PhpLanguageLevels {
/// The one Intelephense checks against; `None`: its default.
pub effective: Option<ide_sdk::php::PhpLanguageLevel>,
/// The one Auto picks, from `composer.json`.
pub auto: Option<ide_sdk::php::PhpLanguageLevel>,
/// The workspace member `path` belongs to: its own settings choose the level, not the
/// workspace's. `None`: the opened project.
pub member: Option<ide_core::IpcPath>,
}
pub async fn sdk_php_language_level(host: &Host, window: &str, path: PathBuf) -> IdeResult<PhpLanguageLevels> {
let project = host.project(window)?;
let (project_root, project_settings) = (project.root.clone(), project.settings.effective());
let config_dir = host.config_dir.clone();
tokio::task::spawn_blocking(move || {
let member = ide_workspace::workspace::Workspace::load(&project_root).ok().flatten().and_then(|w| {
w.projects.into_iter().filter(|p| path.starts_with(p)).max_by_key(|p| p.components().count())
});
let (root, settings) = match &member {
Some(member) => (member, ide_workspace::SettingsStore::load(&config_dir, Some(member)).effective()),
None => (&project_root, project_settings),
};
PhpLanguageLevels {
effective: ide_sdk::php::language_level(root, &settings),
auto: ide_sdk::php::composer_level(root),
member: member.map(ide_core::IpcPath),
}
})
.await
.map_err(join_err)
}
/// SDK / library source folders shown under "External Libraries" in the Project view,
/// with the Maven / Gradle dependency jars of the build model.
pub async fn sdk_project_libraries(host: &Host, window: &str) -> IdeResult<Vec<ide_sdk::libraries::LibraryGroup>> {
@@ -180,10 +144,6 @@ pub async fn sdk_python_pip(
pub(crate) fn register(d: &mut Dispatcher) {
d.add("sdk_detect", |c| async move { sdk_detect(&c.host, &c.window, c.arg("kind")?).await });
d.add("sdk_python_effective", |c| async move { sdk_python_effective(&c.host, &c.window) });
d.add(
"sdk_php_language_level",
|c| async move { sdk_php_language_level(&c.host, &c.window, c.arg("path")?).await },
);
d.add("sdk_project_libraries", |c| async move { sdk_project_libraries(&c.host, &c.window).await });
d.add("sdk_locate_tools", |c| async move {
sdk_locate_tools(&c.host, &c.window, c.arg("names")?, c.arg("near")?).await
-11
Переглянути файл
@@ -667,17 +667,6 @@ impl HostApi for PluginApi {
Ok(())
}
fn open_location(&self, client: Option<&str>, path: &Path, line: u32, column: u32) -> Result<(), HostError> {
let event = PluginEvent::OpenLocation {
plugin_id: self.id().to_owned(),
path: path.to_path_buf().into(),
line,
column,
};
self.shared.sink.emit(client, event);
Ok(())
}
fn setting(&self, root: Option<&Path>, key: &str) -> Option<String> {
let schema: Vec<super::ui_points::SettingSchema> = self
.shared
-1
Переглянути файл
@@ -114,7 +114,6 @@ pub fn forwarded(event: &PluginEvent) -> bool {
| PluginEvent::ViewChanged { .. }
| PluginEvent::ViewMessage { .. }
| PluginEvent::OpenTerminal { .. }
| PluginEvent::OpenLocation { .. }
)
}
-2
Переглянути файл
@@ -192,8 +192,6 @@ pub enum PluginEvent {
args: Vec<String>,
cwd: ide_core::IpcPath,
},
#[serde(rename_all = "camelCase")]
OpenLocation { plugin_id: String, path: ide_core::IpcPath, line: u32, column: u32 },
/// Plugin languages, or the servers they may start, changed: re-fetch
/// `languages` (the host re-detects open documents: [`crate::Host::plugin_languages_changed`]).
LanguagesChanged,
-10
Переглянути файл
@@ -378,19 +378,9 @@ pub(super) fn view(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
}
let mut out = UiDecl::new(d.id.clone(), d.title.clone(), json(&d)?);
out.files = files;
if let Some(icon) = d.icon.as_deref().filter(|i| i.ends_with(".svg")) {
let path = std::path::PathBuf::from(icon);
let svg = super::icons::read_icon(pkg, &path)?;
out.assets.push((view_icon_asset(&d.id), svg));
out.files.push(path);
}
Ok(out)
}
pub fn view_icon_asset(id: &str) -> String {
format!("viewIcon/{id}")
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
struct CustomEditorDecl {
-1
Переглянути файл
@@ -222,7 +222,6 @@ pub fn restricted_command_allowed(cmd: &str) -> bool {
| "project_current"
| "project_roots"
| "index_status"
| "index_file_extensions"
| "jvm_file_presentations"
| "deploy_coverage"
| "deploy_test_connection"
+2 -282
Переглянути файл
@@ -1,7 +1,6 @@
//! Language smoke tests: the everyday code intelligence of each language — completion, go to
//! definition, Find Usages, hover, diagnostics with a quick fix, an intention, rename,
//! formatting, parameter info, the Structure view, auto-import, Optimize Imports and moving a
//! file — on its `fixtures/` project, through the `ops` the app's commands call and the
//! definition, Find Usages, hover, diagnostics with a quick fix, an intention, rename and
//! formatting — on its `fixtures/` project, through the `ops` the app's commands call and the
//! language server the app starts by default.
//!
//! `#[ignore]`d because they need the servers installed. CI's `Language smoke` job installs
@@ -69,35 +68,6 @@ struct Checks {
indent: Indent,
/// Renaming the symbol to the new name edits these files.
rename: (At, &'static str, &'static [&'static str]),
/// Parameter info in a call being typed: a signature naming this parameter.
signature: (Typed, &'static str),
/// The Structure view of a file: these symbols, at any depth.
outline: (&'static str, &'static [&'static str]),
/// Completing a name the file doesn't import yet also imports it.
auto_import: AutoImport,
/// Optimize Imports, with an import typed after a line.
organize_imports: Option<(Typed, Imports)>,
/// Moving a file updates its references: (file, new path, a file that then contains this).
file_move: Option<(&'static str, &'static str, &'static str, &'static str)>,
}
#[derive(Clone, Copy, Debug)]
struct AutoImport {
/// The line typed, ending in the start of the name.
typed: Typed,
/// The completion item.
label: &'static str,
/// What the item's import adds to the file.
result: &'static str,
}
/// What Optimize Imports does with the typed import.
#[derive(Clone, Copy, Debug)]
enum Imports {
/// Removes it (unused).
Removed,
/// Sorts it before this line.
Before(&'static str),
}
#[derive(Clone, Copy, Debug)]
@@ -462,146 +432,6 @@ impl Smoke {
}
}
async fn signature(&self, call: Typed, parameter: &str) {
let (doc, pos, before) = self.type_line(call).await;
self.retry("parameter info", self.warm_up, || async {
let found = ops::lsp::lsp_signature_help(&self.host, WINDOW, doc, pos).await;
match &found {
Ok(Some(h)) if h.signatures.iter().any(|s| s.label.contains(parameter)) => Ok(()),
_ => Err(found.map(|h| h.map(|h| h.signatures.into_iter().map(|s| s.label).collect::<Vec<_>>()))),
}
})
.await;
self.restore(doc, &before).await;
}
async fn outline(&self, file: &str, symbols: &[&str]) {
let (doc, _) = self.doc(file).await;
fn names(items: &[ide_core::OutlineItem], out: &mut BTreeSet<String>) {
for item in items {
out.insert(item.name.clone());
names(&item.children, out);
}
}
self.retry("structure", self.warm_up, || async {
let found = ops::doc::doc_outline(&self.host, WINDOW, doc).await;
let mut shown = BTreeSet::new();
if let Ok(items) = &found {
names(items, &mut shown);
}
if symbols.iter().all(|s| shown.contains(*s)) { Ok(()) } else { Err(shown) }
})
.await;
}
async fn auto_import(&self, a: AutoImport) {
let (doc, pos, before) = self.type_line(a.typed).await;
assert!(!before.contains(a.result), "{a:?}: the file already contains the result");
self.retry("auto-import completion", self.warm_up, || async {
let list = ops::lsp::lsp_completion(&self.host, WINDOW, RequestId(6), doc, pos, None).await;
let items = match &list {
Ok(l) => l.items.iter().filter(|i| i.label == a.label).cloned().collect::<Vec<_>>(),
Err(e) => return Err(format!("{e}")),
};
let text = self.doc(a.typed.file).await.1;
let mut imports = Vec::new();
for item in items {
// Servers compute the import when the item is resolved (on selection).
let item = if item.additional_edits.is_empty() {
ops::lsp::lsp_resolve_completion(&self.host, WINDOW, doc, item.clone()).await.unwrap_or(item)
} else {
item
};
let mut document = ide_text::Document::new(&text);
if document.apply_edits(&item.additional_edits).is_ok() && document.text().contains(a.result) {
return Ok(());
}
// Or accepting it runs a server command that edits the file (kotlin-lsp).
if let Some(command) = item.command.clone() {
let ran = ops::lsp::lsp_execute_command(&self.host, WINDOW, doc, command).await;
let text = self.doc(a.typed.file).await.1;
if ran.is_ok() && text.contains(a.result) {
return Ok(());
}
}
imports.push(format!("{:?} {:?}", item.additional_edits, item.command));
}
let labels: Vec<String> = list.map(|l| l.items.into_iter().take(20).map(|i| i.label).collect()).unwrap();
Err(format!("{:?} items' imports: {imports:?}; items: {labels:?}", a.label))
})
.await;
self.restore(doc, &before).await;
}
async fn organize_imports(&self, import: Typed, expect: Imports) {
let (doc, _, before) = self.type_line(import).await;
let typed = import.text.trim();
let organized = |text: &str| match expect {
Imports::Removed => !text.lines().any(|l| l.trim() == typed),
Imports::Before(line) => {
let at = |needle: &str| text.lines().position(|l| l.trim() == needle);
matches!((at(typed), at(line)), (Some(a), Some(b)) if a < b)
}
};
self.retry("optimize imports", self.warm_up, || async {
let text = self.doc(import.file).await.1;
// The whole file, as Optimize Imports asks (positions past the end fail on jdtls).
let last = text.split('\n').count() as u32 - 1;
let whole = Range::new(Pos::new(0, 0), Pos::new(last, utf16_len(text.rsplit('\n').next().unwrap_or(""))));
let kind = "source.organizeImports".to_string();
let found = ops::lsp::lsp_code_actions(&self.host, WINDOW, doc, whole, vec![kind.clone()]).await;
let actions: Vec<_> = match &found {
Ok(a) => a.iter().filter(|a| a.kind.as_ref().is_some_and(|k| k.starts_with(&kind))).cloned().collect(),
Err(e) => return Err(format!("{e}")),
};
let Some(action) = actions.iter().find(|a| a.is_preferred).or(actions.first()).cloned() else {
return Err(format!(
"no {kind} action: {:?}",
found.map(|a| a.into_iter().map(|a| a.title).collect::<Vec<_>>())
));
};
ops::lsp::lsp_apply_code_action(&self.host, WINDOW, doc, action).await.map_err(|e| e.to_string())?;
let text = self.doc(import.file).await.1;
if organized(&text) { Ok(()) } else { Err(text) }
})
.await;
self.restore(doc, &before).await;
}
async fn file_move(&self, from: &str, to: &str, referencing: &str, result: &str) {
// The servers know the referencing file (opened, as in an editor).
let _ = self.doc(referencing).await;
let moves = vec![ide_workspace::FileMove { from: self.path(from).into(), to: self.path(to).into() }];
let edit = self
.retry("move file", self.warm_up, || async {
let found =
ops::refactor::refactor_file_move_edits(&self.host, WINDOW, RequestId(7), moves.clone()).await;
let want = self.path(referencing);
match &found {
Ok(e)
if e.edit
.files
.iter()
.any(|f| matches!(f, ide_core::FileEdit::Edit { path, .. } if **path == *want)) =>
{
Ok(e.edit.clone())
}
_ => Err(found),
}
})
.await;
ops::refactor::refactor_move_files(&self.host, WINDOW, moves, edit, "Move".into())
.await
.unwrap_or_else(|e| self.fail("move file", e));
if !self.path(to).is_file() {
self.fail("move file", format_args!("{to} doesn't exist after the move"));
}
let text = self.doc(referencing).await.1;
if !text.contains(result) {
self.fail("move file", format_args!("{referencing} has no {result:?} after the move:\n{text}"));
}
}
async fn run(&self, c: &Checks) {
self.definition(c.definition.0, c.definition.1).await;
self.references(c.references.0, c.references.1).await;
@@ -610,17 +440,7 @@ impl Smoke {
self.quick_fix(c.quick_fix).await;
self.intention(c.intention.0, c.intention.1).await;
self.format(c.format.0, c.indent, c.format.1).await;
self.signature(c.signature.0, c.signature.1).await;
self.outline(c.outline.0, c.outline.1).await;
self.auto_import(c.auto_import).await;
if let Some((import, expect)) = c.organize_imports {
self.organize_imports(import, expect).await;
}
self.rename(c.rename.0, c.rename.1, c.rename.2).await;
// Last: it moves a file the other checks use.
if let Some((from, to, referencing, result)) = c.file_move {
self.file_move(from, to, referencing, result).await;
}
let shutdown = self.host.project(WINDOW).unwrap().lsp.clone();
let _ = tokio::time::timeout(Duration::from_secs(20), shutdown.shutdown_all()).await;
}
@@ -660,22 +480,6 @@ const TYPESCRIPT: Checks = Checks {
"formatPrice",
&["src/index.ts", "src/money.ts"],
),
signature: (typed("src/index.ts", "const total = cart.total();", " cart.add("), "product"),
outline: ("src/cart.ts", &["Cart", "add", "total"]),
auto_import: AutoImport {
typed: typed("src/index.ts", "const total = cart.total();", " addMon"),
label: "addMoney",
result: "addMoney",
},
organize_imports: Some((
typed(
"src/index.ts",
"import { cents, formatMoney } from \"./money.ts\";",
"import { readFileSync } from \"node:fs\";",
),
Imports::Removed,
)),
file_move: Some(("src/money.ts", "src/lib/money.ts", "src/index.ts", "\"./lib/money.ts\"")),
};
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
@@ -717,19 +521,6 @@ const PYTHON: Checks = Checks {
"TaskBoard",
&["src/tasks/cli.py", "src/tasks/models.py"],
),
signature: (typed("src/tasks/cli.py", "tasks = build_demo()", " tasks.add("), "title"),
outline: ("src/tasks/models.py", &["Priority", "Task", "TaskList", "pending"]),
auto_import: AutoImport {
typed: typed("src/tasks/cli.py", "tasks = build_demo()", " stamp = datetim"),
label: "datetime",
result: "import datetime",
},
organize_imports: Some((
typed("src/tasks/models.py", "from enum import IntEnum", "import abc"),
Imports::Before("import os"),
)),
// basedpyright has no `workspace/willRenameFiles`.
file_move: None,
};
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
@@ -767,16 +558,6 @@ const RUST: Checks = Checks {
),
indent: Indent::Spaces(4),
rename: (at("src/parser.rs", "pub fn parse(text: &str)", "parse"), "parse_all", &["src/main.rs", "src/parser.rs"]),
signature: (typed("src/main.rs", "let mut inventory = Inventory::new();", " inventory.take("), "sku"),
outline: ("src/lib.rs", &["Inventory", "Item", "take"]),
auto_import: AutoImport {
typed: typed("src/main.rs", "let mut inventory = Inventory::new();", " let _seen = HashSe"),
label: "HashSet",
result: "use std::collections::HashSet;",
},
// rust-analyzer has no `source.organizeImports`.
organize_imports: None,
file_move: Some(("src/parser.rs", "src/csv.rs", "src/lib.rs", "pub mod csv;")),
};
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
@@ -816,16 +597,6 @@ const GO: Checks = Checks {
"Open",
&["cmd/server/main.go", "internal/store/store.go"],
),
signature: (typed("cmd/server/main.go", "s := store.New()", "\ts.Create("), "title"),
outline: ("internal/store/store.go", &["Store", "New", "(*Store).Create"]),
auto_import: AutoImport {
typed: typed("cmd/server/main.go", "s := store.New()", "\t_ = strings.ToUpp"),
label: "ToUpper",
result: "\t\"strings\"",
},
organize_imports: Some((typed("cmd/server/main.go", "\"strconv\"", "\t\"sort\""), Imports::Removed)),
// gopls renames packages, not files: moving a Go file changes no references.
file_move: None,
};
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
@@ -882,37 +653,6 @@ const JAVA: Checks = Checks {
"submit",
&["src/main/java/com/example/orders/App.java", "src/main/java/com/example/orders/OrderBook.java"],
),
signature: (
typed(
"src/main/java/com/example/orders/App.java",
"long revenue = book.revenueCents();",
" book.place(",
),
"customer",
),
outline: (
"src/main/java/com/example/orders/OrderBook.java",
&["OrderBook", "place(String, String, int, long)", "revenueCents()"],
),
auto_import: AutoImport {
typed: typed(
"src/main/java/com/example/orders/App.java",
"long revenue = book.revenueCents();",
" ArrayLis",
),
label: "ArrayList",
result: "import java.util.ArrayList;",
},
organize_imports: Some((
typed("src/main/java/com/example/orders/OrderBook.java", "import java.util.Optional;", "import java.util.Map;"),
Imports::Removed,
)),
file_move: Some((
"src/main/java/com/example/orders/OrderBook.java",
"src/main/java/com/example/orders/Ledger.java",
"src/main/java/com/example/orders/App.java",
"Ledger book",
)),
};
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
@@ -965,26 +705,6 @@ const KOTLIN: Checks = Checks {
"find",
&["src/main/kotlin/com/example/library/App.kt", "src/main/kotlin/com/example/library/Library.kt"],
),
signature: (
typed("src/main/kotlin/com/example/library/App.kt", "val library = Library()", " library.lend("),
"isbn",
),
outline: ("src/main/kotlin/com/example/library/Library.kt", &["Library", "lend", "search"]),
auto_import: AutoImport {
typed: typed(
"src/main/kotlin/com/example/library/App.kt",
"val library = Library()",
" val stamp = LocalDateTi",
),
label: "LocalDateTime",
result: "import java.time.LocalDateTime",
},
organize_imports: Some((
typed("src/main/kotlin/com/example/library/App.kt", "import java.time.LocalDate", "import java.util.UUID"),
Imports::Removed,
)),
// kotlin-lsp has no `workspace/willRenameFiles`.
file_move: None,
};
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
-77
Переглянути файл
@@ -2045,83 +2045,6 @@ fn pinned_programs_fill_views_and_open_terminals() {
assert_eq!(args, ["follow", "build", "--lines=5"]);
}
#[test]
fn views_open_project_files_at_a_line() {
let f = fixture(Limits::default());
let info = f.install(&sample("jobs"));
assert_eq!(info.status, PluginStatus::Inactive, "{:?}", info.error);
std::fs::write(f.project.join("jobs.log"), "build\ndeploy\nfailed\n").unwrap();
let press = |button: &str| {
f.take_events();
let result = f.host.view_event("jobs", "jobs", ide_plugin::ViewEvent::Button { id: button.into() }, f.inv());
let opened = f.take_events().into_iter().find_map(|(client, e)| match e {
PluginEvent::OpenLocation { path, line, column, .. } => Some((client, path.0, line, column)),
_ => None,
});
(result, opened)
};
let (result, opened) = press("log");
assert!(result.is_ok(), "{result:?}");
let (client, path, line, column) = opened.expect("a location");
assert_eq!((client.as_deref(), line, column), (Some("main"), 2, 4));
assert_eq!(path.canonicalize().unwrap(), f.project.join("jobs.log").canonicalize().unwrap());
let (result, opened) = press("outside");
assert!(result.is_err(), "a path outside the project is refused");
assert!(opened.is_none());
f.host.set_capability("jobs", "project.read", false).unwrap();
let (result, opened) = press("log");
assert!(result.unwrap_err().message.contains("project.read"), "needs project.read");
assert!(opened.is_none());
}
#[test]
fn views_can_use_an_svg_icon_from_the_package() {
let f = fixture(Limits::default());
let tmp = tempfile::tempdir().unwrap();
let clean = r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><rect width="16" height="16" fill="#08f"/></svg>"##;
let package = |dir: &str, icon: &str, svg: &str| {
let pkg = tmp.path().join(dir);
for (path, text) in [("panel/index.html", "<p>panel</p>"), ("icons/panel.svg", svg)] {
std::fs::create_dir_all(pkg.join(path).parent().unwrap()).unwrap();
std::fs::write(pkg.join(path), text).unwrap();
}
std::fs::write(
pkg.join("plugin.toml"),
format!(
r#"id = "panel-icon"
name = "Panel Icon"
version = "1.0.0"
engines.openidea = "^1.0"
[[contributes.views]]
id = "panel"
title = "Panel"
icon = "{icon}"
location = "bottom"
web = "panel/index.html"
"#
),
)
.unwrap();
pkg
};
assert!(f.host.install_from_dir(&package("missing", "icons/missing.svg", clean), &Consent::all()).is_err());
let scripted = clean.replace("<rect", "<script>alert(1)</script><rect");
assert!(f.host.install_from_dir(&package("scripted", "icons/panel.svg", &scripted), &Consent::all()).is_err());
let info = f.install(&package("clean", "icons/panel.svg", clean));
assert!(info.error.is_none(), "{:?}", info.error);
let view = f.host.ui_items("views").into_iter().find(|v| v.key == "panel").expect("the view");
assert_eq!(view.decl["icon"].as_str(), Some("icons/panel.svg"));
let assets = f.host.assets("panel-icon", "viewIcon/panel").unwrap();
assert_eq!(assets.len(), 1);
assert!(assets[0].1.contains("<rect"));
}
/// A plugin with web views and no code: its pages and their files are
/// installed with it and served only from the declared directories, while
/// it is enabled and only for the installed version; file icons and
-16
Переглянути файл
@@ -141,19 +141,3 @@ async fn workspace_cmake_before_launch_tasks_resolve_in_the_member() {
assert!(configs.iter().any(|c| c.id == task.target && c.cwd == build.cwd));
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn gradle_init_scripts_are_written_by_the_host_that_runs_the_build() {
let tmp = tempfile::tempdir().unwrap();
let host = host(tmp.path());
let text = "allprojects { }\n".to_string();
let path =
ops::run::run_gradle_init_script(&host, "main", "openidea-gradle-tests".into(), text.clone()).await.unwrap();
assert!(path.contains("openidea-gradle-tests-"), "{path}");
assert_eq!(std::fs::read_to_string(&path).unwrap(), text);
let again = ops::run::run_gradle_init_script(&host, "main", "openidea-gradle-tests".into(), text).await.unwrap();
assert_eq!(again, path);
// A name is not a path.
let escaped = ops::run::run_gradle_init_script(&host, "main", "../escape".into(), String::new()).await;
assert!(escaped.is_err(), "{escaped:?}");
}
-209
Переглянути файл
@@ -1,209 +0,0 @@
//! A day with Git on a `fixtures/` project, through the `ops` the app's commands call: an edit
//! marked in the gutter, Local Changes and its diff, a commit in the log, a branch, a stash, and
//! a merge that conflicts, resolved and committed. Open documents follow every step.
use ide_core::DocId;
use ide_host::{Host, HostConfig, ops};
use ide_vcs::{ChangeKind, CommitOptions, FileStatus, HunkKind, LogQuery};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::Arc;
use std::time::Duration;
const WINDOW: &str = "main";
/// The line every branch changes, in `src/lib.rs`.
const LINE: &str = "pub fn format_price(cents: u64) -> String {";
fn git(root: &Path, args: &[&str]) -> String {
let out = Command::new("git").current_dir(root).args(args).output().unwrap();
assert!(out.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&out.stderr));
String::from_utf8(out.stdout).unwrap()
}
fn copy_dir(from: &Path, to: &Path) {
std::fs::create_dir_all(to).unwrap();
for entry in std::fs::read_dir(from).unwrap().flatten() {
let (src, dst) = (entry.path(), to.join(entry.file_name()));
if entry.file_type().unwrap().is_dir() {
copy_dir(&src, &dst);
} else {
std::fs::copy(&src, &dst).unwrap();
}
}
}
struct Flow {
host: Arc<Host>,
root: PathBuf,
_tmp: tempfile::TempDir,
}
impl Flow {
async fn new(fixture: &str) -> Self {
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let root = base.join(fixture);
copy_dir(&Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures").join(fixture), &root);
git(&root, &["init", "-q", "-b", "main"]);
for (key, value) in [
("user.name", "Test"),
("user.email", "[email protected]"),
("commit.gpgsign", "false"),
("core.autocrlf", "false"),
] {
git(&root, &["config", key, value]);
}
git(&root, &["add", "-A"]);
git(&root, &["commit", "-q", "-m", "Initial commit"]);
let host = Arc::new(Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(|_| {})),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
}));
host.trust.decide(&root, true, false).unwrap();
let project = ops::project::open(&host, WINDOW, &root).await.unwrap();
for _ in 0..500 {
if !project.repos().is_empty() {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
Flow { host, root, _tmp: tmp }
}
async fn open(&self, file: &str) -> DocId {
ops::doc::open(&self.host, WINDOW, self.root.join(file)).await.unwrap().id
}
async fn text(&self, doc: DocId) -> String {
ops::doc::snapshot(&self.host, WINDOW, doc).await.unwrap().text
}
/// Types `with` over `LINE` in the editor (unsaved).
async fn edit_line(&self, doc: DocId, with: &str) {
let text = self.text(doc).await;
let current = text.lines().find(|l| l.starts_with("pub fn format_price")).unwrap().to_owned();
let project = self.host.project(WINDOW).unwrap();
project.documents.replace_all(doc, &text.replacen(&current, with, 1)).unwrap();
}
async fn save(&self, doc: DocId) {
ops::doc::save(&self.host, WINDOW, doc).await.unwrap();
}
async fn status(&self) -> Vec<FileStatus> {
ops::vcs::status(&self.host, WINDOW).await.unwrap()
}
async fn commit(&self, files: &[&str], message: &str) -> String {
let paths = files.iter().map(|f| self.root.join(f)).collect();
ops::vcs::vcs_stage(&self.host, WINDOW, paths).await.unwrap();
let options = CommitOptions { run_hooks: true, ..Default::default() };
ops::vcs::vcs_commit(&self.host, WINDOW, None, message.into(), options).await.unwrap()
}
async fn head(&self) -> ide_vcs::Commit {
let log = ops::vcs::vcs_log(&self.host, WINDOW, None, LogQuery::default()).await.unwrap();
log.into_iter().next().expect("a commit")
}
}
fn changed<'a>(status: &'a [FileStatus], file: &str) -> Option<&'a FileStatus> {
status.iter().find(|s| s.rel_path == file)
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn change_commit_branch_stash_and_merge_a_conflict() {
let f = Flow::new("rust-app").await;
let lib_path = f.root.join("src/lib.rs");
let lib = f.open("src/lib.rs").await;
let original = f.text(lib).await;
let line = original.lines().position(|l| l == LINE).expect("the fixture's line") as u32;
// An edit in the editor: a modified line in the gutter, against HEAD, before saving.
let base = "pub fn format_price(cents: u64) -> String { // base";
f.edit_line(lib, base).await;
let hunks = ops::vcs::vcs_line_hunks(&f.host, WINDOW, lib_path.clone()).await.unwrap();
assert!(
matches!(&hunks[..], [h] if h.kind == HunkKind::Modified && h.start == line && h.old_text.contains(LINE)),
"{hunks:?}"
);
assert!(f.status().await.is_empty(), "nothing saved yet");
// Saved: Local Changes lists it, and its diff shows the edit.
f.save(lib).await;
let status = f.status().await;
assert_eq!(changed(&status, "src/lib.rs").and_then(|s| s.unstaged), Some(ChangeKind::Modified), "{status:?}");
let diff = ops::vcs::vcs_diff_text(&f.host, WINDOW, lib_path.clone(), false).await.unwrap();
assert!(diff.contains(&format!("-{LINE}")) && diff.contains(&format!("+{base}")), "{diff}");
// Commit: the log's head; nothing left to commit; no gutter marks.
let id = f.commit(&["src/lib.rs"], "Mark the base").await;
let head = f.head().await;
assert_eq!((head.id.as_str(), head.summary.as_str()), (id.as_str(), "Mark the base"));
assert!(f.status().await.is_empty());
assert!(ops::vcs::vcs_line_hunks(&f.host, WINDOW, lib_path.clone()).await.unwrap().is_empty());
// A branch changes the line its way.
ops::vcs::vcs_create_branch(&f.host, WINDOW, None, "feature".into(), None, true).await.unwrap();
let theirs = "pub fn format_price(cents: u64) -> String { // feature";
f.edit_line(lib, theirs).await;
f.save(lib).await;
f.commit(&["src/lib.rs"], "Feature's change").await;
let branches = ops::vcs::vcs_branches(&f.host, WINDOW, None).await.unwrap();
assert!(branches.iter().any(|b| b.name == "feature" && b.current), "{branches:?}");
// Back on main, the open file shows main's text.
ops::vcs::vcs_checkout(&f.host, WINDOW, None, "main".into(), false, None).await.unwrap();
assert!(f.text(lib).await.contains(base));
// Stash: work in progress put aside and brought back.
let main_rs = f.open("src/main.rs").await;
let wip = format!("{}// work in progress\n", f.text(main_rs).await);
f.host.project(WINDOW).unwrap().documents.replace_all(main_rs, &wip).unwrap();
f.save(main_rs).await;
ops::vcs::vcs_stash_push(&f.host, WINDOW, None, Some("wip".into()), false, false).await.unwrap();
assert!(f.status().await.is_empty());
assert!(!f.text(main_rs).await.contains("work in progress"));
let stashes = ops::vcs::vcs_stashes(&f.host, WINDOW, None).await.unwrap();
assert!(matches!(&stashes[..], [s] if s.message.contains("wip")), "{stashes:?}");
ops::vcs::vcs_stash_apply(&f.host, WINDOW, None, 0, true, false, None).await.unwrap();
assert_eq!(f.text(main_rs).await, wip);
assert!(ops::vcs::vcs_stashes(&f.host, WINDOW, None).await.unwrap().is_empty());
ops::vcs::vcs_discard(&f.host, WINDOW, vec![f.root.join("src/main.rs")]).await.unwrap();
assert!(f.status().await.is_empty());
// Main changes the same line: merging the branch conflicts.
let ours = "pub fn format_price(cents: u64) -> String { // main";
f.edit_line(lib, ours).await;
f.save(lib).await;
f.commit(&["src/lib.rs"], "Main's change").await;
let merged = ops::vcs::vcs_merge(&f.host, WINDOW, None, "feature".into()).await;
let status = f.status().await;
let conflicted = changed(&status, "src/lib.rs").map(|s| (s.staged, s.unstaged));
assert!(
matches!(conflicted, Some((Some(ChangeKind::Conflicted), _) | (_, Some(ChangeKind::Conflicted)))),
"merge: {merged:?}; status: {status:?}"
);
// The open file shows the conflict as Git left it.
assert!(f.text(lib).await.contains("<<<<<<<"), "{}", f.text(lib).await);
let versions = ops::vcs::vcs_conflict_versions(&f.host, WINDOW, lib_path.clone()).await.unwrap();
let has = |side: &Option<String>, line: &str| side.as_deref().is_some_and(|t| t.contains(line));
assert!(has(&versions.base, base) && has(&versions.ours, ours) && has(&versions.theirs, theirs), "{versions:?}");
// Resolved (Accept Theirs) and committed: a merge commit, nothing left.
let resolved = versions.theirs.clone().unwrap();
f.host.project(WINDOW).unwrap().documents.replace_all(lib, &resolved).unwrap();
f.save(lib).await;
f.commit(&["src/lib.rs"], "Merge feature").await;
let head = f.head().await;
assert_eq!(head.parents.len(), 2, "{head:?}");
assert!(f.status().await.is_empty());
assert_eq!(std::fs::read_to_string(&lib_path).unwrap(), resolved);
}
-51
Переглянути файл
@@ -114,54 +114,3 @@ async fn linked_projects_share_navigation_but_keep_files_repositories_and_run_di
assert_eq!(automatic.index.find_files("same.txt", 100).len(), 1);
host.close_project("main");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn php_language_level_follows_the_member_of_the_file() {
use ide_sdk::php::{PhpLanguageLevel, PhpLevelSource};
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let (api, legacy) = (base.join("api"), base.join("legacy"));
for (member, composer) in [
(&api, r#"{"require": {"php": "^7.4"}}"#),
(&legacy, r#"{"require": {"php": "^7.4"}, "config": {"platform": {"php": "8.0.5"}}}"#),
] {
std::fs::create_dir(member).unwrap();
std::fs::write(member.join("composer.json"), composer).unwrap();
}
let root = base.join("workspace");
Workspace::save(&root, "PHP", vec![api.clone(), legacy.clone()], true).unwrap();
std::fs::write(root.join("composer.json"), r#"{"require": {"php": "^8.2"}}"#).unwrap();
let config_dir = base.join("config");
ide_workspace::SettingsStore::load(&config_dir, Some(&legacy))
.set(ide_workspace::SettingsScope::Project, "languages.php.languageLevel", "8.3".into())
.unwrap();
let host = Host::new(HostConfig {
config_dir,
data_dir: base.join("data"),
local_data_dir: base.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
host.trust.decide(&root, true, false).unwrap();
host.open_project("main", &root).unwrap();
let found = |version: &str, source| Some(PhpLanguageLevel { version: version.into(), source });
let level = async |path: std::path::PathBuf| ops::sdk::sdk_php_language_level(&host, "main", path).await.unwrap();
let level_of_api = level(api.join("src/Invoice.php")).await;
assert_eq!(level_of_api.effective, found("7.4.0", PhpLevelSource::Require));
assert_eq!(level_of_api.auto, level_of_api.effective);
assert_eq!(level_of_api.member.as_deref(), Some(api.as_path()));
// The member's own settings, not the workspace's.
let level_of_legacy = level(legacy.join("index.php")).await;
assert_eq!(level_of_legacy.effective, found("8.3.0", PhpLevelSource::Settings));
assert_eq!(level_of_legacy.auto, found("8.0.5", PhpLevelSource::Platform));
// Outside every member: the workspace's own.
let level_elsewhere = level(base.join("elsewhere.php")).await;
assert_eq!(level_elsewhere.effective, found("8.2.0", PhpLevelSource::Require));
assert_eq!(level_elsewhere.member, None);
host.close_project("main");
}
-30
Переглянути файл
@@ -8,7 +8,6 @@ use ide_language::{LanguageRegistry, Syntax};
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::Ordering;
@@ -65,14 +64,6 @@ pub struct IndexStatus {
pub symbols: u32,
}
/// How many indexed files share an extension (lower case, without the dot).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct ExtensionCount {
pub extension: String,
pub files: u32,
}
pub struct ProjectIndex {
shared: Arc<Shared>,
worker: Mutex<Option<JoinHandle<()>>>,
@@ -168,27 +159,6 @@ impl ProjectIndex {
}
}
/// The extensions of the indexed files, most common first: the project's file
/// types, for suggestions such as Find in Files' file masks. Dotfiles
/// (`.gitignore`) have no extension.
pub fn file_extensions(&self) -> Vec<ExtensionCount> {
let d = self.shared.data.read();
let mut counts: HashMap<String, u32> = HashMap::new();
for file in d.files.iter().flatten() {
let name = &file.rel[file.name_start as usize..];
if let Some((stem, extension)) = name.rsplit_once('.')
&& !stem.is_empty()
&& !extension.is_empty()
{
*counts.entry(extension.to_ascii_lowercase()).or_default() += 1;
}
}
let mut out: Vec<ExtensionCount> =
counts.into_iter().map(|(extension, files)| ExtensionCount { extension, files }).collect();
out.sort_by(|a, b| b.files.cmp(&a.files).then_with(|| a.extension.cmp(&b.extension)));
out
}
/// Fuzzy file search. IDEA-like ranking: file-name matches beat directory
/// matches; `/` in the query matches path segments; recently opened files boost.
pub fn find_files(&self, query: &str, limit: usize) -> Vec<FileMatch> {
-22
Переглянути файл
@@ -111,28 +111,6 @@ fn indexes_files_and_symbols_honouring_excludes() {
assert_eq!(m.path, fx.root.join("src/main.rs"));
}
#[test]
fn counts_file_extensions_most_common_first() {
let fx = Fixture::new(&[
("src/a.rs", "fn a() {}\n"),
("src/b.RS", "fn b() {}\n"),
("src/lib.rs", "fn c() {}\n"),
("Cargo.toml", "[package]\n"),
("README.md", "# r\n"),
("docs/guide.md", "# g\n"),
(".gitignore", "target\n"),
("Makefile", "all:\n"),
("target/debug/gen.rs", "fn generated() {}\n"),
]);
let idx = fx.open();
let counts: Vec<(String, u32)> = idx.file_extensions().into_iter().map(|c| (c.extension, c.files)).collect();
assert_eq!(
counts,
[("rs".into(), 3), ("md".into(), 2), ("toml".into(), 1)],
"case-folded, excluded folders and extension-less files left out"
);
}
#[test]
fn file_ranking_is_idea_like() {
let fx = sample();
-1
Переглянути файл
@@ -105,7 +105,6 @@ pub trait HostApi: Send + Sync {
args: Vec<String>,
cwd: Option<&Path>,
) -> Result<(), HostError>;
fn open_location(&self, client: Option<&str>, path: &Path, line: u32, column: u32) -> Result<(), HostError>;
/// A setting of the plugin as JSON (project over global over the schema default).
fn setting(&self, root: Option<&Path>, key: &str) -> Option<String>;
}
-15
Переглянути файл
@@ -640,21 +640,6 @@ impl views::Host for StoreData {
let title = clip(title, crate::runtime::MAX_TITLE);
Ok(self.host.open_terminal(client.as_deref(), title, &program, args, cwd.as_deref()).map_err(to_wit))
}
fn open_location(&mut self, path: String, line: u32, column: u32) -> Fallible<()> {
if let Err(e) = self.require(Capability::ProjectRead) {
return Ok(Err(e));
}
let Some(root) = self.invocation.workspace_root.clone() else {
return Ok(Err(wit::Error::Invalid("no project is open in this window".into())));
};
let real = match sandbox::resolve_in_root(&root, &path) {
Ok(real) => real,
Err(e) => return Ok(Err(wit::Error::Invalid(e))),
};
let client = self.invocation.client.clone();
Ok(self.host.open_location(client.as_deref(), &real, line, column).map_err(to_wit))
}
}
impl settings::Host for StoreData {
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
1f7402e2b1b4602e4073eb61837c3dc8840f9a4f7275d800dbd6fcf6ce5e40c3
a50d1eb41ab8dd0c9c8d6bae8266906cd6eb5de8e6f6ca6f681990389472bb5b
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
4f6cd5b5e0c12e7dcbccf66a6ad97276bf968bc3ad26f0fd08e1f7765cbfee14
2fb6aa879562733bf5b7f11dabe8fc6a415c9ef695868fe7845417a4245d2dc8
-1
Переглянути файл
@@ -12,7 +12,6 @@ activation = ["on-view:jobs", "on-command:*"]
[capabilities]
required = ["process:jobs"]
optional = ["project.read"]
[[contributes.views]]
id = "jobs"
-2
Переглянути файл
@@ -64,8 +64,6 @@ impl Views for Jobs {
return self.follow();
}
ViewEvent::Button(b) if b == "follow" => return self.follow(),
ViewEvent::Button(b) if b == "log" => return host::open_location("jobs.log", 2, 4),
ViewEvent::Button(b) if b == "outside" => return host::open_location("../outside.log", 0, 0),
_ => return Ok(()),
}
host::refresh_view(VIEW);
+1 -1
Переглянути файл
@@ -1 +1 @@
3d4dd1b6365c7fbafdd3c1f99f4405e5ee40fc5e56c97da960adfe7af2e7edb8
25b0f419a68a3b1651d3c2774d834b05e40ede52bc5ed8c0eba6d27a204efe82
+2 -11
Переглянути файл
@@ -612,18 +612,9 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
// Intelephense reads it as `intelephense.environment.phpVersion` (`workspace/configuration`).
if name == "intelephense"
&& let Some(level) = crate::php::language_level(root, s)
&& let Some(version) = crate::php::language_level(root, s)
{
merge_init_options(cfg, json!({ "environment": { "phpVersion": level.version } }));
}
if name == "intelephense" {
if let Some(stubs) = crate::php::intelephense_stubs(root, s) {
merge_init_options(cfg, json!({ "stubs": stubs }));
}
let include_paths = crate::php::include_paths(root, s);
if !include_paths.is_empty() {
merge_init_options(cfg, json!({ "environment": { "includePaths": include_paths } }));
}
merge_init_options(cfg, json!({ "environment": { "phpVersion": version } }));
}
// Node-based servers (`#!/usr/bin/env node`) run on the selected Node.js.
+11 -177
Переглянути файл
@@ -1,53 +1,24 @@
//! The PHP language level: the one chosen in Settings › PHP, else the one the root
//! `composer.json` declares (`config.platform.php`, else the lowest version `require.php` allows);
//! the Intelephense storage that goes with it; and the stub sets and include paths Intelephense indexes.
//! and the Intelephense storage that goes with it.
use crate::apply::{merge, merge_init_options, setting_path};
use crate::apply::{merge, merge_init_options};
use ide_core::settings::Settings;
use ide_language::LanguageServerConfig;
use serde_json::{Value, json};
use std::path::Path;
/// A PHP version and where it comes from.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, specta::Type)]
#[serde(rename_all = "camelCase")]
pub struct PhpLanguageLevel {
/// `X.Y.Z`.
pub version: String,
pub source: PhpLevelSource,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, specta::Type)]
#[serde(rename_all = "camelCase")]
pub enum PhpLevelSource {
/// `languages.php.languageLevel`.
Settings,
/// `config.platform.php` of `composer.json`.
Platform,
/// The lowest version `require.php` of `composer.json` allows.
Require,
}
/// The project's PHP version: the one chosen in the settings, else [`composer_level`];
/// `None` when neither names one.
pub fn language_level(root: &Path, s: &Settings) -> Option<PhpLanguageLevel> {
/// The project's PHP version as `X.Y.Z`; `None` when neither the settings nor
/// `composer.json` name one.
pub fn language_level(root: &Path, s: &Settings) -> Option<String> {
let explicit = s.languages.php.language_level.trim();
if !explicit.is_empty() {
return version(explicit).map(|v| PhpLanguageLevel::new(v, PhpLevelSource::Settings));
return version(explicit).map(dotted);
}
composer_level(root)
}
/// The PHP version the root `composer.json` declares (the setting's Auto):
/// `config.platform.php`, else the lowest version `require.php` allows.
pub fn composer_level(root: &Path) -> Option<PhpLanguageLevel> {
let text = std::fs::read_to_string(root.join("composer.json")).ok()?;
let composer: Value = serde_json::from_str(&text).ok()?;
if let Some(platform) = composer.pointer("/config/platform/php").and_then(Value::as_str).and_then(version) {
return Some(PhpLanguageLevel::new(platform, PhpLevelSource::Platform));
}
lowest_allowed(composer.pointer("/require/php")?.as_str()?)
.map(|v| PhpLanguageLevel::new(v, PhpLevelSource::Require))
let platform = composer.pointer("/config/platform/php").and_then(Value::as_str).and_then(version);
platform.or_else(|| lowest_allowed(composer.pointer("/require/php")?.as_str()?)).map(dotted)
}
/// Gives each PHP version its own Intelephense workspace storage (below `data_dir`).
@@ -77,74 +48,10 @@ pub fn configure_intelephense_storage(cfg: &mut LanguageServerConfig, data_dir:
merge_init_options(cfg, json!({ "storagePath": storage.to_string_lossy() }));
}
/// The stub sets Intelephense loads when `stubs` is not set (Intelephense 1.18.5). Setting
/// `stubs` replaces them, so additions are sent together with these.
#[rustfmt::skip]
const DEFAULT_STUBS: &[&str] = &[
"apache", "bcmath", "bz2", "calendar", "com_dotnet", "Core", "ctype", "curl", "date", "dba", "dom", "enchant",
"exif", "fileinfo", "filter", "fpm", "ftp", "gd", "hash", "iconv", "imap", "intl", "json", "ldap", "libxml",
"mbstring", "mcrypt", "mssql", "mysqli", "oci8", "odbc", "openssl", "pcntl", "pcre", "PDO", "pgsql", "Phar",
"posix", "pspell", "random", "readline", "Reflection", "regex", "session", "shmop", "SimpleXML", "snmp", "soap",
"sockets", "sodium", "SPL", "sqlite3", "standard", "superglobals", "sybase", "sysvmsg", "sysvsem", "sysvshm",
"tidy", "tokenizer", "uri", "xml", "xmlreader", "xmlrpc", "xmlwriter", "Zend OPcache", "zip", "zlib",
];
/// Stub sets outside the defaults whose names are not lower case; the rest are the lower-case
/// extension name.
const MIXED_CASE_STUBS: &[&str] =
&["Ev", "FFI", "LuaSandbox", "Parle", "SQLite", "SaxonC", "SplType", "ZendCache", "ZendDebugger", "ZendUtils"];
/// `Zend OPcache`, `zend-opcache` and `zend_opcache` name the same stubs.
fn stub_key(name: &str) -> String {
name.chars().filter(char::is_ascii_alphanumeric).map(|c| c.to_ascii_lowercase()).collect()
}
/// The `stubs` Intelephense loads: its defaults plus a stub set for each `ext-*` that the root
/// `composer.json` requires (`require`, `require-dev`) and those in Settings › PHP. `None` when
/// that adds nothing to the defaults, so the server keeps its own.
pub fn intelephense_stubs(root: &Path, s: &Settings) -> Option<Vec<String>> {
let composer: Option<Value> =
std::fs::read_to_string(root.join("composer.json")).ok().and_then(|t| serde_json::from_str(&t).ok());
let extensions = ["require", "require-dev"]
.into_iter()
.filter_map(|section| composer.as_ref()?.get(section)?.as_object())
.flat_map(|deps| deps.keys())
.filter_map(|dep| dep.strip_prefix("ext-"))
.map(|ext| {
let key = stub_key(ext);
MIXED_CASE_STUBS
.iter()
.find(|stub| stub_key(stub) == key)
.map_or(ext.to_ascii_lowercase(), |s| s.to_string())
});
let configured = s.languages.php.stubs.iter().map(|stub| stub.trim().to_owned());
let mut stubs: Vec<String> = DEFAULT_STUBS.iter().map(|s| s.to_string()).collect();
let mut known: std::collections::HashSet<String> = stubs.iter().map(|s| stub_key(s)).collect();
for stub in extensions.chain(configured) {
if !stub.is_empty() && known.insert(stub_key(&stub)) {
stubs.push(stub);
}
}
(stubs.len() > DEFAULT_STUBS.len()).then_some(stubs)
}
/// The folders in Settings › PHP › Include paths, resolved against the project.
pub fn include_paths(root: &Path, s: &Settings) -> Vec<String> {
s.languages
.php
.include_paths
.iter()
.filter_map(|p| setting_path(root, p))
.map(|p| p.to_string_lossy().into_owned())
.collect()
}
type Version = (u32, u32, u32);
impl PhpLanguageLevel {
fn new((major, minor, patch): Version, source: PhpLevelSource) -> Self {
Self { version: format!("{major}.{minor}.{patch}"), source }
}
fn dotted((major, minor, patch): Version) -> String {
format!("{major}.{minor}.{patch}")
}
/// `7`, `7.4`, `v7.4.3`, `8.1.*`, `7.4.0-dev`: missing parts are 0.
@@ -198,18 +105,13 @@ mod tests {
use super::*;
fn level(composer: Option<&str>, explicit: &str) -> Option<String> {
levels(composer, explicit).0.map(|l| l.version)
}
/// The effective level and the composer one.
fn levels(composer: Option<&str>, explicit: &str) -> (Option<PhpLanguageLevel>, Option<PhpLanguageLevel>) {
let tmp = tempfile::tempdir().unwrap();
if let Some(composer) = composer {
std::fs::write(tmp.path().join("composer.json"), composer).unwrap();
}
let mut s = Settings::default();
s.languages.php.language_level = explicit.into();
(language_level(tmp.path(), &s), composer_level(tmp.path()))
language_level(tmp.path(), &s)
}
fn required(constraint: &str) -> Option<String> {
@@ -299,74 +201,6 @@ mod tests {
}
}
fn stubs(composer: Option<Value>, configured: &[&str]) -> Option<Vec<String>> {
let tmp = tempfile::tempdir().unwrap();
if let Some(composer) = composer {
std::fs::write(tmp.path().join("composer.json"), composer.to_string()).unwrap();
}
let mut s = Settings::default();
s.languages.php.stubs = configured.iter().map(|s| s.to_string()).collect();
intelephense_stubs(tmp.path(), &s)
}
fn added(stubs: Option<Vec<String>>) -> Vec<String> {
let stubs = stubs.expect("stubs");
assert_eq!(stubs[..DEFAULT_STUBS.len()], DEFAULT_STUBS.iter().map(|s| s.to_string()).collect::<Vec<_>>());
stubs[DEFAULT_STUBS.len()..].to_vec()
}
#[test]
fn required_extensions_and_configured_stubs_follow_the_defaults() {
let composer = json!({
"require": {"php": "^8.1", "ext-redis": "*", "ext-json": "*", "monolog/monolog": "^3"},
"require-dev": {"ext-Imagick": "*", "ext-ffi": "*", "ext-redis": "*"}
});
assert_eq!(
added(stubs(Some(composer), &[" wordpress ", "Redis", ""])),
["redis", "imagick", "FFI", "wordpress"]
);
assert_eq!(added(stubs(None, &["wordpress"])), ["wordpress"]);
}
#[test]
fn nothing_beyond_the_defaults_sends_nothing() {
assert_eq!(stubs(None, &[]), None);
assert_eq!(stubs(Some(json!({"require": {"php": "^8.1"}})), &[]), None);
// Default stub sets under their extension names: `ext-pdo`, `ext-zend-opcache`, `ext-simplexml`.
let defaults =
json!({"require": {"ext-pdo": "*", "ext-zend-opcache": "*", "ext-simplexml": "*", "ext-json": "*"}});
assert_eq!(stubs(Some(defaults), &["SPL", "core"]), None);
assert_eq!(stubs(Some(json!("not an object")), &[]), None);
}
#[test]
fn include_paths_resolve_against_the_project() {
let root = Path::new("/work/module");
let mut s = Settings::default();
s.languages.php.include_paths = vec!["../platform".into(), "/opt/prestashop".into(), " ".into()];
assert_eq!(
include_paths(root, &s),
[root.join("../platform").to_string_lossy().into_owned(), "/opt/prestashop".to_string()]
);
}
#[test]
fn each_level_names_its_source() {
let found = |version: &str, source| Some(PhpLanguageLevel { version: version.into(), source });
let require = r#"{"require": {"php": "^7.4"}}"#;
let platform = r#"{"require": {"php": "^7.4"}, "config": {"platform": {"php": "8.2.1"}}}"#;
let require_level = found("7.4.0", PhpLevelSource::Require);
assert_eq!(levels(Some(require), ""), (require_level.clone(), require_level.clone()));
let platform_level = found("8.2.1", PhpLevelSource::Platform);
assert_eq!(levels(Some(platform), ""), (platform_level.clone(), platform_level));
// An explicit level: the composer one is still what Auto would pick.
assert_eq!(levels(Some(require), "8.1"), (found("8.1.0", PhpLevelSource::Settings), require_level));
assert_eq!(levels(None, "8.1"), (found("8.1.0", PhpLevelSource::Settings), None));
assert_eq!(levels(None, ""), (None, None));
assert_eq!(levels(Some(r#"{"require": {"php": "*"}}"#), ""), (None, None));
}
#[test]
fn explicit_level_wins() {
let composer = r#"{"require": {"php": "^7.4"}, "config": {"platform": {"php": "7.4.33"}}}"#;
-24
Переглянути файл
@@ -1325,30 +1325,6 @@ fn intelephense_gets_the_php_language_level() {
assert_eq!(options(cfg), json!({"clearCache": true, "environment": {"phpVersion": "8.1.0"}}));
}
#[test]
fn intelephense_gets_the_required_stubs_and_include_paths() {
use serde_json::json;
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("composer.json"), r#"{"require": {"php": "^8.1", "ext-redis": "*"}}"#).unwrap();
let mut s = Settings::default();
s.languages.php.stubs = vec!["wordpress".into()];
s.languages.php.include_paths = vec!["../platform".into()];
let mut cfg = server("intelephense");
configure_server(&mut cfg, tmp.path(), tmp.path(), &s);
let options = serde_json::to_value(cfg.initialization_options).unwrap();
let stubs: Vec<&str> = options["stubs"].as_array().unwrap().iter().filter_map(|v| v.as_str()).collect();
assert_eq!(stubs.len(), 70);
assert_eq!((stubs[0], &stubs[68..]), ("apache", &["redis", "wordpress"][..]));
assert_eq!(
options["environment"],
json!({"phpVersion": "8.1.0", "includePaths": [tmp.path().join("../platform").to_string_lossy()]})
);
let mut other = server("phpactor");
configure_server(&mut other, tmp.path(), tmp.path(), &s);
assert_eq!(other.initialization_options, None);
}
#[test]
fn go_constraints_change_only_protocol_settings() {
use serde_json::json;
+1 -3
Переглянути файл
@@ -20,9 +20,7 @@ The fixtures are standalone: `rust-app` declares its own `[workspace]` and
The language smoke test (`crates/ide-host/tests/language_smoke.rs`) runs completion,
navigation, diagnostics, quick fixes, formatting and rename on these projects with real
language servers, and `smoke/run.test.ts` runs each project's run and test configurations
(the intentionally failing test included, then Rerun Failed Tests): when you change a
fixture, run both for that language.
language servers: when you change a fixture, run it for that language.
## Setup
-1
Переглянути файл
@@ -9,7 +9,6 @@ const config: KnipConfig = {
"scripts/**/*.ts",
"perf/**/*.ts",
"e2e/**/*.ts",
"smoke/**/*.ts",
],
// Plugins' web pages are projects of their own (own package.json, checked by plugins/build.sh and CI).
ignore: ["plugins/**/web-src/**"],
+1 -2
Переглянути файл
@@ -12,12 +12,11 @@
"tauri": "node scripts/tauri.ts",
"test": "vitest run",
"test:watch": "vitest",
"smoke": "vitest run --config smoke/vitest.config.ts",
"lint": "oxlint",
"format": "oxfmt",
"format:check": "oxfmt --check",
"knip": "knip",
"typecheck": "tsrs --noEmit && tsrs -p tsconfig.node.json --noEmit && tsrs -p perf --noEmit && tsrs -p scripts --noEmit && tsrs -p smoke --noEmit",
"typecheck": "tsrs --noEmit && tsrs -p tsconfig.node.json --noEmit && tsrs -p perf --noEmit && tsrs -p scripts --noEmit",
"gen:bindings": "cargo test -p openidea --test export_bindings",
"gen:windows-icons": "node scripts/gen-windows-icons.ts",
"gen:angular-grammar": "lezer-generator src/editor/core/cm/angular/angular.grammar --typeScript -o src/editor/core/cm/angular/parser.ts",
+17 -18
Переглянути файл
@@ -125,23 +125,23 @@ work), but 0.1 code no longer runs: rebuild it against the 1.0 SDK.
### Contribution points
| Point | Declaration | Code needed |
| --------------- | --------------------------------------------------------------------------------------------------------------------------------- | ------------- |
| `commands` | `id`, `title`, `category?`, `when?` | to run them |
| `themes` | `path` (theme JSON), `editor-scheme?` | no |
| `iconThemes` | `id`, `label`, `path` (icon theme JSON, see §5) | no |
| `languages` | `path` (`languages/<id>.toml` format, see §6) | no |
| `runDetectors` | `id`, `name`, `files`, `command`, `args?`, `test?` (§6.2) | no |
| `providers` | `kinds`, `languages` (editor providers, see _Providers_) | yes |
| `secrets` | `name`, `label`, `description?` (see _Network_) | to use them |
| `menus` | `menu` (`editor.context`, `projectView.context`, `editorTab.context`, `tools`), `command`, `when?` | no |
| `keymaps` | `command`, `key`, `mac?` (`Ctrl+Alt+C`; a chord: `Meta+K Meta+C`) | no |
| `statusBar` | `id`, `text`, `tooltip?`, `command?`, `align?`, `priority?` | no |
| `settings` | `schema` (JSON file), `title?` — one table, see _Settings_ | no |
| `views` | `id`, `title`, `icon?` (an icon name, or an SVG of the package), `location` (`left`, `right`, `bottom`), `web?` (see _Web views_) | without `web` |
| `customEditors` | `id`, `title`, `patterns` (file names), `priority` (`default`, `option`), `layout?`, `web?` | without `web` |
| `fileIcons` | `id`, `patterns` (file names), `icon` (SVG), `iconDark?` — whatever icon theme is in use | no |
| `fileTemplates` | `id`, `name`, `extension`, `path` (the new file's content; template variables work) — New menu | no |
| Point | Declaration | Code needed |
| --------------- | -------------------------------------------------------------------------------------------------- | ------------- |
| `commands` | `id`, `title`, `category?`, `when?` | to run them |
| `themes` | `path` (theme JSON), `editor-scheme?` | no |
| `iconThemes` | `id`, `label`, `path` (icon theme JSON, see §5) | no |
| `languages` | `path` (`languages/<id>.toml` format, see §6) | no |
| `runDetectors` | `id`, `name`, `files`, `command`, `args?`, `test?` (§6.2) | no |
| `providers` | `kinds`, `languages` (editor providers, see _Providers_) | yes |
| `secrets` | `name`, `label`, `description?` (see _Network_) | to use them |
| `menus` | `menu` (`editor.context`, `projectView.context`, `editorTab.context`, `tools`), `command`, `when?` | no |
| `keymaps` | `command`, `key`, `mac?` (`Ctrl+Alt+C`; a chord: `Meta+K Meta+C`) | no |
| `statusBar` | `id`, `text`, `tooltip?`, `command?`, `align?`, `priority?` | no |
| `settings` | `schema` (JSON file), `title?` — one table, see _Settings_ | no |
| `views` | `id`, `title`, `icon?`, `location` (`left`, `right`, `bottom`), `web?` (see _Web views_) | without `web` |
| `customEditors` | `id`, `title`, `patterns` (file names), `priority` (`default`, `option`), `layout?`, `web?` | without `web` |
| `fileIcons` | `id`, `patterns` (file names), `icon` (SVG), `iconDark?` — whatever icon theme is in use | no |
| `fileTemplates` | `id`, `name`, `extension`, `path` (the new file's content; template variables work) — New menu | no |
Declared contributions are live as soon as the plugin is enabled — commands
show in Find Action, menus and the status bar, shortcuts work, themes and icon
@@ -313,7 +313,6 @@ then run `openidea-plugin check`.
| `host::refresh_view(view)` | `views.refresh` | The view (or custom editors) render again; call it when the content changed. |
| `host::post_view_message(view, text)` | `views.post-message` | To the script of the view's `html` body. |
| `host::open_terminal(title, program, args)` | `views.open-terminal` | A terminal tab in the invoking window running the approved `process:<program>` in the project root: output that keeps coming, interactive sessions. |
| `host::open_location(path, line, column)` | `views.open-location` | Opens a file inside the project in an editor of the invoking window, the caret at `line`/`column` (0-based, UTF-16): a view's links to code. Needs `project.read`. |
| `host::setting(key)`, `setting_bool`, `setting_string`, `setting_number` | `settings.get` | The user's value (project over global) or the schema's default. |
`run-command` receives an optional string argument: `executeAction("plugin.<plugin id>.<command id>", "arg")`
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
9ad412cb7b853d40467c67305a1126bb87910d179ecfa1c88e13d4a900367c50
28e4bf10a41bdda011111b0e150ebe96205c57f410bad98c19eea3f1286349d6
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
49a3c6bf2511ba137457397203244bdfca3d6e10f62dbc7fde9473dab07f6457
7e015486cc916f5edbac542863373fd7204f5bcd534f6c408d5f9d2b72913862
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
c199dc52e00d3943882d532e7e6095f7b2f8d7d6026cf1ccaa685dd6300f2319
a6cf59e74595e13908e2cbf1752c58665c6963de258413c9d7332d2a7dd9cbd0
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
6047be5eeaa1330d7aa1f182e88ae2f352f244829ad9a01fdc3a2a081bdca95d
b8dde206a74b222b93e61056d4cbe403617ae240d142e01e91420a2aacdb2da4
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
7a3ee410d228d1e39155aa042237d222d23d7f5a45e261086cffc45c6ee1ad32
a681c2abd4a65d6aeb62efd514e9b170f4fca52b0c14d2d380a3b04be0a3fbc6
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
7658a95eb9fc27468cae4b1d20e3b5ab299fde478e07f69ab0fdb4cc10caf11d
3c83bc9559df54457e19e650cdd21bab9d609e22daaa1fc4f596910b70834a34
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
227a30ef0028f167a20825bdd775b15392161e641f6c68030e01d0c79e263bb5
63f1bbdf6eca5a4642cd3453ae384ff3f876de0373c12008b757a63852164b71
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
046f769822102de0d4ecec99ad41027cb792941065226716f38a6e64c50ff364
0db5cb24c358651d0e728ab3efb52286290c1a38ec379435225c935d4165ad6a
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
0b9c3572390a3caab7d47f9b975439f8dde3feff6b9044579d99b8334ac2a692
257478b050ea360c55e904f2a89c6069293139ff0d97ba860de3f29dac927787
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
0af62bcd4583d126a616cafbf2ddc80f039a3ead2b5dcb7144222b0ebc673432
21e7510d6a3712bf0f21d53a5c8d652e3c2787d89a1fc25998cde96efe124207
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
24ef150beefb05622212228e1c44cb487fffe6526776762d713f3ebdf4c02ac0
04844bfbfbcb1770f4f4742658944c592922b037b2387e9340de58ef0d9baacc
-8
Переглянути файл
@@ -245,10 +245,6 @@ mod imp {
wit::views::open_terminal(title, program, args).map_err(error)
}
pub fn open_location(path: &str, line: u32, column: u32) -> Result<(), Error> {
wit::views::open_location(path, line, column).map_err(error)
}
pub fn setting(key: &str) -> Option<String> {
wit::settings::get(key)
}
@@ -391,10 +387,6 @@ pub fn open_terminal(title: &str, program: &str, args: &[String]) -> Result<(),
imp::open_terminal(title, program, args)
}
pub fn open_location(path: &str, line: u32, column: u32) -> Result<(), Error> {
imp::open_location(path, line, column)
}
/// One of the plugin's settings (`[contributes.settings]`) as JSON: the
/// user's value (project over global) or the schema's default.
pub fn setting(key: &str) -> Option<String> {
-13
Переглянути файл
@@ -74,7 +74,6 @@ struct State {
refreshed: Vec<String>,
view_messages: Vec<(String, String)>,
terminals: Vec<MockTerminal>,
locations: Vec<(String, u32, u32)>,
settings: BTreeMap<String, String>,
}
@@ -221,10 +220,6 @@ impl MockHost {
self.state.borrow().view_messages.clone()
}
pub fn opened_locations(&self) -> Vec<(String, u32, u32)> {
self.state.borrow().locations.clone()
}
/// Terminals the plugin opened.
pub fn terminals(&self) -> Vec<MockTerminal> {
self.state.borrow().terminals.clone()
@@ -600,14 +595,6 @@ pub mod current {
})
}
pub fn open_location(path: &str, line: u32, column: u32) -> Result<(), Error> {
with(|s| {
require(s, "project.read")?;
s.locations.push((path.into(), line, column));
Ok(())
})
}
pub fn setting(key: &str) -> Option<String> {
with(|s| s.settings.get(key).cloned())
}
-4
Переглянути файл
@@ -133,10 +133,6 @@ interface views {
/// `program` (pinned by a `process:<program>` grant) with `args` in the
/// project root: long-running output (logs) and interactive sessions.
open-terminal: func(title: string, program: string, args: list<string>) -> result<_, error>;
/// Opens `path` (project-relative or absolute, inside the project) in an
/// editor of the window the call came from, the caret at `line` and
/// `column` (0-based; UTF-16 column): a view's links to code.
open-location: func(path: string, line: u32, column: u32) -> result<_, error>;
}
/// The plugin's own settings (`[contributes.settings]`), as the user set them
-73
Переглянути файл
@@ -1,73 +0,0 @@
/**
* The frontend's view of the desktop app, with a real backend: the window's Tauri runtime
* (callbacks, `Channel`s, the event plugin) in-process, and every app command sent to an
* `openidea-server` through the route remote development uses (`src/platform/tauriCore.ts`).
*/
import { setInvokeRoute } from "@/platform/tauriCore";
import { encodeArgs } from "@/platform/remote";
import { Server } from "./server";
type Callback = (message: unknown) => void;
// One runtime per page, as in the app: the frontend registers its event listeners once
// (`src/platform/ipc.ts`), so they outlive the servers connected one after another.
const callbacks = new Map<number, Callback>();
const listeners: { event: string; handler: number }[] = [];
const channels = new Map<number, { onmessage: (data: unknown) => void }>();
let nextCallback = 1;
let installed = false;
function install() {
if (installed) return;
installed = true;
const internals = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main", windowLabel: "main" } },
transformCallback(cb: Callback) {
const id = nextCallback++;
callbacks.set(id, cb);
return id;
},
unregisterCallback(id: number) {
callbacks.delete(id);
},
convertFileSrc: (path: string) => path,
// Only the window's own plugins reach this: app commands take the route below.
async invoke(cmd: string, args: Record<string, unknown> = {}) {
if (cmd === "plugin:event|listen") {
listeners.push({ event: args.event as string, handler: args.handler as number });
return listeners.length;
}
if (cmd === "plugin:window|get_all_windows") return [];
if (cmd.startsWith("plugin:")) return null;
throw { kind: "unavailable", message: `${cmd} has no route`, detail: null };
},
};
Object.assign(window, {
__TAURI_INTERNALS__: internals,
__TAURI_EVENT_PLUGIN_INTERNALS__: { unregisterListener: () => {} },
});
}
/** Connects this page's frontend to `server`; returns a function that disconnects it. */
export function connectDesktop(server: Server): () => void {
install();
channels.clear();
server.onChannel = (id, data) => channels.get(id)?.onmessage(data);
server.onEvent = (target, event) => {
if (target !== null && target !== "main") return;
for (const l of listeners) {
if (l.event === "ide://event") callbacks.get(l.handler)?.({ event: l.event, id: 0, payload: event });
}
};
setInvokeRoute((cmd, args) => {
if (cmd.startsWith("plugin:")) return null;
const { json, channels: used } = encodeArgs(args);
for (const [id, channel] of used) channels.set(id, channel as unknown as { onmessage: (data: unknown) => void });
return server.invoke(cmd, JSON.parse(json));
});
return () => {
setInvokeRoute(null);
server.onChannel = () => {};
server.onEvent = () => {};
};
}
-232
Переглянути файл
@@ -1,232 +0,0 @@
/**
* Running and testing each language's `fixtures/` project the way the Run tool window does:
* the backend detects the configurations, the run store starts them (with its test
* reporting), parses the output into the test tree, and reruns the failed tests.
*/
import { execFileSync } from "node:child_process";
import { cpSync, mkdtempSync, realpathSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, expect, test } from "vitest";
import { commands, type RunConfig } from "@/bindings";
import { onIdeEvent } from "@/platform/ipc";
import { openProject, useProject } from "@/platform/project";
import {
failedTests,
loadConfigs,
onRunExited,
rerunFailed,
resetRuns,
runtime,
startRun,
stopSession,
useRun,
waitForExit,
} from "@/features/run/store";
import { nodeStatus } from "@/features/run/testing/results";
import { connectDesktop } from "./desktop";
import { repoRoot, Server } from "./server";
interface Case {
fixture: string;
/** Runs in the project copy first (installs its dependencies). */
setup?: (root: string) => void;
/** A configuration that runs to completion printing this, or a server stopped once it prints it. */
run?: { config: string; prints: string; stop?: boolean };
tests: {
config: string;
/** The configuration with the fixture's intentionally failing test switched on. */
failing: (config: RunConfig) => RunConfig;
passed: number;
failed: string;
/** The failure's location ends with this file. */
file: string;
};
}
const env = (config: RunConfig, vars: Record<string, string>): RunConfig => ({
...config,
env: { ...config.env, ...vars },
});
const args = (config: RunConfig, extra: string[]): RunConfig => ({ ...config, args: [...config.args, ...extra] });
const CASES: Record<string, Case> = {
typescript: {
fixture: "ts-app",
setup: (root) => execFileSync("npm", ["install", "--no-audit", "--no-fund"], { cwd: root, stdio: "ignore" }),
run: { config: "npm:start", prints: "Total: $134.97" },
tests: {
config: "npm:test",
failing: (c) => env(c, { OPENIDEA_FAIL: "1" }),
passed: 4,
failed: "intentionally fails (set OPENIDEA_FAIL=1)",
file: "tests/cart.test.ts",
},
},
python: {
fixture: "python-app",
// A project venv with pytest, as the fixture's README sets it up.
setup: (root) => {
execFileSync("python3", ["-m", "venv", ".venv"], { cwd: root, stdio: "ignore" });
execFileSync(join(root, ".venv", "bin", "pip"), ["install", "-q", "pytest"], { cwd: root, stdio: "ignore" });
},
tests: {
config: "pytest",
failing: (c) => env(c, { OPENIDEA_FAIL: "1" }),
passed: 4,
failed: "test_intentionally_failing",
file: "tests/test_models.py",
},
},
rust: {
fixture: "rust-app",
run: { config: "cargo:run:inventory", prints: "Sold 3 mice, 9 left" },
tests: {
config: "cargo:test",
failing: (c) => args(c, ["--features", "failing-tests"]),
// `cargo test` stops after the failing unit tests: the integration tests don't run.
passed: 7,
failed: "intentionally_failing",
file: "src/lib.rs",
},
},
go: {
fixture: "go-app",
run: { config: "go:run:server", prints: "listening on", stop: true },
tests: {
config: "go:test",
failing: (c) => env(c, { OPENIDEA_FAIL: "1" }),
passed: 3,
failed: "TestIntentionallyFailing",
file: "store_test.go",
},
},
java: {
fixture: "java-app",
tests: {
config: "maven:test",
failing: (c) => args(c, ["-DopenideaFail=true"]),
passed: 2,
failed: "intentionallyFails",
file: "OrderBookTest.java",
},
},
kotlin: {
fixture: "kotlin-gradle",
run: { config: "gradle:run", prints: "Lent 'Kotlin in Action' until 2024-01-15" },
tests: {
config: "gradle:test",
failing: (c) => args(c, ["-PopenideaFail"]),
passed: 3,
failed: "intentionally failing",
file: "LibraryTest.kt",
},
},
};
let server: Server | null = null;
let disconnect: (() => void) | null = null;
let base = "";
afterEach(() => {
// As switching projects does: run ids restart with each server.
resetRuns();
disconnect?.();
server?.close();
if (base) rmSync(base, { recursive: true, force: true });
});
async function open(c: Case): Promise<string> {
base = realpathSync(mkdtempSync(join(tmpdir(), "openidea-smoke-")));
const root = join(base, c.fixture);
cpSync(join(repoRoot, "fixtures", c.fixture), root, { recursive: true });
c.setup?.(root);
server = await Server.start(join(base, "home"));
disconnect = connectDesktop(server);
const unsubscribe = onIdeEvent("runExited", (e) => onRunExited(e.run, e.code));
const previous = disconnect;
disconnect = () => {
unsubscribe();
previous();
};
await openProject(root);
const trusted = await commands.projectTrustSet(root, true, false);
if (trusted.status !== "ok") throw new Error(trusted.error.message);
useProject.setState({ project: { ...useProject.getState().project!, trusted: true } });
await loadConfigs();
return root;
}
function config(id: string): RunConfig {
const found = useRun.getState().configs.find((c) => c.id === id);
if (!found)
throw new Error(
`no configuration ${id}: ${useRun
.getState()
.configs.map((c) => c.id)
.join(", ")}`,
);
return found;
}
/** Runs `config` to its end; returns its session id and output. */
async function runToEnd(config: RunConfig, timeoutMs = 8 * 60_000): Promise<{ id: string; output: string[] }> {
const output: string[] = [];
const session = await startRun(config, undefined, undefined, { prepared: true, onLine: (l) => output.push(l) });
if (!session) throw new Error(`${config.id} didn't start`);
await waitForExit([session.id], timeoutMs);
const ended = useRun.getState().sessions.find((s) => s.id === session.id)!;
expect(ended.status, `${config.id} is still running:\n${output.join("\n")}`).not.toBe("running");
return { id: session.id, output };
}
async function smoke(language: string) {
const c = CASES[language]!;
await open(c);
if (c.run) {
const output: string[] = [];
const session = await startRun(config(c.run.config), undefined, undefined, {
prepared: true,
onLine: (l) => output.push(l),
});
expect(session, "the run starts").toBeTruthy();
await expect.poll(() => output.join("\n"), { timeout: 5 * 60_000 }).toContain(c.run.prints);
if (c.run.stop) await stopSession(session!.id);
await waitForExit([session!.id], 60_000);
const ended = useRun.getState().sessions.find((s) => s.id === session!.id)!;
expect(ended.status, output.join("\n")).toBe("finished");
if (!c.run.stop) expect(ended.exitCode, output.join("\n")).toBe(0);
}
// Tests, with the intentionally failing one switched on: one failure, located, the rest passed.
const { id, output } = await runToEnd(c.tests.failing(config(c.tests.config)));
const tests = runtime(id)!.tests!;
const log = `\n--- output ---\n${output.slice(-80).join("\n")}`;
expect(tests.counts(), log).toMatchObject({ passed: c.tests.passed, failed: 1 });
const failure = tests.firstFailure()!;
expect(failure.name, log).toBe(c.tests.failed);
expect(failure.location?.path ?? "", `${JSON.stringify(failure.location)}${log}`).toMatch(
new RegExp(`${c.tests.file.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}$`),
);
expect(failure.output.join("\n"), "the failure's message is kept").not.toBe("");
expect(failedTests(id)).toHaveLength(1);
// Rerun Failed Tests runs that one test only.
const rerunOutput: string[] = [];
const before = useRun.getState().sessions.find((s) => s.id === id)!.startedAt;
expect(rerunFailed(id), "Rerun Failed Tests is offered").toBe(true);
const ended = () => {
const s = useRun.getState().sessions.find((s) => s.id === id)!;
return s.startedAt > before && s.endedAt !== null && s.endedAt >= s.startedAt;
};
await expect.poll(ended, { timeout: 8 * 60_000 }).toBe(true);
const again = runtime(id)!.tests!;
rerunOutput.push(...again.roots.map((r) => `${r.name}: ${nodeStatus(r)}`));
expect(again.counts(), rerunOutput.join("\n")).toMatchObject({ passed: 0, failed: 1 });
expect(again.firstFailure()?.name).toBe(c.tests.failed);
}
for (const language of Object.keys(CASES)) {
test(language, () => smoke(language));
}
-132
Переглянути файл
@@ -1,132 +0,0 @@
/**
* `openidea-server --stdio`, spoken to as the desktop app does in remote development:
* JSON-RPC with `Content-Length` framing over the server's stdin / stdout.
*/
import { type ChildProcessWithoutNullStreams, spawn } from "node:child_process";
import { dirname, join } from "node:path";
const PROTOCOL_VERSION = 2;
const WINDOW = "main";
// Not `new URL(…, import.meta.url)`: the jsdom environment's `URL` isn't Node's.
export const repoRoot = join(dirname(import.meta.filename), "..");
/** The server binary: `OPENIDEA_SERVER`, else the workspace's debug build. */
function serverBinary(): string {
const exe = process.platform === "win32" ? ".exe" : "";
return process.env.OPENIDEA_SERVER ?? join(repoRoot, "target", "debug", `openidea-server${exe}`);
}
interface Pending {
resolve: (value: unknown) => void;
reject: (error: unknown) => void;
}
export class Server {
private nextId = 1;
private readonly pending = new Map<number, Pending>();
private buffer = Buffer.alloc(0);
private readonly stderr: string[] = [];
/** `channel` notifications: a value streamed to the `Channel` with this id. */
onChannel: (id: number, data: unknown) => void = () => {};
/** `event` notifications: an `IdeEvent` for a window (`null`: every window). */
onEvent: (window: string | null, event: unknown) => void = () => {};
private constructor(private readonly child: ChildProcessWithoutNullStreams) {
child.stdout.on("data", (chunk: Buffer) => this.receive(chunk));
child.stderr.on("data", (chunk: Buffer) => {
this.stderr.push(chunk.toString());
if (this.stderr.length > 200) this.stderr.shift();
});
child.on("exit", (code) => {
for (const p of this.pending.values()) p.reject(new Error(`openidea-server exited (${code}): ${this.log()}`));
this.pending.clear();
});
}
/** Starts a server whose settings, caches and tools live under `home`. */
static async start(home: string, env: Record<string, string> = {}): Promise<Server> {
const child = spawn(serverBinary(), ["--stdio"], {
env: { ...process.env, OPENIDEA_SERVER_HOME: home, ...env },
stdio: ["pipe", "pipe", "pipe"],
});
const server = new Server(child);
await server.request("initialize", { version: PROTOCOL_VERSION });
return server;
}
/** The tail of the server's log, for failure messages. */
log(): string {
return this.stderr.join("").split("\n").slice(-40).join("\n");
}
/** Runs an IPC command; rejects with the command's `IdeError`. */
async invoke(cmd: string, args: unknown): Promise<unknown> {
try {
return await this.request("invoke", { window: WINDOW, cmd, args });
} catch (e) {
const message = (e as { message?: string }).message ?? String(e);
try {
throw JSON.parse(message);
} catch (parsed) {
if (parsed instanceof SyntaxError) throw { kind: "protocol", message, detail: null };
throw parsed;
}
}
}
close() {
this.child.stdin.end();
this.child.kill();
}
private request(method: string, params: unknown): Promise<unknown> {
const id = this.nextId++;
return new Promise((resolve, reject) => {
this.pending.set(id, { resolve, reject });
this.send({ jsonrpc: "2.0", id, method, params });
});
}
private send(message: unknown) {
const body = Buffer.from(JSON.stringify(message));
this.child.stdin.write(`Content-Length: ${body.length}\r\n\r\n`);
this.child.stdin.write(body);
}
private receive(chunk: Buffer) {
this.buffer = Buffer.concat([this.buffer, chunk]);
for (;;) {
const end = this.buffer.indexOf("\r\n\r\n");
if (end < 0) return;
const length = /content-length:\s*(\d+)/i.exec(this.buffer.subarray(0, end).toString())?.[1];
if (!length) throw new Error(`bad header: ${this.buffer.subarray(0, end)}`);
const start = end + 4;
if (this.buffer.length < start + Number(length)) return;
const message = JSON.parse(this.buffer.subarray(start, start + Number(length)).toString());
this.buffer = this.buffer.subarray(start + Number(length));
this.dispatch(message);
}
}
private dispatch(message: {
id?: number;
method?: string;
params?: { id?: number; data?: unknown; window?: string | null; event?: unknown };
result?: unknown;
error?: { message: string };
}) {
if (message.method && message.id !== undefined) {
this.send({ jsonrpc: "2.0", id: message.id, error: { code: -32601, message: "not supported" } });
} else if (message.method === "channel") {
this.onChannel(message.params!.id!, message.params!.data);
} else if (message.method === "event") {
this.onEvent(message.params!.window ?? null, message.params!.event);
} else if (message.id !== undefined) {
const pending = this.pending.get(message.id);
this.pending.delete(message.id);
if (message.error) pending?.reject(message.error);
else pending?.resolve(message.result);
}
}
}
-8
Переглянути файл
@@ -1,8 +0,0 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"types": ["node", "vite/client"],
"paths": { "@/*": ["../src/*"] }
},
"include": ["./**/*.ts", "../src/**/*.d.ts"]
}
-20
Переглянути файл
@@ -1,20 +0,0 @@
/**
* Backend smoke tests (`pnpm smoke`): the frontend's own modules driving a real
* `openidea-server` and real toolchains. Not part of `pnpm test`: they need the server
* built (`cargo build -p ide-host --bin openidea-server`) and each language's tools.
*/
import { defineConfig, mergeConfig } from "vitest/config";
import viteConfig from "../vite.config.ts";
export default mergeConfig(
viteConfig({ command: "serve", mode: "test" }),
defineConfig({
test: {
include: ["smoke/**/*.test.ts"],
testTimeout: 10 * 60_000,
hookTimeout: 5 * 60_000,
// Each file starts a server and toolchains of its own.
fileParallelism: false,
},
}),
);
-3
Переглянути файл
@@ -186,7 +186,6 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
caches::caches_schedule_invalidation,
caches::app_restart,
nav::index_status,
nav::index_file_extensions,
nav::spring_route_sources,
nav::find_files,
nav::find_dirs,
@@ -343,7 +342,6 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
run::run_close_stdin,
run::run_resize,
run::run_gradle_jvm_args_script,
run::run_gradle_init_script,
run::run_tomcat_home,
run::run_tomcat_artifacts,
run::run_tomcat_build,
@@ -387,7 +385,6 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
tools::jdk_download,
sdk::sdk_detect,
sdk::sdk_python_effective,
sdk::sdk_php_language_level,
sdk::sdk_project_libraries,
sdk::sdk_locate_tools,
sdk::sdk_python_create_venv,
+1 -7
Переглянути файл
@@ -4,7 +4,7 @@ use crate::state::AppState;
use ide_core::{DocId, IdeResult, IpcPath, Pos};
#[allow(unused_imports)]
pub use ide_host::ops::nav::*;
use ide_index::{ExtensionCount, FileMatch, IndexStatus, SymbolFilter, SymbolMatch};
use ide_index::{FileMatch, IndexStatus, SymbolFilter, SymbolMatch};
use ide_language::FileReference;
use ide_workspace::file_refs::PathCompletion;
use std::path::PathBuf;
@@ -16,12 +16,6 @@ pub fn index_status(window: Window, state: State<'_, AppState>) -> IdeResult<Ind
ide_host::ops::nav::index_status(&state.host, window.label())
}
#[tauri::command]
#[specta::specta]
pub fn index_file_extensions(window: Window, state: State<'_, AppState>) -> IdeResult<Vec<ExtensionCount>> {
ide_host::ops::nav::index_file_extensions(&state.host, window.label())
}
#[tauri::command]
#[specta::specta]
pub fn find_files(window: Window, state: State<'_, AppState>, query: String, limit: u32) -> IdeResult<Vec<FileMatch>> {
-12
Переглянути файл
@@ -189,18 +189,6 @@ pub async fn run_gradle_jvm_args_script(
ide_host::ops::run::run_gradle_jvm_args_script(&state.host, window.label(), jvm_args).await
}
/// Writes one of the IDE's Gradle init scripts where the build runs; returns its path.
#[tauri::command]
#[specta::specta]
pub async fn run_gradle_init_script(
window: Window,
state: State<'_, AppState>,
name: String,
text: String,
) -> IdeResult<String> {
ide_host::ops::run::run_gradle_init_script(&state.host, window.label(), name, text).await
}
/// Results from the JUnit XML reports (Surefire, Failsafe, Gradle) of the module at
/// `module` (relative to the project root) written since `since_ms` (Unix epoch, ms).
#[tauri::command]
-11
Переглянути файл
@@ -24,17 +24,6 @@ pub fn sdk_python_effective(window: Window, state: State<'_, AppState>) -> IdeRe
ide_host::ops::sdk::sdk_python_effective(&state.host, window.label())
}
/// The PHP language level of the project `path` belongs to: the effective one and Auto's.
#[tauri::command]
#[specta::specta]
pub async fn sdk_php_language_level(
window: Window,
state: State<'_, AppState>,
path: PathBuf,
) -> IdeResult<ide_host::ops::sdk::PhpLanguageLevels> {
ide_host::ops::sdk::sdk_php_language_level(&state.host, window.label(), path).await
}
/// SDK / library source folders shown under "External Libraries" in the Project view,
/// with the Maven / Gradle dependency jars of the build model.
#[tauri::command]
+1 -53
Переглянути файл
@@ -325,7 +325,6 @@ export const commands = {
/** Quits through every window's unsaved-changes check, then starts again. */
appRestart: () => __TAURI_INVOKE<void>("app_restart"),
indexStatus: () => typedError<IndexStatus, IdeError>(__TAURI_INVOKE("index_status")),
indexFileExtensions: () => typedError<ExtensionCount[], IdeError>(__TAURI_INVOKE("index_file_extensions")),
/** Spring Web mapping sources for the request-path index of Search Everywhere. */
springRouteSources: () => typedError<RouteSource[], IdeError>(__TAURI_INVOKE("spring_route_sources")),
findFiles: (query: string, limit: number) => typedError<FileMatch[], IdeError>(__TAURI_INVOKE("find_files", { query, limit })),
@@ -630,8 +629,6 @@ export const commands = {
runResize: (id: RunId, cols: number, rows: number) => typedError<null, IdeError>(__TAURI_INVOKE("run_resize", { id, cols, rows })),
/** Writes the Gradle init script adding `jvm_args` to the JVMs the build forks; returns its path. */
runGradleJvmArgsScript: (jvmArgs: string[]) => typedError<string, IdeError>(__TAURI_INVOKE("run_gradle_jvm_args_script", { jvmArgs })),
/** Writes one of the IDE's Gradle init scripts where the build runs; returns its path. */
runGradleInitScript: (name: string, text: string) => typedError<string, IdeError>(__TAURI_INVOKE("run_gradle_init_script", { name, text })),
runTomcatHome: (home: string) => typedError<TomcatHome, IdeError>(__TAURI_INVOKE("run_tomcat_home", { home })),
runTomcatArtifacts: () => typedError<WebArtifact[], IdeError>(__TAURI_INVOKE("run_tomcat_artifacts")),
runTomcatBuild: (config: RunConfig_Deserialize) => typedError<({
@@ -750,8 +747,6 @@ export const commands = {
sdkDetect: (kind: SdkKind) => typedError<Sdk[], IdeError>(__TAURI_INVOKE("sdk_detect", { kind })),
/** The interpreter the project uses: the configured one, else its virtualenv. */
sdkPythonEffective: () => typedError<string | null, IdeError>(__TAURI_INVOKE("sdk_python_effective")),
/** The PHP language level of the project `path` belongs to: the effective one and Auto's. */
sdkPhpLanguageLevel: (path: string) => typedError<PhpLanguageLevels, IdeError>(__TAURI_INVOKE("sdk_php_language_level", { path })),
/**
* SDK / library source folders shown under "External Libraries" in the Project view,
* with the Maven / Gradle dependency jars of the build model.
@@ -3418,12 +3413,6 @@ export type ExpressionAt = {
hasError: boolean,
};
/** How many indexed files share an extension (lower case, without the dot). */
export type ExtensionCount = {
extension: string,
files: number,
};
/** A formatter that runs outside the language servers, with its own settings group. */
export type ExternalFormatter = "prettier" | "oxfmt";
@@ -5394,37 +5383,6 @@ export type PathCompletion = {
dir: boolean,
};
/** A PHP version and where it comes from. */
export type PhpLanguageLevel = {
/** `X.Y.Z`. */
version: string,
source: PhpLevelSource,
};
/**
* The PHP language level of the project `path` belongs to (a workspace member, by path, as
* the language server configuration picks it).
*/
export type PhpLanguageLevels = {
/** The one Intelephense checks against; `None`: its default. */
effective: PhpLanguageLevel | null,
/** The one Auto picks, from `composer.json`. */
auto: PhpLanguageLevel | null,
/**
* The workspace member `path` belongs to: its own settings choose the level, not the
* workspace's. `None`: the opened project.
*/
member: IpcPath | null,
};
export type PhpLevelSource =
/** `languages.php.languageLevel`. */
"settings" |
/** `config.platform.php` of `composer.json`. */
"platform" |
/** The lowest version `require.php` of `composer.json` allows. */
"require";
export type PhpSettings = {
/** `php` CLI executable; empty = the one on `PATH`. */
interpreter?: string,
@@ -5433,16 +5391,6 @@ export type PhpSettings = {
* `composer.json` (`config.platform.php`, else the lowest version `require.php` allows).
*/
languageLevel?: string,
/**
* Folders outside the project whose code the language server indexes too (a platform a
* module extends); absolute, `~/`, or relative to the project.
*/
includePaths?: string[],
/**
* Intelephense stub sets loaded on top of its defaults and the `ext-*` entries of
* `composer.json` (`wordpress`).
*/
stubs?: string[],
};
/** The focused editor when a plugin command is invoked. */
@@ -5480,7 +5428,7 @@ export type PluginEvent =
/** For the script of a view's `html` body. */
{ type: "viewMessage"; pluginId: string; view: string; message: string } |
/** Open a terminal running `program` (already approved and verified). */
{ type: "openTerminal"; pluginId: string; title: string; program: IpcPath; args: string[]; cwd: IpcPath } | { type: "openLocation"; pluginId: string; path: IpcPath; line: number; column: number } |
{ type: "openTerminal"; pluginId: string; title: string; program: IpcPath; args: string[]; cwd: IpcPath } |
/**
* Plugin languages, or the servers they may start, changed: re-fetch
* `languages` (the host re-detects open documents: [`crate::Host::plugin_languages_changed`]).
+10 -40
Переглянути файл
@@ -39,14 +39,7 @@ import { setContext } from "@/platform/context";
import { showFindResults, type FindResultsSource } from "@/workbench/contributions";
import { relativePath, useProject } from "@/platform/project";
import { tx } from "@/platform/i18n";
import {
bindingsFor,
formatBinding,
hasPrimaryModifier,
normalizeBinding,
registerKeyClaim,
shortcutLabel,
} from "@/platform/keymap";
import { bindingsFor, hasPrimaryModifier, normalizeBinding, registerKeyClaim, shortcutLabel } from "@/platform/keymap";
/**
* The last search (IDEA's find-in-file model): a newly opened bar starts from it and ⌘G
@@ -523,12 +516,7 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo
: [{ label: kind === "find" ? "No recent searches" : "No recent replacements", disabled: true }];
};
const filterItems: MenuItem[] = [
{
label: "Search In Selection",
shortcut: formatBinding("Alt+E"),
checked: scoped || undefined,
run: () => toggleScope(target),
},
{ label: "Search In Selection", shortcut: "⌥E", checked: scoped || undefined, run: () => toggleScope(target) },
{ kind: "separator" },
{ kind: "header", label: "Search Scope" },
...SEARCH_CONTEXTS.map((c) => ({
@@ -607,7 +595,7 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo
id: "case",
icon: "case",
title: "Match Case",
shortcut: formatBinding("Alt+C"),
shortcut: "⌥C",
pressed: opts.caseSensitive,
onToggle: () => toggle("caseSensitive"),
},
@@ -615,7 +603,7 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo
id: "word",
icon: "word",
title: "Words",
shortcut: formatBinding("Alt+W"),
shortcut: "⌥W",
pressed: opts.wholeWord,
onToggle: () => toggle("wholeWord"),
},
@@ -623,7 +611,7 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo
id: "regex",
icon: "regex",
title: "Regex",
shortcut: formatBinding("Alt+X"),
shortcut: "⌥X",
pressed: opts.regexp,
onToggle: () => toggle("regexp"),
},
@@ -637,17 +625,11 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo
<IconButton
icon="arrow-up"
title="Previous Occurrence"
shortcut={formatBinding("Shift+Enter")}
shortcut="⇧↵"
size="small"
onClick={() => run(findPrevious)}
/>
<IconButton
icon="arrow-down"
title="Next Occurrence"
shortcut={formatBinding("Enter")}
size="small"
onClick={() => run(findNext)}
/>
<IconButton icon="arrow-down" title="Next Occurrence" shortcut="↵" size="small" onClick={() => run(findNext)} />
<IconButton
ref={filterRef}
icon="filter"
@@ -683,27 +665,15 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo
/>
</div>
<div className={styles.replaceButtons}>
<Button
size="small"
title={tx`Replace (${formatBinding("Alt+P")})`}
onClick={doReplace}
disabled={!canReplace}
>
<Button size="small" title="Replace (⌥P)" onClick={doReplace} disabled={!canReplace}>
<T>Replace</T>
</Button>
<Button
size="small"
title={tx`Replace All (${formatBinding("Alt+A")})`}
onClick={doReplaceAll}
disabled={!canReplace}
>
<Button size="small" title="Replace All (⌥A)" onClick={doReplaceAll} disabled={!canReplace}>
<T>Replace All</T>
</Button>
<Button
size="small"
title={
count?.excluded ? tx`Include (${formatBinding("Alt+L")})` : tx`Exclude (${formatBinding("Alt+L")})`
}
title={count?.excluded ? "Include (⌥L)" : "Exclude (⌥L)"}
onClick={() => run(excludeCurrent)}
disabled={!canReplace || (!count?.total && !count?.excluded)}
>
-12
Переглянути файл
@@ -44,18 +44,6 @@ describe("semanticRanges", () => {
expect(semanticRanges(doc, input)).toEqual([{ from: 0, to: 3, className: "cm-sem-function" }]);
});
it("marks globals (lua-language-server's `global` modifier)", () => {
const input = {
tokenTypes: ["variable", "function"],
tokenModifiers: ["global"],
data: [0, 0, 3, 0, 1, 0, 4, 3, 1, 1],
};
expect(semanticRanges(doc, input)).toEqual([
{ from: 0, to: 3, className: "cm-sem-global" },
{ from: 4, to: 7, className: "cm-sem-function cm-sem-global" },
]);
});
it("colours a constructor (jdtls: class + `constructor`) as a function", () => {
const input = { tokenTypes: ["class"], tokenModifiers: ["constructor", "declaration"], data: [0, 0, 3, 0, 0b11] };
expect(semanticRanges(doc, input)[0]?.className).toBe("cm-sem-function cm-sem-declaration");
-1
Переглянути файл
@@ -56,7 +56,6 @@ const MODIFIER_CLASS: Record<string, string> = {
declaration: "declaration",
definition: "declaration",
defaultLibrary: "builtin",
global: "global",
};
/** Number of `--syn-rainbow-<n>` colours (IDEA's five semantic highlighting colours). */
-2
Переглянути файл
@@ -361,8 +361,6 @@ export const lspTheme = EditorView.theme({
".cm-sem-parameter": { color: "var(--syn-param, var(--syn-variable))" },
".cm-sem-self": { color: "var(--syn-self, var(--syn-keyword))" },
".cm-sem-keyword": { color: "var(--syn-keyword)", fontWeight: "var(--syn-keyword-bold, inherit)" },
// Before the builtin rule: library globals (`print`, `string`) keep the predefined colour.
".cm-sem-global:not(.cm-sem-function)": { color: "var(--syn-global, inherit)" },
".cm-sem-builtin:not(.cm-sem-function)": { color: "var(--syn-builtin, inherit)" },
".cm-sem-static": { fontStyle: "var(--syn-static-italic, italic)" },
".cm-sem-python-static": { fontStyle: "var(--syn-python-static-italic, normal)" },
-1
Переглянути файл
@@ -20,7 +20,6 @@ describe("findColors", () => {
it("skips names that are no property value, keywords and non-colors", () => {
expect(texts(".red, #main { white-space: nowrap; color: inherit }", "css")).toEqual([]);
expect(texts("@media screen { }", "css")).toEqual([]);
expect(texts(" color: $white; background: var(--off-white) off-white;", "scss")).toEqual([]);
expect(texts(" color: #12345;", "css")).toEqual([]);
});
+2 -11
Переглянути файл
@@ -27,10 +27,7 @@ const PROSE = new Set(["markdown", "plaintext", "text", "restructuredtext", "asc
const HEX = String.raw`#(?:[0-9a-fA-F]{8}|[0-9a-fA-F]{6}|[0-9a-fA-F]{3,4})(?![\w-])`;
const NUMBER = String.raw`[-+]?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?`;
const FUNCTION = String.raw`\b(?:rgba?|hsla?)\(\s*${NUMBER}(?:deg|%)?(?:\s*[,\s]\s*${NUMBER}%?){2}(?:\s*[,/]\s*${NUMBER}%?)?\s*\)`;
// No lookbehind (WebKit before 16.4 can't parse it): a name's preceding character is checked in code.
const COLOR_RE = new RegExp(`${FUNCTION}|${HEX}|[a-zA-Z]{3,20}(?![\\w(-])`, "g");
/** Before a name, these make it part of a selector, variable or longer word (`.red`, `$white`, `off-white`). */
const NAME_PREFIX = /[\w.#$@-]/;
const COLOR_RE = new RegExp(`${FUNCTION}|${HEX}|(?<![\\w.#$@-])[a-zA-Z]{3,20}(?![\\w(-])`, "g");
/** Global keywords and words that are valid colors but say nothing about one. */
const NOT_COLORS = new Set(["inherit", "initial", "unset", "revert", "currentcolor", "transparent"]);
@@ -56,13 +53,7 @@ export function findColors(line: string, language: string, isColorName: (word: s
: "name";
if (format === "name") {
// A property value (`color: red`), not a property, selector or at-rule.
if (
!sheet ||
(from > 0 && NAME_PREFIX.test(line[from - 1]!)) ||
NOT_COLORS.has(text.toLowerCase()) ||
!/:\s*(?:\S+\s+)*$/.test(line.slice(0, from))
)
continue;
if (!sheet || NOT_COLORS.has(text.toLowerCase()) || !/:\s*(?:\S+\s+)*$/.test(line.slice(0, from))) continue;
if (!isColorName(text)) continue;
} else if (format === "hex" && !looseHex && !/["'`]$/.test(line.slice(0, from))) continue;
out.push({ from, to: from + text.length, text, format });
+1 -12
Переглянути файл
@@ -54,7 +54,7 @@ const { isJavaDebuggable, javaAttachConfig, javaLaunchConfig } = await import(".
const app: RunConfig = {
id: "application:a.Main",
name: "Main",
kind: "application",
kind: "spring-boot",
command: "java",
args: ["-Xmx1g", "-cp", "${classpath}", "a.Main", "--port", "8081 x"],
cwd: "api",
@@ -93,17 +93,6 @@ describe("Java debugging (java-debug through jdtls)", () => {
});
});
it("debugs Spring Boot with coloured console output, as Run does", async () => {
const boot = { ...app, kind: "spring-boot" };
expect(JSON.parse((await javaLaunchConfig(boot, "/p")).extraJson!).vmArgs).toBe(
"-Dspring.output.ansi.enabled=always -Xmx1g",
);
const own = { ...boot, args: ["-Dspring.output.ansi.enabled=never", ...app.args] };
expect(JSON.parse((await javaLaunchConfig(own, "/p")).extraJson!).vmArgs).toBe(
"-Dspring.output.ansi.enabled=never -Xmx1g",
);
});
it("passes the configuration's VM options to java-debug's vmArgs, before the main class", async () => {
const args = [
"-Ddemo.flag=on",
-21
Переглянути файл
@@ -79,27 +79,6 @@ describe("run config → launch config", () => {
expect(extra(globalPytest).python).toBe("python3");
});
it("debugpy: uv / poetry run the debuggee in the project's environment", () => {
const debug = (command: string, args: string[]) =>
launchConfigFor(rc({ kind: "python", command, args, debugAdapter: "debugpy" }), "/p")!;
const script = debug("uv", ["run", "python", "main.py", "-v"]);
expect(script.program).toBe("/p/main.py");
expect(script.args).toEqual(["-v"]);
expect(extra(script)).toMatchObject({ python: ["uv", "run", "python"], debugLauncherPython: "python3" });
expect(extra(script).module).toBeUndefined();
const mod = debug("poetry", ["run", "python3", "-m", "app"]);
expect(extra(mod)).toMatchObject({ module: "app", python: ["poetry", "run", "python3"] });
const tool = debug("uv", ["run", "pytest", "-x"]);
expect(extra(tool)).toMatchObject({ module: "pytest", python: ["uv", "run", "python"] });
expect(tool.args).toEqual(["-x"]);
const django = debug("pdm", ["run", "python", "manage.py", "runserver"]);
expect(extra(django)).toMatchObject({ django: true, python: ["pdm", "run", "python"] });
});
it("js-debug: npm scripts run through the package manager, node scripts directly", () => {
const npm = launchConfigFor(
rc({ kind: "npm", command: "pnpm", args: ["run", "dev"], cwd: "web", debugAdapter: "js-debug" }),
-81
Переглянути файл
@@ -1,81 +0,0 @@
import { beforeEach, expect, it, vi } from "vitest";
import { useProject } from "@/platform/project";
import type { LaunchConfig } from "@/platform/ipc";
import {
provideNotificationService,
provideToolWindowService,
type ToolWindowService,
} from "@/workbench/contributions";
import { adoptSession, handleDebugEvent, startSession, useDebug } from "../state";
const ipc = vi.hoisted(() => ({
debugStart: vi.fn(),
}));
vi.mock("@/platform/ipc", async (original) => {
const real = await original<typeof import("@/platform/ipc")>();
return { ...real, isTauri: () => true, commands: { ...real.commands, ...ipc } };
});
const attach: LaunchConfig = {
name: "AppKt",
adapter: "kotlin-debug-adapter",
request: "attach",
program: null,
args: [],
cwd: "/p",
env: {},
extraJson: JSON.stringify({ hostName: "127.0.0.1", port: 35549 }),
};
const notify = vi.fn();
beforeEach(() => {
useDebug.setState({ sessions: {}, active: null, console: {} });
useProject.setState({ project: { root: "/p" } as never });
provideNotificationService({ notify });
provideToolWindowService({ show: vi.fn() } as unknown as ToolWindowService);
vi.clearAllMocks();
// The adapter's session announces itself, then the attach fails: the JVM is gone.
ipc.debugStart.mockImplementation(async () => {
handleDebugEvent(43, { kind: "started", name: "AppKt", adapter: "kotlin-debug-adapter", parent: null });
return { status: "error", error: { kind: "internal", message: "attach failed: Internal error.", data: null } };
});
});
/** A finished session that debugged a JVM of run 7. */
function finished(endedAgoMs: number) {
adoptSession(1, { name: "AppKt", process: 7 });
handleDebugEvent(1, { kind: "terminated" });
useDebug.setState((s) => ({
sessions: { ...s.sessions, 1: { ...s.sessions[1]!, endedAt: Date.now() - endedAgoMs } },
}));
}
it("ignores a failed attach to the port a JVM announced as its debugger detached", async () => {
finished(100);
expect(await startSession(attach, { process: 7, rerunnable: false })).toBeNull();
expect(notify).not.toHaveBeenCalled();
const { sessions, active } = useDebug.getState();
expect(Object.keys(sessions)).toEqual(["1"]);
expect(active).toBe(1);
});
it("reports a failed attach to a JVM of another run, or long after the last session ended", async () => {
finished(100);
await startSession(attach, { process: 8, rerunnable: false });
expect(notify).toHaveBeenCalledWith(expect.objectContaining({ title: "Cannot start debugger for AppKt" }));
notify.mockClear();
useDebug.setState({ sessions: {}, active: null, console: {} });
finished(60_000);
await startSession(attach, { process: 7, rerunnable: false });
expect(notify).toHaveBeenCalledWith(expect.objectContaining({ title: "Cannot start debugger for AppKt" }));
expect(useDebug.getState().sessions[1]).toBeUndefined();
});
it("replaces the finished session once an attach soon after it succeeds", async () => {
finished(100);
ipc.debugStart.mockResolvedValueOnce({ status: "ok", data: 44 });
expect(await startSession(attach, { process: 7, rerunnable: false })).toBe(44);
expect(Object.keys(useDebug.getState().sessions)).toEqual(["44"]);
expect(notify).not.toHaveBeenCalled();
});
+2 -3
Переглянути файл
@@ -7,7 +7,6 @@
import { executeAction } from "@/platform/actions";
import { call, commands, IpcError, nextRequestId, type LaunchConfig, type RunConfig } from "@/platform/ipc";
import {
consoleVmArgs,
formatCompileErrors,
isJvmApplication,
joinJavaArgs,
@@ -118,7 +117,7 @@ export async function javaLaunchConfig(
classPaths,
modulePaths: info.modulePaths,
javaExec: resolved.command,
vmArguments: [...consoleVmArgs(rc), ...parsed.vmArgs],
vmArguments: parsed.vmArgs,
programArgs: parsed.programArgs,
}),
};
@@ -140,7 +139,7 @@ export async function javaLaunchConfig(
classPaths,
modulePaths: info.modulePaths,
javaExec: resolved.command === "java" ? undefined : resolved.command,
vmArgs: joinJavaArgs([...consoleVmArgs(rc), ...parsed.vmArgs]),
vmArgs: joinJavaArgs(parsed.vmArgs),
args: joinJavaArgs(parsed.programArgs),
// java-debug spawns the JVM itself: it must shorten a classpath too long for the OS the same way Run does.
shortenCommandLine: info.shortenCommandLine ?? "none",
+13 -28
Переглянути файл
@@ -58,20 +58,15 @@ function cargoLaunch(rc: RunConfig, cwd: string, adapter: string): LaunchConfig
};
}
const PYTHON_NAME = /^python[\d.]*(\.exe)?$/;
function pythonFor(rc: RunConfig, cwd: string): string {
const cmd = rc.command;
const name = cmd.split("/").pop() ?? cmd;
if (PYTHON_NAME.test(name)) return resolveCommand(cmd, cwd);
if (/^python[\d.]*(\.exe)?$/.test(name)) return resolveCommand(cmd, cwd);
// A venv tool such as `.venv/bin/pytest`: use the interpreter next to it.
if (cmd.includes("/")) return resolveCommand(cmd.slice(0, cmd.lastIndexOf("/") + 1) + "python", cwd);
return "python3";
}
/** Project managers whose `run` executes in the project's environment (`uv run python …`). */
const PYTHON_RUNNERS = new Set(["uv", "poetry", "pdm", "pipenv", "hatch", "rye"]);
function debugpyLaunch(rc: RunConfig, cwd: string): LaunchConfig {
const out = base(rc, "debugpy", cwd);
const dbg = workflowSettings().debugger;
@@ -83,29 +78,19 @@ function debugpyLaunch(rc: RunConfig, cwd: string): LaunchConfig {
redirectOutput: true,
};
if (dbg.python.gevent) extra.gevent = true;
const name = (rc.command.split("/").pop() ?? rc.command).replace(/\.exe$/, "");
let args = rc.args;
let tool: string | null = PYTHON_NAME.test(name) ? null : name;
if (PYTHON_RUNNERS.has(name) && args[0] === "run" && args[1]) {
// The debuggee runs through the manager (`uv run python <debugpy> …`) to get the project's
// environment; the adapter and its launcher need a plain interpreter.
const python = PYTHON_NAME.test(args[1]) ? args[1] : "python";
extra.python = [resolveCommand(rc.command, cwd), "run", python];
extra.debugLauncherPython = "python3";
tool = PYTHON_NAME.test(args[1]) ? null : args[1];
args = args.slice(2);
}
if (tool) {
const name = rc.command.split("/").pop() ?? rc.command;
const isPython = /^python[\d.]*(\.exe)?$/.test(name);
if (!isPython) {
// A console script (`pytest`, `uvicorn`, …): run it as a module.
extra.module = tool;
out.args = [...args];
} else if (args[0] === "-m" && args[1]) {
extra.module = args[1];
out.args = args.slice(2);
} else if (args[0]) {
out.program = join(cwd, args[0]);
out.args = args.slice(1);
if (args[0].endsWith("manage.py")) extra.django = true;
extra.module = name.replace(/\.exe$/, "");
out.args = [...rc.args];
} else if (rc.args[0] === "-m" && rc.args[1]) {
extra.module = rc.args[1];
out.args = rc.args.slice(2);
} else if (rc.args[0]) {
out.program = join(cwd, rc.args[0]);
out.args = rc.args.slice(1);
if (rc.args[0].endsWith("manage.py")) extra.django = true;
}
out.extraJson = JSON.stringify(extra);
return out;
+12 -62
Переглянути файл
@@ -38,8 +38,6 @@ export interface DebugSession {
/** Originating configuration, retained for toolbar targeting and prepared debug reruns. */
runConfig?: RunConfig;
startedAt?: number;
/** When it terminated. */
endedAt?: number;
adapter: string;
parent: DebugSessionId | null;
/** Launch configuration (root sessions), used by Rerun. */
@@ -225,58 +223,16 @@ function ownSession(id: DebugSessionId, event: DebugEvent): DebugSession | null
return event.kind === "started" ? adoptSession(id, { name: event.name, adapter: event.adapter }) : adoptSession(id);
}
/**
* A start finished (`id` on success): sessions no start claimed are failed starts' leftovers,
* kept as terminated or, with `discard`, removed.
*/
function settleStart(id: DebugSessionId | null, discard = false) {
/** A start finished (`id` on success): sessions no start claimed are failed starts' leftovers. */
function settleStart(id: DebugSessionId | null) {
pendingStarts = Math.max(0, pendingStarts - 1);
if (id != null) provisional.delete(id);
if (pendingStarts > 0) return;
const leftovers = [...provisional];
provisional.clear();
if (discard) {
useDebug.setState((st) => {
const sessions = { ...st.sessions };
const console = { ...st.console };
for (const s of leftovers) {
delete sessions[s];
delete console[s];
ansiStreams.delete(s);
}
return { sessions, console, active: st.active != null && sessions[st.active] ? st.active : null };
});
publishContext();
return;
}
for (const s of leftovers) if (isLive(useDebug.getState().sessions[s])) markTerminated(s);
}
/** Drops finished sessions; running ones stay (multiple concurrent sessions are fine). */
function dropFinished() {
useDebug.setState((s) => {
const sessions = Object.fromEntries(Object.entries(s.sessions).filter(([, v]) => isLive(v)));
const consoleLines = Object.fromEntries(Object.entries(s.console).filter(([k]) => sessions[+k]));
for (const id of ansiStreams.keys()) if (!sessions[id]) ansiStreams.delete(id);
return { sessions, console: consoleLines, active: s.active != null && sessions[s.active] ? s.active : null };
});
publishContext();
}
/**
* A JDWP agent in server mode listens again, on a new port, when its debugger detaches; a
* debugger that detaches as the JVM exits leaves an announcement of a JVM about to be gone.
* An attach to `process` this soon after a session on it ended may be to such a JVM.
*/
const RELISTEN_MS = 3000;
function justDetached(process: RunId | null | undefined): boolean {
if (process == null) return false;
const now = Date.now();
return Object.values(useDebug.getState().sessions).some(
(s) => s.process === process && s.status === "terminated" && s.endedAt != null && now - s.endedAt < RELISTEN_MS,
);
}
export function publishContext() {
const s = activeSession();
const retained = Object.values(useDebug.getState().sessions);
@@ -504,10 +460,14 @@ export async function startSession(
notifications().notify({ group: "run", level: "warning", title: "Debugging needs the desktop app" });
return null;
}
// Attaching to a JVM that may be gone: the finished session stays until the attach succeeds.
const afterDetach = justDetached(options.process);
const previousActive = useDebug.getState().active;
if (!afterDetach) dropFinished();
// Drop finished sessions; keep running ones (multiple concurrent sessions are fine).
useDebug.setState((s) => {
const sessions = Object.fromEntries(Object.entries(s.sessions).filter(([, v]) => isLive(v)));
const consoleLines = Object.fromEntries(Object.entries(s.console).filter(([k]) => sessions[+k]));
for (const id of ansiStreams.keys()) if (!sessions[id]) ansiStreams.delete(id);
return { sessions, console: consoleLines, active: s.active != null && sessions[s.active] ? s.active : null };
});
publishContext();
try {
if (workflowSettings().run.showOnStart) toolWindowService().show("debug");
} catch {
@@ -522,7 +482,6 @@ export async function startSession(
const id = await call(commands.debugStart(launch));
console.info("Debug adapter started", { name: launch.name, ms: performance.now() - adapterStarted });
owned.add(id);
if (afterDetach) dropFinished();
if (options.preparation?.signal.aborted) {
await call(commands.debugStop(id)).catch(() => undefined);
settleStart(id);
@@ -567,16 +526,7 @@ export async function startSession(
void syncSpecial();
return id;
} catch (e) {
settleStart(null, afterDetach);
if (afterDetach) {
// The JVM that announced the port ended as its previous debugger detached.
console.info("Debugger not attached: the JVM is gone", { name: launch.name, error: e });
const { sessions, active } = useDebug.getState();
if (active == null && previousActive != null && sessions[previousActive])
useDebug.setState({ active: previousActive });
publishContext();
return null;
}
settleStart(null);
if (options.preparation?.signal.aborted || isCancelled(e)) return null;
if (options.preparation)
appendConsole(options.preparation.id, "stderr", (e instanceof Error ? e.message : String(e)) + "\n");
@@ -662,7 +612,7 @@ export function sessionSupports(cap: keyof DebugCapabilities, s: DebugSession |
}
function markTerminated(id: DebugSessionId) {
patch(id, { status: "terminated", endedAt: Date.now(), frames: [], selectedFrame: null, stoppedThread: null });
patch(id, { status: "terminated", frames: [], selectedFrame: null, stoppedThread: null });
const st = useDebug.getState();
if (st.active === id) {
// Prefer another live session (e.g. the parent of a finished child).
+4 -36
Переглянути файл
@@ -4,7 +4,6 @@ import { useVirtualizer } from "@tanstack/react-virtual";
import { copySelectionOnKeyDown } from "@/ui/selectableText";
import { EmptyState, IconButton, showContextMenu, T, type MenuItem } from "@/ui";
import { tx } from "@/platform/i18n";
import { useWorkflowSettings } from "@/platform/workflowSettings";
import { spanStyle } from "@/ui/ansi";
import ansi from "@/ui/ansi.module.css";
import { appendConsole, clearConsole, evaluate, isLive, useDebug, type DebugSession } from "../state";
@@ -24,14 +23,7 @@ export function DebugServiceConsole({ sessionId }: { sessionId: number }) {
export function DebugConsole({ session, interactive = true }: { session: DebugSession; interactive?: boolean }) {
const lines = useDebug((s) => s.console[session.id]);
const scroller = useRef<HTMLDivElement>(null);
// Scroll to End: follows new output; scrolling up turns it off, back to the end turns it on.
const [follow, setFollow] = useState(true);
const stick = useRef(true);
stick.current = follow;
// Settings › Console › Use soft wraps is the default; the toggle overrides it for this console.
const defaultWrap = useWorkflowSettings((s) => s.console.softWrap);
const [wrapOverride, setWrapOverride] = useState<boolean | null>(null);
const softWrap = wrapOverride ?? defaultWrap;
const programmatic = useRef(false);
const [input, setInput] = useState("");
const history = useRef<string[]>(readHistory("console"));
@@ -47,21 +39,14 @@ export function DebugConsole({ session, interactive = true }: { session: DebugSe
getItemKey: (i) => lines?.[i]?.id ?? i,
});
// Wrapping changes every row's height; the end is pinned again below.
useLayoutEffect(() => virtualizer.measure?.(), [softWrap, virtualizer]);
useLayoutEffect(() => {
const el = scroller.current;
if (!el || !stick.current || !lines?.length) return;
programmatic.current = true;
virtualizer.scrollToIndex(lines.length - 1, { align: "end" });
el.scrollTop = el.scrollHeight;
// Rows measured after this frame grow the content: pin the end once more.
requestAnimationFrame(() => {
if (stick.current) el.scrollTop = el.scrollHeight;
requestAnimationFrame(() => (programmatic.current = false));
});
}, [lines, virtualizer, follow, softWrap]);
requestAnimationFrame(() => (programmatic.current = false));
}, [lines, virtualizer]);
const submit = async () => {
const e = input.trim();
@@ -116,12 +101,11 @@ export function DebugConsole({ session, interactive = true }: { session: DebugSe
<div className={styles.console}>
<div
ref={scroller}
className={clsx(styles.consoleOutput, ansi.palette, !softWrap && styles.noWrap)}
className={clsx(styles.consoleOutput, ansi.palette)}
onScroll={(e) => {
if (programmatic.current) return;
const el = e.currentTarget;
const atEnd = el.scrollHeight - el.scrollTop - el.clientHeight < 24;
if (atEnd !== stick.current) setFollow(atEnd);
stick.current = el.scrollHeight - el.scrollTop - el.clientHeight < 24;
}}
onContextMenu={(e) => {
e.preventDefault();
@@ -186,22 +170,6 @@ export function DebugConsole({ session, interactive = true }: { session: DebugSe
{completion.popup}
</>
)}
<IconButton
icon="arrow-down"
title="Scroll to End"
size="small"
iconSize={12}
pressed={follow}
onClick={() => setFollow((v) => !v)}
/>
<IconButton
icon="soft-wrap"
title="Soft-Wrap"
size="small"
iconSize={12}
pressed={softWrap}
onClick={() => setWrapOverride(!softWrap)}
/>
<IconButton
icon="trash"
title="Clear Console"
-6
Переглянути файл
@@ -251,12 +251,6 @@
cursor: text;
}
/* Soft-Wrap off: long lines scroll horizontally. */
.noWrap {
white-space: pre;
word-break: normal;
}
.out {
position: absolute;
top: 0;
-1
Переглянути файл
@@ -130,7 +130,6 @@ export const ICLS_ATTRIBUTES: Record<string, Array<[Part, string]>> = {
DEFAULT_IDENTIFIER: [["FOREGROUND", "--syn-variable"]],
DEFAULT_LOCAL_VARIABLE: [["FOREGROUND", "--syn-variable"]],
DEFAULT_PARAMETER: [["FOREGROUND", "--syn-param"]],
DEFAULT_GLOBAL_VARIABLE: [["FOREGROUND", "--syn-global"]],
DEFAULT_PREDEFINED_SYMBOL: [["FOREGROUND", "--syn-builtin"]],
DEFAULT_METADATA: [
["FOREGROUND", "--syn-annotation"],
+1 -4
Переглянути файл
@@ -12,7 +12,7 @@ import { onIdeEvent } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { shortcutLabel } from "@/platform/keymap";
import { BarButton } from "@/ui/BarButton";
import { maybeEditorService, registerStatusItem } from "@/workbench/contributions";
import { registerStatusItem } from "@/workbench/contributions";
import { removeTask, upsertTask, useTasks } from "@/workbench/tasks";
import { pluginsBackend } from "./backend";
import { bumpView, deliverViewMessage } from "./views/viewStore";
@@ -259,9 +259,6 @@ export function handleRuntimeEvent(e: PluginEvent): boolean {
// The program was approved (`process:`) and verified by the host.
void executeAction("terminal.runCommand", { program: e.program, args: e.args, name: e.title, cwd: e.cwd });
return true;
case "openLocation":
void maybeEditorService()?.openFile(e.path, { selection: { line: e.line, col: e.column }, focus: true });
return true;
default:
return false;
}
+14 -44
Переглянути файл
@@ -290,49 +290,6 @@ function projectFileIcon(pluginId: string, decl: FileIconDecl): () => void {
export const pluginToolWindowId = (pluginId: string, view: string) => `plugin.${pluginId}.${view}`;
function registerView(pluginId: string, decl: ViewDecl, icon: string): () => void {
return registerToolWindow({
id: pluginToolWindowId(pluginId, decl.id),
title: decl.title,
icon,
anchor: decl.location,
order: 900,
component: () =>
decl.web ? (
<WebView pluginId={pluginId} view={decl.id} label={decl.title} />
) : (
<PluginView pluginId={pluginId} view={decl.id} label={decl.title} />
),
});
}
function projectView(pluginId: string, decl: ViewDecl): () => void {
if (!decl.icon?.endsWith(".svg")) return registerView(pluginId, decl, decl.icon ?? "plugin");
let disposed = false;
let undo = () => {};
void pluginsBackend()
.assets(pluginId, `viewIcon/${decl.id}`)
.then((assets) => {
if (disposed) return;
const svg = assets.find(([id]) => id === `viewIcon/${decl.id}`)?.[1];
const name = `ext:${pluginId}/view-${decl.id}`;
const unregister = svg ? registerExternalIcons([[name, svg]]) : () => {};
const remove = registerView(pluginId, decl, svg ? name : "plugin");
undo = () => {
remove();
unregister();
};
})
.catch((e: unknown) => {
console.warn(`plugin ${pluginId}: view icon ${decl.id}`, e);
if (!disposed) undo = registerView(pluginId, decl, "plugin");
});
return () => {
disposed = true;
undo();
};
}
/** Registers the client side of the P7 points; returns their disposer. */
export function defineViewUiPoints(): () => void {
const disposers = [
@@ -369,7 +326,20 @@ export function defineViewUiPoints(): () => void {
}),
defineUiPoint<ViewDecl>("views", {
title: "Tool Windows",
project: ({ pluginId, decl }) => projectView(pluginId, decl),
project: ({ pluginId, decl }) =>
registerToolWindow({
id: pluginToolWindowId(pluginId, decl.id),
title: decl.title,
icon: decl.icon ?? "plugin",
anchor: decl.location,
order: 900,
component: () =>
decl.web ? (
<WebView pluginId={pluginId} view={decl.id} label={decl.title} />
) : (
<PluginView pluginId={pluginId} view={decl.id} label={decl.title} />
),
}),
}),
defineUiPoint<CustomEditorDecl>("customEditors", {
title: "Editors",
+5 -5
Переглянути файл
@@ -2,7 +2,7 @@
import { type KeyboardEvent, type RefObject } from "react";
import clsx from "clsx";
import { IconButton, SearchField } from "@/ui";
import { formatBinding, hasPrimaryModifier } from "@/platform/keymap";
import { hasPrimaryModifier } from "@/platform/keymap";
import { tx } from "@/platform/i18n";
import type { FindOptions } from "./find";
import styles from "./Run.module.css";
@@ -97,7 +97,7 @@ export function ConsoleFindBar({
id: "case",
icon: "case",
title: "Match Case",
shortcut: formatBinding("Alt+C"),
shortcut: "⌥C",
pressed: options.caseSensitive,
onToggle: () => toggle("caseSensitive"),
},
@@ -105,7 +105,7 @@ export function ConsoleFindBar({
id: "word",
icon: "word",
title: "Words",
shortcut: formatBinding("Alt+W"),
shortcut: "⌥W",
pressed: options.wholeWord,
onToggle: () => toggle("wholeWord"),
},
@@ -113,7 +113,7 @@ export function ConsoleFindBar({
id: "regex",
icon: "regex",
title: "Regex",
shortcut: formatBinding("Alt+X"),
shortcut: "⌥X",
pressed: options.regex,
onToggle: () => toggle("regex"),
},
@@ -125,7 +125,7 @@ export function ConsoleFindBar({
<IconButton
icon="arrow-up"
title="Previous Occurrence"
shortcut={formatBinding("Shift+Enter")}
shortcut="⇧↵"
size="small"
disabled={count === 0}
onClick={onPrevious}
-31
Переглянути файл
@@ -256,37 +256,6 @@ describe("context configuration", () => {
expect(contextConfig("docs/readme.md", configs)).toBeNull();
});
it("runs a module that imports relatively as a module of its package", () => {
const cli = "from .models import Priority, TaskList\n\n\ndef main():\n pass\n";
expect(contextConfig("src/tasks/cli.py", configs, cli)).toMatchObject({
kind: "python",
command: "../.venv/bin/python",
args: ["-m", "tasks.cli"],
cwd: "src",
debugAdapter: "debugpy",
});
expect(contextConfig("app/api/routes.py", [], "from . import models\n")).toMatchObject({
command: "python3",
args: ["-m", "app.api.routes"],
cwd: null,
});
expect(contextConfig("src/app/__main__.py", [], "from .cli import main\n")).toMatchObject({
args: ["-m", "app"],
cwd: "src",
});
// Inside a nested Python project: from its folder (the venv command stays relative to the root).
const nested = [cfg({ id: "pytest", kind: "pytest", command: "backend/.venv/bin/pytest", cwd: "backend" })];
expect(contextConfig("backend/app/jobs.py", nested, "from .db import session\n")).toMatchObject({
command: "../backend/.venv/bin/python",
args: ["-m", "app.jobs"],
cwd: "backend",
});
// Absolute imports, a top-level file, a folder that can't be a package: as a script.
expect(contextConfig("src/tasks/cli.py", configs, "import os\n")!.args).toEqual(["src/tasks/cli.py"]);
expect(contextConfig("tool.py", [], "from .x import y\n")!.args).toEqual(["tool.py"]);
expect(contextConfig("my-scripts/run.py", [], "from .x import y\n")!.args).toEqual(["my-scripts/run.py"]);
});
it("runs pytest for a test file even without a detected pytest config", () => {
expect(contextConfig("worker/test_worker.py", [])).toMatchObject({
command: "python3",
+7 -56
Переглянути файл
@@ -236,48 +236,7 @@ function mainConfigFor(relPath: string, configs: RunConfig[]): RunConfig | null
return null;
}
/** `from .models import …`, `from . import x`: the file is a module of a package. */
const RELATIVE_IMPORT = /^[ \t]*from[ \t]+\.+[\w.]*[ \t]+import\b/m;
const IDENTIFIER = /^[A-Za-z_]\w*$/;
/**
* A module that imports relatively runs as `python -m <package>.<module>` from the folder its top
* package sits in (the last `src` of its path, else the Python project's folder): run as a script,
* its relative imports fail. `null` for other files.
*/
export function pythonModuleRun(
relPath: string,
content: string | undefined,
configs: RunConfig[],
): { cwd: string; module: string } | null {
if (!content || !RELATIVE_IMPORT.test(content)) return null;
const project = closest(
configs.filter((c) => c.kind === "python" || c.kind === "pytest"),
relPath,
)?.cwd?.replace(/^\.\/?|\/+$/g, "");
const segs = relPath.replace(/\.py$/, "").split("/");
const first = project && relPath.startsWith(`${project}/`) ? project.split("/").length : 0;
const src = segs.lastIndexOf("src", segs.length - 2);
const start = src >= first ? src + 1 : first;
const parts = segs.slice(start);
// Only a module inside a package can import relatively.
if (parts.length < 2 || !parts.every((p) => IDENTIFIER.test(p))) return null;
if (parts.at(-1) === "__main__" || parts.at(-1) === "__init__") parts.pop();
return { cwd: segs.slice(0, start).join("/"), module: parts.join(".") };
}
/** A command relative to the project root (`.venv/bin/python`), from `cwd` inside it. */
function fromSubfolder(command: string, cwd: string): string {
if (!cwd || !command.includes("/") || command.startsWith("/") || /^[A-Za-z]:/.test(command)) return command;
return "../".repeat(cwd.split("/").length) + command;
}
function scriptConfigFor(
relPath: string,
configs: RunConfig[],
windows = isWindows(),
content?: string,
): RunConfig | null {
function scriptConfigFor(relPath: string, configs: RunConfig[], windows = isWindows()): RunConfig | null {
const base: RunConfig = {
id: `context:file:${relPath}`,
name: relPath.split("/").pop() ?? relPath,
@@ -292,18 +251,10 @@ function scriptConfigFor(
};
if (relPath.endsWith(".py")) {
// Reuse the project's interpreter (venv / uv / poetry) when detected.
const py = projectPython(configs) ?? { command: "python3", prefix: [] };
const module = pythonModuleRun(relPath, content, configs);
if (module)
return {
...base,
kind: "python",
command: fromSubfolder(py.command, module.cwd),
args: [...py.prefix, "-m", module.module],
cwd: module.cwd || null,
debugAdapter: "debugpy",
};
return { ...base, kind: "python", command: py.command, args: [...py.prefix, relPath], debugAdapter: "debugpy" };
const py = projectPython(configs);
if (py)
return { ...base, kind: "python", command: py.command, args: [...py.prefix, relPath], debugAdapter: "debugpy" };
return { ...base, kind: "python", command: "python3", args: [relPath], debugAdapter: "debugpy" };
}
if (/\.[cm]?js$/.test(relPath)) return { ...base, command: "node", args: [relPath], debugAdapter: "js-debug" };
if (/\.ts$/.test(relPath)) return { ...base, command: "npx", args: ["tsx", relPath], debugAdapter: "js-debug" };
@@ -327,7 +278,7 @@ export function contextConfig(
): RunConfig | null {
const role = fileRole(relPath, content, windows, hasDjangoTests(configs));
if (role === "test") return testConfigFor(relPath, configs);
if (role === "main") return mainConfigFor(relPath, configs) ?? scriptConfigFor(relPath, configs, windows, content);
if (role === "script") return scriptConfigFor(relPath, configs, windows, content);
if (role === "main") return mainConfigFor(relPath, configs) ?? scriptConfigFor(relPath, configs, windows);
if (role === "script") return scriptConfigFor(relPath, configs, windows);
return null;
}
+10 -7
Переглянути файл
@@ -85,15 +85,18 @@ export function delegatedGradleConfig(config: RunConfig, module: string, ctx: De
};
}
/**
* Writes an init script where Gradle reads it: on the machine that runs the build (the
* remote host in remote development). It never changes, so once per session.
*/
/** Writes an init script where Gradle can read it; it never changes, so once per session. */
const scriptPaths = new Map<string, Promise<string>>();
function writeScript(name: string, text: string): Promise<string> {
let written = scriptPaths.get(name);
if (!written) {
written = call(commands.runGradleInitScript(name, text)).catch((e) => {
written = (async () => {
const { tempDir, join } = await import("@tauri-apps/api/path");
const path = await join(await tempDir(), name);
await call(commands.fsDelete(path)).catch(() => {});
await call(commands.fsCreateFileBytes(path, Array.from(new TextEncoder().encode(text))));
return path;
})().catch((e) => {
scriptPaths.delete(name);
throw e;
});
@@ -118,7 +121,7 @@ export function withTestEvents<T extends Pick<RunConfig, "kind" | "command" | "a
export async function gradleTestLaunch<T extends RunConfig>(config: T): Promise<T> {
if (!isTauri() || !config.isTest || !isGradleCommand(config)) return config;
try {
return withTestEvents(config, await writeScript("openidea-gradle-tests", TESTS_SCRIPT));
return withTestEvents(config, await writeScript("openidea-gradle-tests.gradle", TESTS_SCRIPT));
} catch (e) {
console.warn("Gradle test init script not written", e);
return config;
@@ -147,7 +150,7 @@ export async function gradleDelegation(config: RunConfig): Promise<RunConfig | n
};
if (!delegatedGradleConfig(config, module, ctx)) return null;
const [script, configurationCache] = await Promise.all([
writeScript("openidea-gradle-run", RUN_SCRIPT),
writeScript("openidea-gradle-run.gradle", RUN_SCRIPT),
supportsConfigurationCache(ctx),
]);
return delegatedGradleConfig(config, module, { ...ctx, script, configurationCache });
+2 -30
Переглянути файл
@@ -65,7 +65,6 @@ const { showSearchEverywhere, hideSearchEverywhere, useSearchEverywhere, pushSea
await import("../everywhere/store");
const { FindInFilesOverlay } = await import("../find/FindInFiles");
const { showFindPopup, hideFindPopup } = await import("../find/store");
const { defaultPreset, useKeymap } = await import("@/platform/keymap");
const tick = () => act(() => new Promise((r) => setTimeout(r, 100)));
@@ -477,40 +476,13 @@ describe("Recent Files multi-selection", () => {
});
describe("Find in Files dialog", () => {
it("streams results and highlights the matches while replacing, as IDEA", async () => {
it("streams results and previews the replacement", async () => {
render(<FindInFilesOverlay />);
act(() => showFindPopup(true, { query: "order" }));
await act(() => new Promise((r) => setTimeout(r, 250)));
expect(screen.getByText("1 match in 1 file")).toBeInTheDocument();
fireEvent.change(screen.getByLabelText("Replace with"), { target: { value: "item" } });
const matches = screen.getByRole("listbox", { name: "Matches" });
expect(matches.querySelector("mark")).not.toBeNull();
expect(matches.querySelector("del, ins")).toBeNull();
expect(screen.getByText("item", { ignore: "script, style, textarea" })).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Replace All" })).toBeEnabled();
});
it.each([
["macos", ["⌥C", "⌥↓", "⇧⌘↵"], ["⌘↵", "⌥⇧↵"]],
["linux", ["Alt+C", "Alt+Down", "Ctrl+Shift+Enter"], ["Ctrl+Enter", "Alt+Shift+Enter"]],
["windows", ["Alt+C", "Alt+Down", "Ctrl+Shift+Enter"], ["Ctrl+Enter", "Alt+Shift+Enter"]],
] as const)("spells its shortcuts the %s way", (os, [matchCase, history, newLine], [openKey, replaceAllKey]) => {
const previous = { os: usePlatform.getState().os, preset: useKeymap.getState().preset };
usePlatform.setState({ os });
useKeymap.setState({ preset: defaultPreset() });
try {
render(<FindInFilesOverlay />);
act(() => showFindPopup(true, { query: "order" }));
const shortcut = (name: string) =>
screen.getAllByRole("button", { name }).map((b) => b.getAttribute("data-tooltip-shortcut"));
expect(shortcut("Match Case")).toEqual([matchCase]);
expect(shortcut("Recent Searches")).toEqual([history, history]);
expect(shortcut("New Line")).toEqual([newLine, newLine]);
expect(document.querySelector("footer")!.textContent).toContain(`${openKey}Open in Find Window`);
expect(screen.getByRole("button", { name: "Replace All" })).toHaveAttribute("title", replaceAllKey);
if (os !== "macos") expect(document.querySelector("[role=dialog]")!.innerHTML).not.toMatch(/[⌘⌥⇧↵]/);
} finally {
usePlatform.setState({ os: previous.os });
useKeymap.setState({ preset: previous.preset });
}
});
});
-46
Переглянути файл
@@ -1,46 +0,0 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const extensions = [
{ extension: "rs", files: 40 },
{ extension: "md", files: 12 },
{ extension: "lock", files: 9 },
{ extension: "toml", files: 6 },
{ extension: "png", files: 5 },
{ extension: "json", files: 3 },
{ extension: "yml", files: 2 },
{ extension: "sh", files: 1 },
];
const languages = [
{ id: "rust", extensions: ["rs"] },
{ id: "markdown", extensions: ["md", "markdown"] },
{ id: "toml", extensions: ["toml"] },
{ id: "json", extensions: ["json"] },
{ id: "yaml", extensions: ["yml", "yaml"] },
{ id: "shell", extensions: ["sh"] },
];
vi.mock("@/platform/ipc", async (orig) => ({
...(await orig<typeof import("@/platform/ipc")>()),
call: async (p: unknown) => p,
commands: {
indexFileExtensions: () => Promise.resolve(extensions),
languages: () => Promise.resolve(languages),
},
}));
const { recentMasks, refreshProjectMasks, rememberMask, useProjectMasks } = await import("../find/store");
beforeEach(() => {
localStorage.clear();
useProjectMasks.setState({ masks: [] });
});
describe("file mask suggestions", () => {
it("are the project's most common language file types, recent masks first", async () => {
await refreshProjectMasks();
expect(useProjectMasks.getState().masks).toEqual(["*.rs", "*.md", "*.toml", "*.json", "*.yml"]);
rememberMask("*.toml");
rememberMask("!*Test*");
expect(recentMasks()).toEqual(["!*Test*", "*.toml", "*.rs", "*.md", "*.json", "*.yml"]);
});
});
+9 -164
Переглянути файл
@@ -63,18 +63,8 @@ vi.mock("@/platform/ipc", async (orig) => ({
}));
const { FindInFilesOverlay } = await import("../find/FindInFiles");
const {
findHistory,
hideFindPopup,
rememberFindString,
runFindPopupCommand,
showFindPopup,
useFindPopup,
useProjectMasks,
} = await import("../find/store");
const { formatBinding } = await import("@/platform/keymap");
const { usePlatform } = await import("@/platform/platformInfo");
const { findHistory, hideFindPopup, rememberFindString, runFindPopupCommand, showFindPopup, useFindPopup } =
await import("../find/store");
const settle = () => act(() => new Promise((r) => setTimeout(r, 250)));
const selectedRows = () =>
@@ -102,7 +92,6 @@ beforeEach(() => {
preserveCase: false,
context: "any",
replacement: "",
newTab: false,
});
});
@@ -217,8 +206,7 @@ describe("Find in Files popup", () => {
});
describe("outdated popup results", () => {
// The results box, whether it holds the list or the empty text.
const results = () => document.querySelector<HTMLElement>("[aria-busy]")!;
const results = () => screen.getByRole("listbox", { name: "Matches" }).parentElement!;
const rowText = () =>
within(screen.getByRole("listbox", { name: "Matches" }))
.getAllByRole("option")
@@ -267,14 +255,13 @@ describe("outdated popup results", () => {
expect(results()).not.toHaveAttribute("data-stale");
expect(rowText()).toHaveLength(1);
expect(screen.getByText("1 match in 1 file")).toBeInTheDocument();
expect(results().querySelector("mark")).not.toBeNull();
expect(results().querySelector("del, ins")).toBeNull();
expect(results().querySelector(replace ? "ins" : "mark")).not.toBeNull();
if (replace) expect(screen.getByRole("button", { name: "Replace" })).toBeEnabled();
await act(async () => finish(null));
},
);
it.each(["Replace", "Replace All", "Enter", "All shortcut", "All mnemonic"])(
it.each(["Replace", "Replace All in This File", "Replace All", "Enter", "All shortcut", "All mnemonic"])(
"blocks %s during debounce and validation",
async (action) => {
render(<FindInFilesOverlay />);
@@ -331,12 +318,12 @@ describe("outdated popup results", () => {
await settle();
expect(results()).toHaveAttribute("data-stale", "true");
expect(rowText()).toHaveLength(3);
const box = results();
await act(async () => finish(null));
expect(results()).not.toHaveAttribute("data-stale");
// IDEA's header shows a count only while something matches.
expect(screen.queryByText(/\bmatch(es)? in\b/)).not.toBeInTheDocument();
expect(box).not.toHaveAttribute("data-stale");
expect(screen.getByText("No matches")).toBeInTheDocument();
expect(screen.getByText("Nothing found")).toBeInTheDocument();
expect(within(results()).queryAllByRole("option")).toHaveLength(0);
expect(within(box).queryAllByRole("option")).toHaveLength(0);
expect(screen.getByRole("button", { name: "Replace" })).toBeDisabled();
});
@@ -367,145 +354,3 @@ describe("outdated popup results", () => {
expect(replaced).toHaveLength(0);
});
});
describe("footer, as IDEA", () => {
it("remembers Open results in new tab and passes it on; ⌥B toggles it", () => {
render(<FindInFilesOverlay />);
act(() => showFindPopup(false, { query: "order" }));
const box = screen.getByRole("checkbox", { name: "Open results in new tab" });
expect(box).not.toBeChecked();
fireEvent.keyDown(field(), { key: "b", code: "KeyB", altKey: true });
expect(box).toBeChecked();
expect(localStorage.getItem("openidea.search.findNewTab.v1")).toBe("true");
fireEvent.click(box);
expect(useFindPopup.getState().newTab).toBe(false);
});
it("keeps OpenIDEA's Replace preview: a diff in place of the code preview", async () => {
render(<FindInFilesOverlay />);
act(() => showFindPopup(false, { query: "order" }));
expect(screen.queryByRole("checkbox", { name: "Preview" })).not.toBeInTheDocument();
act(() => showFindPopup(true, { query: "order" }));
await settle();
expect(screen.getByRole("region", { name: "Preview" })).toBeInTheDocument();
fireEvent.click(screen.getByRole("checkbox", { name: "Preview" }));
expect(screen.queryByRole("region", { name: "Preview" })).not.toBeInTheDocument();
});
it("names the result keys only for a multi-line query", () => {
render(<FindInFilesOverlay />);
act(() => showFindPopup(false, { query: "order" }));
expect(screen.queryByText(/to select usages$/)).not.toBeInTheDocument();
fireEvent.change(field(), { target: { value: "order\nitem" } });
expect(screen.getByText(/^Use .+ and .+ to select usages$/)).toBeInTheDocument();
});
});
describe("mnemonics, as IDEA", () => {
it("⌥P / ⌥M / ⌥D / ⌥S pick the scope tab, whose letter is underlined off macOS", () => {
const os = usePlatform.getState().os;
usePlatform.setState({ os: "linux" });
try {
render(<FindInFilesOverlay />);
act(() => showFindPopup(false, { query: "order" }));
expect(screen.getByRole("tab", { name: "In Project" }).querySelector("u")?.textContent).toBe("P");
for (const [code, tab] of [
["KeyD", "directory"],
["KeyS", "scope"],
["KeyM", "module"],
["KeyP", "project"],
] as const) {
fireEvent.keyDown(field(), { key: code.slice(3).toLowerCase(), code, altKey: true });
expect(useFindPopup.getState().scopeTab).toBe(tab);
}
} finally {
usePlatform.setState({ os });
}
});
});
describe("file mask, as IDEA", () => {
it("turned on with nothing typed takes the first suggestion", () => {
useProjectMasks.setState({ masks: ["*.rs", "*.toml"] });
render(<FindInFilesOverlay />);
act(() => showFindPopup(false));
expect(screen.getByLabelText("File mask")).toHaveAttribute("placeholder", "*.rs");
fireEvent.click(screen.getByRole("checkbox", { name: "File mask:" }));
expect([useFindPopup.getState().maskEnabled, useFindPopup.getState().mask]).toEqual([true, "*.rs"]);
});
});
describe("layout, as IDEA", () => {
it("shows the preview only once something matches", async () => {
render(<FindInFilesOverlay />);
act(() => showFindPopup(false));
expect(screen.queryByRole("region", { name: "Preview" })).not.toBeInTheDocument();
fireEvent.change(field(), { target: { value: "order" } });
await settle();
expect(screen.getByRole("region", { name: "Preview" })).toBeInTheDocument();
});
it("is resizable and opens at the size it was left at", () => {
localStorage.setItem("openidea.search.findPopupSize.v1", JSON.stringify({ w: 700, h: 520 }));
render(<FindInFilesOverlay />);
act(() => showFindPopup(false));
const dialog = screen.getByRole("dialog");
expect([dialog.style.width, dialog.style.height]).toEqual(["700px", "520px"]);
expect(within(dialog).getByRole("separator", { name: "Resize" })).toBeInTheDocument();
});
});
describe("empty results, as IDEA", () => {
const findNothing = () => {
search = async () => null;
};
it("asks for a query while there is none", () => {
render(<FindInFilesOverlay />);
act(() => showFindPopup(false));
expect(screen.getByText("Type search query to find in files")).toBeInTheDocument();
});
it("names the one option in use and clears it", () => {
useFindPopup.setState({ maskEnabled: true, mask: "*.rs" });
render(<FindInFilesOverlay />);
act(() => showFindPopup(false));
expect(screen.getByText("No search text entered.")).toBeInTheDocument();
expect(screen.getByText("Search option used: File mask")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Clear option" }));
expect(useFindPopup.getState().maskEnabled).toBe(false);
expect(screen.getByText("Type search query to find in files")).toBeInTheDocument();
});
it("lists every option in use with its key, and ⇧⌥⌫ clears them all", async () => {
findNothing();
useFindPopup.setState({ caseSensitive: true, wholeWord: true, context: "inComments" });
render(<FindInFilesOverlay />);
act(() => showFindPopup(false, { query: "absent" }));
await settle();
expect(screen.getByText("Nothing found.")).toBeInTheDocument();
expect(screen.getByText("Search options used:")).toBeInTheDocument();
expect(
screen.getByText(`Match Case ${formatBinding("Alt+C")} Words ${formatBinding("Alt+W")} Filter`),
).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Clear all options" })).toBeInTheDocument();
fireEvent.keyDown(field(), { key: "Backspace", altKey: true, shiftKey: true });
const s = useFindPopup.getState();
expect([s.caseSensitive, s.wholeWord, s.isRegex, s.maskEnabled, s.context]).toEqual([
false,
false,
false,
false,
"any",
]);
});
it("offers Search with Regex for a query that reads as one", async () => {
findNothing();
render(<FindInFilesOverlay />);
act(() => showFindPopup(false, { query: "fo+.*bar" }));
await settle();
fireEvent.click(screen.getByRole("button", { name: "Search with Regex" }));
expect(useFindPopup.getState().isRegex).toBe(true);
});
});
+4 -11
Переглянути файл
@@ -39,29 +39,22 @@ afterEach(disposeFindWindow);
describe("Find tool window tabs", () => {
it("reuses the selected tab unless it is pinned", () => {
const a = openInFindWindow(q("a"), "a", { deps });
const b = openInFindWindow(q("b"), "b", { deps });
const a = openInFindWindow(q("a"), "a", null, deps);
const b = openInFindWindow(q("b"), "b", null, deps);
expect(useFindWindow.getState().tabs.map((t) => t.title)).toEqual(["b"]);
expect(useFindWindow.getState().active).toBe(b);
expect(b).not.toBe(a);
pinFindTab(b, true);
const c = openInFindWindow(q("c"), "c", { deps });
const c = openInFindWindow(q("c"), "c", null, deps);
expect(useFindWindow.getState().tabs.map((t) => t.title)).toEqual(["b", "c"]);
expect(useFindWindow.getState().active).toBe(c);
// Selecting the pinned tab again opens the next search beside it.
useFindWindow.setState({ active: b });
openInFindWindow(q("d"), "d", { deps });
openInFindWindow(q("d"), "d", null, deps);
expect(useFindWindow.getState().tabs.map((t) => t.title)).toEqual(["b", "c", "d"]);
});
it("keeps the selected tab with IDEA's Open results in new tab", () => {
openInFindWindow(q("a"), "a", { deps });
const b = openInFindWindow(q("b"), "b", { deps, newTab: true });
expect(useFindWindow.getState().tabs.map((t) => t.title)).toEqual(["a", "b"]);
expect(useFindWindow.getState().active).toBe(b);
});
});
describe("buildFindTree", () => {
+2 -4
Переглянути файл
@@ -5,7 +5,7 @@
*/
import { useEffect, useMemo, useState } from "react";
import { Button, Checkbox, Input, Popup, T, type PopupAnchor } from "@/ui";
import { recentMasks, refreshProjectMasks, useProjectMasks } from "../find/store";
import { recentMasks } from "../find/store";
import { KIND_LABELS, kindsFor, type FilterTab, type SeFilters } from "./filters";
import { loadLanguages } from "./deps";
import { setSearchEverywhereFilter } from "./store";
@@ -135,8 +135,6 @@ export function FilterPopup({
function MaskFilter({ mask, onClose }: { mask: string; onClose: () => void }) {
const [value, setValue] = useState(mask);
const projectMasks = useProjectMasks((p) => p.masks);
useEffect(() => void refreshProjectMasks(), []);
const apply = (m: string) => setSearchEverywhereFilter("text", { mask: m.trim() });
return (
<div className={styles.filterGroup}>
@@ -147,7 +145,7 @@ function MaskFilter({ mask, onClose }: { mask: string; onClose: () => void }) {
id="se-file-mask"
data-autofocus
value={value}
placeholder={projectMasks[0] ?? ""}
placeholder="*.ts, !*.test.*"
spellCheck={false}
onChange={(e) => {
setValue(e.target.value);
+10 -11
Переглянути файл
@@ -4,7 +4,7 @@ import clsx from "clsx";
import { actionToggled, executeAction, executeActionFrom, getAction } from "@/platform/actions";
import type { ProjectFileSet } from "@/platform/ipc";
import { tx as translate, useTx } from "@/platform/i18n";
import { formatBinding, hasPrimaryModifier, hostBinding, registerKeyClaim, shortcutLabel } from "@/platform/keymap";
import { hasPrimaryModifier, registerKeyClaim, shortcutLabel } from "@/platform/keymap";
import {
Checkbox,
Dialog,
@@ -98,7 +98,6 @@ const INITIAL_SELECTION: Selection = { key: null, anchorKey: null, lead: -1, anc
function SearchEverywhereDialog() {
const tx = useTx();
const tab = useSearchEverywhere((s) => s.tab);
const hint = hintFor(tab, tx);
const query = useSearchEverywhere((s) => s.query);
const includeNonProject = useSearchEverywhere((s) => s.includeNonProject);
const fileSet = useSearchEverywhere((s) => s.fileSet);
@@ -340,7 +339,7 @@ function SearchEverywhereDialog() {
? [{ label: "Open Settings Page", run: () => activate(row) }]
: [
{ label: "Open", run: () => activate(row) },
{ label: "Open to the Side", shortcut: formatBinding("Shift+Enter"), run: () => activate(row, true) },
{ label: "Open to the Side", shortcut: "⇧↵", run: () => activate(row, true) },
{ kind: "separator" },
{ label: "Copy Path", run: () => copy(row.path) },
{ label: "Copy Path from Project Root", run: () => copy(row.rel) },
@@ -504,7 +503,7 @@ function SearchEverywhereDialog() {
size="small"
className={styles.headerButton}
title={tx("Open in Find Tool Window")}
shortcut={tab === "text" ? formatBinding(hostBinding("Meta+Enter")) : undefined}
shortcut={tab === "text" ? "⌘↵" : undefined}
onClick={() => closeThen(() => void executeAction("find.inPath", { query: parsed.text }))}
/>
</div>
@@ -514,7 +513,7 @@ function SearchEverywhereDialog() {
type="button"
className={styles.magnifier}
aria-label={tx("Search history")}
title={tx`Search history (${formatBinding("Alt+Up")} / ${formatBinding("Alt+Down")})`}
title={tx("Search history (⌥↑ / ⌥↓)")}
onMouseDown={(e) => e.preventDefault()}
onClick={(e) => openHistory(e.currentTarget)}
>
@@ -540,9 +539,9 @@ function SearchEverywhereDialog() {
onKeyDown={onKeyDown}
/>
{snap?.loading && !emptyQuery && <Spinner size={14} className={styles.spinner} />}
{hint && (
{hintFor(tab) && (
<span className={styles.hint} aria-hidden>
{hint}
<T>{hintFor(tab)}</T>
</span>
)}
</div>
@@ -646,7 +645,7 @@ function describe(row: SeRow | undefined): string {
case "action": {
const a = getAction(row.id);
const text = a?.description ?? (row.category ? `${row.category} | ${row.title}` : row.title);
return `${text} · ${translate`${formatBinding("Alt+Enter")} to assign a shortcut`}`;
return `${text} · ${translate("⌥↵ to assign a shortcut")}`;
}
case "setting":
return [...row.path, row.title].map((p) => translate(p)).join(" | ");
@@ -675,12 +674,12 @@ function previewOf(row: SeRow | undefined): { path: string; line: number; highli
}
}
function hintFor(tab: SeTab, tx: ReturnType<typeof useTx>): string {
function hintFor(tab: SeTab): string {
switch (tab) {
case "all":
return tx("Type / to see commands");
return "Type / to see commands";
case "text":
return tx`${formatBinding(hostBinding("Meta+Enter"))} to open in Find tool window`;
return "⌘↵ to open in Find tool window";
default:
return "";
}
+27 -77
Переглянути файл
@@ -1,8 +1,5 @@
/* IDEA's Find in Files is a popup: Popup.background, not the dialog surface. */
.dialog {
max-height: calc(90vh - 12px);
background: var(--bg-popup, var(--bg-elev));
font-family: var(--font-ui);
max-height: min(86vh, calc(90vh - 24px));
}
.dialog > :global([data-dialog-body]) {
display: flex;
@@ -20,14 +17,13 @@
display: flex;
align-items: center;
gap: 10px;
height: 42px;
padding: 0 14px 0 20px;
border-bottom: 1px solid var(--border-popup);
height: 34px;
padding: 0 8px 0 12px;
color: var(--fg-subtle);
}
.title {
color: var(--fg-strong);
font-weight: 600;
color: var(--fg-emphasis);
font-weight: 500;
}
.status {
display: inline-flex;
@@ -43,8 +39,7 @@
.mask {
display: flex;
align-items: center;
height: var(--h-control);
background: var(--bg-field);
height: var(--h-control-small);
border: 1px solid var(--border-strong);
border-radius: var(--radius-small);
padding-left: 6px;
@@ -58,18 +53,18 @@
border: 0;
outline: none;
color: var(--fg);
font-family: var(--font-mono);
font-size: var(--fs-small);
}
.fields {
flex: none;
display: flex;
flex-direction: column;
gap: 8px;
padding: 8px 8px 0;
gap: 6px;
padding: 0 12px 8px;
}
/* The query fields sit on the popup surface, framed only by their border. */
.fields .field {
.field {
width: 100%;
background: transparent;
}
.field input {
font-family: var(--font-mono);
@@ -80,15 +75,13 @@
font-size: var(--fs-small);
padding-left: 2px;
}
/* Scope tabs line up with the title; the selected one is a neutral pressed pill, as in IDEA. */
.scopeRow {
--bg-tab-selected: var(--bg-toolbar-pressed);
--border-tab-selected: transparent;
flex: none;
display: flex;
align-items: center;
gap: 12px;
padding: 8px 14px 4px 20px;
padding: 0 12px 0 6px;
border-bottom: 1px solid var(--border-popup);
}
.scopeDetail {
flex: 1;
@@ -114,24 +107,15 @@
.dirInput:focus {
border-color: var(--accent);
}
/* Results alone (empty state) or results over the preview; grows with the popup. */
.split {
flex: 1 1 auto;
height: 500px;
min-height: 0;
display: flex;
flex-direction: column;
}
.split > * {
flex: 1;
min-height: 0;
}
.results {
flex: 1;
flex: 0 1 242px;
min-height: 0;
height: 242px;
display: flex;
flex-direction: column;
padding: 2px 0;
font-family: var(--font-mono);
font-weight: var(--fw-code);
}
.results > * {
flex: 1;
@@ -147,8 +131,6 @@
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
font-family: var(--font-mono);
font-weight: var(--fw-code);
}
.rowFile {
flex: none;
@@ -156,6 +138,7 @@
overflow: hidden;
text-overflow: ellipsis;
color: var(--fg-subtle);
font-family: var(--font-ui);
}
.rowFileActive {
color: var(--fg-muted);
@@ -170,24 +153,22 @@
align-items: center;
justify-content: space-between;
gap: 10px;
height: 36px;
padding: 0 20px;
height: 24px;
padding: 0 12px;
border-top: 1px solid var(--border-popup);
border-bottom: 1px solid var(--border-popup);
font-size: var(--fs-small);
color: var(--fg-subtle);
}
.previewPath {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.previewName {
color: var(--fg-strong);
margin-right: 8px;
}
.previewBox {
flex: 1;
flex: 0 1 220px;
min-height: 0;
height: 220px;
display: flex;
flex-direction: column;
}
@@ -198,8 +179,9 @@
align-items: center;
justify-content: flex-end;
gap: 8px;
min-height: 46px;
padding: 8px 20px;
min-height: 38px;
padding: 6px 12px;
border-top: 1px solid var(--border-popup);
}
.footer > button,
.footer > label {
@@ -222,35 +204,3 @@
opacity: 0.55;
text-decoration: line-through;
}
.empty {
display: flex;
flex-direction: column;
align-items: center;
gap: 2px;
padding: 0 20px;
text-align: center;
line-height: 1.6;
}
.emptyOptions {
display: flex;
flex-direction: column;
align-items: center;
margin-top: 1.2em;
}
.link {
padding: 0;
border: 0;
background: none;
color: var(--link);
font: inherit;
cursor: pointer;
}
.link:hover {
color: var(--link-hover);
}
/* IDEA's disabled "Ctrl+Enter" label before Open in Find Window. */
.okHint {
flex: none;
color: var(--fg-faint);
white-space: nowrap;
}
+158 -278
Переглянути файл
@@ -3,8 +3,7 @@ import clsx from "clsx";
import { openEditorPaths, useEditorRegistry } from "@/editor/api";
import { executeAction } from "@/platform/actions";
import { setContext } from "@/platform/context";
import { t, useTxTemplate, tx } from "@/platform/i18n";
import { formatBinding, hostBinding, shortcutLabel } from "@/platform/keymap";
import { useTxTemplate, tx } from "@/platform/i18n";
import { call, commands, isTauri, type SearchScope } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { useProjectModules } from "@/platform/projectRoots";
@@ -16,13 +15,9 @@ import {
IconButton,
List,
Menu,
Mnemonic,
SearchField,
Select,
Spinner,
SplitGroup,
SplitHandle,
SplitPanel,
Tabs,
listNavigate,
type MenuItem,
@@ -64,19 +59,12 @@ import {
hideFindPopup,
recentMasks,
rememberFindString,
refreshProjectMasks,
rememberMask,
resolveDirectory,
resolveFindScope,
setFindPopupCommandHandler,
loadFindPopupSize,
loadFindPopupSplit,
saveFindPopupSize,
saveFindPopupSplit,
setFindPopupNewTab,
setFindPopupPinned,
useFindPopup,
useProjectMasks,
type FindOptions,
type BuiltinScope,
type FindPopupCommand,
@@ -101,19 +89,18 @@ async function chooseDirectory(current: string): Promise<string | null> {
const POPUP_MAX_MATCHES = 2000;
const SEARCH_DEBOUNCE_MS = 150;
const ROW = 24;
const ROW = 22;
export function FindInFilesOverlay() {
const open = useFindPopup((s) => s.open);
return open ? <FindInFilesDialog /> : null;
}
/** IDEA's scope tabs and their Alt mnemonics. */
const SCOPE_TABS: Array<{ id: ScopeTab; label: string; mnemonic: string }> = [
{ id: "project", label: "In Project", mnemonic: "P" },
{ id: "module", label: "Module", mnemonic: "M" },
{ id: "directory", label: "Directory", mnemonic: "D" },
{ id: "scope", label: "Scope", mnemonic: "S" },
const SCOPE_TABS: Array<{ id: ScopeTab; label: string }> = [
{ id: "project", label: "In Project" },
{ id: "module", label: "Module" },
{ id: "directory", label: "Directory" },
{ id: "scope", label: "Scope" },
];
const NAMED_SCOPES: Array<{ value: BuiltinScope; label: string }> = [
@@ -147,18 +134,11 @@ function FindInFilesDialog() {
const [historyMenu, setHistoryMenu] = useState<"find" | "replace" | null>(null);
const [contextMenu, setContextMenu] = useState(false);
const [previewVersion, setPreviewVersion] = useState(0);
// OpenIDEA's Replace › Preview: the preview shows the replacement as a diff.
const [previewMode, setPreviewMode] = useState(false);
const [diffPreview, setDiffPreview] = useState<{ key: string; lines: PreviewLine[] } | null>(null);
const [initialSize] = useState(loadFindPopupSize);
const [split, setSplit] = useState(loadFindPopupSplit);
const keepSplit = (layout: Record<string, number>) => {
setSplit(layout);
saveFindPopupSplit(layout);
};
const [marks, setMarks] = useState<ReplaceMarks>(NO_MARKS);
const [running, setRunning] = useState<ReplaceRun | null>(null);
const [progress, setProgress] = useState<ReplaceProgress | null>(null);
const [previewMode, setPreviewMode] = useState(false);
const [diffPreview, setDiffPreview] = useState<{ key: string; lines: PreviewLine[] } | null>(null);
const busy = !!running;
const patternRef = useRef<HTMLInputElement>(null);
const patternBoxRef = useRef<HTMLDivElement>(null);
@@ -169,11 +149,6 @@ function FindInFilesDialog() {
const set = (patch: Partial<FindOptions>) => useFindPopup.setState(patch);
useEffect(() => () => session.dispose(), [session]);
const projectMasks = useProjectMasks((p) => p.masks);
useEffect(() => void refreshProjectMasks(), []);
/** Turning the mask on with nothing typed takes the first suggestion, as IDEA's combo box shows one. */
const enableMask = (on: boolean) =>
set(on && !s.mask.trim() ? { maskEnabled: true, mask: recentMasks()[0] ?? "" } : { maskEnabled: on });
useEffect(() => {
if (modules.length && !modules.some((m) => m.path === s.module))
useFindPopup.setState({ module: modules[0]!.path });
@@ -283,11 +258,7 @@ function FindInFilesDialog() {
if (s.maskEnabled) rememberMask(s.mask);
const pinned = buildQuery(options, scope, 0);
close();
openInFindWindow(pinned, describeQuery(pinned, root), {
replacement: s.replace ? s.replacement : null,
preserveCase: s.preserveCase,
newTab: s.newTab,
});
openInFindWindow(pinned, describeQuery(pinned, root), s.replace ? s.replacement : null, undefined, s.preserveCase);
};
// Check again after a confirmation: its captured rows may have been superseded.
@@ -379,6 +350,23 @@ function FindInFilesDialog() {
if (i >= 0) setIndex(i);
}
};
const skip = () => {
const i = nextPending(rows, rows.indexOf(chosen[chosen.length - 1]!), marks);
if (i >= 0) setIndex(i);
};
const replaceInFile = async () => {
if (!selected) return;
const next = await replaceUsages(
pendingUsages(
rows.filter((r) => r.path === selected.path),
marks,
),
);
if (next) {
const i = nextPending(rows, active, next);
if (i >= 0) setIndex(i);
}
};
const replaceAll = async (usages: Usage[]) => {
const done = await replaceUsages(usages);
if (done) close();
@@ -425,41 +413,19 @@ function FindInFilesDialog() {
| undefined;
if (toggle) set({ [toggle]: !s[toggle] });
else if (code === "KeyK") {
enableMask(!s.maskEnabled);
set({ maskEnabled: !s.maskEnabled });
if (!s.maskEnabled) setTimeout(() => maskInputRef.current?.select(), 0);
} else if (code === "KeyE" && s.replace) set({ preserveCase: !s.preserveCase });
else if (code === "KeyB") setFindPopupNewTab(!s.newTab);
else if (SCOPE_TABS.some((t) => code === `Key${t.mnemonic}`))
selectScope(SCOPE_TABS.find((t) => code === `Key${t.mnemonic}`)!.id);
else if (code === "KeyA" && s.replace) {
if (rows.length && !busy) void confirmReplaceAll();
} else return false;
return true;
};
const selectScope = (id: ScopeTab) => {
// IDEA starts the Directory scope at the current file's folder.
if (id === "directory" && !s.directory.trim()) {
const active = maybeEditorService()?.activePath();
const folders = project?.workspace?.projects ?? (root ? [root] : []);
const dir = active && folders.some((r) => active.startsWith(r + "/")) ? dirname(active) : root;
set({ scopeTab: "directory", directory: dir ?? "" });
} else set({ scopeTab: id });
};
/** IDEA's "Clear all options" (⇧⌥⌫): back to a plain search everywhere. */
const clearOptions = () =>
set({ caseSensitive: false, wholeWord: false, isRegex: false, maskEnabled: false, context: "any" });
const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
const target = e.target as HTMLElement;
const inField =
(target.tagName === "INPUT" || target.tagName === "TEXTAREA") && target.closest("[data-find-field]");
if (e.key === "Backspace" && e.altKey && e.shiftKey && !e.metaKey && !e.ctrlKey) {
e.preventDefault();
clearOptions();
return;
}
if (e.key === "Enter" && e.altKey && e.shiftKey && !e.metaKey && !e.ctrlKey) {
// ⇧⌥↵: Replace All.
e.preventDefault();
@@ -533,75 +499,12 @@ function FindInFilesDialog() {
run: () => set({ context: c.value }),
}));
const pendingSelected = s.replace && !stale ? pendingUsages(chosen, marks).length : 0;
// A multi-line query takes the arrow keys, so IDEA names the keys that still move through results.
const nextKey = shortcutLabel("find.popup.nextResult");
const previousKey = shortcutLabel("find.popup.previousResult");
const navigationHint =
s.pattern.includes("\n") && nextKey && previousKey ? tx`Use ${nextKey} and ${previousKey} to select usages` : "";
const resultsBox = (
<div
className={clsx(styles.results, stale && styles.outdated)}
data-stale={stale || undefined}
aria-busy={stale || state.status === "searching"}
>
<List<MatchRow>
items={rows}
getKey={(r, i) => `${r.key}:${i}`}
activeIndex={active}
isSelected={(r) => isRowSelected(sel, r.key)}
onActivate={(r, i, e) => {
if (e.type === "click" && (e as MouseEvent).detail < 2) return onRowClick(i, e as MouseEvent);
openRow(r, e.shiftKey);
}}
focusable={false}
rowHeight={ROW}
aria-label="Matches"
empty={
<EmptyResults state={state} options={options} onClear={clearOptions} onRegex={() => set({ isRegex: true })} />
}
renderItem={(r, st) => {
const state = s.replace ? groupState(r, marks) : "pending";
return (
<>
<span
className={clsx(
styles.rowText,
state === "done" && styles.rowDone,
state === "excluded" && styles.rowExcluded,
)}
>
<MatchText
text={r.text}
ranges={stale ? [] : r.ranges}
source={{ path: r.path, line: r.line, col: r.textCol }}
/>
</span>
<span className={clsx(styles.rowFile, st.active && styles.rowFileActive)}>
{state === "done" && (
<span className={styles.rowLine}>
<T>replaced ·</T>{" "}
</span>
)}
{workspace ? r.relPath : basename(r.relPath)} <span className={styles.rowLine}>{r.line + 1}</span>
</span>
</>
);
}}
/>
</div>
);
return (
<Dialog
open
onClose={close}
width={820}
resizable="both"
minWidth={560}
minHeight={400}
initialSize={initialSize}
onResized={saveFindPopupSize}
position="top"
transparentBackdrop
// IDEA's Find in Files is a modeless dialog: it survives switching to another app.
@@ -618,17 +521,13 @@ function FindInFilesDialog() {
{summary}
</span>
<span className={styles.spacer} />
<Checkbox
checked={s.maskEnabled}
onChange={enableMask}
label={<Mnemonic text={tx("File mask:")} char="K" />}
/>
<Checkbox checked={s.maskEnabled} onChange={(v) => set({ maskEnabled: v })} label="File mask:" />
<div ref={maskRef} className={clsx(styles.mask, !s.maskEnabled && styles.maskOff)}>
<input
ref={maskInputRef}
className={styles.maskInput}
value={s.mask}
placeholder={projectMasks[0] ?? ""}
placeholder="*.kt, !*Test*"
aria-label={tx("File mask")}
spellCheck={false}
onChange={(e) => set({ mask: e.target.value, maskEnabled: true })}
@@ -658,7 +557,7 @@ function FindInFilesDialog() {
data-autofocus
value={s.pattern}
onChange={(v) => set({ pattern: v })}
placeholder="Search"
placeholder={s.isRegex ? "Regular expression" : "Text to find"}
aria-label="Text to find"
invalid={state.status === "invalid"}
className={styles.field}
@@ -669,7 +568,7 @@ function FindInFilesDialog() {
id: "case",
icon: "case",
title: "Match Case",
shortcut: formatBinding("Alt+C"),
shortcut: "⌥C",
pressed: s.caseSensitive,
onToggle: (v) => set({ caseSensitive: v }),
},
@@ -677,7 +576,7 @@ function FindInFilesDialog() {
id: "word",
icon: "word",
title: "Words",
shortcut: formatBinding("Alt+W"),
shortcut: "⌥W",
pressed: s.wholeWord,
onToggle: (v) => set({ wholeWord: v }),
},
@@ -685,7 +584,7 @@ function FindInFilesDialog() {
id: "regex",
icon: "regex",
title: "Regex",
shortcut: formatBinding("Alt+X"),
shortcut: "⌥X",
pressed: s.isRegex,
onToggle: (v) => set({ isRegex: v }),
},
@@ -699,7 +598,7 @@ function FindInFilesDialog() {
value={s.replacement}
onChange={(v) => set({ replacement: v })}
leadingIcon="replace"
placeholder="Replace"
placeholder="Replace with"
aria-label="Replace with"
className={styles.field}
multiline
@@ -709,7 +608,7 @@ function FindInFilesDialog() {
id: "preserveCase",
icon: "preserve-case",
title: "Preserve Case",
shortcut: formatBinding("Alt+E"),
shortcut: "⌥E",
pressed: s.preserveCase,
onToggle: (v) => set({ preserveCase: v }),
},
@@ -722,13 +621,17 @@ function FindInFilesDialog() {
<Tabs
variant="compact"
aria-label="Search scope"
items={SCOPE_TABS.map((t) => ({
id: t.id,
label: <Mnemonic text={tx(t.label)} char={t.mnemonic} />,
text: t.label,
}))}
items={SCOPE_TABS.map((t) => ({ id: t.id, label: t.label }))}
activeId={s.scopeTab}
onSelect={(id) => selectScope(id as ScopeTab)}
onSelect={(id) => {
// IDEA starts the Directory scope at the current file's folder.
if (id === "directory" && !s.directory.trim()) {
const active = maybeEditorService()?.activePath();
const folders = project?.workspace?.projects ?? (root ? [root] : []);
const dir = active && folders.some((r) => active.startsWith(r + "/")) ? dirname(active) : root;
set({ scopeTab: "directory", directory: dir ?? "" });
} else set({ scopeTab: id as ScopeTab });
}}
/>
<div className={styles.scopeDetail}>
{s.scopeTab === "directory" && (
@@ -803,82 +706,128 @@ function FindInFilesDialog() {
)}
</div>
</div>
<div className={styles.split}>
{rows.length ? (
<SplitGroup orientation="vertical" id="find-popup-split" defaultLayout={split} onLayoutChanged={keepSplit}>
<SplitPanel id="results" minSize={ROW * 3} defaultSize="48%">
{resultsBox}
</SplitPanel>
<SplitHandle hairline={false} />
<SplitPanel id="preview" minSize={96}>
<div className={styles.previewHeader}>
{selected ? (
<span className={styles.previewPath}>
<span className={styles.previewName}>{basename(selected.relPath)}</span>
{selected.relPath.includes("/") && dirname(selected.relPath)}
</span>
) : (
<span />
)}
</div>
<div className={styles.previewBox}>
{!stale && previewMode && s.replace && selected ? (
<ReplaceDiffPreview
lines={diffPreview?.key === diffPreviewKey ? diffPreview.lines : null}
line={selected.line}
<div
className={clsx(styles.results, stale && styles.outdated)}
data-stale={stale || undefined}
aria-busy={stale || state.status === "searching"}
>
<List<MatchRow>
items={rows}
getKey={(r, i) => `${r.key}:${i}`}
activeIndex={active}
isSelected={(r) => isRowSelected(sel, r.key)}
onActivate={(r, i, e) => {
if (e.type === "click" && (e as MouseEvent).detail < 2) return onRowClick(i, e as MouseEvent);
openRow(r, e.shiftKey);
}}
focusable={false}
rowHeight={ROW}
aria-label="Matches"
empty={<span>{emptyText(state, s.pattern)}</span>}
renderItem={(r, st) => {
const state = s.replace ? groupState(r, marks) : "pending";
return (
<>
<span
className={clsx(
styles.rowText,
state === "done" && styles.rowDone,
state === "excluded" && styles.rowExcluded,
)}
>
<MatchText
text={r.text}
ranges={stale ? [] : r.ranges}
source={{ path: r.path, line: r.line, col: r.textCol }}
active={st.active}
replacement={!stale && s.replace && state !== "done" ? s.replacement : null}
query={query}
preserveCase={s.preserveCase}
/>
) : (
<CodePreview
path={selected?.path ?? null}
line={selected?.line ?? 0}
highlights={fileHighlights}
version={previewVersion}
/>
)}
</div>
</SplitPanel>
</SplitGroup>
</span>
<span className={clsx(styles.rowFile, st.active && styles.rowFileActive)}>
{state === "done" && (
<span className={styles.rowLine}>
<T>replaced ·</T>{" "}
</span>
)}
{workspace ? r.relPath : basename(r.relPath)} <span className={styles.rowLine}>{r.line + 1}</span>
</span>
</>
);
}}
/>
</div>
<div className={styles.previewHeader}>
{selected ? (
<>
<span className={styles.previewPath}>{selected.relPath}</span>
<span className={styles.rowLine}>
{selected.line + 1}:{selected.col + 1}
</span>
</>
) : (
resultsBox
<span />
)}
</div>
<div className={styles.previewBox}>
{!stale && previewMode && s.replace && selected ? (
<ReplaceDiffPreview
lines={diffPreview?.key === diffPreviewKey ? diffPreview.lines : null}
line={selected.line}
/>
) : (
<CodePreview
path={selected?.path ?? null}
line={selected?.line ?? 0}
highlights={fileHighlights}
version={previewVersion}
/>
)}
</div>
<footer className={styles.footer}>
<Checkbox
checked={s.newTab}
onChange={setFindPopupNewTab}
label={<Mnemonic text={tx("Open results in new tab")} char="B" />}
/>
{s.replace && <Checkbox checked={previewMode} onChange={setPreviewMode} label="Preview" />}
{navigationHint && <span className={styles.hint}>{navigationHint}</span>}
<span className={styles.spacer} />
<span className={styles.hint}>
{s.replace ? (
<T>↵ Replace Selected · ⇧⌥↵ Replace All · ⌘↵ Open in Find Window</T>
) : (
<T>↵ Open · ⇧↵ Open to the side · ⌘↵ Open in Find Window</T>
)}
</span>
{s.replace && progress && (
<span className={styles.hint} aria-live="polite">
{tx`Replacing… ${progress.done}/${progress.total} files`}
</span>
)}
{s.replace && running && (
<Button onClick={() => running.cancel()}>
<Button size="small" onClick={() => running.cancel()}>
<T>Stop</T>
</Button>
)}
<span className={styles.okHint}>{formatBinding(hostBinding("Meta+Enter"))}</span>
<Button disabled={!s.pattern} onClick={pin}>
<T>Open in Find Window</T>
</Button>
{s.replace && (
<>
<Checkbox checked={previewMode} onChange={setPreviewMode} label="Preview" />
<Button size="small" variant="secondary" disabled={stale || !selected || busy} onClick={skip}>
<T>Skip</T>
</Button>
<Button size="small" disabled={stale || !selected || busy} onClick={() => void replaceSelected()}>
{pendingSelected > 1 ? txt(`Replace ${pendingSelected} Occurrences`) : <T>Replace</T>}
</Button>
<Button size="small" disabled={stale || !selected || busy} onClick={() => void replaceInFile()}>
<T>Replace All in This File</T>
</Button>
<Button
title={formatBinding("Shift+Alt+Enter")}
size="small"
title="Replace All (⇧⌥↵, ⌥A)"
disabled={stale || !rows.length || busy || state.status === "searching"}
onClick={() => void confirmReplaceAll()}
>
<Mnemonic text={tx("Replace All")} char="A" />
</Button>
<Button variant="primary" disabled={stale || !selected || busy} onClick={() => void replaceSelected()}>
{pendingSelected > 1 ? txt(`Replace ${pendingSelected} Occurrences`) : <T>Replace</T>}
<T>Replace All</T>
</Button>
</>
)}
<Button size="small" variant={s.replace ? "secondary" : "primary"} disabled={!s.pattern} onClick={pin}>
<T>Open in Find Window</T>
</Button>
</footer>
</div>
<Menu
@@ -908,89 +857,20 @@ function FindInFilesDialog() {
);
}
/** IDEA's header count: shown once something matched. */
function statusText(s: FindState): string {
if (!s.matchCount) return "";
const key = s.summary?.limitHit ? "search.find.matchesIncomplete" : "search.find.matches";
return t(key, { matches: s.matchCount, files: s.files.length });
if (s.status === "invalid") return "Invalid pattern";
if (s.status === "error") return s.error ?? "Search failed";
if (s.status === "idle") return "";
const files = s.files.length;
const more = s.summary?.limitHit ? "+" : "";
if (!s.matchCount) return s.status === "done" ? "No matches" : "Searching…";
return `${s.matchCount}${more} match${s.matchCount === 1 ? "" : "es"} in ${files}${more} file${files === 1 ? "" : "s"}`;
}
const REGEX_CHARS = /[.$|()[\]{}^?*+\\]/;
/** Whether text with regex syntax in it is also a valid pattern: IDEA then offers "Search with Regex". */
function couldBeRegex(text: string): boolean {
if (!REGEX_CHARS.test(text)) return false;
try {
new RegExp(text);
return true;
} catch {
return false;
}
}
/** IDEA's empty results text: why nothing is listed, the search options in use and how to clear them. */
function EmptyResults({
state,
options: o,
onClear,
onRegex,
}: {
state: FindState;
options: FindOptions;
onClear: () => void;
onRegex: () => void;
}) {
const masked = o.maskEnabled && !!o.mask.trim();
if (!o.pattern && !masked) return <div className={styles.empty}>{tx("Type search query to find in files")}</div>;
if (state.status === "invalid") return <div className={styles.empty}>{state.error ?? tx("Invalid pattern")}</div>;
if (state.status === "error") return <div className={styles.empty}>{state.error ?? tx("Search failed")}</div>;
if (o.pattern && state.status !== "done") return <div className={styles.empty}>{tx("Searching…")}</div>;
const used = [
o.caseSensitive && { label: "Match Case", key: "Alt+C" },
o.wholeWord && { label: "Words", key: "Alt+W" },
o.isRegex && { label: "Regex", key: "Alt+X" },
masked && { label: "File mask", key: "Alt+K" },
o.context !== "any" && { label: "Filter", key: "" },
].filter((u) => !!u);
const regex = !!o.pattern && !o.isRegex && couldBeRegex(o.pattern);
const clearKey = formatBinding("Shift+Alt+Backspace");
return (
<div className={styles.empty}>
<div>
{o.pattern ? tx("Nothing found") : tx("No search text entered")}
{used.length || regex ? "." : ""}
</div>
{regex ? (
<div className={styles.emptyOptions}>
<div>
<button type="button" className={styles.link} onClick={onRegex}>
<T>Search with Regex</T>
</button>{" "}
{formatBinding("Alt+X")}
</div>
</div>
) : used.length ? (
<div className={styles.emptyOptions}>
{used.length === 1 ? (
<div>{tx`Search option used: ${tx(used[0]!.label)}`}</div>
) : (
<>
<div>
<T>Search options used:</T>
</div>
<div>
{used.map((u) => [tx(u.label), u.key && formatBinding(u.key)].filter(Boolean).join(" ")).join(" ")}
</div>
</>
)}
<div>
<button type="button" className={styles.link} onClick={onClear}>
{used.length === 1 ? <T>Clear option</T> : <T>Clear all options</T>}
</button>{" "}
{clearKey}
</div>
</div>
) : null}
</div>
);
function emptyText(s: FindState, pattern: string): string {
if (!pattern) return "Type text to search the project";
if (s.status === "invalid") return s.error ?? "Invalid pattern";
if (s.status === "searching" || s.status === "validating") return "Searching…";
if (s.status === "error") return s.error ?? "Search failed";
return "Nothing found";
}
Loaded 100 of 154 files, more files were not shown because too many files have changed in this diff. Show more