дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-21 09:00:49 +02:00
Порівняти коміти
22
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
3ab381ffff | ||
|
|
7c3b40b1c4 | ||
|
|
38279f3c29 | ||
|
|
958b3db122 | ||
|
|
8620fae5d5 | ||
|
|
c216818c08 | ||
|
|
e4f98bca3d | ||
|
|
0f727b47bc | ||
|
|
f03fabfa5f | ||
|
|
d21a4ca9d9 | ||
|
|
f6490426f3 | ||
|
|
669ea49e3d | ||
|
|
c57a52348b | ||
|
|
431cfafab3 | ||
|
|
dfd7a177f5 | ||
|
|
5c3b144db9 | ||
|
|
7492bebeef | ||
|
|
9673a704a2 | ||
|
|
a6569552b1 | ||
|
|
437e8b747e | ||
|
|
a4f2f5ef3d | ||
|
|
2c7eebb35f |
No files matched your search
@@ -0,0 +1,41 @@
|
||||
name: Cancel runs of closed PRs
|
||||
on:
|
||||
# pull_request_target so it also runs for PRs from forks. It never checks out or
|
||||
# runs PR code: it only lists and cancels workflow runs of the closed PR's branch.
|
||||
pull_request_target:
|
||||
types: [closed]
|
||||
|
||||
permissions:
|
||||
actions: write
|
||||
|
||||
jobs:
|
||||
cancel:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
// A merged or closed PR's remaining CI only holds runners other PRs wait for.
|
||||
const pr = context.payload.pull_request;
|
||||
const { owner, repo } = context.repo;
|
||||
const headRepo = pr.head.repo?.full_name;
|
||||
// The API's status filter lags behind new runs: list the branch and check each one.
|
||||
const runs = await github.paginate(github.rest.actions.listWorkflowRunsForRepo, {
|
||||
owner,
|
||||
repo,
|
||||
branch: pr.head.ref,
|
||||
per_page: 100,
|
||||
});
|
||||
let cancelled = 0;
|
||||
for (const run of runs) {
|
||||
if (run.id === context.runId || run.status === 'completed') continue;
|
||||
if (run.head_repository?.full_name !== headRepo) continue;
|
||||
if (!['pull_request', 'pull_request_target'].includes(run.event)) continue;
|
||||
try {
|
||||
await github.rest.actions.cancelWorkflowRun({ owner, repo, run_id: run.id });
|
||||
cancelled++;
|
||||
} catch (e) {
|
||||
core.warning(`run ${run.id}: ${e.message}`);
|
||||
}
|
||||
}
|
||||
core.info(`Cancelled ${cancelled} run(s) of #${pr.number}`);
|
||||
@@ -203,7 +203,11 @@ async fn a_task_runs_on_a_v2_agent_and_resumes_its_session() {
|
||||
let agent2 = Arc::new(FakeV2Agent::default());
|
||||
let mgr2 = manager(tmp.path(), agent2.clone());
|
||||
mgr2.prompt(&task.id, text("again"), false).await.unwrap();
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
// The task is Ready until the resumed turn starts: wait for the turn's entries first.
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(10);
|
||||
while mgr2.entries(&task.id, None).unwrap().len() < 8 && std::time::Instant::now() < deadline {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
wait_for(&mgr2, &task.id, AgentStatus::Ready).await;
|
||||
let entries = mgr2.entries(&task.id, None).unwrap();
|
||||
assert_eq!(summary(&entries[6..]), ["user: again", "agent: second turn"]);
|
||||
|
||||
@@ -20,6 +20,7 @@ mod native;
|
||||
mod provider;
|
||||
pub mod registry;
|
||||
pub mod security;
|
||||
mod shell;
|
||||
mod skills;
|
||||
mod timeline;
|
||||
mod worktree;
|
||||
@@ -400,6 +401,9 @@ struct TaskState {
|
||||
/// the like), as it sent them: unlike a turn they outlive it, so an idle release
|
||||
/// waits for the last one. A (re)started process runs nothing yet.
|
||||
background_tasks: Vec<Value>,
|
||||
/// Shell commands the user ran with `!` since the last prompt, as the text block that
|
||||
/// goes ahead of the next one.
|
||||
shell_context: Vec<String>,
|
||||
}
|
||||
|
||||
impl TaskState {
|
||||
@@ -957,6 +961,26 @@ impl AgentManager {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Runs `command` (a composer line starting with `!`) in the task's folder with the user's
|
||||
/// shell, without starting a turn: it shows as one entry with its output and exit code,
|
||||
/// and goes to the agent with the next message.
|
||||
pub async fn run_shell(&self, id: &str, command: &str, cancel: ide_core::CancellationToken) -> IdeResult<()> {
|
||||
let task = self.task(id)?;
|
||||
let command = command.trim();
|
||||
if command.is_empty() {
|
||||
return Err(IdeError::invalid("empty command"));
|
||||
}
|
||||
let cwd = {
|
||||
let s = task.state.lock();
|
||||
if s.task.status == AgentStatus::Archived {
|
||||
return Err(IdeError::invalid("the task is archived"));
|
||||
}
|
||||
s.task.cwd.0.clone()
|
||||
};
|
||||
task.shell(command, &cwd, &cancel).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Drops a queued message.
|
||||
pub fn unqueue(&self, id: &str, queued: &str) -> IdeResult<AgentQueued> {
|
||||
let task = self.task(id)?;
|
||||
@@ -1885,6 +1909,7 @@ impl Task {
|
||||
title_renamed: file.title_renamed,
|
||||
busy: false,
|
||||
background_tasks: Vec::new(),
|
||||
shell_context: Vec::new(),
|
||||
}),
|
||||
live: Mutex::new(None),
|
||||
connecting: tokio::sync::Mutex::new(()),
|
||||
@@ -2115,6 +2140,33 @@ impl Task {
|
||||
}
|
||||
}
|
||||
|
||||
/// Folds an update made here (not by the agent) into the main conversation.
|
||||
fn apply_local(self: &Arc<Self>, update: &Value) {
|
||||
let changed = self.state.lock().conversation.apply(None, update, now_ms());
|
||||
self.mark_dirty(changed);
|
||||
}
|
||||
|
||||
async fn shell(self: &Arc<Self>, command: &str, cwd: &Path, cancel: &ide_core::CancellationToken) {
|
||||
let call = format!("shell-{}", uuid::Uuid::new_v4().simple());
|
||||
self.apply_local(&json!({
|
||||
"sessionUpdate": "tool_call",
|
||||
"toolCallId": call,
|
||||
"title": format!("! {command}"),
|
||||
"kind": "execute",
|
||||
"status": "in_progress",
|
||||
}));
|
||||
let ran = shell::run(command, cwd, cancel).await;
|
||||
let status = if ran.code == Some(0) { "completed" } else { "failed" };
|
||||
self.apply_local(&json!({
|
||||
"sessionUpdate": "tool_call_update",
|
||||
"toolCallId": call,
|
||||
"status": status,
|
||||
"content": [{ "type": "content", "content": { "type": "text", "text": ran.shown() } }],
|
||||
}));
|
||||
self.state.lock().shell_context.push(ran.context(command));
|
||||
self.persist();
|
||||
}
|
||||
|
||||
fn push_entry(self: &Arc<Self>, entry: AgentEntry) -> usize {
|
||||
let i = self.state.lock().conversation.main.push(entry);
|
||||
self.mark_dirty([(None, i)]);
|
||||
@@ -2431,7 +2483,14 @@ impl Task {
|
||||
if !prompt.images.is_empty() && !live.capabilities.images {
|
||||
return Err(Failure::from("This agent can't read images.".to_owned()));
|
||||
}
|
||||
let mut content = self.content(&live, prompt).await;
|
||||
let shell = std::mem::take(&mut self.state.lock().shell_context);
|
||||
let with_shell = |mut content: Vec<Value>| {
|
||||
if !shell.is_empty() {
|
||||
content.insert(0, json!({ "type": "text", "text": shell.join("\n") }));
|
||||
}
|
||||
content
|
||||
};
|
||||
let mut content = with_shell(self.content(&live, prompt).await);
|
||||
let mut result: Result<Value, RpcError> =
|
||||
live.peer.request("session/prompt", json!({ "sessionId": live.session, "prompt": content }), None).await;
|
||||
if live.driver == provider::Driver::Copilot
|
||||
@@ -2453,7 +2512,7 @@ impl Task {
|
||||
if !prompt.images.is_empty() && !live.capabilities.images {
|
||||
return Err(Failure::from("This agent can't read images.".to_owned()));
|
||||
}
|
||||
content = self.content(&live, prompt).await;
|
||||
content = with_shell(self.content(&live, prompt).await);
|
||||
result = live
|
||||
.peer
|
||||
.request("session/prompt", json!({ "sessionId": live.session, "prompt": content }), None)
|
||||
|
||||
@@ -24,7 +24,9 @@ use std::process::Command;
|
||||
use std::time::Duration;
|
||||
|
||||
pub const REGISTRY_URL: &str = "https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json";
|
||||
const COPILOT_RELEASE_BASE: &str = "https://github.com/github/copilot-cli/releases/download";
|
||||
const MAX_REGISTRY_BYTES: u64 = 1024 * 1024;
|
||||
const MAX_CHECKSUM_BYTES: u64 = 64 * 1024;
|
||||
/// [`maintain`] refreshes a saved index older than this, so updates show without opening
|
||||
/// the registry.
|
||||
const REFRESH_AFTER: Duration = Duration::from_secs(24 * 60 * 60);
|
||||
@@ -142,6 +144,9 @@ struct Binary {
|
||||
env: BTreeMap<String, String>,
|
||||
#[serde(default)]
|
||||
sha256: Option<String>,
|
||||
/// Checksum manifest (`SHA256SUMS.txt`) naming `archive`'s filename when `sha256` is not inline.
|
||||
#[serde(skip)]
|
||||
sha256_url: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize)]
|
||||
@@ -172,11 +177,48 @@ fn parse(text: &str) -> IdeResult<Vec<Entry>> {
|
||||
if let Some(name) = provider::builtin_name(&e.id) {
|
||||
e.name = name.to_owned();
|
||||
}
|
||||
if e.id == "copilot" {
|
||||
add_copilot_release_binaries(&mut e, COPILOT_RELEASE_BASE);
|
||||
}
|
||||
e
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Upstream `github-copilot-cli` lists only an `npx` wrapper in the ACP Registry, while
|
||||
/// `github/copilot-cli` publishes standalone archives and `SHA256SUMS.txt` on every GitHub
|
||||
/// release. Supplying them installs Copilot without Node.js, npm, `~/.npmrc`, or mirror lag.
|
||||
fn add_copilot_release_binaries(entry: &mut Entry, release_base: &str) {
|
||||
let tag = format!("v{}", entry.version.trim_start_matches('v'));
|
||||
let base = format!("{}/{}", release_base.trim_end_matches('/'), tag);
|
||||
let sha256_url = format!("{base}/SHA256SUMS.txt");
|
||||
let (args, env) = match &entry.distribution.npx {
|
||||
Some(p) => (p.args.clone(), p.env.clone()),
|
||||
None => (vec!["--acp".into()], BTreeMap::new()),
|
||||
};
|
||||
let linux = if cfg!(target_env = "musl") { "linuxmusl" } else { "linux" };
|
||||
let linux_arm = format!("copilot-{linux}-arm64.tar.gz");
|
||||
let linux_x64 = format!("copilot-{linux}-x64.tar.gz");
|
||||
let targets = [
|
||||
("darwin-aarch64", "copilot-darwin-arm64.tar.gz", "./copilot"),
|
||||
("darwin-x86_64", "copilot-darwin-x64.tar.gz", "./copilot"),
|
||||
("linux-aarch64", linux_arm.as_str(), "./copilot"),
|
||||
("linux-x86_64", linux_x64.as_str(), "./copilot"),
|
||||
("windows-aarch64", "copilot-win32-arm64.zip", "copilot.exe"),
|
||||
("windows-x86_64", "copilot-win32-x64.zip", "copilot.exe"),
|
||||
];
|
||||
for (key, asset, cmd) in targets {
|
||||
entry.distribution.binary.entry(key.to_owned()).or_insert_with(|| Binary {
|
||||
archive: format!("{base}/{asset}"),
|
||||
cmd: cmd.to_owned(),
|
||||
args: args.clone(),
|
||||
env: env.clone(),
|
||||
sha256: None,
|
||||
sha256_url: Some(sha256_url.clone()),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn safe_segment(s: &str) -> bool {
|
||||
!s.is_empty()
|
||||
&& !s.starts_with('.')
|
||||
@@ -316,7 +358,7 @@ fn visible(
|
||||
None
|
||||
};
|
||||
let choice = choose(e, platform, on_path);
|
||||
let no_checksum = matches!(choice, Some(Choice::Binary(b)) if b.sha256.is_none());
|
||||
let no_checksum = matches!(choice, Some(Choice::Binary(b)) if b.sha256.is_none() && b.sha256_url.is_none());
|
||||
let distribution = choice.map(|c| c.kind());
|
||||
if distribution.is_none() && installed.is_none() {
|
||||
return None;
|
||||
@@ -423,6 +465,20 @@ fn install_entry(
|
||||
on_path: &dyn Fn(&str) -> bool,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<()> {
|
||||
install_entry_with(paths, entry, platform, on_path, &install_npm, cancel, emit)
|
||||
}
|
||||
|
||||
type NpmInstaller = dyn Fn(&Package, &Entry, &Path, Platform, &CancellationToken, Emit) -> IdeResult<PathBuf>;
|
||||
|
||||
fn install_entry_with(
|
||||
paths: &RegistryPaths,
|
||||
entry: &Entry,
|
||||
platform: Platform,
|
||||
on_path: &dyn Fn(&str) -> bool,
|
||||
npm_installer: &NpmInstaller,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<()> {
|
||||
if is_builtin(&entry.id) {
|
||||
return Err(IdeError::invalid(format!("{} is built in", entry.name)));
|
||||
@@ -443,9 +499,32 @@ fn install_entry(
|
||||
}
|
||||
fs::create_dir_all(&dir)?;
|
||||
let installed = match &choice {
|
||||
Choice::Binary(b) => install_binary(b, &dir, cancel, emit).map(|exe| (exe, b.args.clone(), b.env.clone())),
|
||||
Choice::Binary(b) => match install_binary(b, &dir, cancel, emit) {
|
||||
Ok(exe) => Ok((exe, b.args.clone(), b.env.clone())),
|
||||
Err(e)
|
||||
if !cancel.is_cancelled()
|
||||
&& e.kind != ErrorKind::Cancelled
|
||||
&& !e.message.starts_with("checksum mismatch:")
|
||||
&& entry.distribution.npx.is_some()
|
||||
&& on_path("npm")
|
||||
&& on_path("node") =>
|
||||
{
|
||||
let p = entry.distribution.npx.as_ref().expect("checked");
|
||||
emit(InstallEvent::Line {
|
||||
text: format!("Binary download failed ({}); falling back to npm…", e.message),
|
||||
});
|
||||
fs::remove_dir_all(&dir)?;
|
||||
fs::create_dir_all(&dir)?;
|
||||
npm_installer(p, entry, &dir, platform, cancel, emit)
|
||||
.map(|exe| (exe, p.args.clone(), p.env.clone()))
|
||||
.map_err(|npm_err| {
|
||||
IdeError::new(npm_err.kind, format!("{}; npm fallback failed: {}", e.message, npm_err.message))
|
||||
})
|
||||
}
|
||||
Err(e) => Err(e),
|
||||
},
|
||||
Choice::Npx(p) => {
|
||||
install_npm(p, entry, &dir, platform, cancel, emit).map(|exe| (exe, p.args.clone(), p.env.clone()))
|
||||
npm_installer(p, entry, &dir, platform, cancel, emit).map(|exe| (exe, p.args.clone(), p.env.clone()))
|
||||
}
|
||||
Choice::Uvx(p) => {
|
||||
install_uv(p, entry, &dir, platform, cancel, emit).map(|exe| (exe, p.args.clone(), p.env.clone()))
|
||||
@@ -508,13 +587,23 @@ fn install_binary(b: &Binary, dir: &Path, cancel: &CancellationToken, emit: Emit
|
||||
fs::create_dir_all(&downloads)?;
|
||||
let file = downloads.join(name);
|
||||
emit(InstallEvent::Line { text: format!("Downloading {}", b.archive) });
|
||||
http()?.download(&b.archive, &file, None, cancel, emit)?;
|
||||
match &b.sha256 {
|
||||
Some(expected) => {
|
||||
let http = http()?;
|
||||
http.download(&b.archive, &file, None, cancel, emit)?;
|
||||
match (&b.sha256, &b.sha256_url) {
|
||||
(Some(expected), _) => {
|
||||
verify_sha256(&file, expected)?;
|
||||
emit(InstallEvent::Line { text: "SHA-256 checksum verified".into() });
|
||||
}
|
||||
None => emit(InstallEvent::Line { text: "The registry gives no checksum for this download".into() }),
|
||||
(None, Some(checksum_url)) => {
|
||||
check_url(checksum_url)?;
|
||||
let text = http.get_text_limited(checksum_url, Some(MAX_CHECKSUM_BYTES), cancel)?;
|
||||
let expected = ide_tools::sources::parse_checksum(&text, name).ok_or_else(|| {
|
||||
IdeError::new(ErrorKind::Protocol, format!("no SHA-256 checksum for {name} in {checksum_url}"))
|
||||
})?;
|
||||
verify_sha256(&file, &expected)?;
|
||||
emit(InstallEvent::Line { text: "SHA-256 checksum verified".into() });
|
||||
}
|
||||
(None, None) => emit(InstallEvent::Line { text: "The registry gives no checksum for this download".into() }),
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
@@ -567,6 +656,20 @@ fn install_npm(
|
||||
platform: Platform,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<PathBuf> {
|
||||
let (name, _) = split_npm_spec(&p.package);
|
||||
let npm = which::which("npm").map_err(|_| IdeError::unavailable(format!("npm is required to install {name}")))?;
|
||||
install_npm_with(&npm, p, entry, dir, platform, cancel, emit)
|
||||
}
|
||||
|
||||
fn install_npm_with(
|
||||
npm: &Path,
|
||||
p: &Package,
|
||||
entry: &Entry,
|
||||
dir: &Path,
|
||||
platform: Platform,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<PathBuf> {
|
||||
let (name, version) = split_npm_spec(&p.package);
|
||||
let spec = match version {
|
||||
@@ -574,10 +677,27 @@ fn install_npm(
|
||||
_ => format!("{name}@{}", entry.version),
|
||||
};
|
||||
check_spec(&spec)?;
|
||||
let npm = which::which("npm").map_err(|_| IdeError::unavailable(format!("npm is required to install {name}")))?;
|
||||
let mut cmd = Command::new(npm);
|
||||
cmd.arg("install").arg("--prefix").arg(dir).args(["--no-audit", "--no-fund"]).arg(&spec).current_dir(dir);
|
||||
ide_tools::run_streamed(cmd, cancel, emit)?;
|
||||
let specs = [spec.clone()];
|
||||
ide_tools::run_npm_with_public_fallback(
|
||||
|extra| {
|
||||
if !extra.is_empty() {
|
||||
let _ = fs::remove_dir_all(dir.join("node_modules"));
|
||||
}
|
||||
let mut cmd = Command::new(npm);
|
||||
cmd.arg("install")
|
||||
.arg("--prefix")
|
||||
.arg(dir)
|
||||
.args(["--no-audit", "--no-fund"])
|
||||
.args(extra)
|
||||
.arg(&spec)
|
||||
.current_dir(dir);
|
||||
cmd
|
||||
},
|
||||
&specs,
|
||||
false,
|
||||
cancel,
|
||||
emit,
|
||||
)?;
|
||||
let modules = dir.join("node_modules");
|
||||
let manifest: serde_json::Value = fs::read_to_string(modules.join(name).join("package.json"))
|
||||
.ok()
|
||||
@@ -872,6 +992,58 @@ mod tests {
|
||||
assert!(check_url("ftp://x/a").is_err());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn npm_registry_agent_retries_against_public_npmjs_on_mirror_miss() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let install_dir = dir.path().join("acme/1.2.0");
|
||||
fs::create_dir_all(&install_dir).unwrap();
|
||||
let log = dir.path().join("npm-calls.log");
|
||||
let npm = dir.path().join("npm");
|
||||
fs::write(
|
||||
&npm,
|
||||
format!(
|
||||
r#"#!/bin/sh
|
||||
echo "$@" >> '{}'
|
||||
case " $* " in
|
||||
*" --registry=https://registry.npmjs.org/ --@acme:registry=https://registry.npmjs.org/ "*)
|
||||
prefix=""; while [ $# -gt 0 ]; do [ "$1" = "--prefix" ] && prefix="$2"; shift; done
|
||||
mkdir -p "$prefix/node_modules/.bin" "$prefix/node_modules/@acme/agent-acp"
|
||||
printf '#!/bin/sh\necho 1.2.0\n' > "$prefix/node_modules/.bin/agent-acp"
|
||||
chmod +x "$prefix/node_modules/.bin/agent-acp"
|
||||
printf '{{"bin":"cli.js"}}\n' > "$prefix/node_modules/@acme/agent-acp/package.json"
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
echo "npm error code ETARGET" >&2
|
||||
echo "npm error notarget No matching version found for @acme/[email protected]." >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
"#,
|
||||
log.display()
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
archive::make_executable(&npm).unwrap();
|
||||
|
||||
let index = r#"{"agents":[
|
||||
{"id":"acme","name":"Acme","version":"1.2.0",
|
||||
"distribution":{"npx":{"package":"@acme/[email protected]","args":["--acp"]}}}
|
||||
]}"#;
|
||||
let entry = parse(index).unwrap().remove(0);
|
||||
let pkg = entry.distribution.npx.as_ref().unwrap();
|
||||
let exe =
|
||||
install_npm_with(&npm, pkg, &entry, &install_dir, MAC_ARM, &CancellationToken::new(), &|_| {}).unwrap();
|
||||
let calls: Vec<String> = fs::read_to_string(&log).unwrap().lines().map(str::to_owned).collect();
|
||||
assert_eq!(calls.len(), 2, "{calls:?}");
|
||||
assert!(!calls[0].contains("--registry="), "{calls:?}");
|
||||
assert!(calls[1].contains("--registry=https://registry.npmjs.org/"), "{calls:?}");
|
||||
assert!(calls[1].contains("--@acme:registry=https://registry.npmjs.org/"), "{calls:?}");
|
||||
assert_eq!(exe, install_dir.join("node_modules/.bin/agent-acp"));
|
||||
assert!(exe.is_file());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checksums_are_verified() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
@@ -969,11 +1141,18 @@ mod tests {
|
||||
assert_eq!(entries.len(), 1);
|
||||
assert_eq!((entries[0].id.as_str(), entries[0].name.as_str()), ("copilot", "GitHub Copilot"));
|
||||
|
||||
let shown = visible(&p, &entries, MAC_ARM, &|c| c == "npm" || c == "node");
|
||||
// Copilot installs as a verified GitHub Release binary even without Node.js or npm.
|
||||
let shown = visible(&p, &entries, MAC_ARM, &|_| false);
|
||||
assert_eq!(shown.len(), 1);
|
||||
assert_eq!(
|
||||
(shown[0].id.as_str(), shown[0].name.as_str(), shown[0].installed.as_deref()),
|
||||
("copilot", "GitHub Copilot", None)
|
||||
(
|
||||
shown[0].id.as_str(),
|
||||
shown[0].name.as_str(),
|
||||
shown[0].installed.as_deref(),
|
||||
shown[0].distribution,
|
||||
shown[0].no_checksum,
|
||||
),
|
||||
("copilot", "GitHub Copilot", None, Some(RegistryDistribution::Binary), false)
|
||||
);
|
||||
|
||||
CustomAgent {
|
||||
@@ -987,7 +1166,7 @@ mod tests {
|
||||
.write(&p.agent_file("copilot"))
|
||||
.unwrap();
|
||||
|
||||
let shown = visible(&p, &entries, MAC_ARM, &|c| c == "npm" || c == "node");
|
||||
let shown = visible(&p, &entries, MAC_ARM, &|_| false);
|
||||
assert_eq!((shown[0].installed.as_deref(), shown[0].update), (Some("1.0.104"), true));
|
||||
|
||||
write_atomic(&p.cache_file, index.as_bytes()).unwrap();
|
||||
@@ -1007,4 +1186,82 @@ mod tests {
|
||||
let fallback = provider::load(Some(&p.agents_dir), None).into_iter().find(|s| s.id == "copilot").unwrap();
|
||||
assert_eq!(fallback.source, AgentSource::Builtin);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn installs_copilot_from_verified_release_archive_and_falls_back_to_npm_when_unavailable() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let p = paths(dir.path());
|
||||
let served = dir.path().join("releases/v1.0.114");
|
||||
fs::create_dir_all(&served).unwrap();
|
||||
let archive = served.join("copilot-darwin-arm64.tar.gz");
|
||||
let stage = dir.path().join("archive-stage");
|
||||
fs::create_dir_all(&stage).unwrap();
|
||||
let staged_exe = stage.join("copilot");
|
||||
fs::write(&staged_exe, "#!/bin/sh\necho 1.0.114\n").unwrap();
|
||||
archive::make_executable(&staged_exe).unwrap();
|
||||
assert!(
|
||||
Command::new("tar")
|
||||
.arg("-czf")
|
||||
.arg(&archive)
|
||||
.arg("-C")
|
||||
.arg(&stage)
|
||||
.arg("copilot")
|
||||
.status()
|
||||
.unwrap()
|
||||
.success()
|
||||
);
|
||||
let sha = ide_tools::sources::sha256_file(&archive).unwrap();
|
||||
let sums = served.join("SHA256SUMS.txt");
|
||||
fs::write(&sums, format!("{sha} copilot-darwin-arm64.tar.gz\n")).unwrap();
|
||||
|
||||
let index = r#"{"agents":[
|
||||
{"id":"github-copilot-cli","name":"Copilot","version":"1.0.114",
|
||||
"distribution":{"npx":{"package":"@github/[email protected]","args":["--acp"]}}}
|
||||
]}"#;
|
||||
let mut entry = parse(index).unwrap().remove(0);
|
||||
entry.distribution.binary.clear();
|
||||
add_copilot_release_binaries(&mut entry, &format!("file://{}", dir.path().join("releases").display()));
|
||||
|
||||
let fake_npm = |_: &Package, _: &Entry, dest: &Path, _: Platform, _: &CancellationToken, _: Emit| {
|
||||
let exe = dest.join("node_modules/.bin/copilot");
|
||||
fs::create_dir_all(exe.parent().unwrap())?;
|
||||
fs::write(&exe, "#!/bin/sh\necho npm-1.0.114\n")?;
|
||||
archive::make_executable(&exe)?;
|
||||
Ok(exe)
|
||||
};
|
||||
let node_on_path = |cmd: &str| matches!(cmd, "npm" | "node");
|
||||
|
||||
let cancel = CancellationToken::new();
|
||||
let lines = std::sync::Mutex::new(Vec::new());
|
||||
let emit = |e: InstallEvent| {
|
||||
if let InstallEvent::Line { text } = e {
|
||||
lines.lock().unwrap().push(text);
|
||||
}
|
||||
};
|
||||
|
||||
// 1. Verified GitHub Release archive installs directly without invoking npm.
|
||||
install_entry_with(&p, &entry, MAC_ARM, &|_| false, &fake_npm, &cancel, &emit).unwrap();
|
||||
assert!(lines.lock().unwrap().iter().any(|l| l == "SHA-256 checksum verified"));
|
||||
let installed_bin = p.tools_dir.join("copilot/1.0.114/copilot");
|
||||
assert!(installed_bin.is_file());
|
||||
let saved = CustomAgent::read(&p.agent_file("copilot")).unwrap();
|
||||
assert_eq!(saved.command, installed_bin.to_string_lossy());
|
||||
assert_eq!(saved.args, ["--acp"]);
|
||||
|
||||
// 2. A tampered binary fails checksum verification and never falls back to npm.
|
||||
fs::write(&sums, format!("{} copilot-darwin-arm64.tar.gz\n", "0".repeat(64))).unwrap();
|
||||
let err = install_entry_with(&p, &entry, MAC_ARM, &node_on_path, &fake_npm, &cancel, &emit).unwrap_err();
|
||||
assert!(err.message.contains("checksum mismatch"), "{err:?}");
|
||||
assert!(!p.tools_dir.join("copilot/1.0.114").exists());
|
||||
|
||||
// 3. When the release download itself is unreachable, npm fallback installs it.
|
||||
fs::remove_file(&archive).unwrap();
|
||||
lines.lock().unwrap().clear();
|
||||
install_entry_with(&p, &entry, MAC_ARM, &node_on_path, &fake_npm, &cancel, &emit).unwrap();
|
||||
assert!(lines.lock().unwrap().iter().any(|l| l.contains("falling back to npm")));
|
||||
let npm_bin = p.tools_dir.join("copilot/1.0.114/node_modules/.bin/copilot");
|
||||
assert!(npm_bin.is_file());
|
||||
assert_eq!(CustomAgent::read(&p.agent_file("copilot")).unwrap().command, npm_bin.to_string_lossy());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
//! `!` commands from the composer: run in the task's folder with the user's shell, outside
|
||||
//! any turn, and handed to the agent with the next message as Claude Code's bash mode does.
|
||||
|
||||
use ide_core::CancellationToken;
|
||||
use std::path::Path;
|
||||
use std::process::Stdio;
|
||||
use tokio::io::AsyncReadExt;
|
||||
use tokio::process::Command;
|
||||
|
||||
/// Output kept from each stream; longer output keeps its tail.
|
||||
const MAX_STREAM: usize = 32 * 1024;
|
||||
|
||||
#[derive(Debug, Default, PartialEq)]
|
||||
pub(crate) struct Ran {
|
||||
/// The exit code; `None` when it didn't start, was stopped or ended by a signal.
|
||||
pub code: Option<i32>,
|
||||
pub stdout: String,
|
||||
pub stderr: String,
|
||||
/// Why it didn't finish: it couldn't start, or it was stopped.
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
impl Ran {
|
||||
/// What the conversation shows: the output, then how it ended unless it succeeded.
|
||||
pub fn shown(&self) -> String {
|
||||
let mut text = [self.stdout.trim_end(), self.stderr.trim_end()]
|
||||
.into_iter()
|
||||
.filter(|t| !t.is_empty())
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
let end = match (&self.error, self.code) {
|
||||
(Some(error), _) => Some(error.clone()),
|
||||
(None, Some(0)) => None,
|
||||
(None, Some(code)) => Some(format!("Exit code {code}")),
|
||||
(None, None) => Some("Terminated".into()),
|
||||
};
|
||||
if let Some(end) = end {
|
||||
if !text.is_empty() {
|
||||
text.push('\n');
|
||||
}
|
||||
text.push_str(&end);
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
/// The block that goes to the agent ahead of the next message.
|
||||
pub fn context(&self, command: &str) -> String {
|
||||
let mut stderr = self.stderr.trim_end().to_owned();
|
||||
if let Some(error) = &self.error {
|
||||
if !stderr.is_empty() {
|
||||
stderr.push('\n');
|
||||
}
|
||||
stderr.push_str(error);
|
||||
} else if let Some(code) = self.code.filter(|c| *c != 0) {
|
||||
if !stderr.is_empty() {
|
||||
stderr.push('\n');
|
||||
}
|
||||
stderr.push_str(&format!("Exit code {code}"));
|
||||
}
|
||||
format!(
|
||||
"<bash-input>{command}</bash-input>\n<bash-stdout>{}</bash-stdout><bash-stderr>{stderr}</bash-stderr>",
|
||||
self.stdout.trim_end()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `command` with the user's shell in `cwd` until it ends or `cancel` stops it.
|
||||
pub(crate) async fn run(command: &str, cwd: &Path, cancel: &CancellationToken) -> Ran {
|
||||
let mut cmd = shell(command);
|
||||
ide_core::process::prepare(cmd.as_std_mut());
|
||||
cmd.current_dir(cwd).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).kill_on_drop(true);
|
||||
let mut child = match cmd.spawn() {
|
||||
Ok(child) => child,
|
||||
Err(e) => return Ran { error: Some(format!("Cannot run it: {e}")), ..Ran::default() },
|
||||
};
|
||||
let (Some(mut out), Some(mut err)) = (child.stdout.take(), child.stderr.take()) else {
|
||||
return Ran { error: Some("Cannot read its output".into()), ..Ran::default() };
|
||||
};
|
||||
let finished = async move {
|
||||
let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
|
||||
let _ = tokio::join!(out.read_to_end(&mut stdout), err.read_to_end(&mut stderr));
|
||||
let code = child.wait().await.ok().and_then(|s| s.code());
|
||||
Ran { code, stdout: tail(&stdout), stderr: tail(&stderr), error: None }
|
||||
};
|
||||
tokio::select! {
|
||||
ran = finished => ran,
|
||||
// Dropping the child kills it.
|
||||
() = cancel.cancelled() => Ran { error: Some("Stopped".into()), ..Ran::default() },
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn shell(command: &str) -> Command {
|
||||
let shell = std::env::var("SHELL").ok().filter(|s| !s.trim().is_empty()).unwrap_or_else(|| "/bin/sh".into());
|
||||
let mut cmd = Command::new(shell);
|
||||
cmd.arg("-c").arg(command);
|
||||
cmd
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn shell(command: &str) -> Command {
|
||||
let mut cmd = Command::new(std::env::var("COMSPEC").unwrap_or_else(|_| "cmd.exe".into()));
|
||||
// `/S /C "…"` runs the line as typed: cmd strips only the outer quotes.
|
||||
cmd.raw_arg("/D /S /C \"").raw_arg(command).raw_arg("\"");
|
||||
cmd
|
||||
}
|
||||
|
||||
fn tail(bytes: &[u8]) -> String {
|
||||
let text = String::from_utf8_lossy(bytes);
|
||||
if text.len() <= MAX_STREAM {
|
||||
return text.into_owned();
|
||||
}
|
||||
let mut cut = text.len() - MAX_STREAM;
|
||||
while !text.is_char_boundary(cut) {
|
||||
cut += 1;
|
||||
}
|
||||
format!("…{}", &text[cut..])
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(windows)))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn runs_in_the_folder_and_reports_output_and_exit_code() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::write(dir.path().join("marker.txt"), "").unwrap();
|
||||
let ran = run("ls; echo oops >&2; exit 3", dir.path(), &CancellationToken::new()).await;
|
||||
assert_eq!(ran.code, Some(3));
|
||||
assert_eq!(ran.stdout.trim(), "marker.txt");
|
||||
assert_eq!(ran.stderr.trim(), "oops");
|
||||
assert_eq!(ran.shown(), "marker.txt\noops\nExit code 3");
|
||||
assert_eq!(
|
||||
ran.context("ls"),
|
||||
"<bash-input>ls</bash-input>\n<bash-stdout>marker.txt</bash-stdout><bash-stderr>oops\nExit code 3</bash-stderr>"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_stopped_command_is_killed() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let cancel = CancellationToken::new();
|
||||
let stop = cancel.clone();
|
||||
tokio::spawn(async move {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
|
||||
stop.cancel();
|
||||
});
|
||||
let started = std::time::Instant::now();
|
||||
let ran = run("sleep 30", dir.path(), &cancel).await;
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(5));
|
||||
assert_eq!(ran.shown(), "Stopped");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_output_keeps_its_tail() {
|
||||
let long = "x".repeat(MAX_STREAM + 10) + "end";
|
||||
let kept = tail(long.as_bytes());
|
||||
assert!(kept.starts_with('…') && kept.ends_with("end"));
|
||||
}
|
||||
}
|
||||
@@ -59,6 +59,8 @@ struct FakeAgent {
|
||||
session_steering: bool,
|
||||
/// Records the `mcpServers` array passed to `session/new`, `session/load`, and `session/fork`.
|
||||
mcp_calls: Mutex<Vec<(String, Vec<String>)>>,
|
||||
/// The content blocks of each `session/prompt`.
|
||||
prompts: Mutex<Vec<Value>>,
|
||||
}
|
||||
|
||||
impl FakeAgent {
|
||||
@@ -247,7 +249,17 @@ impl Handler for FakeAgent {
|
||||
Ok(json!({}))
|
||||
}
|
||||
"session/prompt" => {
|
||||
let text = params.pointer("/prompt/0/text").and_then(Value::as_str).unwrap_or_default().to_owned();
|
||||
self.prompts.lock().push(params.get("prompt").cloned().unwrap_or(Value::Null));
|
||||
// `!` commands run since the last message come first; the message follows.
|
||||
let first = match params.pointer("/prompt/0/text").and_then(Value::as_str) {
|
||||
Some(t) if t.starts_with("<bash-input>") => 1,
|
||||
_ => 0,
|
||||
};
|
||||
let text = params
|
||||
.pointer(&format!("/prompt/{first}/text"))
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default()
|
||||
.to_owned();
|
||||
if text.starts_with("<send_user_message_question_reply>") {
|
||||
self.say(&session, "answer received");
|
||||
return Ok(json!({"stopReason": "end_turn"}));
|
||||
@@ -1361,6 +1373,53 @@ async fn messages_sent_while_busy_are_queued_and_send_now_interrupts() {
|
||||
assert!(mgr.task(&task.id).unwrap().state.lock().task.queue.is_empty());
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn shell_commands_show_in_the_conversation_and_go_with_the_next_message() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("again"),
|
||||
provider: "claude".into(),
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let turns = agent.prompts.lock().len();
|
||||
|
||||
mgr.run_shell(&task.id, " echo shell-out ", ide_core::CancellationToken::new()).await.unwrap();
|
||||
assert_eq!(agent.prompts.lock().len(), turns, "a `!` command starts no turn");
|
||||
let entries = mgr.entries(&task.id, None).unwrap();
|
||||
let Some(AgentEntry::Tool { title, kind, status, output, .. }) = entries.last() else {
|
||||
panic!("no entry for the command: {entries:?}")
|
||||
};
|
||||
assert_eq!((title.as_str(), kind.as_str(), *status), ("! echo shell-out", "execute", AgentToolStatus::Completed));
|
||||
assert_eq!(output.as_deref(), Some("shell-out"));
|
||||
|
||||
mgr.prompt(&task.id, text("again"), false).await.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let sent = agent.prompts.lock().last().cloned().unwrap();
|
||||
assert_eq!(
|
||||
sent.pointer("/0/text").and_then(Value::as_str),
|
||||
Some(
|
||||
"<bash-input>echo shell-out</bash-input>\n<bash-stdout>shell-out</bash-stdout><bash-stderr></bash-stderr>"
|
||||
)
|
||||
);
|
||||
assert_eq!(sent.pointer("/1/text").and_then(Value::as_str), Some("again"));
|
||||
// Only once.
|
||||
mgr.prompt(&task.id, text("again"), false).await.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let sent = agent.prompts.lock().last().cloned().unwrap();
|
||||
assert_eq!(sent.pointer("/0/text").and_then(Value::as_str), Some("again"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn send_now_interrupts_the_turn_when_steering_is_refused() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -182,7 +182,7 @@ fn collect(
|
||||
}
|
||||
|
||||
/// Scans every input, storing project inputs relative to the project.
|
||||
fn scan_all(
|
||||
pub(super) fn scan_all(
|
||||
root: &Path,
|
||||
inputs: Vec<PathBuf>,
|
||||
cancel: &CancellationToken,
|
||||
@@ -210,7 +210,7 @@ pub fn launch_fingerprint(
|
||||
if projects.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let plan = launch_plan(root, model, module, test, BuildKind::Build)?;
|
||||
let plan = launch_plan(root, model, module, test, BuildKind::Build, cancel)?;
|
||||
let Some(collected) = collect(root, &projects, &plan, local_repo)? else { return Ok(None) };
|
||||
let Collected { inputs, environment, steps, inherited_hash } = collected;
|
||||
let parameters = serde_json::to_string(&(root, module, test, steps, environment, inherited_hash, projects))
|
||||
@@ -229,7 +229,7 @@ pub fn menu_fingerprint(
|
||||
file: Option<&Path>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Option<LaunchFingerprint>> {
|
||||
let plan = plan(root, model, BuildKind::Build, file, None)?;
|
||||
let plan = plan(root, model, BuildKind::Build, file, None, None, cancel)?;
|
||||
if plan.system != BuildSystem::Maven {
|
||||
return Ok(None);
|
||||
}
|
||||
@@ -264,6 +264,23 @@ pub fn menu_fingerprint(
|
||||
Ok(Some(LaunchFingerprint { version: 2, parameters, files: scan_all(root, inputs, cancel)? }))
|
||||
}
|
||||
|
||||
/// Input fingerprint of one Maven module's menu build (#4078): its POM chain,
|
||||
/// source and resource trees plus the launcher settings that shape the build.
|
||||
/// `None` disables the module-scoped reuse (unresolved custom roots).
|
||||
/// All filesystem work belongs on the caller's blocking thread.
|
||||
pub(super) fn module_fingerprint(
|
||||
root: &Path,
|
||||
project: &maven::MavenProject,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Option<LaunchFingerprint>> {
|
||||
let projects = [project];
|
||||
let Some(inputs) = maven::launch_inputs(root, &projects, None) else { return Ok(None) };
|
||||
let parameters =
|
||||
serde_json::to_string(&("module-build", &project.dir, &project.command, &project.options, &project.env))
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
Ok(Some(LaunchFingerprint { version: 2, parameters, files: scan_all(root, inputs, cancel)? }))
|
||||
}
|
||||
|
||||
impl LaunchFingerprint {
|
||||
/// Folders (relative to the project) of the Maven projects whose POM is an input.
|
||||
pub(super) fn project_dirs(&self) -> impl Iterator<Item = &Path> {
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
|
||||
mod fingerprint;
|
||||
mod launch_resources;
|
||||
mod modules;
|
||||
mod parse;
|
||||
mod single;
|
||||
mod structure;
|
||||
@@ -12,6 +13,7 @@ mod up_to_date;
|
||||
|
||||
pub use fingerprint::{LaunchFingerprint, launch_fingerprint, menu_fingerprint};
|
||||
pub use launch_resources::process_launch_resources;
|
||||
pub use modules::record_module_build;
|
||||
pub use single::{
|
||||
SingleFileTarget, compile_file_plan, find_javac, javac_step, module_classpath, single_file_classpath,
|
||||
single_file_target,
|
||||
@@ -220,12 +222,16 @@ fn ancestors_within<'a>(root: &'a Path, file: &'a Path) -> impl Iterator<Item =
|
||||
|
||||
/// The build of `root`, or of the module containing `file` (Build Module / Recompile).
|
||||
/// `cmake`: the CMake profiles of the settings (the first one is built), if any.
|
||||
/// `cache` enables the module-scoped Maven narrowing of `Build` project builds;
|
||||
/// `None` plans every build exactly as before.
|
||||
pub fn plan(
|
||||
root: &Path,
|
||||
model: &BuildModel,
|
||||
kind: BuildKind,
|
||||
file: Option<&Path>,
|
||||
cmake: Option<&[CMakeProfile]>,
|
||||
cache: Option<&Path>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<BuildPlan> {
|
||||
let project_name = root.file_name().map_or_else(|| "project".to_owned(), |n| n.to_string_lossy().into_owned());
|
||||
let module_dir = match file {
|
||||
@@ -262,7 +268,7 @@ pub fn plan(
|
||||
None => project_name,
|
||||
};
|
||||
let steps = match system {
|
||||
BuildSystem::Maven => maven_steps(root, model, kind, module_dir.as_deref())?,
|
||||
BuildSystem::Maven => maven_steps(root, model, kind, module_dir.as_deref(), cache, cancel)?,
|
||||
BuildSystem::Gradle => gradle_steps(root, model, kind, module_dir.as_deref())?,
|
||||
BuildSystem::Cargo => cargo_steps(&dir, kind),
|
||||
// Go builds the file's package (a module holds many).
|
||||
@@ -281,6 +287,8 @@ pub(super) fn maven_steps(
|
||||
model: &BuildModel,
|
||||
kind: BuildKind,
|
||||
module: Option<&Path>,
|
||||
cache: Option<&Path>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Vec<BuildStep>> {
|
||||
let fallback;
|
||||
let m = match &model.maven {
|
||||
@@ -320,7 +328,15 @@ pub(super) fn maven_steps(
|
||||
s.env = p.env.clone();
|
||||
s
|
||||
};
|
||||
let Some(module) = module else { return Ok(tops.iter().map(|p| step(p, &[])).collect()) };
|
||||
let Some(module) = module else {
|
||||
if kind == BuildKind::Build
|
||||
&& let Some(cache) = cache
|
||||
&& let Some(steps) = modules::narrowed_maven_steps(cache, root, m, &step, cancel)?
|
||||
{
|
||||
return Ok(steps);
|
||||
}
|
||||
return Ok(tops.iter().map(|p| step(p, &[])).collect());
|
||||
};
|
||||
// The reactor root containing the module builds it with what it depends on (`-pl … -am`).
|
||||
let rel = rel_str(root, module);
|
||||
if !m.projects.iter().any(|p| p.dir == rel) {
|
||||
@@ -881,8 +897,15 @@ pub fn launch_has_non_java_sources(root: &Path, model: &BuildModel, module: &Pat
|
||||
has_non_java_sources(module)
|
||||
}
|
||||
|
||||
fn launch_plan(root: &Path, model: &BuildModel, module: &Path, test: bool, kind: BuildKind) -> IdeResult<BuildPlan> {
|
||||
let mut plan = plan(root, model, kind, Some(module), None)?;
|
||||
fn launch_plan(
|
||||
root: &Path,
|
||||
model: &BuildModel,
|
||||
module: &Path,
|
||||
test: bool,
|
||||
kind: BuildKind,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<BuildPlan> {
|
||||
let mut plan = plan(root, model, kind, Some(module), None, None, cancel)?;
|
||||
if plan.system == BuildSystem::Maven && !test {
|
||||
for step in &mut plan.steps {
|
||||
if let Some(goal) = step.args.last_mut() {
|
||||
@@ -909,7 +932,7 @@ pub fn build_for_launch(
|
||||
kind: BuildKind,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<LaunchBuild> {
|
||||
let plan = launch_plan(root, model, module, test, kind)?;
|
||||
let plan = launch_plan(root, model, module, test, kind, cancel)?;
|
||||
let result = run(root, &plan, cancel, &|_| {})?;
|
||||
let failure = if !result.success {
|
||||
let errors: Vec<String> = result
|
||||
@@ -974,7 +997,9 @@ mod tests {
|
||||
write(root, "../external/main.go", "package main\nimport \"example.com/lib\"\nfunc main(){_ = lib.Value()}\n");
|
||||
// std canonicalization also exercises verbatim paths on Windows.
|
||||
for root in [root.to_path_buf(), std::fs::canonicalize(root).unwrap()] {
|
||||
let plan = plan(&root, &BuildModel::default(), BuildKind::Build, None, None).unwrap();
|
||||
let plan =
|
||||
plan(&root, &BuildModel::default(), BuildKind::Build, None, None, None, &CancellationToken::new())
|
||||
.unwrap();
|
||||
for step in plan.steps {
|
||||
let result = std::process::Command::new(&go)
|
||||
.args(&step.args)
|
||||
@@ -1000,7 +1025,7 @@ mod tests {
|
||||
let canonical = std::fs::canonicalize(&root).unwrap();
|
||||
for root in [&root, &canonical, &canonical.join("..").join("workspace")] {
|
||||
for kind in [BuildKind::Build, BuildKind::Rebuild, BuildKind::Artifacts] {
|
||||
let p = plan(root, &BuildModel::default(), kind, None, None).unwrap();
|
||||
let p = plan(root, &BuildModel::default(), kind, None, None, None, &CancellationToken::new()).unwrap();
|
||||
assert_eq!(p.system, BuildSystem::Go);
|
||||
assert_eq!(p.steps.len(), 3);
|
||||
for (step, module) in p.steps.iter().zip(["api", "lib with spaces", "../shared"]) {
|
||||
@@ -1015,20 +1040,30 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
let member =
|
||||
plan(&root, &BuildModel::default(), BuildKind::Build, Some(&root.join("api/pkg/a.go")), None).unwrap();
|
||||
let member = plan(
|
||||
&root,
|
||||
&BuildModel::default(),
|
||||
BuildKind::Build,
|
||||
Some(&root.join("api/pkg/a.go")),
|
||||
None,
|
||||
None,
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(member.steps.len(), 1);
|
||||
assert_eq!(member.steps[0].cwd, root.join("api"));
|
||||
assert_eq!(member.steps[0].args, ["build", "./pkg/..."]);
|
||||
write(&root, "go.work", "use ./missing\n");
|
||||
assert!(
|
||||
plan(&root, &BuildModel::default(), BuildKind::Build, None, None)
|
||||
plan(&root, &BuildModel::default(), BuildKind::Build, None, None, None, &CancellationToken::new())
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("go.mod")
|
||||
);
|
||||
write(&root, "go.work", "go 1.22\n");
|
||||
assert!(plan(&root, &BuildModel::default(), BuildKind::Build, None, None).is_err());
|
||||
assert!(
|
||||
plan(&root, &BuildModel::default(), BuildKind::Build, None, None, None, &CancellationToken::new()).is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1049,11 +1084,21 @@ mod tests {
|
||||
let mut model = crate::load_linked(root, &root.join("cache"), None, &Default::default(), &settings);
|
||||
model.gradle[0].env.insert("JAVA_HOME".into(), "/jdk-a".into());
|
||||
model.gradle[1].env.insert("JAVA_HOME".into(), "/jdk-b".into());
|
||||
let all = super::plan(root, &model, super::BuildKind::Build, None, None).unwrap();
|
||||
let all =
|
||||
super::plan(root, &model, super::BuildKind::Build, None, None, None, &CancellationToken::new()).unwrap();
|
||||
assert_eq!(all.steps.len(), 2);
|
||||
assert_eq!(all.steps[0].cwd, root.join("a"));
|
||||
assert_eq!(all.steps[1].cwd, root.join("b"));
|
||||
let module = super::plan(root, &model, super::BuildKind::Rebuild, Some(&root.join("b/app")), None).unwrap();
|
||||
let module = super::plan(
|
||||
root,
|
||||
&model,
|
||||
super::BuildKind::Rebuild,
|
||||
Some(&root.join("b/app")),
|
||||
None,
|
||||
None,
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(module.steps.len(), 1);
|
||||
assert_eq!(module.steps[0].program, root.join("b").join(wrapper).to_string_lossy());
|
||||
assert_eq!(module.steps[0].cwd, root.join("b"));
|
||||
@@ -1066,11 +1111,31 @@ mod tests {
|
||||
let mut nested = model.gradle[1].projects[1].clone();
|
||||
nested.path = ":b:app".into();
|
||||
model.gradle[0].projects.push(nested);
|
||||
let nested = super::plan(root, &model, super::BuildKind::Build, Some(&root.join("b/app")), None).unwrap();
|
||||
let nested = super::plan(
|
||||
root,
|
||||
&model,
|
||||
super::BuildKind::Build,
|
||||
Some(&root.join("b/app")),
|
||||
None,
|
||||
None,
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(nested.steps[0].program, root.join("b").join(wrapper).to_string_lossy());
|
||||
assert_eq!(nested.steps[0].args, ["--console=plain", ":app:classes", ":app:testClasses"]);
|
||||
model.gradle.clear();
|
||||
assert!(super::plan(root, &model, super::BuildKind::Build, Some(&root.join("b/app")), None).is_err());
|
||||
assert!(
|
||||
super::plan(
|
||||
root,
|
||||
&model,
|
||||
super::BuildKind::Build,
|
||||
Some(&root.join("b/app")),
|
||||
None,
|
||||
None,
|
||||
&CancellationToken::new()
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1092,18 +1157,24 @@ mod tests {
|
||||
};
|
||||
let mut model = crate::load_linked(&root, &base.join("cache"), None, &Default::default(), &settings);
|
||||
model.gradle[0].env.insert("JAVA_HOME".into(), "/external-jdk".into());
|
||||
let all = super::plan(&root, &model, super::BuildKind::Build, None, None).unwrap();
|
||||
let all =
|
||||
super::plan(&root, &model, super::BuildKind::Build, None, None, None, &CancellationToken::new()).unwrap();
|
||||
assert_eq!(all.steps[0].cwd, external);
|
||||
// Linked roots are saved with forward slashes, so on Windows the program mixes separators.
|
||||
assert_eq!(std::path::Path::new(&all.steps[0].program), external.join(wrapper));
|
||||
let module = super::plan(&root, &model, super::BuildKind::Rebuild, Some(&source), None).unwrap();
|
||||
let module =
|
||||
super::plan(&root, &model, super::BuildKind::Rebuild, Some(&source), None, None, &CancellationToken::new())
|
||||
.unwrap();
|
||||
assert_eq!(module.steps[0].cwd, external);
|
||||
assert_eq!(module.steps[0].env["JAVA_HOME"], "/external-jdk");
|
||||
assert_eq!(module.steps[0].args, ["--console=plain", ":app:clean", ":app:classes", ":app:testClasses"]);
|
||||
let other = base.join("unlinked");
|
||||
std::fs::create_dir(&other).unwrap();
|
||||
std::fs::write(other.join("build.gradle"), "").unwrap();
|
||||
assert!(super::plan(&root, &model, super::BuildKind::Build, Some(&other), None).is_err());
|
||||
assert!(
|
||||
super::plan(&root, &model, super::BuildKind::Build, Some(&other), None, None, &CancellationToken::new())
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
use super::*;
|
||||
|
||||
@@ -1144,7 +1215,7 @@ mod tests {
|
||||
write(&root, "pom.xml", "<project><artifactId>demo</artifactId></project>");
|
||||
let model = crate::load(&root, &tmp.path().join("cache"), None);
|
||||
for (kind, expected) in [(BuildKind::Build, true), (BuildKind::Rebuild, true), (BuildKind::Artifacts, false)] {
|
||||
let plan = plan(&root, &model, kind, None, None).unwrap();
|
||||
let plan = plan(&root, &model, kind, None, None, None, &CancellationToken::new()).unwrap();
|
||||
assert_eq!(
|
||||
plan.steps[0].args.iter().any(|arg| arg == "-Djacoco.skip=true"),
|
||||
expected,
|
||||
@@ -1165,7 +1236,7 @@ mod tests {
|
||||
write(&root, "core/pom.xml", "<project><artifactId>core</artifactId></project>");
|
||||
write(&root, "core/src/main/java/A.java", "class A {}");
|
||||
let model = crate::load(&root, &tmp.path().join("cache"), None);
|
||||
let p = plan(&root, &model, BuildKind::Build, None, None).unwrap();
|
||||
let p = plan(&root, &model, BuildKind::Build, None, None, None, &CancellationToken::new()).unwrap();
|
||||
assert_eq!(p.system, BuildSystem::Maven);
|
||||
assert_eq!(p.title, "demo");
|
||||
assert_eq!(p.steps.len(), 1);
|
||||
@@ -1173,7 +1244,16 @@ mod tests {
|
||||
p.steps[0].args,
|
||||
["-B", "-Dstyle.color=never", maven::LOCAL_REPO_TRACKING_ARG, "-Djacoco.skip=true", "test-compile"]
|
||||
);
|
||||
let p = plan(&root, &model, BuildKind::Rebuild, Some(&root.join("core/src/main/java/A.java")), None).unwrap();
|
||||
let p = plan(
|
||||
&root,
|
||||
&model,
|
||||
BuildKind::Rebuild,
|
||||
Some(&root.join("core/src/main/java/A.java")),
|
||||
None,
|
||||
None,
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
p.steps[0].args,
|
||||
[
|
||||
@@ -1195,24 +1275,36 @@ mod tests {
|
||||
write(&g, "settings.gradle", "include 'app'");
|
||||
write(&g, "app/build.gradle", "apply plugin: 'java'");
|
||||
let model = crate::load(&g, &tmp.path().join("cache2"), None);
|
||||
let p = plan(&g, &model, BuildKind::Build, Some(&g.join("app/src/A.java")), None).unwrap();
|
||||
let p =
|
||||
plan(&g, &model, BuildKind::Build, Some(&g.join("app/src/A.java")), None, None, &CancellationToken::new())
|
||||
.unwrap();
|
||||
assert_eq!(p.system, BuildSystem::Gradle);
|
||||
assert_eq!(p.steps[0].args, ["--console=plain", ":app:classes", ":app:testClasses"]);
|
||||
assert_eq!(
|
||||
plan(&g, &model, BuildKind::Artifacts, None, None).unwrap().steps[0].args,
|
||||
plan(&g, &model, BuildKind::Artifacts, None, None, None, &CancellationToken::new()).unwrap().steps[0].args,
|
||||
["--console=plain", "assemble"]
|
||||
);
|
||||
|
||||
let c = tmp.path().join("c");
|
||||
write(&c, "Cargo.toml", "[package]\nname='c'");
|
||||
let p = plan(&c, &BuildModel::default(), BuildKind::Rebuild, None, None).unwrap();
|
||||
let p =
|
||||
plan(&c, &BuildModel::default(), BuildKind::Rebuild, None, None, None, &CancellationToken::new()).unwrap();
|
||||
assert_eq!(p.system, BuildSystem::Cargo);
|
||||
assert_eq!(p.steps.len(), 2);
|
||||
assert_eq!(p.steps[0].args[0], "clean");
|
||||
|
||||
let go = tmp.path().join("go");
|
||||
write(&go, "go.mod", "module x");
|
||||
let p = plan(&go, &BuildModel::default(), BuildKind::Build, Some(&go.join("pkg/a/a.go")), None).unwrap();
|
||||
let p = plan(
|
||||
&go,
|
||||
&BuildModel::default(),
|
||||
BuildKind::Build,
|
||||
Some(&go.join("pkg/a/a.go")),
|
||||
None,
|
||||
None,
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(p.steps[0].args, ["build", "./pkg/a/..."]);
|
||||
assert_eq!(p.steps[0].cwd, go);
|
||||
|
||||
@@ -1220,9 +1312,11 @@ mod tests {
|
||||
write(&ts, "package.json", r#"{"scripts":{"build":"vite build"}}"#);
|
||||
write(&ts, "tsconfig.json", "{}");
|
||||
write(&ts, "pnpm-lock.yaml", "");
|
||||
let p = plan(&ts, &BuildModel::default(), BuildKind::Build, None, None).unwrap();
|
||||
let p =
|
||||
plan(&ts, &BuildModel::default(), BuildKind::Build, None, None, None, &CancellationToken::new()).unwrap();
|
||||
assert_eq!(p.steps[0].args, ["--noEmit", "--pretty", "false", "-p", "."]);
|
||||
let p = plan(&ts, &BuildModel::default(), BuildKind::Artifacts, None, None).unwrap();
|
||||
let p = plan(&ts, &BuildModel::default(), BuildKind::Artifacts, None, None, None, &CancellationToken::new())
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
(p.steps[0].program.as_str(), p.steps[0].args.as_slice()),
|
||||
("pnpm", &["run".to_owned(), "build".to_owned()][..])
|
||||
@@ -1235,21 +1329,32 @@ mod tests {
|
||||
write(&net, "src/Api/Api.csproj", "<Project/>");
|
||||
write(&net, "src/Api/package.json", "{}");
|
||||
write(&net, "src/Api/Program.cs", "");
|
||||
let p = plan(&net, &BuildModel::default(), BuildKind::Build, None, None).unwrap();
|
||||
let p =
|
||||
plan(&net, &BuildModel::default(), BuildKind::Build, None, None, None, &CancellationToken::new()).unwrap();
|
||||
assert_eq!(p.system, BuildSystem::Dotnet);
|
||||
assert_eq!(p.steps[0].args, ["build", "App.sln", "-nologo", "-clp:NoSummary"]);
|
||||
assert_eq!(p.steps[0].env["MSBUILDTERMINALLOGGER"], "off");
|
||||
let p = plan(&net, &BuildModel::default(), BuildKind::Rebuild, Some(&net.join("src/Api/Program.cs")), None)
|
||||
.unwrap();
|
||||
let p = plan(
|
||||
&net,
|
||||
&BuildModel::default(),
|
||||
BuildKind::Rebuild,
|
||||
Some(&net.join("src/Api/Program.cs")),
|
||||
None,
|
||||
None,
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(p.steps[0].args, ["build", "Api.csproj", "-nologo", "-clp:NoSummary", "--no-incremental"]);
|
||||
assert_eq!(p.steps[0].cwd, net.join("src/Api"));
|
||||
let p = plan(&net, &BuildModel::default(), BuildKind::Artifacts, None, None).unwrap();
|
||||
let p = plan(&net, &BuildModel::default(), BuildKind::Artifacts, None, None, None, &CancellationToken::new())
|
||||
.unwrap();
|
||||
assert_eq!(p.steps[0].args[0], "publish");
|
||||
|
||||
let cm = tmp.path().join("cm");
|
||||
write(&cm, "CMakeLists.txt", "project(app)");
|
||||
let args = |p: &BuildPlan| p.steps.iter().map(|s| s.args.join(" ")).collect::<Vec<_>>();
|
||||
let p = plan(&cm, &BuildModel::default(), BuildKind::Build, None, None).unwrap();
|
||||
let p =
|
||||
plan(&cm, &BuildModel::default(), BuildKind::Build, None, None, None, &CancellationToken::new()).unwrap();
|
||||
assert_eq!(p.system, BuildSystem::CMake);
|
||||
assert_eq!(
|
||||
args(&p),
|
||||
@@ -1260,7 +1365,8 @@ mod tests {
|
||||
"an unconfigured project is configured first"
|
||||
);
|
||||
write(&cm, "cmake-build-release/CMakeCache.txt", "");
|
||||
let p = plan(&cm, &BuildModel::default(), BuildKind::Rebuild, None, None).unwrap();
|
||||
let p =
|
||||
plan(&cm, &BuildModel::default(), BuildKind::Rebuild, None, None, None, &CancellationToken::new()).unwrap();
|
||||
assert_eq!(
|
||||
args(&p),
|
||||
["--build cmake-build-release --config Debug --clean-first"],
|
||||
@@ -1272,17 +1378,34 @@ mod tests {
|
||||
build_args: vec!["-j".into(), "8".into()],
|
||||
..CMakeProfile::default()
|
||||
};
|
||||
let p =
|
||||
plan(&cm, &BuildModel::default(), BuildKind::Build, None, Some(std::slice::from_ref(&profile))).unwrap();
|
||||
let p = plan(
|
||||
&cm,
|
||||
&BuildModel::default(),
|
||||
BuildKind::Build,
|
||||
None,
|
||||
Some(std::slice::from_ref(&profile)),
|
||||
None,
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(args(&p), ["--build cmake-build-release --config Release -j 8"]);
|
||||
let p = plan(&cm, &BuildModel::default(), BuildKind::Build, None, Some(&[CMakeProfile::default()])).unwrap();
|
||||
let p = plan(
|
||||
&cm,
|
||||
&BuildModel::default(),
|
||||
BuildKind::Build,
|
||||
None,
|
||||
Some(&[CMakeProfile::default()]),
|
||||
None,
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(p.steps[0].args[..4], ["-S", ".", "-B", "cmake-build-debug"]);
|
||||
|
||||
let siblings = tmp.path().join("siblings");
|
||||
write(&siblings, "core/pom.xml", "<project><artifactId>core</artifactId></project>");
|
||||
write(&siblings, "system/pom.xml", "<project><artifactId>system</artifactId></project>");
|
||||
let model = crate::load(&siblings, &tmp.path().join("cache3"), None);
|
||||
let p = plan(&siblings, &model, BuildKind::Build, None, None).unwrap();
|
||||
let p = plan(&siblings, &model, BuildKind::Build, None, None, None, &CancellationToken::new()).unwrap();
|
||||
assert_eq!(p.system, BuildSystem::Maven);
|
||||
assert_eq!(
|
||||
p.steps.iter().map(|s| s.cwd.clone()).collect::<Vec<_>>(),
|
||||
@@ -1291,7 +1414,9 @@ mod tests {
|
||||
|
||||
let none = tmp.path().join("none");
|
||||
std::fs::create_dir_all(&none).unwrap();
|
||||
assert!(plan(&none, &BuildModel::default(), BuildKind::Build, None, None).is_err());
|
||||
assert!(
|
||||
plan(&none, &BuildModel::default(), BuildKind::Build, None, None, None, &CancellationToken::new()).is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1490,7 +1615,8 @@ mod tests {
|
||||
let model = reactor_model();
|
||||
for (test, goal) in [(false, "compile"), (true, "test-compile")] {
|
||||
// A normal launch is incremental: no `clean` (IDEA's Make, not Rebuild).
|
||||
let plan = launch_plan(root, &model, &root.join("app"), test, BuildKind::Build).unwrap();
|
||||
let plan = launch_plan(root, &model, &root.join("app"), test, BuildKind::Build, &CancellationToken::new())
|
||||
.unwrap();
|
||||
let step = &plan.steps[0];
|
||||
assert_eq!(step.cwd, root);
|
||||
assert_eq!(step.program, "mvnw");
|
||||
@@ -1511,7 +1637,9 @@ mod tests {
|
||||
]
|
||||
);
|
||||
// Rebuild cleans first, as IDEA's Rebuild does.
|
||||
let plan = launch_plan(root, &model, &root.join("app"), test, BuildKind::Rebuild).unwrap();
|
||||
let plan =
|
||||
launch_plan(root, &model, &root.join("app"), test, BuildKind::Rebuild, &CancellationToken::new())
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
plan.steps[0].args,
|
||||
[
|
||||
|
||||
@@ -0,0 +1,408 @@
|
||||
//! Module-scoped Maven menu builds (`Build Project` on a multi-module reactor, #4078).
|
||||
//!
|
||||
//! A project build used to run every linked reactor from end to end; only the
|
||||
//! all-or-nothing up-to-date check could skip it, so one edited file anywhere
|
||||
//! paid a full reactor build. This module narrows the scope: per-module input
|
||||
//! fingerprints recorded after the last successful build tell which modules'
|
||||
//! sources, resources, POM chain or outputs changed, the module dependency graph
|
||||
//! spreads that to the modules depending on them, and the reactor runs
|
||||
//! `mvn -pl <modules> -am` over just that set. Maven still decides what
|
||||
//! recompiles inside the selected modules; `-am` keeps the upstream modules a
|
||||
//! changed module was built against. Reactors without a usable record, and any
|
||||
//! analysis that cannot resolve its inputs, build everything as before.
|
||||
|
||||
use super::up_to_date::restamp;
|
||||
use super::*;
|
||||
use std::fs;
|
||||
|
||||
/// The per-module input fingerprints of one reactor's last successful build.
|
||||
#[derive(serde::Serialize, serde::Deserialize)]
|
||||
struct ReactorRecord {
|
||||
/// Module directory (project-relative, `/`-separated) → its record.
|
||||
modules: BTreeMap<String, ModuleRecord>,
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize, serde::Deserialize)]
|
||||
struct ModuleRecord {
|
||||
fingerprint: LaunchFingerprint,
|
||||
/// Output folders of the module that existed after the build, relative to the
|
||||
/// project. Deleting one outside the IDE (`mvn clean` in a terminal) leaves every
|
||||
/// input unchanged, so the module is rebuilt only while they are gone.
|
||||
outputs: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
fn record_path(cache: &Path, top_dir: &str) -> PathBuf {
|
||||
let base = cache.join("menu-build").join("modules");
|
||||
if top_dir.is_empty() { base.join("root.json") } else { base.join(format!("{top_dir}.json")) }
|
||||
}
|
||||
|
||||
fn load_record(cache: &Path, top_dir: &str) -> Option<ReactorRecord> {
|
||||
let bytes = fs::read(record_path(cache, top_dir)).ok()?;
|
||||
serde_json::from_slice(&bytes).ok()
|
||||
}
|
||||
|
||||
/// Projects of `reactor` that (transitively) depend on one of `changed`, through
|
||||
/// dependencies whose version matches the provider. The reverse of the launch
|
||||
/// upstream walk: a changed module's new classes force its consumers to recompile,
|
||||
/// `test`-scoped ones included, since the project build compiles every module's tests.
|
||||
fn affected_projects(reactor: &[&maven::MavenProject], changed: &HashSet<String>) -> HashSet<String> {
|
||||
let mut affected = changed.clone();
|
||||
let mut pending: Vec<&str> = changed.iter().map(String::as_str).collect();
|
||||
while let Some(dir) = pending.pop() {
|
||||
let Some(upstream) = reactor.iter().find(|p| p.dir == dir) else { continue };
|
||||
for consumer in reactor {
|
||||
if affected.contains(&consumer.dir) {
|
||||
continue;
|
||||
}
|
||||
let depends = consumer.dependencies.iter().any(|d| {
|
||||
d.resolved()
|
||||
&& upstream.group_id == d.group_id
|
||||
&& upstream.artifact_id == d.artifact_id
|
||||
&& d.version.as_ref().is_none_or(|v| *v == upstream.version)
|
||||
});
|
||||
if depends {
|
||||
affected.insert(consumer.dir.clone());
|
||||
pending.push(consumer.dir.as_str());
|
||||
}
|
||||
}
|
||||
}
|
||||
affected
|
||||
}
|
||||
|
||||
/// `-pl` entries of the affected modules, relative to the reactor root the step
|
||||
/// runs in, sorted so the command line does not depend on the model's project
|
||||
/// order (Maven reorders the selection into its own reactor order anyway).
|
||||
fn selection(reactor: &[&maven::MavenProject], top_dir: &str, affected: &HashSet<String>) -> String {
|
||||
let mut entries: Vec<String> = reactor
|
||||
.iter()
|
||||
.filter(|p| affected.contains(&p.dir))
|
||||
.map(|p| {
|
||||
Path::new(&p.dir).strip_prefix(top_dir).unwrap_or(Path::new(&p.dir)).to_string_lossy().replace('\\', "/")
|
||||
})
|
||||
.collect();
|
||||
entries.sort();
|
||||
entries.join(",")
|
||||
}
|
||||
|
||||
/// Narrowed `Build Project` steps: per reactor, one full step when the reactor
|
||||
/// or most of it is affected, one `-pl <modules> -am` step for the affected
|
||||
/// subset, or no step at all when nothing changed since the last successful
|
||||
/// build. `None` = some module's inputs cannot be fingerprinted, so the caller
|
||||
/// falls back to the unscoped build. The `step` closure builds a reactor step
|
||||
/// with the caller's goals and options.
|
||||
pub(super) fn narrowed_maven_steps(
|
||||
cache: &Path,
|
||||
root: &Path,
|
||||
m: &maven::MavenModel,
|
||||
step: &impl Fn(&maven::MavenProject, &[String]) -> BuildStep,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Option<Vec<BuildStep>>> {
|
||||
let mut steps = Vec::new();
|
||||
for top in m.projects.iter().filter(|p| !p.aggregated) {
|
||||
let Some(record) = load_record(cache, &top.dir) else {
|
||||
steps.push(step(top, &[]));
|
||||
continue;
|
||||
};
|
||||
let reactor = reactor_projects(m, top);
|
||||
let mut changed = HashSet::new();
|
||||
let mut lying: Vec<PathBuf> = Vec::new();
|
||||
for project in &reactor {
|
||||
let Some(current) = fingerprint::module_fingerprint(root, project, cancel)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(recorded) = record.modules.get(&project.dir) else {
|
||||
changed.insert(project.dir.clone());
|
||||
continue;
|
||||
};
|
||||
if recorded.fingerprint != current {
|
||||
changed.insert(project.dir.clone());
|
||||
lying.extend(recorded.fingerprint.mtime_preserved_edits(¤t));
|
||||
}
|
||||
if !recorded.outputs.iter().all(|out| root.join(out).is_dir()) {
|
||||
changed.insert(project.dir.clone());
|
||||
}
|
||||
}
|
||||
if changed.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let affected = affected_projects(&reactor, &changed);
|
||||
restamp(root, &lying);
|
||||
if affected.len() >= reactor.len() || affected.contains(&top.dir) {
|
||||
steps.push(step(top, &[]));
|
||||
} else {
|
||||
let pl = selection(&reactor, &top.dir, &affected);
|
||||
steps.push(step(top, &["-pl".into(), pl, "-am".into()]));
|
||||
}
|
||||
}
|
||||
Ok(Some(steps))
|
||||
}
|
||||
|
||||
/// Records the per-module inputs of every linked reactor as the baseline of the
|
||||
/// next narrowed build. Failures are swallowed: a missing record only costs one
|
||||
/// unscoped Maven run. Called after a successful project build.
|
||||
pub fn record_module_build(cache: &Path, root: &Path, model: &BuildModel, cancel: &CancellationToken) {
|
||||
let Some(m) = &model.maven else { return };
|
||||
for top in m.projects.iter().filter(|p| !p.aggregated) {
|
||||
let mut modules = BTreeMap::new();
|
||||
for project in reactor_projects(m, top) {
|
||||
let Ok(Some(fingerprint)) = fingerprint::module_fingerprint(root, project, cancel) else { continue };
|
||||
let outputs = ["target/classes", "target/test-classes"]
|
||||
.iter()
|
||||
.map(|out| Path::new(&project.dir).join(out))
|
||||
.filter(|rel| root.join(rel).is_dir())
|
||||
.collect();
|
||||
modules.insert(project.dir.clone(), ModuleRecord { fingerprint, outputs });
|
||||
}
|
||||
let path = record_path(cache, &top.dir);
|
||||
if path.parent().is_some_and(|p| fs::create_dir_all(p).is_err()) {
|
||||
continue;
|
||||
}
|
||||
let Ok(bytes) = serde_json::to_vec(&ReactorRecord { modules }) else { continue };
|
||||
let _ = fs::write(&path, bytes);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn write(root: &Path, rel: &str, value: &str) {
|
||||
let path = root.join(rel);
|
||||
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
fs::write(path, value).unwrap();
|
||||
}
|
||||
|
||||
/// `other` ← nothing, `app` ← `mid` ← `lib`, all under one reactor root.
|
||||
fn fixture(root: &Path) -> BuildModel {
|
||||
write(
|
||||
root,
|
||||
"pom.xml",
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>root</artifactId><version>1</version><packaging>pom</packaging><modules><module>lib</module><module>mid</module><module>app</module><module>other</module></modules></project>"#,
|
||||
);
|
||||
for (dir, class, deps) in [
|
||||
("lib", "L", ""),
|
||||
(
|
||||
"mid",
|
||||
"M",
|
||||
"<dependencies><dependency><groupId>t</groupId><artifactId>lib</artifactId><version>1</version></dependency></dependencies>",
|
||||
),
|
||||
(
|
||||
"app",
|
||||
"A",
|
||||
"<dependencies><dependency><groupId>t</groupId><artifactId>mid</artifactId><version>1</version></dependency></dependencies>",
|
||||
),
|
||||
("other", "O", ""),
|
||||
] {
|
||||
write(
|
||||
root,
|
||||
&format!("{dir}/pom.xml"),
|
||||
&format!(
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>{dir}</artifactId>{deps}</project>"#
|
||||
),
|
||||
);
|
||||
write(
|
||||
root,
|
||||
&format!("{dir}/src/main/java/t/{class}.java"),
|
||||
&format!("package t; public class {class} {{}}"),
|
||||
);
|
||||
}
|
||||
BuildModel { maven: Some(maven::load(root)), ..Default::default() }
|
||||
}
|
||||
|
||||
fn steps(cache: &Path, root: &Path, model: &BuildModel) -> Option<Vec<BuildStep>> {
|
||||
narrowed_maven_steps(
|
||||
cache,
|
||||
root,
|
||||
model.maven.as_ref().unwrap(),
|
||||
&|p, extra| {
|
||||
let mut s = BuildStep::new(&p.command, &["-B"], &subdir(root, &p.dir), Format::Maven);
|
||||
s.args.extend(extra.iter().cloned());
|
||||
s.args.push("test-compile".into());
|
||||
s
|
||||
},
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn pl_arg(step: &BuildStep) -> String {
|
||||
let i = step.args.iter().position(|a| a == "-pl").unwrap();
|
||||
step.args[i + 1].clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changed_module_selects_itself_and_transitive_dependents() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let model = fixture(root);
|
||||
let cache = root.join("cache");
|
||||
record_module_build(&cache, root, &model, &CancellationToken::new());
|
||||
write(root, "lib/src/main/java/t/L.java", "package t; public class L { int x; }");
|
||||
let steps = steps(&cache, root, &model).unwrap();
|
||||
assert_eq!(steps.len(), 1);
|
||||
assert_eq!(pl_arg(&steps[0]), "app,lib,mid");
|
||||
assert!(steps[0].args.contains(&"-am".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unchanged_reactor_runs_nothing() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let model = fixture(root);
|
||||
let cache = root.join("cache");
|
||||
record_module_build(&cache, root, &model, &CancellationToken::new());
|
||||
assert!(steps(&cache, root, &model).unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_or_corrupt_record_builds_everything() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let model = fixture(root);
|
||||
let cache = root.join("cache");
|
||||
assert_eq!(steps(&cache, root, &model).unwrap().len(), 1);
|
||||
record_module_build(&cache, root, &model, &CancellationToken::new());
|
||||
fs::create_dir_all(cache.join("menu-build").join("modules")).unwrap();
|
||||
fs::write(cache.join("menu-build").join("modules").join("root.json"), b"{not json").unwrap();
|
||||
assert_eq!(steps(&cache, root, &model).unwrap().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleted_output_rebuilds_the_module_without_spreading() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let model = fixture(root);
|
||||
let cache = root.join("cache");
|
||||
for out in ["mid/target/classes/t", "other/target/classes"] {
|
||||
fs::create_dir_all(root.join(out)).unwrap();
|
||||
}
|
||||
record_module_build(&cache, root, &model, &CancellationToken::new());
|
||||
fs::remove_dir_all(root.join("mid/target")).unwrap();
|
||||
let steps = steps(&cache, root, &model).unwrap();
|
||||
assert_eq!(pl_arg(&steps[0]), "app,mid");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mtime_preserved_edit_is_restamped_before_the_build() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let model = fixture(root);
|
||||
let cache = root.join("cache");
|
||||
let rel = "lib/src/main/java/t/L.java";
|
||||
write(root, rel, "package t; public class L { int x; }");
|
||||
let mtime = fs::metadata(root.join(rel)).unwrap().modified().unwrap();
|
||||
record_module_build(&cache, root, &model, &CancellationToken::new());
|
||||
write(root, rel, "package t; public class L { int z; }");
|
||||
fs::File::options().write(true).open(root.join(rel)).unwrap().set_modified(mtime).unwrap();
|
||||
assert!(!steps(&cache, root, &model).unwrap().is_empty());
|
||||
assert!(fs::metadata(root.join(rel)).unwrap().modified().unwrap() > mtime);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_scoped_consumers_are_rebuilt_and_version_mismatch_does_not_spread() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
write(
|
||||
root,
|
||||
"pom.xml",
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>root</artifactId><version>1</version><packaging>pom</packaging><modules><module>lib</module><module>tester</module><module>v2</module></modules></project>"#,
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"lib/pom.xml",
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>lib</artifactId></project>"#,
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"tester/pom.xml",
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>tester</artifactId><dependencies><dependency><groupId>t</groupId><artifactId>lib</artifactId><version>1</version><scope>test</scope></dependency></dependencies></project>"#,
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"v2/pom.xml",
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>v2</artifactId><dependencies><dependency><groupId>t</groupId><artifactId>lib</artifactId><version>2</version></dependency></dependencies></project>"#,
|
||||
);
|
||||
for module in ["lib", "tester", "v2"] {
|
||||
write(root, &format!("{module}/src/main/java/t/{module}.java"), "package t;");
|
||||
}
|
||||
let model = BuildModel { maven: Some(maven::load(root)), ..Default::default() };
|
||||
let cache = root.join("cache");
|
||||
record_module_build(&cache, root, &model, &CancellationToken::new());
|
||||
write(root, "lib/src/main/java/t/L.java", "package t; public class L {}");
|
||||
let steps = steps(&cache, root, &model).unwrap();
|
||||
// `tester`'s tests compile against `lib`.
|
||||
assert_eq!(pl_arg(&steps[0]), "lib,tester");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn root_pom_change_selects_the_whole_reactor() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let model = fixture(root);
|
||||
let cache = root.join("cache");
|
||||
record_module_build(&cache, root, &model, &CancellationToken::new());
|
||||
write(
|
||||
root,
|
||||
"pom.xml",
|
||||
fs::read_to_string(root.join("pom.xml")).unwrap().replace("<modules>", "<!-- x --><modules>").as_str(),
|
||||
);
|
||||
let steps = steps(&cache, root, &model).unwrap();
|
||||
assert_eq!(steps.len(), 1);
|
||||
assert!(!steps[0].args.contains(&"-pl".into()));
|
||||
}
|
||||
|
||||
/// A folder of two sibling reactors: `chain` (lib ← mid ← app) and `solo`.
|
||||
fn two_reactors(root: &Path) -> BuildModel {
|
||||
write(
|
||||
root,
|
||||
"chain/pom.xml",
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>chain</artifactId><version>1</version><packaging>pom</packaging><modules><module>lib</module><module>mid</module><module>app</module></modules></project>"#,
|
||||
);
|
||||
for (dir, class, deps) in [
|
||||
("lib", "L", ""),
|
||||
(
|
||||
"mid",
|
||||
"M",
|
||||
"<dependencies><dependency><groupId>t</groupId><artifactId>lib</artifactId><version>1</version></dependency></dependencies>",
|
||||
),
|
||||
(
|
||||
"app",
|
||||
"A",
|
||||
"<dependencies><dependency><groupId>t</groupId><artifactId>mid</artifactId><version>1</version></dependency></dependencies>",
|
||||
),
|
||||
] {
|
||||
write(
|
||||
root,
|
||||
&format!("chain/{dir}/pom.xml"),
|
||||
&format!(
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>chain</artifactId><version>1</version></parent><artifactId>{dir}</artifactId>{deps}</project>"#
|
||||
),
|
||||
);
|
||||
write(
|
||||
root,
|
||||
&format!("chain/{dir}/src/main/java/t/{class}.java"),
|
||||
&format!("package t; public class {class} {{}}"),
|
||||
);
|
||||
}
|
||||
write(
|
||||
root,
|
||||
"solo/pom.xml",
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>solo</artifactId><version>1</version></project>"#,
|
||||
);
|
||||
write(root, "solo/src/main/java/t/S.java", "package t;");
|
||||
BuildModel { maven: Some(maven::load(root)), ..Default::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unrelated_reactors_are_judged_separately() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let model = two_reactors(root);
|
||||
let cache = root.join("cache");
|
||||
record_module_build(&cache, root, &model, &CancellationToken::new());
|
||||
write(root, "solo/src/main/java/t/S.java", "package t; public class S {}");
|
||||
let steps = steps(&cache, root, &model).unwrap();
|
||||
assert_eq!(steps.len(), 1);
|
||||
assert_eq!(steps[0].cwd, subdir(root, "solo"));
|
||||
}
|
||||
}
|
||||
@@ -41,7 +41,7 @@ fn record_path(cache: &Path, root: &Path, file: Option<&Path>) -> PathBuf {
|
||||
/// Re-stamps files whose content changed without advancing mtime (git
|
||||
/// checkout, external sync): timestamp-incremental Maven would otherwise skip
|
||||
/// them as "unchanged" and the rebuild would compile nothing.
|
||||
fn restamp(root: &Path, edits: &[PathBuf]) {
|
||||
pub(super) fn restamp(root: &Path, edits: &[PathBuf]) {
|
||||
let now = std::time::SystemTime::now();
|
||||
for rel in edits {
|
||||
let path = root.join(rel);
|
||||
|
||||
@@ -78,14 +78,14 @@ fn has_kotlin_sources(root: &Path) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
fn plan(root: &Path, model: &BuildModel) -> IdeResult<compile::BuildPlan> {
|
||||
fn plan(root: &Path, model: &BuildModel, cancel: &CancellationToken) -> IdeResult<compile::BuildPlan> {
|
||||
if model.maven.as_ref().is_none_or(|m| m.projects.is_empty()) {
|
||||
return Err(IdeError::invalid("Kotlin bridge requires a Maven build root"));
|
||||
}
|
||||
Ok(compile::BuildPlan {
|
||||
system: compile::BuildSystem::Maven,
|
||||
title: root.file_name().unwrap_or_default().to_string_lossy().into_owned(),
|
||||
steps: compile::maven_steps(root, model, BuildKind::Build, None)?,
|
||||
steps: compile::maven_steps(root, model, BuildKind::Build, None, None, cancel)?,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -99,7 +99,7 @@ pub fn build(
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Outcome> {
|
||||
std::fs::create_dir_all(generation)?;
|
||||
let mut plan = plan(root, model)?;
|
||||
let mut plan = plan(root, model, cancel)?;
|
||||
let mut manifests = Vec::new();
|
||||
for (index, step) in plan.steps.iter_mut().enumerate() {
|
||||
step.args.push("--fail-at-end".into());
|
||||
@@ -522,7 +522,7 @@ mod tests {
|
||||
}
|
||||
std::fs::write(root.join("kotlin/App.kt"), "class App").unwrap();
|
||||
assert!(has_kotlin(root, &model), "{marker}");
|
||||
let plan = plan(root, &model).unwrap();
|
||||
let plan = plan(root, &model, &CancellationToken::new()).unwrap();
|
||||
assert_eq!(plan.system, compile::BuildSystem::Maven);
|
||||
assert_eq!(plan.steps.len(), 2);
|
||||
for (step, name) in plan.steps.iter().zip(["java", "kotlin"]) {
|
||||
@@ -562,7 +562,7 @@ mod tests {
|
||||
..Default::default()
|
||||
};
|
||||
assert!(has_kotlin(workspace.path(), &model));
|
||||
assert_eq!(plan(workspace.path(), &model).unwrap().steps[0].cwd, external.path());
|
||||
assert_eq!(plan(workspace.path(), &model, &CancellationToken::new()).unwrap().steps[0].cwd, external.path());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -460,6 +460,8 @@ pub struct TerminalSettings {
|
||||
/// `block` | `underline` | `bar`.
|
||||
pub cursor_shape: String,
|
||||
pub cursor_blink: bool,
|
||||
/// Cap PTY→xterm paint rate: `unlimited` | `60` | `30` | `15` | `10`.
|
||||
pub max_fps: String,
|
||||
pub use_editor_font: bool,
|
||||
pub font_family: String,
|
||||
pub font_size: f32,
|
||||
@@ -491,6 +493,7 @@ impl Default for TerminalSettings {
|
||||
escape_to_editor: false,
|
||||
cursor_shape: "block".into(),
|
||||
cursor_blink: true,
|
||||
max_fps: "unlimited".into(),
|
||||
use_editor_font: true,
|
||||
font_family: "JetBrains Mono".into(),
|
||||
font_size: 13.0,
|
||||
|
||||
@@ -22,6 +22,8 @@ use tokio::process::{Child, Command};
|
||||
pub const PORT_PLACEHOLDER: &str = "${port}";
|
||||
/// Replaced by the session's working directory (the project) in adapter arguments.
|
||||
pub const ROOT_PLACEHOLDER: &str = "${root}";
|
||||
/// java-analyzer's debug adapter (`java-analyzer dap`), a separate process over stdio.
|
||||
pub const JAVA_ANALYZER: &str = "java-analyzer";
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Transport {
|
||||
@@ -134,6 +136,14 @@ fn builtin(adapter: &str) -> Option<DebuggerConfig> {
|
||||
"tcp",
|
||||
"Install Microsoft java-debug (Settings › Languages & Frameworks › Language Servers)",
|
||||
),
|
||||
// The Java language server's own debugger, for modules jdtls doesn't serve; the host
|
||||
// runs the executable of the java-analyzer serving the module.
|
||||
JAVA_ANALYZER => cfg(
|
||||
"java-analyzer",
|
||||
&["dap"],
|
||||
"stdio",
|
||||
"Configure java-analyzer as a Java language server (Settings › Languages & Frameworks › Language Servers)",
|
||||
),
|
||||
"bun-dap" => cfg(
|
||||
"bun-dap",
|
||||
&["${port}", "127.0.0.1"],
|
||||
@@ -920,6 +930,13 @@ mod tests {
|
||||
}
|
||||
let delve = resolve(&builtin("delve").unwrap(), PathBuf::from("/"));
|
||||
assert_eq!(delve.transport, Transport::Tcp);
|
||||
// java-analyzer debugs over stdio with its `dap` subcommand.
|
||||
let java_analyzer = resolve(&builtin(JAVA_ANALYZER).unwrap(), PathBuf::from("/"));
|
||||
assert_eq!(
|
||||
(java_analyzer.command.as_str(), java_analyzer.args.as_slice()),
|
||||
("java-analyzer", &["dap".to_owned()][..])
|
||||
);
|
||||
assert_eq!(java_analyzer.transport, Transport::Stdio);
|
||||
// GDB's own DAP interpreter over stdio, with the required version in its hint.
|
||||
let gdb = builtin("gdb").unwrap();
|
||||
assert_eq!(gdb.command, "gdb");
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -5,6 +5,7 @@
|
||||
//! Every function blocks; callers run them off the UI / command threads.
|
||||
|
||||
mod connection;
|
||||
mod engine;
|
||||
mod model;
|
||||
mod process;
|
||||
|
||||
@@ -114,6 +115,11 @@ fn failure(args: &[&str], stderr: &str, stdout: &str) -> IdeError {
|
||||
|
||||
/// Whether docker can be used right now.
|
||||
pub fn availability(ep: &DockerEndpoint) -> DockerAvailability {
|
||||
if docker_executable().is_none()
|
||||
&& let Some(available) = engine::availability(ep, Duration::from_secs(15))
|
||||
{
|
||||
return available;
|
||||
}
|
||||
let Ok(cmd) = command(ep, &["version", "--format", "{{json .}}"]) else {
|
||||
return DockerAvailability::NotInstalled;
|
||||
};
|
||||
@@ -125,6 +131,11 @@ pub fn availability(ep: &DockerEndpoint) -> DockerAvailability {
|
||||
|
||||
/// Availability plus containers, images, volumes and networks (listed in parallel).
|
||||
pub fn snapshot(ep: &DockerEndpoint) -> DockerSnapshot {
|
||||
if docker_executable().is_none()
|
||||
&& let Some(listed) = engine::snapshot(ep, QUICK)
|
||||
{
|
||||
return listed;
|
||||
}
|
||||
let availability = availability(ep);
|
||||
let executable = docker_executable().map(|p| ide_core::ipc_path::to_ipc(&p));
|
||||
let mut snap = DockerSnapshot {
|
||||
@@ -202,6 +213,11 @@ pub fn container_op(ep: &DockerEndpoint, ids: &[String], op: ContainerOp) -> Ide
|
||||
if ids.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
if docker_executable().is_none()
|
||||
&& let Some(ran) = engine::container_op(ep, ids, op, LIFECYCLE)
|
||||
{
|
||||
return ran;
|
||||
}
|
||||
let mut args = vec!["container", op.verb()];
|
||||
args.extend(ids.iter().map(String::as_str));
|
||||
run(ep, &args, LIFECYCLE).map(drop)
|
||||
@@ -232,6 +248,11 @@ pub fn remove(ep: &DockerEndpoint, object: DockerObject, ids: &[String], force:
|
||||
if ids.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
if docker_executable().is_none()
|
||||
&& let Some(ran) = engine::remove(ep, object, ids, force, LIFECYCLE)
|
||||
{
|
||||
return ran;
|
||||
}
|
||||
let mut args = vec![object.noun(), "rm"];
|
||||
if force && matches!(object, DockerObject::Container | DockerObject::Image | DockerObject::Volume) {
|
||||
args.push("--force");
|
||||
@@ -242,6 +263,11 @@ pub fn remove(ep: &DockerEndpoint, object: DockerObject, ids: &[String], force:
|
||||
|
||||
/// `docker inspect` of one object, pretty-printed.
|
||||
pub fn inspect(ep: &DockerEndpoint, object: DockerObject, id: &str) -> IdeResult<String> {
|
||||
if docker_executable().is_none()
|
||||
&& let Some(inspected) = engine::inspect(ep, object, id, QUICK)
|
||||
{
|
||||
return inspected;
|
||||
}
|
||||
let out = run(ep, &["inspect", "--type", object.noun(), id], QUICK)?;
|
||||
match serde_json::from_str::<serde_json::Value>(&out) {
|
||||
// A one-element array for a single id: show the object itself.
|
||||
|
||||
@@ -211,10 +211,10 @@ pub fn parse_labels(raw: &str) -> BTreeMap<String, String> {
|
||||
out
|
||||
}
|
||||
|
||||
const COMPOSE_PROJECT: &str = "com.docker.compose.project";
|
||||
const COMPOSE_SERVICE: &str = "com.docker.compose.service";
|
||||
const COMPOSE_DIR: &str = "com.docker.compose.project.working_dir";
|
||||
const COMPOSE_FILES: &str = "com.docker.compose.project.config_files";
|
||||
pub(crate) const COMPOSE_PROJECT: &str = "com.docker.compose.project";
|
||||
pub(crate) const COMPOSE_SERVICE: &str = "com.docker.compose.service";
|
||||
pub(crate) const COMPOSE_DIR: &str = "com.docker.compose.project.working_dir";
|
||||
pub(crate) const COMPOSE_FILES: &str = "com.docker.compose.project.config_files";
|
||||
|
||||
fn lines<T: for<'de> Deserialize<'de>>(text: &str) -> impl Iterator<Item = T> + '_ {
|
||||
text.lines().filter(|l| l.trim_start().starts_with('{')).filter_map(|l| match serde_json::from_str::<T>(l) {
|
||||
@@ -253,7 +253,7 @@ struct RawContainer {
|
||||
networks: String,
|
||||
}
|
||||
|
||||
fn split_csv(raw: &str) -> Vec<String> {
|
||||
pub(crate) fn split_csv(raw: &str) -> Vec<String> {
|
||||
raw.split(',').map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned).collect()
|
||||
}
|
||||
|
||||
|
||||
@@ -34,7 +34,7 @@ use std::path::{Component, Path, PathBuf};
|
||||
|
||||
pub const MANIFEST_FILE: &str = "plugin.toml";
|
||||
/// The plugin API (engine) version this host implements.
|
||||
pub const ENGINE_VERSION: &str = "1.12.0";
|
||||
pub const ENGINE_VERSION: &str = "1.13.0";
|
||||
/// The 0.1 API, still accepted for contribution-only packages and 0.1 components.
|
||||
pub const LEGACY_API: &str = "0.1";
|
||||
/// Marketplace categories, in the order they are shown.
|
||||
|
||||
@@ -268,6 +268,24 @@ pub async fn agent_prompt(host: &Host, window: &str, task: String, prompt: Agent
|
||||
host.project(window)?.agents.prompt(&task, prompt, now).await
|
||||
}
|
||||
|
||||
/// Runs a `!` line of the composer in the task's folder with the user's shell, without
|
||||
/// starting a turn; its output goes to the agent with the next message.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_shell(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
task: String,
|
||||
command: String,
|
||||
request: RequestId,
|
||||
) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let agents = host.project(window)?.agents.clone();
|
||||
let cancel = host.begin_request(request);
|
||||
let result = agents.run_shell(&task, &command, cancel).await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
/// Answers a non-blocking question, without cancelling the current turn.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_answer_question(
|
||||
@@ -1080,6 +1098,7 @@ ide_command::domain!(
|
||||
agent_rollback_changes,
|
||||
agent_send_queued_now,
|
||||
agent_set_command,
|
||||
agent_shell,
|
||||
agent_set_config,
|
||||
agent_set_env,
|
||||
agent_set_mcp_overrides,
|
||||
|
||||
@@ -815,7 +815,15 @@ pub async fn build_run(
|
||||
if compile::menu_up_to_date(&cache, &root, &model, file.as_deref(), &token) {
|
||||
let started = std::time::Instant::now();
|
||||
let plan = prepare_plan(
|
||||
compile::plan(&root, &model, kind, file.as_deref(), settings.cmake.profiles.as_deref())?,
|
||||
compile::plan(
|
||||
&root,
|
||||
&model,
|
||||
kind,
|
||||
file.as_deref(),
|
||||
settings.cmake.profiles.as_deref(),
|
||||
None,
|
||||
&token,
|
||||
)?,
|
||||
&root,
|
||||
&settings,
|
||||
);
|
||||
@@ -853,7 +861,15 @@ pub async fn build_run(
|
||||
if member == &root { cache.clone() } else { cache.join(crate::project::project_key(member)) };
|
||||
let model = with_profiles(load(member, &member_cache, &settings), &member_cache);
|
||||
let plan = prepare_plan(
|
||||
compile::plan(member, &model, kind, file.as_deref(), settings.cmake.profiles.as_deref())?,
|
||||
compile::plan(
|
||||
member,
|
||||
&model,
|
||||
kind,
|
||||
file.as_deref(),
|
||||
settings.cmake.profiles.as_deref(),
|
||||
None,
|
||||
&token,
|
||||
)?,
|
||||
member,
|
||||
&settings,
|
||||
);
|
||||
@@ -867,7 +883,15 @@ pub async fn build_run(
|
||||
plan
|
||||
} else {
|
||||
let model = with_profiles(load(&root, &cache, &settings), &cache);
|
||||
match compile::plan(&root, &model, kind, file.as_deref(), settings.cmake.profiles.as_deref()) {
|
||||
match compile::plan(
|
||||
&root,
|
||||
&model,
|
||||
kind,
|
||||
file.as_deref(),
|
||||
settings.cmake.profiles.as_deref(),
|
||||
Some(&cache),
|
||||
&token,
|
||||
) {
|
||||
Ok(plan) => prepare_plan(plan, &root, &settings),
|
||||
// No build tool: a Java project builds from its Project Structure.
|
||||
Err(e) if e.kind == ide_core::error::ErrorKind::NotFound => {
|
||||
@@ -882,6 +906,11 @@ pub async fn build_run(
|
||||
if result.success && single && kind == BuildKind::Build {
|
||||
let model = with_profiles(load(&root, &cache, &settings), &cache);
|
||||
compile::record_menu_build(&cache, &root, &model, file.as_deref(), &token);
|
||||
// Only a project build covers every changed module; after Build Module the
|
||||
// others may still be stale.
|
||||
if file.is_none() {
|
||||
compile::record_module_build(&cache, &root, &model, &token);
|
||||
}
|
||||
}
|
||||
for (path, items) in compile::diagnostics(&result.messages) {
|
||||
sink.emit(IdeEvent::Diagnostics { path: path.into(), source: compile::DIAGNOSTICS_SOURCE.into(), items });
|
||||
@@ -1015,7 +1044,16 @@ mod build_tool_settings_tests {
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join(marker), source).unwrap();
|
||||
let plan = prepare_plan(
|
||||
compile::plan(&dir, &Default::default(), BuildKind::Artifacts, None, None).unwrap(),
|
||||
compile::plan(
|
||||
&dir,
|
||||
&Default::default(),
|
||||
BuildKind::Artifacts,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
&ide_core::CancellationToken::new(),
|
||||
)
|
||||
.unwrap(),
|
||||
root,
|
||||
&settings,
|
||||
);
|
||||
@@ -1089,7 +1127,9 @@ mod build_tool_settings_tests {
|
||||
let expected = root.join(if runner.is_empty() { "project-jdk" } else { runner });
|
||||
let model = load(&root, &root.join("cache"), &settings);
|
||||
assert_eq!(model.maven.as_ref().unwrap().projects[0].env["JAVA_HOME"], expected.to_string_lossy());
|
||||
let plan = compile::plan(&root, &model, BuildKind::Build, None, None).unwrap();
|
||||
let plan =
|
||||
compile::plan(&root, &model, BuildKind::Build, None, None, None, &ide_core::CancellationToken::new())
|
||||
.unwrap();
|
||||
assert!(!plan.steps.is_empty());
|
||||
for step in plan.steps {
|
||||
assert_eq!(step.env["JAVA_HOME"], expected.to_string_lossy());
|
||||
@@ -1121,7 +1161,9 @@ mod build_tool_settings_tests {
|
||||
let expected = root.join(name);
|
||||
let model = load(&root, &root.join("cache"), &settings);
|
||||
assert_eq!(model.maven.as_ref().unwrap().projects[0].env["JAVA_HOME"], expected.to_string_lossy());
|
||||
let plan = compile::plan(&root, &model, BuildKind::Build, None, None).unwrap();
|
||||
let plan =
|
||||
compile::plan(&root, &model, BuildKind::Build, None, None, None, &ide_core::CancellationToken::new())
|
||||
.unwrap();
|
||||
assert!(!plan.steps.is_empty());
|
||||
for step in plan.steps {
|
||||
assert_eq!(step.env["JAVA_HOME"], expected.to_string_lossy());
|
||||
|
||||
@@ -113,7 +113,11 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
let java_analyzer = java_analyzer_command(host, window, &config)?;
|
||||
let custom = |command: &str| {
|
||||
if let Some(binary) = java_analyzer {
|
||||
return Some(binary.to_string_lossy().into_owned());
|
||||
}
|
||||
let path = ide_sdk::apply::tool_command(&root, &settings, command)
|
||||
.or_else(|| ruby_tools.into_iter().find(|(name, _)| *name == command).map(|(_, path)| path))?;
|
||||
Some(path.to_string_lossy().into_owned())
|
||||
@@ -142,6 +146,28 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
|
||||
result
|
||||
}
|
||||
|
||||
/// For java-analyzer's debugger, the executable of the java-analyzer serving the module
|
||||
/// (`projectRoot`, else the working directory), so the session debugs with the server that
|
||||
/// analyzes the code.
|
||||
fn java_analyzer_command(host: &Host, window: &str, config: &LaunchConfig) -> IdeResult<Option<PathBuf>> {
|
||||
if config.adapter != ide_dap::adapter::JAVA_ANALYZER {
|
||||
return Ok(None);
|
||||
}
|
||||
let project = host.project(window)?;
|
||||
let extra: serde_json::Value =
|
||||
config.extra_json.as_deref().and_then(|e| serde_json::from_str(e).ok()).unwrap_or_default();
|
||||
let module = extra["projectRoot"]
|
||||
.as_str()
|
||||
.map(PathBuf::from)
|
||||
.or_else(|| config.cwd.clone().map(PathBuf::from))
|
||||
.unwrap_or_else(|| project.root.clone());
|
||||
project.lsp.java_analyzer_binary(&module).map(Some).ok_or_else(|| {
|
||||
ide_core::IdeError::unavailable(
|
||||
"No java-analyzer serves this module: configure it as a Java language server to debug without jdtls",
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn require_unity_editor(pid: u32) -> IdeResult<()> {
|
||||
if !ide_core::process::process_alive(pid) {
|
||||
return Err(ide_core::IdeError::unavailable(format!(
|
||||
@@ -178,13 +204,16 @@ fn attach_jvm_inspector(host: &Host, window: &str, session: DebugSessionId, port
|
||||
}
|
||||
|
||||
/// A JVM the debugger starts itself: an Application or Spring Boot configuration, launched by
|
||||
/// java-debug or the Kotlin debugger (JAR Application debugs through a run with a JDWP agent).
|
||||
/// java-debug, java-analyzer or the Kotlin debugger (JAR Application debugs through a run with a
|
||||
/// JDWP agent).
|
||||
fn is_jvm_launch(config: &LaunchConfig) -> bool {
|
||||
config.request == "launch" && matches!(config.adapter.as_str(), "java-debug" | ide_dap::kotlin::ADAPTER)
|
||||
config.request == "launch"
|
||||
&& matches!(config.adapter.as_str(), "java-debug" | ide_dap::kotlin::ADAPTER | ide_dap::adapter::JAVA_ANALYZER)
|
||||
}
|
||||
|
||||
/// Plugins' Java agents ([`ide_run::java_agent`]) after the configuration's VM options:
|
||||
/// java-debug's `vmArgs` (one line, or a list) or the Kotlin debugger's `vmArguments` (a list).
|
||||
/// java-debug's and java-analyzer's `vmArgs` (one line, or a list) or the Kotlin debugger's
|
||||
/// `vmArguments` (a list).
|
||||
fn add_java_agents(mut config: LaunchConfig, options: &[String]) -> LaunchConfig {
|
||||
if options.is_empty() || !is_jvm_launch(&config) {
|
||||
return config;
|
||||
@@ -194,7 +223,7 @@ fn add_java_agents(mut config: LaunchConfig, options: &[String]) -> LaunchConfig
|
||||
else {
|
||||
return config;
|
||||
};
|
||||
let key = if config.adapter == "java-debug" { "vmArgs" } else { "vmArguments" };
|
||||
let key = if config.adapter == ide_dap::kotlin::ADAPTER { "vmArguments" } else { "vmArgs" };
|
||||
let value = match extra.get(key) {
|
||||
None | Some(serde_json::Value::Null) if key == "vmArgs" => {
|
||||
ide_run::java_agent::add_to_vm_args_text("", options).into()
|
||||
@@ -735,6 +764,9 @@ mod tests {
|
||||
assert_eq!(field(&add_java_agents(kotlin, options), "vmArguments"), serde_json::json!(["-Xmx1g", agent]));
|
||||
let kotlin = launch(ide_dap::kotlin::ADAPTER, "launch", serde_json::json!({}));
|
||||
assert_eq!(field(&add_java_agents(kotlin, options), "vmArguments"), serde_json::json!([agent]));
|
||||
let java_analyzer =
|
||||
launch(ide_dap::adapter::JAVA_ANALYZER, "launch", serde_json::json!({"vmArgs": ["-Xmx1g"]}));
|
||||
assert_eq!(vm_args(&add_java_agents(java_analyzer, options)), serde_json::json!(["-Xmx1g", agent]));
|
||||
// Attaching (remote debug included), other adapters, and no granted agent: unchanged.
|
||||
for config in [
|
||||
launch("java-debug", "attach", serde_json::json!({"vmArgs": "-Xmx1g"})),
|
||||
|
||||
@@ -5,12 +5,14 @@ use crate::Host;
|
||||
use ide_command::command;
|
||||
|
||||
use super::build::load;
|
||||
use ide_build::BuildModel;
|
||||
use ide_build::compile;
|
||||
use ide_core::error::ErrorKind;
|
||||
use ide_core::settings::Settings;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, RequestId};
|
||||
use ide_lsp::jdtls::{JavaBuildStatus, JavaLaunchInfo};
|
||||
use ide_run::BuildPolicy;
|
||||
use std::path::PathBuf;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Cancellable with `cancel_request(request)`.
|
||||
/// Builds according to `policy`, then resolves the runtime (or test)
|
||||
@@ -45,6 +47,9 @@ pub(crate) async fn resolve_launch(
|
||||
let started = std::time::Instant::now();
|
||||
let project = host.project(window)?;
|
||||
let module = project.root.join(module);
|
||||
if !project.lsp.java_served_by_jdtls(&module) {
|
||||
return resolve_launch_without_jdtls(host, &project, module, test, policy, cancel).await;
|
||||
}
|
||||
let settings = project.settings.effective();
|
||||
// A launch builds incrementally unless the configuration asks for Rebuild or NoBuild.
|
||||
let build = policy != BuildPolicy::NoBuild;
|
||||
@@ -161,35 +166,7 @@ pub(crate) async fn resolve_launch(
|
||||
}
|
||||
}
|
||||
let compile_ms = started.elapsed().as_millis() - lsp_ms;
|
||||
// The module/project JDK, else the JDK jdtls compiles the module against, else one matching its Java version.
|
||||
let project_jdk = ide_sdk::apply::module_jdk(&project.root, &module, &settings);
|
||||
let from_jdtls = info.java_home.as_deref().map(ide_sdk::java::java_executable).filter(|p| p.is_file());
|
||||
let java = project_jdk.map(|j| ide_sdk::java::java_executable(&j.home)).or(from_jdtls).or_else(|| {
|
||||
// The build model's level includes what the module inherits from its parent POMs.
|
||||
let release = model
|
||||
.maven
|
||||
.as_ref()
|
||||
.and_then(|m| m.projects.iter().find(|p| project.root.join(&p.dir) == module))
|
||||
.and_then(|p| p.java_version)
|
||||
.or_else(|| ide_sdk::java::project_java_version(&module));
|
||||
let jdks = ide_sdk::java::installed_jdks();
|
||||
info.hints.extend(ide_sdk::java::missing_jdk_message(&jdks, release));
|
||||
ide_sdk::java::pick_jdk(&jdks, release).map(|j| ide_sdk::java::java_executable(&j.home))
|
||||
});
|
||||
info.java_exec = Some(java.map(|p| p.to_string_lossy().into_owned()).unwrap_or_else(|| "java".to_owned()));
|
||||
let exec = PathBuf::from(info.java_exec.as_deref().unwrap_or("java"));
|
||||
let shorten =
|
||||
ide_run::java_cmdline::shortening_for(&exec, &info.class_paths, &info.module_paths, cfg!(windows));
|
||||
info.shorten_command_line = Some(shorten.as_str().to_owned());
|
||||
if info.error_count > 0 {
|
||||
let own = ide_sdk::lombok::agent_in_args(settings.languages.java.jdtls_vm_args.split_whitespace());
|
||||
let managed = ide_tools::managed_bundle(&data_dir, "lombok");
|
||||
let repo = ide_sdk::apply::maven_local_repository(&project.root, &settings);
|
||||
let root = project.root.clone();
|
||||
// Detection may read the project's sources.
|
||||
let lombok = ide_sdk::lombok::lombok_agent(&root, own, managed, repo);
|
||||
info.hints.extend(lombok.problem());
|
||||
}
|
||||
finish_launch(&mut info, &project.root, &module, &settings, &model, &data_dir);
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
@@ -206,6 +183,151 @@ pub(crate) async fn resolve_launch(
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
/// A launch of a module jdtls doesn't serve (another Java language server, or none): the
|
||||
/// build tool compiles it, and the classpath comes from that server, else from Maven.
|
||||
async fn resolve_launch_without_jdtls(
|
||||
host: &Host,
|
||||
project: &std::sync::Arc<crate::Project>,
|
||||
module: PathBuf,
|
||||
test: bool,
|
||||
policy: BuildPolicy,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<JavaLaunchInfo> {
|
||||
let started = std::time::Instant::now();
|
||||
let settings = project.settings.effective();
|
||||
let kind = if policy == BuildPolicy::Rebuild { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
|
||||
let (model, built) = {
|
||||
let (root, cache, settings, module, cancel) =
|
||||
(project.root.clone(), project.build_cache_dir(), settings.clone(), module.clone(), cancel.clone());
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let model = load(&root, &cache, &settings);
|
||||
let built = if policy == BuildPolicy::NoBuild {
|
||||
None
|
||||
} else {
|
||||
Some(compile::build_for_launch(&root, &model, &module, test, kind, &cancel))
|
||||
};
|
||||
(model, built)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
};
|
||||
let mut info =
|
||||
JavaLaunchInfo { path_list_separator: if cfg!(windows) { ";" } else { ":" }.into(), ..Default::default() };
|
||||
let mut class_paths = Vec::new();
|
||||
match built {
|
||||
None => {}
|
||||
Some(Err(e)) if e.kind == ErrorKind::Cancelled => return Err(e),
|
||||
Some(Err(e)) => {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"Cannot build the module without jdtls: {}. Running needs a Maven or Gradle build, or jdtls",
|
||||
e.message
|
||||
)));
|
||||
}
|
||||
Some(Ok(built)) => {
|
||||
info.build = Some(match built.failure {
|
||||
None => JavaBuildStatus::Succeeded,
|
||||
Some(failure) if policy == BuildPolicy::MakeAndContinueOnErrors => {
|
||||
info.hints.push(failure);
|
||||
JavaBuildStatus::Failed
|
||||
}
|
||||
Some(failure) => return Err(IdeError::internal(failure)),
|
||||
});
|
||||
class_paths.extend(built.class_dirs.iter().map(|p| p.to_string_lossy().into_owned()));
|
||||
}
|
||||
}
|
||||
let build_ms = started.elapsed().as_millis();
|
||||
let from_server = project.lsp.java_server_classpath(&module, test, cancel).await?;
|
||||
let data_dir = host.local_data_dir.clone();
|
||||
let project = project.clone();
|
||||
let cancel = cancel.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
match from_server {
|
||||
Some(server) => {
|
||||
info.project_root = server.classpath.project_root;
|
||||
info.module_paths = server.classpath.module_paths;
|
||||
info.java_home = server.jdk_home.map(Into::into);
|
||||
append_unique_class_paths(&mut class_paths, server.classpath.class_paths);
|
||||
}
|
||||
None => {
|
||||
let is_maven = model
|
||||
.maven
|
||||
.as_ref()
|
||||
.is_some_and(|m| m.projects.iter().any(|p| project.root.join(&p.dir) == module));
|
||||
if !is_maven {
|
||||
return Err(IdeError::unavailable(
|
||||
"Cannot resolve the classpath: the Java language server does not report it \
|
||||
(java-analyzer/projectClasspath), and the module is not a Maven project",
|
||||
));
|
||||
}
|
||||
let local_repo = ide_sdk::apply::maven_local_repository(&project.root, &settings);
|
||||
let classpath = compile::module_classpath(
|
||||
&project.root,
|
||||
&model,
|
||||
&module,
|
||||
test,
|
||||
local_repo,
|
||||
&project.build_cache_dir(),
|
||||
&cancel,
|
||||
)?;
|
||||
append_unique_class_paths(
|
||||
&mut class_paths,
|
||||
std::env::split_paths(&classpath).map(|p| p.to_string_lossy().into_owned()),
|
||||
);
|
||||
}
|
||||
}
|
||||
info.class_paths = class_paths;
|
||||
apply_library_classpath(&mut info, &project.root, &settings.project_structure.libraries, test);
|
||||
finish_launch(&mut info, &project.root, &module, &settings, &model, &data_dir);
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
tracing::info!(build_ms, total_ms = started.elapsed().as_millis(), "Java launch resolved without jdtls");
|
||||
Ok(info)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
/// Picks the `java` launcher and how to shorten its command line, and explains likely
|
||||
/// causes of compile errors.
|
||||
fn finish_launch(
|
||||
info: &mut JavaLaunchInfo,
|
||||
root: &Path,
|
||||
module: &Path,
|
||||
settings: &Settings,
|
||||
model: &BuildModel,
|
||||
data_dir: &Path,
|
||||
) {
|
||||
// The module/project JDK, else the JDK the Java language server builds the module with, else one
|
||||
// matching its Java version.
|
||||
let project_jdk = ide_sdk::apply::module_jdk(root, module, settings);
|
||||
let from_server = info.java_home.as_deref().map(ide_sdk::java::java_executable).filter(|p| p.is_file());
|
||||
let java = project_jdk.map(|j| ide_sdk::java::java_executable(&j.home)).or(from_server).or_else(|| {
|
||||
// The build model's level includes what the module inherits from its parent POMs.
|
||||
let release = model
|
||||
.maven
|
||||
.as_ref()
|
||||
.and_then(|m| m.projects.iter().find(|p| root.join(&p.dir) == module))
|
||||
.and_then(|p| p.java_version)
|
||||
.or_else(|| ide_sdk::java::project_java_version(module));
|
||||
let jdks = ide_sdk::java::installed_jdks();
|
||||
info.hints.extend(ide_sdk::java::missing_jdk_message(&jdks, release));
|
||||
ide_sdk::java::pick_jdk(&jdks, release).map(|j| ide_sdk::java::java_executable(&j.home))
|
||||
});
|
||||
info.java_exec = Some(java.map(|p| p.to_string_lossy().into_owned()).unwrap_or_else(|| "java".to_owned()));
|
||||
let exec = PathBuf::from(info.java_exec.as_deref().unwrap_or("java"));
|
||||
let shorten = ide_run::java_cmdline::shortening_for(&exec, &info.class_paths, &info.module_paths, cfg!(windows));
|
||||
info.shorten_command_line = Some(shorten.as_str().to_owned());
|
||||
if info.error_count > 0 {
|
||||
let own = ide_sdk::lombok::agent_in_args(settings.languages.java.jdtls_vm_args.split_whitespace());
|
||||
let managed = ide_tools::managed_bundle(data_dir, "lombok");
|
||||
let repo = ide_sdk::apply::maven_local_repository(root, settings);
|
||||
// Detection may read the project's sources.
|
||||
let lombok = ide_sdk::lombok::lombok_agent(root, own, managed, repo);
|
||||
info.hints.extend(lombok.problem());
|
||||
}
|
||||
}
|
||||
|
||||
/// With Settings › Maven › Delegate IDE build/run actions to Maven, javac's verdict replaces
|
||||
/// JDT's. Classes JDT wrote for sources with errors look up to date to Maven's incremental
|
||||
/// compiler, so a launch JDT reports errors for recompiles everything.
|
||||
@@ -374,6 +496,21 @@ fn use_snapshot_on(
|
||||
copies
|
||||
}
|
||||
|
||||
/// The debug adapter for the JVMs of `module`: `java-debug` inside jdtls, or `java-analyzer`
|
||||
/// (`java-analyzer dap`) when jdtls doesn't serve the module and java-analyzer does.
|
||||
#[command(trust = trusted)]
|
||||
pub fn java_debug_adapter(host: &Host, window: &str, module: PathBuf) -> IdeResult<String> {
|
||||
let project = host.project(window)?;
|
||||
let module = project.root.join(module);
|
||||
let lsp = &project.lsp;
|
||||
Ok(if !lsp.java_served_by_jdtls(&module) && lsp.java_analyzer_binary(&module).is_some() {
|
||||
ide_dap::adapter::JAVA_ANALYZER
|
||||
} else {
|
||||
"java-debug"
|
||||
}
|
||||
.to_owned())
|
||||
}
|
||||
|
||||
/// Port of java-debug's DAP server inside the jdtls serving `module` (started on demand).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn java_debug_server(host: &Host, window: &str, module: PathBuf) -> IdeResult<u16> {
|
||||
@@ -671,4 +808,4 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
ide_command::domain!(java: java_build_workspace, java_debug_server, java_resolve_launch);
|
||||
ide_command::domain!(java: java_build_workspace, java_debug_adapter, java_debug_server, java_resolve_launch);
|
||||
@@ -98,6 +98,7 @@ ide_command::domains!(
|
||||
plugins_commit: crate::plugins::commit,
|
||||
plugins_index_ops: crate::plugins::index_ops,
|
||||
plugins_run_targets: crate::plugins::run_targets,
|
||||
plugins_search: crate::plugins::search,
|
||||
plugins_views: crate::plugins::views,
|
||||
project: crate::ops::project,
|
||||
refactor: crate::ops::refactor,
|
||||
|
||||
@@ -51,6 +51,7 @@ pub mod remote;
|
||||
pub mod remote_host;
|
||||
mod run_detectors;
|
||||
pub mod run_targets;
|
||||
pub mod search;
|
||||
mod semantic_tokens;
|
||||
mod snippets;
|
||||
mod theme;
|
||||
|
||||
@@ -76,6 +76,7 @@ pub fn register_builtin_points(
|
||||
registry.register(Arc::new(super::navigation::IndexersPoint))?;
|
||||
registry.register(Arc::new(super::providers::ProvidersPoint::new(providers.clone())))?;
|
||||
registry.register(Arc::new(UiPoint::new(super::providers::SECRETS_POINT, ui.clone(), super::providers::secret)))?;
|
||||
registry.register(Arc::new(UiPoint::new(super::search::POINT, ui.clone(), super::search::declaration)))?;
|
||||
registry.register(Arc::new(UiPoint::new(super::endpoints::POINT, ui.clone(), super::endpoints::declaration)))?;
|
||||
registry.register(Arc::new(UiPoint::new(
|
||||
"runConfigurations",
|
||||
|
||||
@@ -0,0 +1,298 @@
|
||||
//! Cancellable, non-interactive Search Everywhere providers.
|
||||
use super::PluginHost;
|
||||
use ide_command::command;
|
||||
use ide_core::{IdeError, IdeResult, RequestId, ipc_path::to_ipc};
|
||||
use ide_extension::{Capability, Package, UiDecl, decode, validate_item_id};
|
||||
use ide_plugin::{
|
||||
Invocation,
|
||||
search::{SearchPage, SearchTarget},
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
path::Path,
|
||||
sync::Arc,
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
pub(super) const POINT: &str = "searchCategories";
|
||||
pub const MAX_RESULTS: u32 = 200;
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Decl {
|
||||
id: String,
|
||||
title: String,
|
||||
}
|
||||
|
||||
pub(super) fn declaration(pkg: &Package, value: toml::Value) -> Result<UiDecl, String> {
|
||||
let d: Decl = decode(POINT, value)?;
|
||||
pkg.manifest.needs_api("contributes.searchCategories", 13)?;
|
||||
validate_item_id(&d.id, "search category id")?;
|
||||
if pkg.manifest.wasm.is_none()
|
||||
|| d.title.trim().is_empty()
|
||||
|| d.title.len() > 256
|
||||
|| d.title.chars().any(char::is_control)
|
||||
{
|
||||
return Err("search categories need code and a title of 1–256 bytes".into());
|
||||
}
|
||||
Ok(UiDecl::new(d.id.clone(), d.title.clone(), serde_json::to_value(d).map_err(|e| e.to_string())?))
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, specta::Type)]
|
||||
#[serde(tag = "kind", content = "value", rename_all = "camelCase")]
|
||||
pub enum PluginSearchTarget {
|
||||
Location(ide_core::Location),
|
||||
Command { id: String, arg: Option<String> },
|
||||
}
|
||||
#[derive(Clone, Debug, Serialize, specta::Type)]
|
||||
pub struct PluginSearchItem {
|
||||
pub id: String,
|
||||
pub title: String,
|
||||
pub description: Option<String>,
|
||||
pub target: PluginSearchTarget,
|
||||
}
|
||||
#[derive(Clone, Debug, Default, Serialize, specta::Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PluginSearchPage {
|
||||
pub items: Vec<PluginSearchItem>,
|
||||
pub has_more: bool,
|
||||
}
|
||||
|
||||
/// One page of `plugin_id`'s results for its search `category`. Cancellable with
|
||||
/// `cancel_request(request)`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[command(trust = trusted)]
|
||||
pub async fn plugin_search(
|
||||
host: &crate::Host,
|
||||
plugins: &Arc<PluginHost>,
|
||||
window: &str,
|
||||
plugin_id: String,
|
||||
category: String,
|
||||
query: String,
|
||||
limit: u32,
|
||||
request: RequestId,
|
||||
) -> IdeResult<PluginSearchPage> {
|
||||
if query.len() > 1024 || !(1..=MAX_RESULTS).contains(&limit) {
|
||||
return Err(IdeError::invalid("search query exceeds 1024 bytes or limit is outside 1–200"));
|
||||
}
|
||||
let root = host.project(window).ok().map(|p| p.root.clone());
|
||||
let invocation = Invocation { workspace_root: root, client: Some(window.to_owned()), ..Default::default() };
|
||||
let cancel = host.begin_project_request(window, request);
|
||||
let worker_cancel = cancel.clone();
|
||||
let plugins = plugins.clone();
|
||||
// Startup and file reads can outlive a provider call. The request still returns
|
||||
// promptly; the worker checks this token before doing or publishing more work.
|
||||
let result = tokio::select! {
|
||||
_ = cancel.cancelled() => Err(IdeError::cancelled()),
|
||||
result = tokio::time::timeout(Duration::from_secs(2), host.blocking(move || {
|
||||
plugins.search_category(&plugin_id, &category, query, limit, invocation, &worker_cancel)
|
||||
})) => match result {
|
||||
Ok(result) => result,
|
||||
Err(_) => Err(IdeError::new(ide_core::error::ErrorKind::TimedOut, "plugin search timed out")),
|
||||
},
|
||||
};
|
||||
cancel.cancel();
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
impl PluginHost {
|
||||
fn search_category(
|
||||
&self,
|
||||
plugin: &str,
|
||||
category: &str,
|
||||
query: String,
|
||||
limit: u32,
|
||||
invocation: Invocation,
|
||||
cancel: &ide_core::CancellationToken,
|
||||
) -> IdeResult<PluginSearchPage> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let loaded = self.get(plugin)?;
|
||||
let workspace = self.shared.workspace();
|
||||
let eligible = || {
|
||||
loaded.status().is_live()
|
||||
&& loaded.meta.lock().pending.is_empty()
|
||||
&& self.ui.items(POINT, Some(plugin)).iter().any(|d| d.key == category)
|
||||
&& loaded.dev_root.as_deref().is_none_or(|r| invocation.workspace_root.as_deref() == Some(r))
|
||||
&& invocation
|
||||
.workspace_root
|
||||
.as_ref()
|
||||
.is_none_or(|r| workspace.as_ref().is_some_and(|w| w.projects().contains(r) && w.trusted(r)))
|
||||
};
|
||||
if !eligible() {
|
||||
return Err(IdeError::unavailable("search category is no longer available"));
|
||||
}
|
||||
let id = category.to_owned();
|
||||
let page = self.code_call_with_budget(
|
||||
plugin,
|
||||
invocation.clone(),
|
||||
"searching",
|
||||
Some(cancel),
|
||||
Some(Duration::from_secs(2)),
|
||||
move |rt, ctx| rt.search(&id, &query, limit, ctx),
|
||||
)?;
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
if !eligible() || !self.plugins.read().get(plugin).is_some_and(|p| Arc::ptr_eq(p, &loaded)) {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let commands = self.ui.items(super::points::COMMANDS, Some(plugin)).into_iter().map(|d| d.key).collect();
|
||||
let can_read = loaded.meta.lock().granted.contains(&Capability::ProjectRead);
|
||||
let check = || {
|
||||
if cancel.is_cancelled()
|
||||
|| !eligible()
|
||||
|| !self.plugins.read().get(plugin).is_some_and(|p| Arc::ptr_eq(p, &loaded))
|
||||
{
|
||||
Err(IdeError::cancelled())
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
let page = validate(page, limit, &commands, |location| {
|
||||
check()?;
|
||||
if !can_read {
|
||||
return Err(IdeError::invalid("search locations require project.read"));
|
||||
}
|
||||
let root = invocation
|
||||
.workspace_root
|
||||
.as_deref()
|
||||
.ok_or_else(|| IdeError::invalid("search locations need a project"))?;
|
||||
let path =
|
||||
ide_plugin::resolve_in_root(root, &location.path.to_string_lossy()).map_err(IdeError::invalid)?;
|
||||
let w = workspace.as_ref().ok_or_else(|| IdeError::unavailable("project closed"))?;
|
||||
let text = w
|
||||
.buffer_text_in(invocation.client.as_deref(), &path)
|
||||
.map(Ok)
|
||||
.unwrap_or_else(|| ide_plugin::read_text(&path).map_err(IdeError::invalid))?;
|
||||
check()?;
|
||||
Ok((path, text))
|
||||
})?;
|
||||
check()?;
|
||||
Ok(page)
|
||||
}
|
||||
}
|
||||
|
||||
fn validate(
|
||||
page: SearchPage,
|
||||
limit: u32,
|
||||
commands: &BTreeSet<String>,
|
||||
mut document: impl FnMut(&ide_plugin::Location) -> IdeResult<(std::path::PathBuf, String)>,
|
||||
) -> IdeResult<PluginSearchPage> {
|
||||
if page.items.len() > limit as usize {
|
||||
return Err(IdeError::invalid("search provider exceeded its result limit"));
|
||||
}
|
||||
let mut ids = BTreeSet::new();
|
||||
let mut bytes = 0;
|
||||
let mut document_bytes = 0;
|
||||
let mut texts = BTreeMap::new();
|
||||
let mut items = Vec::with_capacity(page.items.len());
|
||||
for item in page.items {
|
||||
bytes += item.id.len() + item.title.len() + item.description.as_ref().map_or(0, String::len);
|
||||
if item.id.is_empty()
|
||||
|| item.id.len() > 256
|
||||
|| !ids.insert(item.id.clone())
|
||||
|| item.title.trim().is_empty()
|
||||
|| item.title.len() > 1024
|
||||
|| item.title.chars().any(char::is_control)
|
||||
|| item.description.as_ref().is_some_and(|s| s.len() > 4096 || s.chars().any(char::is_control))
|
||||
{
|
||||
return Err(IdeError::invalid("invalid or duplicate search result"));
|
||||
}
|
||||
let target = match item.target {
|
||||
SearchTarget::Command { id, arg } => {
|
||||
bytes += id.len() + arg.as_ref().map_or(0, String::len);
|
||||
if !commands.contains(&id) || arg.as_ref().is_some_and(|s| s.len() > 16 << 10) {
|
||||
return Err(IdeError::invalid(
|
||||
"search results may only run their plugin's declared commands, with at most 16 KiB of arguments",
|
||||
));
|
||||
}
|
||||
PluginSearchTarget::Command { id, arg }
|
||||
}
|
||||
SearchTarget::Location(location) => {
|
||||
bytes += location.path.as_os_str().len();
|
||||
if !texts.contains_key(&location.path) {
|
||||
let (path, text) = document(&location)?;
|
||||
document_bytes += text.len();
|
||||
if document_bytes > 16 << 20 {
|
||||
return Err(IdeError::invalid("search documents exceed 16 MiB"));
|
||||
}
|
||||
let lines: Vec<usize> =
|
||||
text.split('\n').map(|s| s.trim_end_matches('\r').encode_utf16().count()).collect();
|
||||
texts.insert(location.path.clone(), (path, lines));
|
||||
}
|
||||
let (path, lines) = &texts[&location.path];
|
||||
let range = location.range;
|
||||
if range.start > range.end
|
||||
|| [range.start, range.end]
|
||||
.iter()
|
||||
.any(|p| lines.get(p.line as usize).is_none_or(|len| p.col as usize > *len))
|
||||
{
|
||||
return Err(IdeError::invalid("search location is outside its UTF-16 document range"));
|
||||
}
|
||||
PluginSearchTarget::Location(ide_core::Location {
|
||||
path: to_ipc(Path::new(path)).into(),
|
||||
range,
|
||||
uri: None,
|
||||
})
|
||||
}
|
||||
};
|
||||
if bytes > 1 << 20 {
|
||||
return Err(IdeError::invalid("search results exceed 1 MiB"));
|
||||
}
|
||||
items.push(PluginSearchItem { id: item.id, title: item.title, description: item.description, target });
|
||||
}
|
||||
Ok(PluginSearchPage { items, has_more: page.has_more && limit < MAX_RESULTS })
|
||||
}
|
||||
|
||||
ide_command::domain!(plugins_search: plugin_search);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ide_plugin::search::SearchItem;
|
||||
fn command(id: &str) -> SearchItem {
|
||||
SearchItem {
|
||||
id: "one".into(),
|
||||
title: "Open route".into(),
|
||||
description: None,
|
||||
target: SearchTarget::Command { id: id.into(), arg: Some("/users/:id".into()) },
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn bounded_results_and_only_own_declared_commands() {
|
||||
let declared = BTreeSet::from(["open".into()]);
|
||||
let check = |items, limit| validate(SearchPage { items, has_more: true }, limit, &declared, |_| unreachable!());
|
||||
assert!(check(vec![command("open")], 1).unwrap().has_more);
|
||||
assert!(!check(vec![command("open")], MAX_RESULTS).unwrap().has_more);
|
||||
assert!(check(vec![command("other.plugin.command")], 1).is_err());
|
||||
assert!(check(vec![command("open"), command("open")], 2).is_err());
|
||||
assert!(check(vec![command("open")], 0).is_err());
|
||||
let mut bad = command("open");
|
||||
bad.title = "bad\nresult".into();
|
||||
assert!(check(vec![bad], 1).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn source_locations_use_utf16_and_validate_whole_page() {
|
||||
let item = |end| SearchItem {
|
||||
id: "source".into(),
|
||||
title: "Handler".into(),
|
||||
description: None,
|
||||
target: SearchTarget::Location(ide_plugin::Location {
|
||||
path: "routes.txt".into(),
|
||||
range: ide_core::Range::new(ide_core::Pos::new(0, 2), ide_core::Pos::new(0, end)),
|
||||
}),
|
||||
};
|
||||
let check = |end| {
|
||||
validate(SearchPage { items: vec![item(end)], has_more: false }, 50, &BTreeSet::new(), |_| {
|
||||
Ok(("/project/routes.txt".into(), "😀x\n".into()))
|
||||
})
|
||||
};
|
||||
assert!(check(3).is_ok());
|
||||
assert!(check(4).is_err());
|
||||
assert!(check(1).is_err());
|
||||
}
|
||||
}
|
||||
@@ -174,6 +174,7 @@ async fn restricted_vcs_commands_run_no_program_of_the_repository() {
|
||||
call!("vcs_status", "", ops::vcs::vcs_status(host, w)),
|
||||
call!("vcs_status_paths", "", ops::vcs::vcs_status_paths(host, w, vec![file.clone()])),
|
||||
sync!("vcs_roots", "", vcs::vcs_roots(host, w)),
|
||||
call!("vcs_detected_roots", "", vcs::vcs_detected_roots(host, w)),
|
||||
call!("vcs_branch_info", "", vcs::vcs_branch_info(host, w, root())),
|
||||
call!("vcs_line_hunks", "", vcs::vcs_line_hunks(host, w, file.clone())),
|
||||
call!("vcs_file_at", "", vcs::vcs_file_at(host, w, file.clone(), None)),
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
//! Java project queries for launches when jdtls does not serve the module: another Java
|
||||
//! language server (java-analyzer) answers the classpath and JDK, if it supports it.
|
||||
|
||||
use crate::LspManager;
|
||||
use crate::jdtls::{JavaClasspath, SERVER as JDTLS};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, LanguageId};
|
||||
use serde_json::{Value, json};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
/// `{ uri, scope: "runtime" | "test" }` → `{ projectRoot, classPaths, modulePaths, jdkHome }`.
|
||||
const CLASSPATH: &str = "java-analyzer/projectClasspath";
|
||||
/// Waiting for the server to start and import the project.
|
||||
const READY_TIMEOUT: Duration = Duration::from_secs(120);
|
||||
const REQUEST_TIMEOUT: Duration = Duration::from_secs(120);
|
||||
|
||||
/// Classpath and JDK of a module, as a Java language server other than jdtls computes them.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct ServerClasspath {
|
||||
pub classpath: JavaClasspath,
|
||||
pub jdk_home: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl LspManager {
|
||||
/// Whether jdtls serves the Java files of `path`. Without it, launches build with the
|
||||
/// build tool and take the classpath from [`Self::java_server_classpath`] or the build model.
|
||||
pub fn java_served_by_jdtls(&self, path: &Path) -> bool {
|
||||
self.servers_for(&LanguageId::new("java"), path).iter().any(|s| s.name == JDTLS)
|
||||
}
|
||||
|
||||
/// The java-analyzer executable among the Java servers of `path`, whatever the server is
|
||||
/// named in settings: its `dap` subcommand debugs modules jdtls doesn't serve.
|
||||
pub fn java_analyzer_binary(&self, path: &Path) -> Option<PathBuf> {
|
||||
self.servers_for(&LanguageId::new("java"), path).into_iter().find_map(|s| {
|
||||
let binary = s.resolved_binary.read().clone().unwrap_or_else(|| s.effective_config().command.into());
|
||||
is_java_analyzer(&binary).then_some(binary)
|
||||
})
|
||||
}
|
||||
|
||||
/// Runtime (`test == false`) or test classpath of the module at `path` from the first
|
||||
/// Java server other than jdtls. `None` when there is none or it doesn't support the query.
|
||||
pub async fn java_server_classpath(
|
||||
&self,
|
||||
path: &Path,
|
||||
test: bool,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Option<ServerClasspath>> {
|
||||
let Some(server) =
|
||||
self.servers_for(&LanguageId::new("java"), path).into_iter().find(|s| s.name != JDTLS && !s.gave_up())
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
self.ensure_started(&server);
|
||||
let Some(run) = crate::jdtls::cancellable_wait(cancel, server.wait_ready(READY_TIMEOUT)).await? else {
|
||||
tracing::debug!(server = server.name, "Java server not ready; no classpath from it");
|
||||
return Ok(None);
|
||||
};
|
||||
let params = json!({
|
||||
"uri": crate::uri::path_to_uri_string(path),
|
||||
"scope": if test { "test" } else { "runtime" },
|
||||
});
|
||||
let request = run.peer.request::<Value, Value>(CLASSPATH, params, Some(cancel.clone()));
|
||||
match tokio::time::timeout(REQUEST_TIMEOUT, request).await {
|
||||
Ok(Ok(v)) => Ok(parse(&v)),
|
||||
Ok(Err(ide_jsonrpc::RpcError::Server { code: ide_jsonrpc::codes::METHOD_NOT_FOUND, .. })) => Ok(None),
|
||||
Ok(Err(e)) if cancel.is_cancelled() => {
|
||||
tracing::debug!("{CLASSPATH}: {e}");
|
||||
Err(IdeError::cancelled())
|
||||
}
|
||||
Ok(Err(e)) => Err(crate::rpc_err(&server.name, CLASSPATH, e)),
|
||||
Err(_) => Err(IdeError::unavailable(format!(
|
||||
"{}: {CLASSPATH} timed out after {} s",
|
||||
server.name,
|
||||
REQUEST_TIMEOUT.as_secs()
|
||||
))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `None` for a `null` answer (the server has no module for the path).
|
||||
fn parse(v: &Value) -> Option<ServerClasspath> {
|
||||
if v.is_null() {
|
||||
return None;
|
||||
}
|
||||
let strings = |key: &str| -> Vec<String> {
|
||||
v.get(key)
|
||||
.and_then(Value::as_array)
|
||||
.map(|a| a.iter().filter_map(Value::as_str).map(str::to_owned).collect())
|
||||
.unwrap_or_default()
|
||||
};
|
||||
let path = |key: &str| v.get(key).and_then(Value::as_str).filter(|s| !s.is_empty()).map(PathBuf::from);
|
||||
Some(ServerClasspath {
|
||||
classpath: JavaClasspath {
|
||||
project_root: path("projectRoot").map(Into::into),
|
||||
class_paths: strings("classPaths"),
|
||||
module_paths: strings("modulePaths"),
|
||||
},
|
||||
jdk_home: path("jdkHome"),
|
||||
})
|
||||
}
|
||||
|
||||
/// `java-analyzer` or `java-analyzer.exe`, wherever it is installed.
|
||||
fn is_java_analyzer(binary: &Path) -> bool {
|
||||
binary.file_stem().is_some_and(|stem| stem == "java-analyzer")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn recognises_java_analyzer_by_its_executable() {
|
||||
assert!(is_java_analyzer(Path::new("/src/java-analyzer/target/release/java-analyzer")));
|
||||
assert!(is_java_analyzer(Path::new("java-analyzer")));
|
||||
assert!(is_java_analyzer(Path::new("/tools/java-analyzer.exe")));
|
||||
assert!(!is_java_analyzer(Path::new("/opt/jdtls/bin/jdtls")));
|
||||
assert!(!is_java_analyzer(Path::new("/opt/java-analyzer/bin/start.sh")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_a_classpath_answer() {
|
||||
let v = json!({
|
||||
"projectRoot": "/p/app",
|
||||
"classPaths": ["/p/app/target/classes", "/m2/a.jar"],
|
||||
"modulePaths": [],
|
||||
"outputDirs": ["/p/app/target/classes"],
|
||||
"jdkHome": "/jdk",
|
||||
"languageLevel": 17,
|
||||
});
|
||||
let cp = parse(&v).unwrap();
|
||||
assert_eq!(cp.classpath.class_paths, ["/p/app/target/classes", "/m2/a.jar"]);
|
||||
assert!(cp.classpath.module_paths.is_empty());
|
||||
assert_eq!(cp.classpath.project_root, Some(PathBuf::from("/p/app").into()));
|
||||
assert_eq!(cp.jdk_home, Some(PathBuf::from("/jdk")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_null_answer_has_no_classpath() {
|
||||
assert_eq!(parse(&Value::Null), None);
|
||||
assert_eq!(parse(&json!({ "classPaths": [], "jdkHome": "" })).unwrap().jdk_home, None);
|
||||
}
|
||||
}
|
||||
@@ -523,7 +523,10 @@ fn missing_bundle(e: &IdeError) -> bool {
|
||||
}
|
||||
|
||||
/// Cancel local waits without interrupting a shared server's startup or import.
|
||||
async fn cancellable_wait<T>(cancel: &CancellationToken, wait: impl std::future::Future<Output = T>) -> IdeResult<T> {
|
||||
pub(crate) async fn cancellable_wait<T>(
|
||||
cancel: &CancellationToken,
|
||||
wait: impl std::future::Future<Output = T>,
|
||||
) -> IdeResult<T> {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = cancel.cancelled() => Err(IdeError::cancelled()),
|
||||
|
||||
@@ -20,6 +20,7 @@ mod go_scope;
|
||||
mod handler;
|
||||
mod injections;
|
||||
mod inspect;
|
||||
pub mod java_project;
|
||||
pub mod jdtls;
|
||||
mod kotlin_lsp;
|
||||
mod launch;
|
||||
|
||||
@@ -12,6 +12,7 @@ mod actor;
|
||||
pub mod indexing;
|
||||
mod runtime;
|
||||
mod sandbox;
|
||||
pub mod search;
|
||||
mod types;
|
||||
mod wit_host;
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ use crate::types::{
|
||||
use crate::wit_host::injections_bindings::exports::openidea::plugin::injections as wit_inj;
|
||||
use crate::wit_host::language_features_bindings::exports::openidea::plugin::language_features as wit_lf;
|
||||
use crate::wit_host::run_target_validation_bindings::exports::openidea::plugin::run_target_validation as wit_rtv;
|
||||
use crate::wit_host::search_bindings::exports::openidea::plugin::search_provider as wit_search;
|
||||
use crate::wit_host::{
|
||||
bindings, commit_checks_bindings, details_bindings, endpoints_bindings, file_actions_bindings, hover_bindings,
|
||||
indexing_bindings, inlay_bindings, providers_bindings, semantic_bindings, syntax_bindings, views_bindings,
|
||||
@@ -56,7 +57,7 @@ use views_bindings::exports::openidea::plugin::view_provider as wit_view;
|
||||
use views_bindings::openidea::plugin::view_types as wit_vt;
|
||||
|
||||
/// The API version of the world above, `major.minor` of [`host_api`].
|
||||
pub const API_VERSION: &str = "1.12";
|
||||
pub const API_VERSION: &str = "1.13";
|
||||
const EPOCH_TICK: Duration = Duration::from_millis(10);
|
||||
pub(crate) const MAX_TEXT: usize = 1 << 20;
|
||||
/// The most text, and the most PNG bytes, `ui.read-clipboard` returns.
|
||||
@@ -1047,6 +1048,7 @@ struct Exports {
|
||||
commit_checks: Option<wit_cc::Guest>,
|
||||
inlay: Option<wit_inlay::Guest>,
|
||||
endpoints: Option<wit_endpoints::Guest>,
|
||||
search: Option<wit_search::Guest>,
|
||||
run_configurations: Option<wit_configs::Guest>,
|
||||
launch_configurations: Option<wit_launch::Guest>,
|
||||
test_results: Option<wit_tests::Guest>,
|
||||
@@ -1187,6 +1189,7 @@ impl Runtime {
|
||||
let commit_check_indices = wit_cc::GuestIndices::new(&pre).ok();
|
||||
let inlay_indices = wit_inlay::GuestIndices::new(&pre).ok();
|
||||
let endpoint_indices = wit_endpoints::GuestIndices::new(&pre).ok();
|
||||
let search_indices = wit_search::GuestIndices::new(&pre).ok();
|
||||
let configs_indices = wit_configs::GuestIndices::new(&pre).ok();
|
||||
let launch_indices = wit_launch::GuestIndices::new(&pre).ok();
|
||||
let tests_indices = wit_tests::GuestIndices::new(&pre).ok();
|
||||
@@ -1251,6 +1254,7 @@ impl Runtime {
|
||||
Some(indices) => Some(indices.load(&mut store, &instance).map_err(api_hint)?),
|
||||
None => None,
|
||||
};
|
||||
let search = search_indices.map(|i| i.load(&mut store, &instance)).transpose().map_err(api_hint)?;
|
||||
let endpoints = match endpoint_indices {
|
||||
Some(indices) => Some(indices.load(&mut store, &instance).map_err(api_hint)?),
|
||||
None => None,
|
||||
@@ -1273,6 +1277,7 @@ impl Runtime {
|
||||
commit_checks,
|
||||
inlay,
|
||||
endpoints,
|
||||
search,
|
||||
run_configurations,
|
||||
launch_configurations,
|
||||
test_results,
|
||||
@@ -1841,6 +1846,55 @@ impl Runtime {
|
||||
}
|
||||
}
|
||||
|
||||
/// An on-demand category query, always non-interactive and bounded.
|
||||
pub fn search(
|
||||
&mut self,
|
||||
category: &str,
|
||||
query: &str,
|
||||
limit: u32,
|
||||
invocation: Invocation,
|
||||
) -> Result<crate::search::SearchPage, CallError> {
|
||||
if self.exports.search.is_none() {
|
||||
return Err(CallError::missing_export("search-provider"));
|
||||
}
|
||||
let result = self.call(invocation, Duration::from_secs(2), |e, store| {
|
||||
let ctx = store.data_mut().new_invocation()?;
|
||||
let r = e.search.as_ref().expect("checked").call_search(
|
||||
&mut *store,
|
||||
category,
|
||||
query,
|
||||
limit,
|
||||
wasmtime::component::Resource::new_borrow(ctx.rep()),
|
||||
);
|
||||
store.data_mut().drop_invocation(ctx);
|
||||
r
|
||||
})?;
|
||||
let page = result.map_err(|e| CallError::Guest(e.into()))?;
|
||||
if page.items.len() > limit as usize {
|
||||
return Err(CallError::Guest(GuestError::Invalid("too many search results".into())));
|
||||
}
|
||||
Ok(crate::search::SearchPage {
|
||||
has_more: page.has_more,
|
||||
items: page
|
||||
.items
|
||||
.into_iter()
|
||||
.map(|i| crate::search::SearchItem {
|
||||
id: i.id,
|
||||
title: i.title,
|
||||
description: i.description,
|
||||
target: match i.target {
|
||||
wit_search::SearchTarget::Location(l) => {
|
||||
crate::search::SearchTarget::Location(location_from_wit(l))
|
||||
}
|
||||
wit_search::SearchTarget::Command(c) => {
|
||||
crate::search::SearchTarget::Command { id: c.id, arg: c.arg }
|
||||
}
|
||||
},
|
||||
})
|
||||
.collect(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Project routes, with an explicit project invocation and background budget.
|
||||
pub fn endpoints(&mut self, invocation: Invocation, timeout: Duration) -> Result<Vec<crate::Endpoint>, CallError> {
|
||||
if self.exports.endpoints.is_none() {
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
//! Results returned by a plugin's optional Search Everywhere provider.
|
||||
use crate::Location;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum SearchTarget {
|
||||
Location(Location),
|
||||
Command { id: String, arg: Option<String> },
|
||||
}
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SearchItem {
|
||||
pub id: String,
|
||||
pub title: String,
|
||||
pub description: Option<String>,
|
||||
pub target: SearchTarget,
|
||||
}
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct SearchPage {
|
||||
pub items: Vec<SearchItem>,
|
||||
pub has_more: bool,
|
||||
}
|
||||
@@ -2192,6 +2192,18 @@ pub(crate) mod endpoints_bindings {
|
||||
});
|
||||
}
|
||||
|
||||
pub(crate) mod search_bindings {
|
||||
wasmtime::component::bindgen!({
|
||||
world: "search", path: "../../wit",
|
||||
with: {
|
||||
"openidea:plugin/types": super::bindings::openidea::plugin::types,
|
||||
"openidea:plugin/workspace": super::bindings::openidea::plugin::workspace,
|
||||
"openidea:plugin/editor": super::bindings::openidea::plugin::editor,
|
||||
"openidea:plugin/invocation": super::bindings::openidea::plugin::invocation,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/// The optional `file-actions` export.
|
||||
pub(crate) mod file_actions_bindings {
|
||||
wasmtime::component::bindgen!({
|
||||
|
||||
@@ -36,6 +36,7 @@ fn components() -> Vec<PathBuf> {
|
||||
repo().join("crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm"),
|
||||
repo().join("crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm"),
|
||||
repo().join("crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm"),
|
||||
repo().join("crates/ide-plugin/tests/fixtures/search/dist/plugin.wasm"),
|
||||
];
|
||||
let official = repo().join("plugins/official");
|
||||
let mut dirs: Vec<_> = std::fs::read_dir(&official).unwrap().map(|e| e.unwrap().path()).collect();
|
||||
@@ -91,7 +92,7 @@ fn the_sdk_carries_the_hosts_wit() {
|
||||
|
||||
#[test]
|
||||
fn the_version_check_runs_compatible_components_and_explains_the_rest() {
|
||||
let host = v("1.12.0");
|
||||
let host = v("1.13.0");
|
||||
for ok in [
|
||||
"1.0.0",
|
||||
"1.3.0",
|
||||
@@ -104,15 +105,16 @@ fn the_version_check_runs_compatible_components_and_explains_the_rest() {
|
||||
"1.10.0",
|
||||
"1.11.0",
|
||||
"1.12.0",
|
||||
"1.13.0",
|
||||
"1.0.0-rc.1",
|
||||
] {
|
||||
assert_eq!(check_api(&v(ok), &host), Ok(()), "{ok}");
|
||||
}
|
||||
let newer = check_api(&v("1.13.0"), &host).unwrap_err();
|
||||
assert!(newer.contains("1.12") && newer.contains("update OpenIDEA"), "{newer}");
|
||||
let newer = check_api(&v("1.14.0"), &host).unwrap_err();
|
||||
assert!(newer.contains("1.13") && newer.contains("update OpenIDEA"), "{newer}");
|
||||
assert!(check_api(&v("2.0.0"), &host).unwrap_err().contains("update OpenIDEA"));
|
||||
let older = check_api(&v("0.2.0"), &host).unwrap_err();
|
||||
assert!(older.contains("rebuild it with the 1.12 SDK"), "{older}");
|
||||
assert!(older.contains("rebuild it with the 1.13 SDK"), "{older}");
|
||||
// 0.x: every minor is its own API.
|
||||
assert_eq!(check_api(&v("0.2.0"), &v("0.2.5")), Ok(()));
|
||||
assert!(check_api(&v("0.1.0"), &v("0.2.0")).is_err());
|
||||
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
36b8ec8be8a65e60d601cd53e9ae0e8ab2865cb69de9b83ca31a9cb277aa0801
|
||||
1e2844d1172750841afd4ba2a8b811522e90522588b1330474207468cbf2a3df
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
631e3140cbd600a3e9af8ee1871e4461fc92fb7e492226507ed2089e5ee6d411
|
||||
c4d00fe3170a0159e56af61fe715ffb892755cce17cdae5ecb1355fd8e90189e
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
ac15b6576fb3536d92d388a9a35775cfa380ad7c8b17fc8375ac403a32cc6b5e
|
||||
ce791decf9a771b43872777a5c97050d9b7b48f5dd0ba0342ad0580bceb93d8c
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
90d0d2643fb70422ac4f8cccd1d74bda4dfe89b4b2e9d28cc5136e4d5b2969f1
|
||||
f8e768db576e717ec00696098faa3434e9cea0680a1770f303bc071206727607
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
a8639ee0478bad01370c9117b02ba791d7283e5728c982f7dc6a66e540b06781
|
||||
2bd0f9e7f3ca03410389d0b125372eb322fae411272b597795cbd77ea894076d
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
a3f38583f118bf8ae4c85994293b77fec599cef6a4e15509f94fb3c1cc4a69e2
|
||||
30dee06cb90e54e7d930996569a3d44e9c9013077c2439880f99e1c99e15cf58
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
b4629333f12d2b227c9da8411f7a11a5fe832ce15e93d7c9a33644b5d022d50f
|
||||
63772fa0f67274c5326a162340aa773c54bd08d0233c726213feedc827bd1a6c
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
d4914c689dacb014dcc9af6952a8620f32ed0d13e43e458de3f23d49311467f2
|
||||
910d62d7f53480961b8c25b5e8d6300bee3fc0e413f35d3b7d78d6e238c65387
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
9547bea771af3ea663455282a1fc4f5d0ed95ea4a3c794b98106dc54744d3717
|
||||
b05e1146eb97d5c787c826206b0d2257d1390f21a87501efa8901de3f5cb6017
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
d1789382c8508b18e243b7812678a2ad98187f289a818a1935bc63e771ba8d26
|
||||
aa14bcafa1009b014ba2ca754711fc3b19149ff05dfefddd10edb94d16551c3d
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
a3980ccb70b911f218d0809985531c133861732d4ed04302896ce79c473f358f
|
||||
3c0d0aa400e83c2f8e77fbec32277a23af290d4469d62d5c0046923ee7ae2c49
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
297774561d9383cf5c364483bca25810cd5271f4e5081b53bd6d6cb06224d200
|
||||
a1a3f1691d6d7e837f893580f75935bf83a6c0ae9224ac832c9401885f9ef504
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
c5005462f40a2a1e384f87c6ca3d2651cc5bd1d75148dd6f16c904c15d622be7
|
||||
97f80158eda60e5b34e4760607cfdf5c8f22debf49e438a4b3fffaf7184ad59e
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
b89751bbab2ab1f1cb27b22c36ede99dfc090d78d03bd0325aaa64b0d08deacf
|
||||
7eff77b3997303adab7b8ef7999b563325e333f0696c63e1a6505579a2a41070
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
e45d268957df9650d2766206638a485bd44878fd5cf31f96733b23ed25e990dc
|
||||
507827131b48fc6c679d8c2558c2e519e03e77ebbdeaaf25d9322f36d721201e
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
b110ed23919ae6c7d35c0cddb690731470280da4a2c97c6723baca0976990e2f
|
||||
ba97c6ec41ee0e2996ddd1d1c9432fad2ea0afb4c237f67c2ffb61cd25b4296c
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
5dc1e01c268c7a755346bb9459600a5e6b605a60b0ce9cd62132dbeb6656dbb1
|
||||
2db9659a4a5fee1cf7179fc5f66ee7ea93f98fa8e844db4213be8cb280998b62
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
7e271a84f33e4f477dbaedc723f9fbe2decdcccf67f4df418a33cfb48cb83688
|
||||
f6ca5c93b202794571b09d0882b6809e28cd54be61765265565e991c49f9b021
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
8b1eb9f66077c8bbccb4ac39bbee1d8474846341260f4b2c4391741292ab268e
|
||||
ef28c6f306a3adfc7d9fc7e6ec057845b2dc159866cd07745e949436de8a2107
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
834b204b6417860ccc9c0dfc4ab8ee5c2fda2a57cb452d34198dbbdebc61d49c
|
||||
abcb633eb89a522e4659cb21770517bb51e889d55c80854d6adc55d0ba33c41b
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
6981a004f521cab1cc8c1c53252d8790ecae15e8c736b2817b78549d34c1d8c9
|
||||
d696eacb402c81a04c42440593363fafe67d11487905a18151976253544415df
|
||||
@@ -5,9 +5,9 @@ wit_bindgen::generate!({
|
||||
inline: "
|
||||
package fixture:misbehave;
|
||||
world misbehave {
|
||||
include openidea:plugin/plugin-syntax@1.12.0;
|
||||
export openidea:plugin/providers@1.12.0;
|
||||
export openidea:plugin/file-actions@1.12.0;
|
||||
include openidea:plugin/plugin-syntax@1.13.0;
|
||||
export openidea:plugin/providers@1.13.0;
|
||||
export openidea:plugin/file-actions@1.13.0;
|
||||
}
|
||||
",
|
||||
path: "../../../../../wit",
|
||||
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
6effad574d5bee69cabd68503b1f870118afbcd3260d3d49472b15b7140bfc40
|
||||
fe55436cf32ce58ba8f8a681617e3e6d7fb94aaac1ce52eb4be620450f68b588
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
04b41e556a8a2984f367cddec6cd7077e6990275313c781fe58a6723b2321c8a
|
||||
e6b23695cff3baf9e6d522b778799c937aff0df9037c62b14b96ad0ad2721225
|
||||
+336
@@ -0,0 +1,336 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "anyhow"
|
||||
version = "1.0.104"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
||||
|
||||
[[package]]
|
||||
name = "equivalent"
|
||||
version = "1.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
|
||||
|
||||
[[package]]
|
||||
name = "foldhash"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.17.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
|
||||
dependencies = [
|
||||
"foldhash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "heck"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
|
||||
|
||||
[[package]]
|
||||
name = "id-arena"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
|
||||
|
||||
[[package]]
|
||||
name = "indexmap"
|
||||
version = "2.14.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
|
||||
dependencies = [
|
||||
"equivalent",
|
||||
"hashbrown",
|
||||
"serde",
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
|
||||
|
||||
[[package]]
|
||||
name = "leb128fmt"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
|
||||
|
||||
[[package]]
|
||||
name = "log"
|
||||
version = "0.4.35"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
|
||||
|
||||
[[package]]
|
||||
name = "macro-string"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6e7b3a5bbb2f63aaa223a671ea1bd0e7bc16bd30ce387324cf63995deaddbbd2"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||
|
||||
[[package]]
|
||||
name = "openidea-plugin"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"wit-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "openidea-test-search"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"openidea-plugin",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "prettyplease"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "semver"
|
||||
version = "1.0.28"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_core"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
|
||||
dependencies = [
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_json"
|
||||
version = "1.0.154"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"memchr",
|
||||
"serde",
|
||||
"serde_core",
|
||||
"zmij",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||
|
||||
[[package]]
|
||||
name = "wasm-encoder"
|
||||
version = "0.262.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4495a6f85dd94c411c749303efcbc5defade0b0cbdbc0541495241ab917a9b5a"
|
||||
dependencies = [
|
||||
"leb128fmt",
|
||||
"wasmparser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-metadata"
|
||||
version = "0.262.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c86ff6668190d9fb70372b306b4f9fe8930f0e2f57ce72e4922bf2f117900949"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"indexmap",
|
||||
"wasm-encoder",
|
||||
"wasmparser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasmparser"
|
||||
version = "0.262.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "974d643b125b272607e2fff8012ea14a8328acd7621e4bafa7afb32500052b1b"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"hashbrown",
|
||||
"indexmap",
|
||||
"semver",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen"
|
||||
version = "0.63.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b85a987ab61d365382d25c7d47e26edd48941b3bf6e3fbf76eff918bc71dab06"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"wit-bindgen-rust-macro",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen-core"
|
||||
version = "0.63.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "775e122e390603abfacd548027016cd0113a6e2bf2f8ce6bdd3658b013456ea8"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"heck",
|
||||
"wit-parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen-rust"
|
||||
version = "0.63.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "84e26e13b9d972026778d2ffb7985736de116026fdc8d9464f966e12df2eb240"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"heck",
|
||||
"indexmap",
|
||||
"prettyplease",
|
||||
"syn",
|
||||
"wasm-metadata",
|
||||
"wit-bindgen-core",
|
||||
"wit-component",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen-rust-macro"
|
||||
version = "0.63.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "16a008a0d6b4840677326beb4edbeb210a2f1b7d0183fb7cc33f466b90fd7fb6"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"macro-string",
|
||||
"prettyplease",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"wit-bindgen-core",
|
||||
"wit-bindgen-rust",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-component"
|
||||
version = "0.262.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "078def49fdb49cab405c3006e05793b3fdaf7069126ba6b9c97d01ec8c98fe4c"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"bitflags",
|
||||
"indexmap",
|
||||
"log",
|
||||
"serde",
|
||||
"serde_derive",
|
||||
"serde_json",
|
||||
"wasm-encoder",
|
||||
"wasm-metadata",
|
||||
"wasmparser",
|
||||
"wit-parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-parser"
|
||||
version = "0.262.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "00f0dc051466ffe46787721fca3d088536f158ae400be044f1b1c386ba9397ad"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"hashbrown",
|
||||
"id-arena",
|
||||
"indexmap",
|
||||
"log",
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_derive",
|
||||
"serde_json",
|
||||
"unicode-ident",
|
||||
"wasmparser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zmij"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
||||
@@ -0,0 +1,23 @@
|
||||
[package]
|
||||
name = "openidea-test-search"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
publish = false
|
||||
|
||||
[workspace]
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[features]
|
||||
search-first = []
|
||||
|
||||
[dependencies]
|
||||
openidea-plugin = { path = "../../../../../sdk/rust/openidea-plugin" }
|
||||
|
||||
[profile.release]
|
||||
opt-level = "s"
|
||||
lto = true
|
||||
strip = true
|
||||
codegen-units = 1
|
||||
panic = "abort"
|
||||
Бінарний файл не відображається.
@@ -0,0 +1 @@
|
||||
c66907db0638d971126a5dd70a9b2e6a18af3d29f2c2fa2d860a726be9b76f75
|
||||
@@ -0,0 +1,18 @@
|
||||
id = "test.search"
|
||||
name = "Search fixture"
|
||||
version = "0.1.0"
|
||||
engines.openidea = "^1.13"
|
||||
wasm = "dist/plugin.wasm"
|
||||
capabilities.required = ["project.read"]
|
||||
|
||||
[[contributes.searchCategories]]
|
||||
id = "routes"
|
||||
title = "Routes"
|
||||
|
||||
[[contributes.searchCategories]]
|
||||
id = "requests"
|
||||
title = "Requests"
|
||||
|
||||
[[contributes.commands]]
|
||||
id = "open"
|
||||
title = "Open request"
|
||||
@@ -0,0 +1,54 @@
|
||||
use openidea_plugin::search::{SearchItem, SearchPage, SearchProvider, SearchTarget};
|
||||
use openidea_plugin::{Error, Invocation, Location, Plugin, Position, Range, register_plugin};
|
||||
|
||||
#[derive(Default)]
|
||||
struct Fixture;
|
||||
impl Plugin for Fixture {
|
||||
fn run_command(&mut self, id: &str, _: &Invocation, arg: Option<&str>) -> Result<Option<String>, Error> {
|
||||
if id == "open" {
|
||||
return Ok(arg.map(str::to_owned));
|
||||
}
|
||||
Err(Error::NotFound(id.into()))
|
||||
}
|
||||
}
|
||||
impl SearchProvider for Fixture {
|
||||
fn search(&mut self, category: &str, query: &str, limit: u32, ctx: &Invocation) -> Result<SearchPage, Error> {
|
||||
if query == "spin" {
|
||||
loop {
|
||||
std::hint::spin_loop();
|
||||
}
|
||||
}
|
||||
if query == "prompt" {
|
||||
openidea_plugin::host::input("Search must not prompt", None)?;
|
||||
}
|
||||
let target = if category == "routes" {
|
||||
let project = ctx.project().ok_or("no project")?;
|
||||
SearchTarget::Location(Location {
|
||||
path: format!("{}/routes.txt", project.root()?),
|
||||
range: Range { start: Position::new(0, 0), end: Position::new(0, 0) },
|
||||
})
|
||||
} else {
|
||||
SearchTarget::Command { id: "open".into(), arg: Some(query.into()) }
|
||||
};
|
||||
Ok(SearchPage {
|
||||
items: (0..limit.min(2))
|
||||
.map(|n| SearchItem {
|
||||
id: n.to_string(),
|
||||
title: format!("{category}: {query}"),
|
||||
description: Some("Search fixture".into()),
|
||||
target: target.clone(),
|
||||
})
|
||||
.collect(),
|
||||
has_more: limit < 2,
|
||||
})
|
||||
}
|
||||
}
|
||||
impl openidea_plugin::endpoints::EndpointsProvider for Fixture {
|
||||
fn endpoints(&mut self, _: &Invocation) -> Result<Vec<openidea_plugin::endpoints::Endpoint>, Error> {
|
||||
Ok(vec![])
|
||||
}
|
||||
}
|
||||
#[cfg(not(feature = "search-first"))]
|
||||
register_plugin!(Fixture, endpoints, search);
|
||||
#[cfg(feature = "search-first")]
|
||||
register_plugin!(Fixture, search, endpoints);
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
bd2e104a54f46eeff56945c43e71369dd0a67c4ed55b0aa8a71e5cac4c20c037
|
||||
a5c854e0ddb90ffddc600c196a78efc4e318b675ef8f7ef9c1059d05bbdc6de6
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
d196a3cec49a5bf4909242903561aa4f74248122fa63bb1de78126c815a4a4b9
|
||||
496e2cb9969f14ef82b2b5982e96c14bf5f586716f15141d5b80b025c4860ef0
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
084a3036772ac0dfe7c18f4d036a67e67462f3acc080dd6a5130595db3c03b3c
|
||||
6b790c68221c7a4071e99ba2794a3f156e90109185814bf6b21cf4f5ef907642
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
39f86e1c941e73a2a5cba9edd45e035459503eb7280e4dfc5c19192c123d5c29
|
||||
e7974d1c1b09578664869857cfa9ab05080540096c5a2b8601adb2ee30649d6f
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
54210827ba484cb857649f08c2cd7d35918d717fd5e82d9516568492e376c0df
|
||||
9563467036c1a365aa6df01cc7fbdb50c4b8b66656bb0d3b5864da58a3b8763d
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
7a56e3d76935a0133b07eff1e3ce95d149fafae372747a6a41ca7c4deff61222
|
||||
17d352320df9d4ccb67f80a4b6a7e8b13c7c1402375e1d1cf86154ce9026c9dd
|
||||
Бінарний файл не відображається.
Loaded 100 of 315 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача