дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-26 20:46:22 +02:00
Порівняти коміти
7
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
c57156ef4b | ||
|
|
f55cdcdc31 | ||
|
|
7d267ab50e | ||
|
|
50986088f9 | ||
|
|
7a0f60377c | ||
|
|
945f09347e | ||
|
|
2924824e7b |
No files matched your search
@@ -2,6 +2,7 @@
|
||||
//! Capabilities were checked by the runtime before any of this runs.
|
||||
|
||||
use super::{PluginEvent, PluginEventSink};
|
||||
use ide_core::ipc_path::to_ipc;
|
||||
use ide_core::{CancellationToken, TextEdit};
|
||||
use ide_extension::Package;
|
||||
use ide_language::ProgramPin;
|
||||
@@ -419,7 +420,7 @@ impl HostApi for PluginApi {
|
||||
let info = repo.branch_info().map_err(failed)?;
|
||||
let changed = repo.status().map_err(failed)?.len();
|
||||
Ok(Some(RepositoryStatus {
|
||||
root: repo.root().to_string_lossy().into_owned(),
|
||||
root: to_ipc(repo.root()),
|
||||
branch: info.head,
|
||||
commit: info.head_commit,
|
||||
upstream: info.upstream,
|
||||
@@ -467,7 +468,7 @@ impl HostApi for PluginApi {
|
||||
}
|
||||
let Ok(rel) = entry.path().strip_prefix(root) else { continue };
|
||||
if matcher.is_match(rel) {
|
||||
out.push(entry.path().to_string_lossy().into_owned());
|
||||
out.push(to_ipc(entry.path()));
|
||||
}
|
||||
}
|
||||
out.sort();
|
||||
@@ -806,6 +807,19 @@ mod tests {
|
||||
PluginApi { pkg: Package::new(manifest, dir.to_path_buf()), shared }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repository_and_search_paths_match_ipc_events() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
assert!(std::process::Command::new("git").args(["init", "-q"]).arg(tmp.path()).status().unwrap().success());
|
||||
let root = tmp.path().canonicalize().unwrap();
|
||||
std::fs::create_dir(root.join("src")).unwrap();
|
||||
let file = root.join("src/Example.java");
|
||||
std::fs::write(&file, "class Example {}\n").unwrap();
|
||||
let api = api(&root, Arc::default());
|
||||
assert_eq!(api.find_files(&root, "**/*.java", 8).unwrap(), [to_ipc(&file)]);
|
||||
assert_eq!(api.vcs_status(&root).unwrap().unwrap().root, to_ipc(&root));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn programs_run_only_as_approved() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
//! `plugins/build.sh <dir>` after changing their source or `wit/`.
|
||||
|
||||
use ide_core::error::ErrorKind;
|
||||
use ide_core::ipc_path::to_ipc;
|
||||
use ide_host::plugins::*;
|
||||
use ide_plugin::{EditorContext, HostError, Invocation, Limits};
|
||||
use parking_lot::Mutex;
|
||||
@@ -214,7 +215,7 @@ fn fixture(limits: Limits) -> Fixture {
|
||||
std::fs::create_dir_all(project.join("src")).unwrap();
|
||||
std::fs::write(project.join("src/notes.txt"), "one two three\nfour five\n").unwrap();
|
||||
std::fs::write(tmp.path().join("secret.txt"), "top secret").unwrap();
|
||||
let project = project.canonicalize().unwrap();
|
||||
let project = dunce::canonicalize(project).unwrap();
|
||||
let events: Events = Arc::default();
|
||||
let sink = {
|
||||
let events = events.clone();
|
||||
@@ -359,7 +360,7 @@ fn read_file_is_confined_to_the_project() {
|
||||
let inv = Invocation { client: None, workspace_root: None, editor: None };
|
||||
let err = f.host.run_command("misbehave", "read", Some("src/notes.txt"), inv).unwrap_err().message;
|
||||
assert!(err.contains("no project is open"), "{err}");
|
||||
assert_eq!(f.run("misbehave", "root", None).unwrap().unwrap(), f.project.to_string_lossy());
|
||||
assert_eq!(f.run("misbehave", "root", None).unwrap().unwrap(), to_ipc(&f.project));
|
||||
assert_eq!(f.status("misbehave"), PluginStatus::Active);
|
||||
}
|
||||
|
||||
@@ -1740,7 +1741,7 @@ fn official_checkstyle_checks_on_save() {
|
||||
let java = f.project.join("src/A.java");
|
||||
std::fs::write(&java, "class A {\n\tint x;\n}\n").unwrap();
|
||||
let saved = |f: &Fixture| {
|
||||
f.host.post_events(Some("main"), vec![WorkbenchEvent::FileSaved(java.to_string_lossy().into_owned())]);
|
||||
f.host.post_events(Some("main"), vec![WorkbenchEvent::FileSaved(to_ipc(&java))]);
|
||||
f.host.flush_events_at(Instant::now() + Duration::from_secs(3));
|
||||
};
|
||||
saved(&f);
|
||||
@@ -1793,7 +1794,7 @@ fn official_license_header_reports_fixes_and_scans() {
|
||||
f.workspace.diagnostics.lock().get(&("openidea.license-header".into(), path.to_path_buf())).cloned()
|
||||
};
|
||||
|
||||
f.host.post_events(Some("main"), vec![WorkbenchEvent::FileOpened(a.to_string_lossy().into_owned())]);
|
||||
f.host.post_events(Some("main"), vec![WorkbenchEvent::FileOpened(to_ipc(&a))]);
|
||||
f.host.flush_events_at(Instant::now() + Duration::from_secs(3));
|
||||
assert!(f.host.wait_events(Duration::from_secs(20)));
|
||||
let d = diagnostics(&a).expect("published on open");
|
||||
@@ -1818,7 +1819,7 @@ fn official_license_header_reports_fixes_and_scans() {
|
||||
f.host.run_command("openidea.license-header", "scan", None, f.inv()).unwrap();
|
||||
assert_eq!(diagnostics(&b).map(|d| d.len()), Some(1), "found by the scan");
|
||||
std::fs::write(&a, "// Copyright (c) 2026 X\nfn a() {}\n").unwrap();
|
||||
f.host.post_events(Some("main"), vec![WorkbenchEvent::FileSaved(a.to_string_lossy().into_owned())]);
|
||||
f.host.post_events(Some("main"), vec![WorkbenchEvent::FileSaved(to_ipc(&a))]);
|
||||
f.host.flush_events_at(Instant::now() + Duration::from_secs(3));
|
||||
assert!(f.host.wait_events(Duration::from_secs(20)));
|
||||
assert_eq!(diagnostics(&a).map(|d| d.len()), Some(0), "cleared once the header is there");
|
||||
|
||||
@@ -13,6 +13,7 @@ use crate::types::{
|
||||
};
|
||||
use crate::wit_host::{bindings, providers_bindings, syntax_bindings, views_bindings};
|
||||
use ide_core::CancellationToken;
|
||||
use ide_core::ipc_path::to_ipc;
|
||||
use ide_extension::Capability;
|
||||
use parking_lot::Mutex;
|
||||
use std::path::Path;
|
||||
@@ -935,12 +936,7 @@ fn location_from_wit(l: wit_types::Location) -> Location {
|
||||
}
|
||||
|
||||
fn doc_to_wit(d: &ProviderDocument) -> wit_prov::Document {
|
||||
wit_prov::Document {
|
||||
path: d.path.to_string_lossy().into_owned(),
|
||||
language: d.language.clone(),
|
||||
version: d.version,
|
||||
text: d.text.clone(),
|
||||
}
|
||||
wit_prov::Document { path: to_ipc(&d.path), language: d.language.clone(), version: d.version, text: d.text.clone() }
|
||||
}
|
||||
|
||||
/// Resets the budgets for the next call: fuel, deadline, cancellation.
|
||||
@@ -1012,7 +1008,7 @@ fn code_action_to_wit(a: &CodeAction) -> wit_prov::CodeAction {
|
||||
.edits
|
||||
.iter()
|
||||
.map(|(path, edits)| wit_prov::FileEdit {
|
||||
path: path.to_string_lossy().into_owned(),
|
||||
path: to_ipc(path),
|
||||
edits: edits
|
||||
.iter()
|
||||
.map(|e| wit_types::TextEdit { range: range_to_wit(e.range), text: e.new_text.clone() })
|
||||
@@ -1131,6 +1127,27 @@ fn event_to_wit_view(e: ViewEvent) -> wit_vt::ViewEvent {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn provider_and_resolved_action_paths_match_ipc_events() {
|
||||
for (path, expected) in [
|
||||
(r"C:\project\Example.java", "C:/project/Example.java"),
|
||||
(r"\\?\C:\project\Example.java", "C:/project/Example.java"),
|
||||
(r"\\server\share\Example.java", "//server/share/Example.java"),
|
||||
] {
|
||||
let doc = ProviderDocument { path: path.into(), ..Default::default() };
|
||||
assert_eq!(doc_to_wit(&doc).path, expected);
|
||||
let action = CodeAction {
|
||||
title: "Fix".into(),
|
||||
kind: None,
|
||||
preferred: false,
|
||||
edits: vec![(path.into(), Vec::new())],
|
||||
data: None,
|
||||
};
|
||||
assert_eq!(code_action_to_wit(&action).edits[0].path, expected);
|
||||
}
|
||||
}
|
||||
|
||||
fn ext(kind: &str) -> wit_types::Extension {
|
||||
wit_types::Extension { kind: kind.into(), data: "{}".into() }
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
use crate::runtime::{StoreData, clip};
|
||||
use crate::sandbox;
|
||||
use crate::types::{EditorContext, EventKind, HostError, HttpRequest, NotificationLevel, StatusItem, net_host};
|
||||
use ide_core::ipc_path::to_ipc;
|
||||
use ide_extension::Capability;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, Instant};
|
||||
@@ -310,7 +311,8 @@ impl workspace::HostProject for StoreData {
|
||||
if let Err(e) = self.require(Capability::ProjectRead) {
|
||||
return Ok(Err(e));
|
||||
}
|
||||
Ok(Ok(self.table.get(&this)?.root.to_string_lossy().into_owned()))
|
||||
// Paths reach plugins in IPC form (`/` on Windows), as the UI's event paths do, so they compare as text.
|
||||
Ok(Ok(to_ipc(&self.table.get(&this)?.root)))
|
||||
}
|
||||
|
||||
fn read_file(&mut self, this: Resource<ProjectRes>, path: String) -> Fallible<String> {
|
||||
@@ -346,7 +348,7 @@ impl editor::Host for StoreData {}
|
||||
|
||||
impl editor::HostTextEditor for StoreData {
|
||||
fn path(&mut self, this: Resource<EditorRes>) -> wasmtime::Result<String> {
|
||||
Ok(self.table.get(&this)?.ctx.path.to_string_lossy().into_owned())
|
||||
Ok(to_ipc(&self.table.get(&this)?.ctx.path))
|
||||
}
|
||||
|
||||
fn language(&mut self, this: Resource<EditorRes>) -> wasmtime::Result<String> {
|
||||
|
||||
@@ -3,8 +3,9 @@
|
||||
//! its templates (`default="true"`) and temporary configurations. A configuration found in more
|
||||
//! than one place is taken from the first, in that order.
|
||||
//!
|
||||
//! Python, Django server, Django tests, pytest, npm, Jest, Vitest, Node.js, Shell Script and
|
||||
//! compound configurations become the matching kinds; other types are skipped with their type.
|
||||
//! Python, Django server, Django tests, pytest, npm, Jest, Vitest, Node.js, Shell Script,
|
||||
//! Application, Spring Boot and compound configurations become the matching kinds; other types
|
||||
//! are skipped with their type.
|
||||
//! `$PROJECT_DIR$` (and `$MODULE_DIR$`, `$MODULE_WORKING_DIR$`, `$ContentRoot$`,
|
||||
//! `$ProjectFileDir$`, all the project directory here) and `$USER_HOME$` are replaced; another
|
||||
//! path variable skips the configuration.
|
||||
@@ -162,6 +163,8 @@ const VITEST: &str = "JavaScriptTestRunnerVitest";
|
||||
const NODE: &str = "NodeJSConfigurationType";
|
||||
const SHELL: &str = "ShConfigurationType";
|
||||
const COMPOUND: &str = "CompoundRunConfigurationType";
|
||||
const APPLICATION: &str = "Application";
|
||||
const SPRING_BOOT: &str = "SpringBootApplicationConfigurationType";
|
||||
|
||||
type Res<T> = Result<T, SkipReason>;
|
||||
|
||||
@@ -329,6 +332,8 @@ impl Cx<'_> {
|
||||
JEST | VITEST => self.js_tests(name, c, ty == VITEST, &mut ignored)?,
|
||||
NODE => self.node(name, c, &mut ignored)?,
|
||||
SHELL => self.shell(name, c)?,
|
||||
APPLICATION => self.java_app(name, c, false, &mut ignored)?,
|
||||
SPRING_BOOT => self.java_app(name, c, true, &mut ignored)?,
|
||||
COMPOUND => {
|
||||
members = c.children_named("toRun").filter_map(|t| t.attr("name")).map(str::to_owned).collect();
|
||||
config(name, "compound", String::new(), Vec::new(), None)
|
||||
@@ -695,6 +700,54 @@ impl Cx<'_> {
|
||||
Ok(rc)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------- Java
|
||||
|
||||
/// IDEA's Application and Spring Boot types, as the `application` / `spring-boot` forms run
|
||||
/// them: `java <vm options> -cp ${classpath} <main> [--spring.profiles.active=…] <arguments>`
|
||||
/// with the module's runtime classpath.
|
||||
fn java_app(&self, name: &str, c: &El, spring: bool, ignored: &mut Vec<String>) -> Res<RunConfig> {
|
||||
let main = if spring { "SPRING_BOOT_MAIN_CLASS" } else { "MAIN_CLASS_NAME" };
|
||||
let Some(main) = self.text(c.option(main))? else { return Err(SkipReason::NothingToRun) };
|
||||
let (_, cwd) = self.cwd(c.option("WORKING_DIRECTORY"))?;
|
||||
let mut args = self.words(c.option("VM_PARAMETERS"))?;
|
||||
args.extend(["-cp".to_owned(), "${classpath}".to_owned(), main]);
|
||||
if spring && let Some(profiles) = self.text(c.option("ACTIVE_PROFILES"))? {
|
||||
args.push(format!("--spring.profiles.active={profiles}"));
|
||||
}
|
||||
args.extend(self.words(c.option("PROGRAM_PARAMETERS"))?);
|
||||
let mut rc =
|
||||
config(name, if spring { "spring-boot" } else { "application" }, "java".into(), args, Some("java-debug"));
|
||||
rc.cwd = cwd.map(Into::into);
|
||||
self.envs(c, &mut rc);
|
||||
if let Some(module) = c.child("module").and_then(|m| m.attr("name")).filter(|m| !m.is_empty()) {
|
||||
match module_dir(self.root, module) {
|
||||
Some(dir) => rc.extras.module = Some(dir),
|
||||
None => ignored.push(format!("module {module}")),
|
||||
}
|
||||
}
|
||||
// Options the forms have no field for.
|
||||
if c.flag("ALTERNATIVE_JRE_PATH_ENABLED") {
|
||||
ignored.push("JRE".into());
|
||||
}
|
||||
if c.flag("INCLUDE_PROVIDED_SCOPE") {
|
||||
ignored.push("provided scope".into());
|
||||
}
|
||||
if c.child("classpathModifications").is_some_and(|m| !m.children.is_empty()) {
|
||||
ignored.push("classpath modifications".into());
|
||||
}
|
||||
if spring {
|
||||
for (option, label) in [("HIDE_BANNER", "hide banner"), ("DEBUG_MODE", "debug output")] {
|
||||
if c.flag(option) {
|
||||
ignored.push(label.into());
|
||||
}
|
||||
}
|
||||
if c.child("additionalParameters").is_some_and(|p| !p.children.is_empty()) {
|
||||
ignored.push("override configuration properties".into());
|
||||
}
|
||||
}
|
||||
Ok(rc)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------- Shell
|
||||
|
||||
/// A script file (with its interpreter) or script text, kept as the Shell Script form's fields.
|
||||
@@ -835,6 +888,56 @@ fn module_count(root: &Path) -> usize {
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// The folder (relative, `""` for the project's own) of IDEA module `name`: a Maven module is
|
||||
/// named after its `artifactId` (usually its folder), a Gradle one `<project>.<path>.<source set>`.
|
||||
fn module_dir(root: &Path, name: &str) -> Option<String> {
|
||||
let folder = |dir: &Path| dir.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let exact = |dir: &Path| folder(dir) == name || pom_artifact(dir).is_some_and(|a| a == name);
|
||||
if let Some(dir) = find_module(root, &exact) {
|
||||
return Some(dir);
|
||||
}
|
||||
let gradle = name.strip_suffix(".main").or_else(|| name.strip_suffix(".test")).unwrap_or(name);
|
||||
let last = gradle.rsplit('.').next().filter(|last| *last != name)?;
|
||||
find_module(root, &|dir: &Path| folder(dir) == last)
|
||||
}
|
||||
|
||||
/// The shallowest build folder under `root` (itself included) that `names` accepts.
|
||||
fn find_module(root: &Path, names: &dyn Fn(&Path) -> bool) -> Option<String> {
|
||||
const BUILDS: [&str; 3] = ["pom.xml", "build.gradle", "build.gradle.kts"];
|
||||
let mut level = vec![root.to_path_buf()];
|
||||
for _ in 0..5 {
|
||||
if let Some(found) = level.iter().find(|d| BUILDS.iter().any(|b| d.join(b).is_file()) && names(d)) {
|
||||
let rel = found.strip_prefix(root).ok()?;
|
||||
return Some(rel.to_string_lossy().replace('\\', "/"));
|
||||
}
|
||||
let mut next: Vec<PathBuf> = level
|
||||
.iter()
|
||||
.filter_map(|d| std::fs::read_dir(d).ok())
|
||||
.flat_map(|entries| entries.flatten().map(|e| e.path()))
|
||||
.filter(|p| p.is_dir())
|
||||
.filter(|p| {
|
||||
let n = p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
!n.starts_with('.') && !["node_modules", "target", "build", "out", "src"].contains(&n.as_str())
|
||||
})
|
||||
.collect();
|
||||
next.sort();
|
||||
level = next;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The `artifactId` of the module's own `pom.xml` (not its parent's).
|
||||
fn pom_artifact(dir: &Path) -> Option<String> {
|
||||
let pom = std::fs::read_to_string(dir.join("pom.xml")).ok()?;
|
||||
let own = match (pom.find("<parent>"), pom.find("</parent>")) {
|
||||
(Some(start), Some(end)) if start < end => format!("{}{}", &pom[..start], &pom[end..]),
|
||||
_ => pom,
|
||||
};
|
||||
let start = own.find("<artifactId>")? + "<artifactId>".len();
|
||||
let end = start + own[start..].find("</artifactId>")?;
|
||||
Some(own[start..end].trim().to_owned())
|
||||
}
|
||||
|
||||
/// `--settings` from PyCharm's "Settings" field: a file (`mysite/settings/dev.py`, relative to
|
||||
/// the project) becomes its module relative to the working directory; a module stays as it is.
|
||||
fn settings_module(value: &str, root: &Path, dir: &Path) -> String {
|
||||
|
||||
@@ -204,7 +204,7 @@ pub fn explode(war: &Path, destination: &Path, resources_only: bool) -> IdeResul
|
||||
}
|
||||
|
||||
/// Updates the exploded artifact deployment from the module's own class output directories and
|
||||
/// its web resources (`src/main/webapp`), file by file and only what changed, instead of
|
||||
/// its web resources ([`web_sources`]), file by file and only what changed, instead of
|
||||
/// rebuilding and re-exploding the WAR. `module` and `class_paths` are absolute.
|
||||
/// `Ok(false)`: not possible this way (not deployed from the artifact yet, the module's output
|
||||
/// isn't on the classpath, or a module it depends on was compiled since the last update, whose
|
||||
@@ -232,9 +232,10 @@ pub fn sync_outputs(base: &Path, module: &Path, class_paths: &[PathBuf], resourc
|
||||
for dir in own {
|
||||
sync_tree(dir, dir, &classes, Path::new("WEB-INF/classes"), resources_only, &mut current)?;
|
||||
}
|
||||
let webapp = module.join("src/main/webapp");
|
||||
if webapp.is_dir() {
|
||||
sync_tree(&webapp, &webapp, &dest, Path::new(""), resources_only, &mut current)?;
|
||||
for (dir, target) in web_sources(module) {
|
||||
if dir.is_dir() {
|
||||
sync_tree(&dir, &dir, &dest.join(&target), &target, resources_only, &mut current)?;
|
||||
}
|
||||
}
|
||||
for rel in previous.iter().filter(|p| !current.contains(*p)) {
|
||||
let path = dest.join(rel);
|
||||
@@ -246,6 +247,59 @@ pub fn sync_outputs(base: &Path, module: &Path, class_paths: &[PathBuf], resourc
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// The folders whose files the WAR puts at its root (or under the second path): the web app
|
||||
/// folder (`src/main/webapp`, maven-war-plugin's `warSourceDirectory`, Gradle's
|
||||
/// `webAppDirName` / `webAppDirectory`), then maven-war-plugin's `webResources`.
|
||||
pub fn web_sources(module: &Path) -> Vec<(PathBuf, PathBuf)> {
|
||||
let rel = |dir: &str| {
|
||||
let dir = ["${project.basedir}/", "${basedir}/"].iter().find_map(|p| dir.strip_prefix(p)).unwrap_or(dir);
|
||||
module.join(dir.trim())
|
||||
};
|
||||
if let Ok(pom) = fs::read_to_string(module.join("pom.xml"))
|
||||
&& let Some(war) = war_plugin(&pom)
|
||||
{
|
||||
let mut out = vec![(rel(tag(war, "warSourceDirectory").unwrap_or("src/main/webapp")), PathBuf::new())];
|
||||
let mut rest = tag_block(war, "webResources").unwrap_or_default();
|
||||
while let Some(start) = rest.find("<resource>") {
|
||||
let end = rest[start..].find("</resource>").map_or(rest.len(), |e| start + e);
|
||||
let resource = &rest[start..end];
|
||||
if let Some(dir) = tag(resource, "directory") {
|
||||
out.push((rel(dir), PathBuf::from(tag(resource, "targetPath").unwrap_or_default())));
|
||||
}
|
||||
rest = &rest[end..];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
let gradle = ["build.gradle", "build.gradle.kts"].iter().find_map(|f| fs::read_to_string(module.join(f)).ok());
|
||||
let web_app_dir = gradle.as_deref().and_then(|text| {
|
||||
text.lines()
|
||||
.filter(|l| !l.trim_start().starts_with("//"))
|
||||
.find(|l| l.contains("webAppDirName") || l.contains("webAppDirectory"))
|
||||
.and_then(|l| l.split(['"', '\'']).nth(1).map(str::to_owned))
|
||||
});
|
||||
vec![(rel(web_app_dir.as_deref().unwrap_or("src/main/webapp")), PathBuf::new())]
|
||||
}
|
||||
|
||||
/// The `<plugin>` element of maven-war-plugin in `pom`, if it is configured there.
|
||||
fn war_plugin(pom: &str) -> Option<&str> {
|
||||
let at = pom.find("<artifactId>maven-war-plugin</artifactId>")?;
|
||||
let start = pom[..at].rfind("<plugin>")?;
|
||||
let end = pom[at..].find("</plugin>").map_or(pom.len(), |e| at + e);
|
||||
Some(&pom[start..end])
|
||||
}
|
||||
|
||||
/// The text of the first `<name>` element in `xml`.
|
||||
fn tag<'a>(xml: &'a str, name: &str) -> Option<&'a str> {
|
||||
tag_block(xml, name).map(str::trim).filter(|t| !t.is_empty())
|
||||
}
|
||||
|
||||
fn tag_block<'a>(xml: &'a str, name: &str) -> Option<&'a str> {
|
||||
let open = format!("<{name}>");
|
||||
let start = xml.find(&open)? + open.len();
|
||||
let end = start + xml[start..].find(&format!("</{name}>"))?;
|
||||
Some(&xml[start..end])
|
||||
}
|
||||
|
||||
fn modified_since(dir: &Path, since: std::time::SystemTime) -> bool {
|
||||
let Ok(entries) = fs::read_dir(dir) else { return false };
|
||||
entries.flatten().any(|e| match e.file_type() {
|
||||
@@ -574,6 +628,83 @@ mod tests {
|
||||
fs::File::create(dep.join("Core.class")).unwrap().set_modified(later).unwrap();
|
||||
assert!(!sync_outputs(&base, &module, &paths, false).unwrap());
|
||||
}
|
||||
#[test]
|
||||
fn web_sources_follow_the_war_plugin_and_gradle_settings() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let module = tmp.path();
|
||||
let rel = |sources: Vec<(PathBuf, PathBuf)>| -> Vec<(String, String)> {
|
||||
sources
|
||||
.into_iter()
|
||||
.map(|(d, t)| {
|
||||
let d = d.strip_prefix(module).unwrap().to_string_lossy().replace('\\', "/");
|
||||
(d, t.to_string_lossy().into_owned())
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
assert_eq!(rel(web_sources(module)), [("src/main/webapp".to_owned(), String::new())]);
|
||||
|
||||
// An Eclipse-style layout: the JSPs come in through webResources.
|
||||
fs::write(
|
||||
module.join("pom.xml"),
|
||||
r#"<project><build><plugins>
|
||||
<plugin><artifactId>maven-compiler-plugin</artifactId></plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<configuration>
|
||||
<warSourceDirectory>${basedir}/web</warSourceDirectory>
|
||||
<webResources>
|
||||
<resource><directory>WebContent</directory><includes><include>**/*</include></includes></resource>
|
||||
<resource><directory>extra</directory><targetPath>static</targetPath></resource>
|
||||
</webResources>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins></build></project>"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
rel(web_sources(module)),
|
||||
[
|
||||
("web".to_owned(), String::new()),
|
||||
("WebContent".to_owned(), String::new()),
|
||||
("extra".to_owned(), "static".to_owned())
|
||||
]
|
||||
);
|
||||
|
||||
fs::remove_file(module.join("pom.xml")).unwrap();
|
||||
fs::write(
|
||||
module.join("build.gradle"),
|
||||
"plugins { id 'war' }\n// webAppDirName = 'old'\nwebAppDirName = 'WebContent'\n",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(rel(web_sources(module)), [("WebContent".to_owned(), String::new())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn updates_web_resources_outside_src_main_webapp() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
let (base, module) = (root.join("base"), root.join("web"));
|
||||
let (dest, out) = (base.join("deployment"), module.join("target/classes"));
|
||||
for dir in [dest.join("WEB-INF/classes"), out.clone(), module.join("WebContent/jsp")] {
|
||||
fs::create_dir_all(dir).unwrap();
|
||||
}
|
||||
fs::write(
|
||||
module.join("pom.xml"),
|
||||
"<project><plugin><artifactId>maven-war-plugin</artifactId><configuration><webResources>\
|
||||
<resource><directory>WebContent</directory></resource></webResources></configuration></plugin></project>",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(dest.join("index.jsp"), "old").unwrap();
|
||||
fs::write(module.join("WebContent/jsp/list.jsp"), "new").unwrap();
|
||||
fs::write(base.join("artifact-path.txt"), "web.war").unwrap();
|
||||
|
||||
assert!(sync_outputs(&base, &module, std::slice::from_ref(&out), true).unwrap());
|
||||
assert_eq!(fs::read_to_string(dest.join("jsp/list.jsp")).unwrap(), "new");
|
||||
// Files the WAR brought that no source here maps to stay.
|
||||
assert_eq!(fs::read_to_string(dest.join("index.jsp")).unwrap(), "old");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deployment_errors_identify_the_checked_path() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -239,8 +239,8 @@ fn workspace_run_manager_skips_templates_and_temporary_configurations() {
|
||||
<envs><env name="VITE_API" value="http://localhost:8000" /></envs>
|
||||
<method v="2" />
|
||||
</configuration>
|
||||
<configuration name="Main" type="Application" factoryName="Application">
|
||||
<option name="MAIN_CLASS_NAME" value="shop.Main" />
|
||||
<configuration name="Main" type="JUnit" factoryName="JUnit">
|
||||
<option name="MAIN_CLASS_NAME" value="shop.MainTest" />
|
||||
<method v="2" />
|
||||
</configuration>"#
|
||||
)),
|
||||
@@ -272,7 +272,7 @@ fn workspace_run_manager_skips_templates_and_temporary_configurations() {
|
||||
assert_eq!(get(&r, "Custom").args, s(&["-m", "pytest", "tests/a.py", "--maxfail=2"]));
|
||||
|
||||
assert_eq!(reason(&r, "Unittests in tests"), &SkipReason::UnsupportedType { type_: "tests (Unittests)".into() });
|
||||
assert_eq!(reason(&r, "Main"), &SkipReason::UnsupportedType { type_: "Application".into() });
|
||||
assert_eq!(reason(&r, "Main"), &SkipReason::UnsupportedType { type_: "JUnit".into() });
|
||||
|
||||
let dev = get(&r, "dev");
|
||||
assert_eq!((dev.kind.as_str(), dev.command.as_str()), ("npm", "pnpm"));
|
||||
@@ -526,14 +526,11 @@ fn sources_are_offered_when_their_files_exist() {
|
||||
),
|
||||
);
|
||||
assert!(available(dir.path()).is_empty());
|
||||
write(dir.path(), ".idea/workspace.xml", &workspace(r#"<configuration name="App" type="Application" />"#));
|
||||
write(dir.path(), ".idea/workspace.xml", &workspace(r#"<configuration name="App" type="JUnit" />"#));
|
||||
assert_eq!(available(dir.path()), [RunImportSource::Jetbrains]);
|
||||
write(dir.path(), ".vscode/launch.json", "{}");
|
||||
assert_eq!(available(dir.path()), [RunImportSource::Vscode, RunImportSource::Jetbrains]);
|
||||
assert_eq!(
|
||||
reason(&import_from(dir.path(), &[]), "App"),
|
||||
&SkipReason::UnsupportedType { type_: "Application".into() }
|
||||
);
|
||||
assert_eq!(reason(&import_from(dir.path(), &[]), "App"), &SkipReason::UnsupportedType { type_: "JUnit".into() });
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -702,3 +699,91 @@ fn flags_defaults_inherited_variables_and_nested_django_tests() {
|
||||
assert_eq!((tests.kind.as_str(), tests.is_test), ("python", true));
|
||||
assert_eq!(tests.args[..3], s(&["backend/manage.py", "test", "orders"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_applications_and_spring_boot_keep_their_module() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap();
|
||||
write(&root, "pom.xml", "<project><artifactId>shop</artifactId><packaging>pom</packaging></project>");
|
||||
write(
|
||||
&root,
|
||||
"example-service/pom.xml",
|
||||
"<project><parent><artifactId>shop</artifactId></parent><artifactId>example-service</artifactId></project>",
|
||||
);
|
||||
// IDEA names a Maven module after its artifactId, which needn't be its folder.
|
||||
write(
|
||||
&root,
|
||||
"services/api/pom.xml",
|
||||
"<project><parent><artifactId>shop</artifactId></parent><artifactId>api-service</artifactId></project>",
|
||||
);
|
||||
write(
|
||||
&root,
|
||||
".idea/workspace.xml",
|
||||
&workspace(
|
||||
r#" <configuration name="ExampleApplication" type="SpringBootApplicationConfigurationType" factoryName="Spring Boot">
|
||||
<module name="example-service" />
|
||||
<option name="SPRING_BOOT_MAIN_CLASS" value="com.example.ExampleApplication" />
|
||||
<option name="ACTIVE_PROFILES" value="dev,local" />
|
||||
<option name="VM_PARAMETERS" value="-Xmx512m -Dfile.encoding=UTF-8" />
|
||||
<option name="PROGRAM_PARAMETERS" value="--server.port=8081" />
|
||||
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/example-service" />
|
||||
<option name="HIDE_BANNER" value="true" />
|
||||
<envs>
|
||||
<env name="TZ" value="UTC" />
|
||||
</envs>
|
||||
<method v="2">
|
||||
<option name="Make" enabled="true" />
|
||||
</method>
|
||||
</configuration>
|
||||
<configuration name="Api" type="Application" factoryName="Application">
|
||||
<option name="MAIN_CLASS_NAME" value="com.example.api.Main" />
|
||||
<module name="api-service" />
|
||||
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="true" />
|
||||
<option name="ALTERNATIVE_JRE_PATH" value="17" />
|
||||
<method v="2" />
|
||||
</configuration>
|
||||
<configuration name="Gone" type="Application" factoryName="Application">
|
||||
<option name="MAIN_CLASS_NAME" value="Gone" />
|
||||
<module name="removed-module" />
|
||||
</configuration>
|
||||
<configuration name="NoMain" type="SpringBootApplicationConfigurationType" factoryName="Spring Boot">
|
||||
<module name="example-service" />
|
||||
</configuration>"#,
|
||||
),
|
||||
);
|
||||
|
||||
let r = import_from(&root, &[]);
|
||||
|
||||
let boot = get(&r, "ExampleApplication");
|
||||
assert_eq!(boot.kind, "spring-boot");
|
||||
assert_eq!(boot.command, "java");
|
||||
assert_eq!(
|
||||
boot.args,
|
||||
s(&[
|
||||
"-Xmx512m",
|
||||
"-Dfile.encoding=UTF-8",
|
||||
"-cp",
|
||||
"${classpath}",
|
||||
"com.example.ExampleApplication",
|
||||
"--spring.profiles.active=dev,local",
|
||||
"--server.port=8081",
|
||||
])
|
||||
);
|
||||
assert_eq!(boot.extras.module.as_deref(), Some("example-service"));
|
||||
assert_eq!(cwd(boot), Some(PathBuf::from("example-service")));
|
||||
assert_eq!(boot.env.get("TZ").map(String::as_str), Some("UTC"));
|
||||
assert_eq!(boot.debug_adapter.as_deref(), Some("java-debug"));
|
||||
assert_eq!(ignored(&r, "ExampleApplication"), ["before launch", "hide banner"]);
|
||||
|
||||
let api = get(&r, "Api");
|
||||
assert_eq!(api.kind, "application");
|
||||
assert_eq!(api.args, s(&["-cp", "${classpath}", "com.example.api.Main"]));
|
||||
assert_eq!(api.extras.module.as_deref(), Some("services/api"));
|
||||
assert_eq!(ignored(&r, "Api"), ["JRE"]);
|
||||
|
||||
// A module that isn't here any more: the form finds it by the main class.
|
||||
assert_eq!(get(&r, "Gone").extras.module, None);
|
||||
assert_eq!(ignored(&r, "Gone"), ["module removed-module"]);
|
||||
|
||||
assert_eq!(reason(&r, "NoMain"), &SkipReason::NothingToRun);
|
||||
}
|
||||
@@ -11,9 +11,10 @@ editors, and contribute menus, shortcuts, settings, themes, file icon themes
|
||||
and languages. Plugins that only contribute data (themes, icons, languages,
|
||||
menus, settings) need no code at all.
|
||||
|
||||
> **Preview.** The plugin system ships as a preview: until it is declared
|
||||
> stable the API (`openidea:[email protected]`) may still change, and the official
|
||||
> plugins are versioned `0.x`. See _Evolving the plugin API_ below.
|
||||
> **Preview.** The plugin system ships as a preview and the official plugins
|
||||
> are versioned `0.x`. Released API versions only grow: a plugin built for
|
||||
> `openidea:[email protected]` keeps loading in later 1.x IDEs. See _Evolving the
|
||||
> plugin API_ below.
|
||||
|
||||
```
|
||||
plugins/
|
||||
@@ -919,8 +920,8 @@ the API itself follows _Evolving the plugin API_ below.
|
||||
|
||||
## 10. Evolving the plugin API
|
||||
|
||||
While the plugin system is a preview the API may still change freely. Once it
|
||||
is declared stable wasmtime decides what stays compatible: it resolves interface names
|
||||
Released versions are frozen: 1.0.0 shipped with OpenIDEA 0.1.36 and 1.1.0
|
||||
with 0.1.37. wasmtime decides what stays compatible: it resolves interface names
|
||||
by semver (a component importing `openidea:plugin/[email protected]` links against a
|
||||
host defining `@1.1.0`, and the host finds its exports the same way), but
|
||||
function types must match exactly — a record with another field count, or a
|
||||
@@ -960,7 +961,7 @@ Checked automatically:
|
||||
- SDK `tests/api_frozen.rs`: `tests/api/<version>/` holds the WIT of each
|
||||
released version; every interface, type, function and world import or
|
||||
export in it must still exist unchanged in `wit/` (rules 1–3). Copy `wit/`
|
||||
there when releasing; there is no snapshot before the first release.
|
||||
there when a version ships.
|
||||
- `crates/ide-plugin/tests/api_compat.rs`: the versions agree, the SDK's copy
|
||||
matches, the version check (rules 4, 5); a simulated next-minor host (every
|
||||
import stubbed at the newer version, plus extra functions and an extra
|
||||
|
||||
+1
-1
@@ -103,7 +103,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openidea-plugin-openidea-checkstyle"
|
||||
version = "0.1.0"
|
||||
version = "0.1.1"
|
||||
dependencies = [
|
||||
"openidea-plugin",
|
||||
]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "openidea-plugin-openidea-checkstyle"
|
||||
version = "0.1.0"
|
||||
version = "0.1.1"
|
||||
edition = "2024"
|
||||
publish = false
|
||||
|
||||
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
2f4608630c5e41453458ecee5bc4e2f1994a680d4307a5f002f9dd5ccc04d457
|
||||
69273e1ddfd2fff9f49c11d4fbdc60a771f8e3befe440e1623c2ab97469aa250
|
||||
@@ -1,6 +1,6 @@
|
||||
id = "openidea.checkstyle"
|
||||
name = "Checkstyle"
|
||||
version = "0.1.0"
|
||||
version = "0.1.1"
|
||||
description = "Checks Java files with Checkstyle when you save them: problems in the editor and the Problems view, quick fixes for tabs, trailing spaces and missing final newlines."
|
||||
authors = ["OpenIDEA contributors"]
|
||||
license = "Apache-2.0"
|
||||
|
||||
@@ -110,6 +110,26 @@ fn project_of(path: &str) -> Option<Project> {
|
||||
.max_by_key(|p| p.root().map(|r| r.len()).unwrap_or(0))
|
||||
}
|
||||
|
||||
fn windows_path(path: &str) -> String {
|
||||
let path = path.replace('\\', "/");
|
||||
if let Some(rest) = path.strip_prefix("//?/UNC/") {
|
||||
format!("//{rest}")
|
||||
} else {
|
||||
path.strip_prefix("//?/").unwrap_or(&path).to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
fn report_matches_file(reported: &str, path: &str) -> bool {
|
||||
// WASI plugins run on every host, so interpret the host's path rather than cfg(windows).
|
||||
let drive = path.as_bytes().get(1) == Some(&b':') && path.as_bytes()[0].is_ascii_alphabetic();
|
||||
if drive || path.starts_with("//") || path.starts_with(r"\\") {
|
||||
let (reported, path) = (windows_path(reported), windows_path(path));
|
||||
reported == path || path.ends_with(&reported)
|
||||
} else {
|
||||
reported == path || path.ends_with(reported)
|
||||
}
|
||||
}
|
||||
|
||||
/// The configuration for files of `project`.
|
||||
fn config_for(project: &Project) -> String {
|
||||
PROJECT_CONFIGS
|
||||
@@ -138,11 +158,8 @@ impl Checkstyle {
|
||||
return Err(Error::Failed(format!("checkstyle: {}", out.stderr.lines().next().unwrap_or("no report"))));
|
||||
}
|
||||
let report = parse_report(&out.stdout);
|
||||
let problems = report
|
||||
.into_iter()
|
||||
.find(|(f, _)| f == path || path.ends_with(f.as_str()))
|
||||
.map(|(_, p)| p)
|
||||
.unwrap_or_default();
|
||||
let problems =
|
||||
report.into_iter().find(|(f, _)| report_matches_file(f, path)).map(|(_, p)| p).unwrap_or_default();
|
||||
let text = project.read_file(path).unwrap_or_default();
|
||||
let diagnostics: Vec<Diagnostic> = problems.iter().map(|p| diagnostic(p, &text)).collect();
|
||||
host::publish_diagnostics(path, &diagnostics)?;
|
||||
@@ -233,7 +250,7 @@ impl Plugin for Checkstyle {
|
||||
|
||||
register_plugin!(Checkstyle, providers);
|
||||
|
||||
#[cfg(test)]
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use openidea_plugin::ProcessOutput;
|
||||
@@ -288,6 +305,45 @@ mod tests {
|
||||
assert_eq!(actions[1].edits[0].1[0].text, " void f() {}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unix_report_paths_preserve_backslashes() {
|
||||
assert!(report_matches_file("/project/A\\B.java", "/project/A\\B.java"));
|
||||
assert!(!report_matches_file("/project/A\\B.java", "/project/A/B.java"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_reports_match_the_saved_file_and_keep_quick_fixes() {
|
||||
for (root, reported) in [
|
||||
("C:/project", r"C:\project\src\A.java"),
|
||||
("C:/project", r"\\?\C:\project\src\A.java"),
|
||||
("C:/project", r"src\A.java"),
|
||||
("//server/share/project", r"\\server\share\project\src\A.java"),
|
||||
("//server/share/project", r"\\?\UNC\server\share\project\src\A.java"),
|
||||
] {
|
||||
let host =
|
||||
MockHost::install().with_capabilities(&["project.read", "events", "storage", "process:checkstyle"]);
|
||||
host.set_project_root(Some(root));
|
||||
host.add_file("src/A.java", "class A {\n\tint x;\n void f() {} \n}");
|
||||
let xml = REPORT.replace("/project/src/A.java", reported);
|
||||
host.on_process("checkstyle", move |_, _| {
|
||||
Ok(ProcessOutput { status: Some(1), stdout: xml.clone(), stderr: String::new() })
|
||||
});
|
||||
let path = format!("{root}/src/A.java");
|
||||
let mut plugin = Checkstyle::default();
|
||||
plugin.handle_events(&[Event::FileSaved(path.clone())], &host.invocation());
|
||||
assert_eq!(host.diagnostics()[&path].len(), 2, "{reported}");
|
||||
let doc = Document {
|
||||
path: path.clone(),
|
||||
language: "java".into(),
|
||||
version: 1,
|
||||
text: "class A {\n\tint x;\n void f() {} \n}".into(),
|
||||
};
|
||||
let actions = plugin.code_actions(&doc, Range::new(Position::new(1, 0), Position::new(2, 0)));
|
||||
assert_eq!(actions.len(), 2, "{reported}");
|
||||
assert_eq!(actions[0].edits[0].0, path);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_projects_configuration_wins() {
|
||||
let host = MockHost::install().with_capabilities(&["project.read", "events", "storage", "process:checkstyle"]);
|
||||
|
||||
@@ -63,7 +63,7 @@ import { cloneCaretAbove, cloneCaretBelow } from "./cm/verticalMotion";
|
||||
import { pasteAsPlainText, pasteFromHistory, unwrapAtCaret } from "./extras";
|
||||
import { cyclicExpandWord } from "./wordCompletion";
|
||||
import { qualifiedReference } from "./copyReference";
|
||||
import { symbolChain } from "./view/outline";
|
||||
import { declarationChain } from "./view/outline";
|
||||
import { recordClipboard } from "./clipboardHistory";
|
||||
import { useDocMeta, useOutline } from "./model/document";
|
||||
import { fontZoom, setFontZoom, stepFontZoom } from "./cm/prefs";
|
||||
@@ -414,12 +414,14 @@ function copyReference(view: EditorView, slot: EditorSlot) {
|
||||
const line = state.doc.lineAt(head);
|
||||
const meta = slot.model.getMeta();
|
||||
const outline = useOutline.getState()[slot.model.path] ?? [];
|
||||
// A package is not a member to qualify: jdtls lists the whole `package …;` statement as one.
|
||||
const chain = declarationChain(outline, line.number - 1, head - line.from).filter((i) => i.kind !== "package");
|
||||
const reference = qualifiedReference({
|
||||
language: meta.language,
|
||||
path: slot.model.path,
|
||||
root: useProject.getState().project?.root ?? null,
|
||||
text: state.doc.toString(),
|
||||
chain: symbolChain(outline, line.number - 1, head - line.from).map((i) => i.name),
|
||||
chain: chain.map((i) => i.name),
|
||||
line: line.number - 1,
|
||||
});
|
||||
recordClipboard(reference);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Edit › Copy Reference (⌥⇧⌘C): the fully qualified name of the symbol at
|
||||
* the caret, built from the file's outline (symbols enclosing the caret) and
|
||||
* the language's module conventions; `path:line` where there is no symbol.
|
||||
* Edit › Copy Reference (⌥⇧⌘C): with the caret on a declaration's name, its
|
||||
* fully qualified name, built from the file's outline and the language's module
|
||||
* conventions; anywhere else `path:line`, as in IDEA.
|
||||
*/
|
||||
|
||||
export interface ReferenceInput {
|
||||
@@ -11,7 +11,7 @@ export interface ReferenceInput {
|
||||
/** Project root, for project-relative paths and module names. */
|
||||
root: string | null;
|
||||
text: string;
|
||||
/** Names of the outline symbols enclosing the caret, outermost first. */
|
||||
/** Names of the outline symbols down to the one named at the caret, outermost first; empty off a name. */
|
||||
chain: string[];
|
||||
/** 0-based caret line. */
|
||||
line: number;
|
||||
@@ -59,42 +59,37 @@ const declared = (text: string, re: RegExp) => re.exec(text)?.[1] ?? null;
|
||||
export function qualifiedReference(r: ReferenceInput): string {
|
||||
const fallback = `${relativePath(r.path, r.root)}:${r.line + 1}`;
|
||||
const chain = r.chain.filter(Boolean);
|
||||
if (!chain.length) return fallback;
|
||||
switch (r.language) {
|
||||
case "java":
|
||||
case "groovy": {
|
||||
if (!chain.length) return fallback;
|
||||
const pkg = declared(r.text, /^\s*package\s+([\w.]+)\s*;?/m);
|
||||
const [type, ...rest] = chain;
|
||||
const typePath = [pkg, type].filter(Boolean).join(".");
|
||||
// `pkg.Outer.Inner#member`: the last symbol is the member unless the caret is in a type only.
|
||||
// `pkg.Outer.Inner#member`: the last symbol is the member unless the caret is on a type's name.
|
||||
return rest.length ? `${[typePath, ...rest.slice(0, -1)].join(".")}#${rest[rest.length - 1]}` : typePath;
|
||||
}
|
||||
case "kotlin":
|
||||
case "scala": {
|
||||
if (!chain.length) return fallback;
|
||||
const pkg = declared(r.text, /^\s*package\s+([\w.]+)/m);
|
||||
return [pkg, ...chain].filter(Boolean).join(".");
|
||||
}
|
||||
case "csharp": {
|
||||
if (!chain.length) return fallback;
|
||||
case "csharp":
|
||||
return chain.join(".");
|
||||
}
|
||||
case "rust": {
|
||||
if (!chain.length) return rustModulePath(r.path);
|
||||
case "rust":
|
||||
return [rustModulePath(r.path), ...chain.map((n) => (n.startsWith("impl") ? rustImplType(n) : n))].join("::");
|
||||
}
|
||||
case "python":
|
||||
return [pythonModulePath(r.path, r.root), ...chain].join(".");
|
||||
case "go": {
|
||||
const pkg = declared(r.text, /^\s*package\s+(\w+)/m) ?? stem(r.path);
|
||||
return chain.length ? [pkg, ...chain].join(".") : fallback;
|
||||
return [pkg, ...chain].join(".");
|
||||
}
|
||||
case "cpp":
|
||||
case "c":
|
||||
case "objective-cpp":
|
||||
case "php":
|
||||
return chain.length ? chain.join("::") : fallback;
|
||||
return chain.join("::");
|
||||
default:
|
||||
return chain.length ? `${relativePath(r.path, r.root)}:${chain.join(".")}` : fallback;
|
||||
return `${relativePath(r.path, r.root)}:${chain.join(".")}`;
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,9 @@ import { describe, expect, it } from "vitest";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { cyclicExpandWord, expandCandidates, prefixStart } from "./wordCompletion";
|
||||
import type { OutlineItem } from "@/platform/ipc";
|
||||
import { pythonModulePath, qualifiedReference, rustImplType, rustModulePath } from "./copyReference";
|
||||
import { declarationChain } from "./view/outline";
|
||||
|
||||
describe("cyclic expand word", () => {
|
||||
const text = "alphaOne x alphaTwo y al| alphaThree alphaOne";
|
||||
@@ -101,5 +103,33 @@ describe("copy reference", () => {
|
||||
expect(
|
||||
qualifiedReference({ ...base, root: null, language: "markdown", path: "/x/a.md", text: "", chain: [] }),
|
||||
).toBe("/x/a.md:5");
|
||||
expect(qualifiedReference({ ...base, language: "python", path: "/p/pkg/mod.py", text: "", chain: [] })).toBe(
|
||||
"pkg/mod.py:5",
|
||||
);
|
||||
expect(qualifiedReference({ ...base, language: "rust", path: "/p/src/a.rs", text: "", chain: [] })).toBe(
|
||||
"src/a.rs:5",
|
||||
);
|
||||
});
|
||||
|
||||
it("names a symbol only with the caret on its name, like IDEA", () => {
|
||||
const item = (name: string, range: number[], sel: number[], children: OutlineItem[] = []): OutlineItem => ({
|
||||
name,
|
||||
detail: null,
|
||||
kind: "class",
|
||||
range: { start: { line: range[0]!, col: range[1]! }, end: { line: range[2]!, col: range[3]! } },
|
||||
selection_range: { start: { line: sel[0]!, col: sel[1]! }, end: { line: sel[2]!, col: sel[3]! } },
|
||||
children,
|
||||
});
|
||||
// class Book { line 0, name at cols 6-10
|
||||
// void sum() { line 1, name at cols 7-10
|
||||
// total += 1; line 2
|
||||
const outline = [item("Book", [0, 0, 4, 1], [0, 6, 0, 10], [item("sum", [1, 2, 3, 3], [1, 7, 1, 10])])];
|
||||
const names = (line: number, col: number) => declarationChain(outline, line, col).map((i) => i.name);
|
||||
expect(names(1, 8)).toEqual(["Book", "sum"]);
|
||||
expect(names(1, 10)).toEqual(["Book", "sum"]);
|
||||
expect(names(0, 6)).toEqual(["Book"]);
|
||||
expect(names(2, 6)).toEqual([]);
|
||||
expect(names(1, 2)).toEqual([]);
|
||||
expect(names(5, 0)).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -14,3 +14,11 @@ export function symbolChain(items: readonly OutlineItem[], line: number, col: nu
|
||||
level = hit.children;
|
||||
}
|
||||
}
|
||||
|
||||
/** The chain up to the innermost item whose name (selection range) holds (line, col); empty off every name. */
|
||||
export function declarationChain(items: readonly OutlineItem[], line: number, col: number): OutlineItem[] {
|
||||
const pos = { line, col };
|
||||
const chain = symbolChain(items, line, col);
|
||||
const named = chain.findLastIndex((i) => before(i.selection_range.start, pos) && before(pos, i.selection_range.end));
|
||||
return chain.slice(0, named + 1);
|
||||
}
|
||||
@@ -6228,7 +6228,7 @@
|
||||
"Last Page": "最后一页",
|
||||
"{first}-{last} of {total}": "{first}-{last},共 {total}",
|
||||
"Model & effort settings": "模型与推理强度",
|
||||
"Logcat": "Logcat",
|
||||
"Logcat": "Logcat 日志",
|
||||
"Device": "设备",
|
||||
"No devices": "没有设备",
|
||||
"Minimum level": "最低级别",
|
||||
|
||||
Reference in new issue
Заблокувати користувача