Compare commits

..
Author SHA1 Message Date
l0ng-ai d4ca3d7857 fix(plugins): keep the applied plugin theme over an older plugin list
refreshPlugins' generation guard drops a list answered after a newer refresh, but not
one answered after a themeChanged event. Opening a project refreshes the list while the
plugin theme is being re-applied: the event set One Dark Vivid Islands, then the earlier
list arrived without an active theme and the editor fell back to the built-in dark
theme while the menu still showed the plugin theme checked. Theme events and theme
choices now go through setActivePluginTheme, which stamps them; a list requested before
the latest stamp keeps the current active theme.

Fixes #5793
2026-11-25 15:42:19 +08:00
306 changed files with 1235 additions and 14640 deletions

No files matched your search

+1 -2
View File
@@ -23,7 +23,6 @@ on:
- "Cargo.lock"
- "src/features/run/**"
- "src/features/debugger/**"
- "src/features/build/**"
- "src/features/build-tools/**"
- "src/platform/**"
- "src/workbench/**"
@@ -106,7 +105,7 @@ jobs:
# ide-lsp/dap/run/sdk/tools.
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-http|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/'
# The workflow's paths, less those handled per language below.
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|relatedProviders|core/cm/(cornerInset|iconArea)|lsp/(availability|diagnostics|files|hint|lsp|positions))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|relatedProviders|core/cm/(cornerInset|iconArea)|lsp/(availability|diagnostics|files|hint|lsp|positions))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
langs=""
while read -r f; do
case "$f" in
Generated
-4
View File
@@ -4252,20 +4252,16 @@ name = "ide-core"
version = "0.1.51"
dependencies = [
"base64 0.22.1",
"dirs 6.0.0",
"dunce",
"encoding_rs",
"libc",
"portable-pty",
"serde",
"serde_json",
"sha2 0.10.9",
"specta",
"specta-typescript",
"tempfile",
"thiserror 2.0.21",
"tokio-util",
"tracing",
"windows-sys 0.61.2",
]
+1 -19
View File
@@ -6,24 +6,6 @@
[Simple Icons](https://github.com/simple-icons/simple-icons), retrieved through
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md).
## Agent logos
The `src/ui/openidea/agents/` logos of agents listed in the
[ACP agent registry](https://github.com/agentclientprotocol/registry) (`agoragentic-acp`, `amp-acp`,
`antigravity-acp`, `autohand`, `bob`, `cline`, `codebuddy-code`, `cortex-code`, `corust-agent`,
`crow-cli`, `deepagents`, `devin`, `dimcode`, `dirac`, `factory-droid`, `fast-agent`, `glm-acp-agent`,
`grok-build`, `harn`, `junie`, `kilo`, `kimchi`, `minimax-code`, `minion-code`, `muse-code`, `nova`,
`pi-acp`, `poolside`, `sigit`, `stakpak`, `vtcode`) are the registry's icons, with a root `fill`
moved onto a group. The registry is licensed under Apache-2.0; the logos remain trademarks of
their owners.
## Microsoft ConPTY
`crates/ide-core/resources/conpty/` contains the unmodified Microsoft Windows Console
ConPTY runtime 1.25.260930003, embedded in Windows builds. Copyright (c) Microsoft
Corporation. Licensed under MIT; see its [license](crates/ide-core/resources/conpty/LICENSE)
and [package provenance](crates/ide-core/resources/conpty/README.md).
## Project Lombok
`java/lombok/lombok-1.18.48-openidea.3.jar` contains Project Lombok v1.18.48 with the Equinox
@@ -84,7 +66,7 @@ At render time `src/ui/icons.tsx` may recolour monochrome icons to `currentColor
These icons of [flutter-intellij](https://github.com/flutter/flutter-intellij) (commit `d02813ad5890`) are used
under the BSD 3-Clause License:
- `src/ui/expui/flutter/*.svg`: the Flutter tool window icons, copied unmodified from
- `src/ui/expui/flutter/*.svg`: the DevTools tool window icons, copied unmodified from
`resources/icons/expui/`.
- `src/ui/expui/flutter/[email protected]` and `[email protected]`: the Flutter outline's widget
icons, `resources/icons/custom/[email protected]` and `[email protected]`, renamed, content unmodified.
+5 -16
View File
@@ -2291,25 +2291,14 @@ impl AgentManager {
}
}
/// Stops sending events to UI sinks (project closing).
pub fn detach_sinks(&self) {
self.shared.sinks.write().clear();
}
/// Stops every agent (project closed).
pub fn shutdown(&self) {
self.detach_sinks();
let tasks: Vec<_> = self.tasks.read().values().cloned().collect();
for task in tasks {
let was_live = task.kill().is_some();
if was_live {
// Persist late subagent updates and cleared live background state.
task.persist();
} else {
// Flush pending delayed saves without rewriting untouched or archived tasks.
task.save();
}
for task in self.tasks.read().values() {
task.kill();
// What arrived after the last save (a subagent's late updates).
task.persist();
}
self.shared.sinks.write().clear();
}
}
-41
View File
@@ -1632,47 +1632,6 @@ async fn shutdown_writes_the_saves_still_waiting_and_a_delete_drops_them() {
assert_eq!(saved_title(&kept_path).as_deref(), Some("renamed"));
}
/// Closing a project with many restored/archived tasks must not rewrite tasks that never changed.
#[tokio::test]
async fn shutdown_skips_rewriting_untouched_restored_tasks() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let untouched = idle_task(&mgr, "untouched").await;
let archived = idle_task(&mgr, "archived").await;
mgr.archive(&archived.id).unwrap();
let dirty = idle_task(&mgr, "dirty").await;
mgr.shutdown();
let (untouched_path, archived_path, dirty_path) =
(task_file(tmp.path(), &untouched.id), task_file(tmp.path(), &archived.id), task_file(tmp.path(), &dirty.id));
let restored = manager(tmp.path(), Arc::new(FakeAgent::default()));
let before_untouched = FILE_WRITES.lock().get(&untouched_path).copied().unwrap_or(0);
let before_archived = FILE_WRITES.lock().get(&archived_path).copied().unwrap_or(0);
let before_dirty = FILE_WRITES.lock().get(&dirty_path).copied().unwrap_or(0);
let dirty_handle = restored.task(&dirty.id).unwrap();
dirty_handle.state.lock().task.title = "updated".into();
dirty_handle.persist_soon();
restored.shutdown();
assert_eq!(
FILE_WRITES.lock().get(&untouched_path).copied().unwrap_or(0),
before_untouched,
"untouched task should not be rewritten on shutdown"
);
assert_eq!(
FILE_WRITES.lock().get(&archived_path).copied().unwrap_or(0),
before_archived,
"archived task should not be rewritten on shutdown"
);
assert!(
FILE_WRITES.lock().get(&dirty_path).copied().unwrap_or(0) > before_dirty,
"pending persist_soon task must still be flushed on shutdown"
);
assert_eq!(saved_title(&dirty_path).as_deref(), Some("updated"));
}
/// Archiving saves the task as it is, including changes nobody asked to be saved.
#[tokio::test]
async fn archiving_saves_the_task_before_it_returns() {
+1 -2
View File
@@ -26,10 +26,9 @@ pub fn plan(root: &Path, model: &BuildModel, module: &Path, cache: &Path) -> Ide
let module = dunce::canonicalize(root.join(module))?;
if let Some(p) = model.maven.as_ref().and_then(|m| m.projects.iter().find(|p| root.join(&p.dir) == module)) {
let mut args = p.options.clone();
let repo = crate::maven::local_repository_for(&p.options);
args.extend([
"process-resources".into(),
crate::maven::plugin_goal("help:evaluate", repo.as_deref()),
"help:evaluate".into(),
"-Dexpression=project.build.outputDirectory".into(),
format!("-Doutput={}", manifest.display()),
]);
+2 -7
View File
@@ -6,7 +6,7 @@ use std::io::Read;
use std::time::SystemTime;
/// `(byte length, mtime, blake3 hex)`; the hash is recorded for files inside the project only.
pub(crate) type Stamp = (u64, SystemTime, Option<String>);
type Stamp = (u64, SystemTime, Option<String>);
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct LaunchFingerprint {
@@ -182,7 +182,7 @@ fn collect(
}
/// Scans every input, storing project inputs relative to the project.
pub(crate) fn scan_all(
pub(super) fn scan_all(
root: &Path,
inputs: Vec<PathBuf>,
cancel: &CancellationToken,
@@ -282,11 +282,6 @@ pub(super) fn module_fingerprint(
}
impl LaunchFingerprint {
/// The fingerprint of `parameters` and the files under `inputs` (see [`scan_all`]).
pub(crate) fn new(parameters: String, files: BTreeMap<PathBuf, Option<Stamp>>) -> Self {
LaunchFingerprint { version: 2, parameters, files }
}
/// Folders (relative to the project) of the Maven projects whose POM is an input.
pub(super) fn project_dirs(&self) -> impl Iterator<Item = &Path> {
self.files
+1 -23
View File
@@ -3,7 +3,7 @@
//! background with cancellation and parses the compiler output into messages
//! for the Build tool window, the Problems view and the editor.
pub(crate) mod fingerprint;
mod fingerprint;
mod launch_resources;
mod modules;
mod parse;
@@ -845,28 +845,6 @@ fn reactor_projects<'a>(m: &'a maven::MavenModel, top: &'a maven::MavenProject)
projects
}
/// A step running Maven, its output parsed as Maven's.
pub(crate) fn maven_build_step(program: &str, args: &[&str], cwd: &Path) -> BuildStep {
BuildStep::new(program, args, cwd, Format::Maven)
}
pub(crate) fn gradle_build_step(program: &str, args: &[&str], cwd: &Path) -> BuildStep {
BuildStep::new(program, args, cwd, Format::Gradle)
}
/// The linked reactor root building the project at `module` (project-relative).
pub(crate) fn maven_reactor_dir<'a>(m: &'a maven::MavenModel, module: &str) -> Option<&'a maven::MavenProject> {
maven_reactor(m, module)
}
/// The projects of the reactor `top`.
pub(crate) fn reactor_projects_of<'a>(
m: &'a maven::MavenModel,
top: &'a maven::MavenProject,
) -> Vec<&'a maven::MavenProject> {
reactor_projects(m, top)
}
fn maven_reactor<'a>(m: &'a maven::MavenModel, module: &str) -> Option<&'a maven::MavenProject> {
m.projects.iter().filter(|p| !p.aggregated).find(|top| reactor_projects(m, top).iter().any(|p| p.dir == module))
}
+1 -3
View File
@@ -361,9 +361,7 @@ fn classpaths(
if compile_first {
args.push("compile");
}
let build_classpath =
maven::plugin_goal("dependency:build-classpath", maven::local_repository_for(&top.options).as_deref());
args.extend([build_classpath.as_str(), output_arg.as_str(), scope_arg.as_str(), "-q"]);
args.extend(["dependency:build-classpath", output_arg.as_str(), scope_arg.as_str(), "-q"]);
let top_dir = subdir(root, &top.dir);
let owned_args: Vec<String> = args.into_iter().map(str::to_owned).collect();
let out = process::run_bounded(&top.command, &owned_args, &top_dir, &top.env, cancel, |_, _| {}).map_err(|e| {
-482
View File
@@ -1,482 +0,0 @@
//! What the incremental build needs from a class file (JVMS §4): its name, supertypes, the
//! classes its constant pool refers to, and fingerprints of its API and of its compile-time
//! constants. Bounds-checked: a malformed file is `None`, never a panic.
use std::collections::BTreeSet;
/// A class file, as the dependency graph and the API diff see it.
#[derive(Clone, Debug, PartialEq)]
pub struct ClassFile {
/// Internal name (`com/acme/Order$Line`).
pub name: String,
pub super_name: Option<String>,
pub interfaces: Vec<String>,
/// Classes named in the constant pool: references, descriptors, signatures, annotation types.
pub refs: BTreeSet<String>,
/// What other classes compile against: non-private, non-synthetic members and their
/// signatures, supertypes, nested classes, permitted subclasses, record components.
pub api: u64,
/// The compile-time constants (`static final` fields with a `ConstantValue`), which javac
/// copies into the classes that use them: a change can't be traced through references.
pub constants: u64,
}
const ACC_PRIVATE: u16 = 0x0002;
const ACC_SYNTHETIC: u16 = 0x1000;
struct Bytes<'a> {
data: &'a [u8],
pos: usize,
}
impl<'a> Bytes<'a> {
fn take(&mut self, n: usize) -> Option<&'a [u8]> {
let end = self.pos.checked_add(n)?;
let slice = self.data.get(self.pos..end)?;
self.pos = end;
Some(slice)
}
fn u1(&mut self) -> Option<u8> {
Some(self.take(1)?[0])
}
fn u2(&mut self) -> Option<u16> {
let b = self.take(2)?;
Some(u16::from_be_bytes([b[0], b[1]]))
}
fn u4(&mut self) -> Option<u32> {
let b = self.take(4)?;
Some(u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
}
}
#[derive(Clone, Debug)]
enum Entry {
Empty,
Utf8(String),
Class(u16),
String(u16),
/// Integer, float, long, double: the raw bytes.
Number(Vec<u8>),
NameAndType(u16),
MethodType(u16),
Other,
}
struct Pool(Vec<Entry>);
impl Pool {
fn utf8(&self, index: u16) -> Option<&str> {
match self.0.get(index as usize)? {
Entry::Utf8(s) => Some(s),
_ => None,
}
}
fn class(&self, index: u16) -> Option<&str> {
match self.0.get(index as usize)? {
Entry::Class(name) => self.utf8(*name),
_ => None,
}
}
/// A `ConstantValue`'s value, as bytes.
fn constant(&self, index: u16) -> Option<Vec<u8>> {
match self.0.get(index as usize)? {
Entry::Number(bytes) => Some(bytes.clone()),
Entry::String(utf8) => Some(self.utf8(*utf8)?.as_bytes().to_vec()),
_ => None,
}
}
}
/// FNV-1a: stable across Rust versions, so recorded fingerprints stay comparable.
#[derive(Clone, Copy)]
struct Fnv(u64);
impl Fnv {
fn new() -> Self {
Fnv(0xcbf2_9ce4_8422_2325)
}
fn bytes(&mut self, bytes: &[u8]) {
for b in bytes {
self.0 = (self.0 ^ u64::from(*b)).wrapping_mul(0x100_0000_01b3);
}
// A separator, so `ab`+`c` and `a`+`bc` differ.
self.0 = (self.0 ^ 0xff).wrapping_mul(0x100_0000_01b3);
}
fn str(&mut self, s: &str) {
self.bytes(s.as_bytes());
}
fn u16(&mut self, v: u16) {
self.bytes(&v.to_be_bytes());
}
}
/// Adds the class names a descriptor or signature mentions (`Lcom/acme/Order<Lx/Y;>;`).
fn descriptor_refs(text: &str, out: &mut BTreeSet<String>) {
let bytes = text.as_bytes();
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'L'
&& (i == 0
|| matches!(
bytes[i - 1],
b'(' | b')'
| b'['
| b';'
| b'<'
| b'>'
| b'+'
| b'-'
| b':'
| b'*'
| b'I'
| b'J'
| b'Z'
| b'B'
| b'C'
| b'S'
| b'F'
| b'D'
| b'V'
| b'^'
))
{
let start = i + 1;
let mut end = start;
while end < bytes.len() && !matches!(bytes[end], b';' | b'<' | b'.') {
end += 1;
}
if end < bytes.len() && end > start {
let name = &text[start..end];
if name.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'/' | b'$' | b'_') || b >= 0x80) {
out.insert(name.to_owned());
}
}
i = end;
} else {
i += 1;
}
}
}
fn class_ref(name: &str, out: &mut BTreeSet<String>) {
if name.starts_with('[') {
descriptor_refs(name, out);
} else {
out.insert(name.to_owned());
}
}
struct Member {
access: u16,
name: String,
descriptor: String,
/// Fingerprint of the attributes that are part of the API.
extra: u64,
constant: Option<Vec<u8>>,
}
fn attributes(r: &mut Bytes, pool: &Pool, mut on: impl FnMut(&str, &[u8])) -> Option<()> {
let count = r.u2()?;
for _ in 0..count {
let name = pool.utf8(r.u2()?)?.to_owned();
let len = r.u4()? as usize;
let body = r.take(len)?;
on(&name, body);
}
Some(())
}
fn members(r: &mut Bytes, pool: &Pool, refs: &mut BTreeSet<String>) -> Option<Vec<Member>> {
let count = r.u2()?;
let mut out = Vec::with_capacity(count as usize);
for _ in 0..count {
let access = r.u2()?;
let name = pool.utf8(r.u2()?)?.to_owned();
let descriptor = pool.utf8(r.u2()?)?.to_owned();
descriptor_refs(&descriptor, refs);
let mut extra = Fnv::new();
let mut constant = None;
attributes(r, pool, |attr, body| {
let mut b = Bytes { data: body, pos: 0 };
match attr {
"Signature" => {
if let Some(sig) = b.u2().and_then(|i| pool.utf8(i)) {
descriptor_refs(sig, refs);
extra.str("S");
extra.str(sig);
}
}
"ConstantValue" => constant = b.u2().and_then(|i| pool.constant(i)),
"Exceptions" => {
let mut names: Vec<&str> = Vec::new();
if let Some(n) = b.u2() {
for _ in 0..n {
if let Some(c) = b.u2().and_then(|i| pool.class(i)) {
names.push(c);
}
}
}
names.sort_unstable();
extra.str("E");
for n in names {
extra.str(n);
}
}
// An annotation element's default value is compiled into its uses.
"AnnotationDefault" => {
extra.str("D");
element_value(&mut b, pool, refs, &mut extra);
}
_ => {}
}
})?;
out.push(Member { access, name, descriptor, extra: extra.0, constant });
}
Some(out)
}
/// Parses a class file; `None` when it isn't a well-formed one.
pub fn parse(data: &[u8]) -> Option<ClassFile> {
let mut r = Bytes { data, pos: 0 };
if r.u4()? != 0xCAFE_BABE {
return None;
}
r.u2()?;
r.u2()?;
let count = r.u2()?;
let mut entries = vec![Entry::Empty];
let mut i = 1;
while i < count {
let tag = r.u1()?;
let entry = match tag {
1 => {
let len = r.u2()? as usize;
Entry::Utf8(String::from_utf8_lossy(r.take(len)?).into_owned())
}
3 | 4 => Entry::Number(r.take(4)?.to_vec()),
5 | 6 => Entry::Number(r.take(8)?.to_vec()),
7 => Entry::Class(r.u2()?),
8 => Entry::String(r.u2()?),
9..=11 => {
r.take(4)?;
Entry::Other
}
12 => {
r.u2()?;
Entry::NameAndType(r.u2()?)
}
15 => {
r.take(3)?;
Entry::Other
}
16 => Entry::MethodType(r.u2()?),
17 | 18 => {
r.take(4)?;
Entry::Other
}
19 | 20 => {
r.take(2)?;
Entry::Other
}
_ => return None,
};
let wide = matches!(tag, 5 | 6);
entries.push(entry);
i += 1;
if wide {
entries.push(Entry::Empty);
i += 1;
}
}
let pool = Pool(entries);
let mut refs = BTreeSet::new();
for entry in &pool.0 {
match entry {
Entry::Class(name) => class_ref(pool.utf8(*name)?, &mut refs),
Entry::NameAndType(descriptor) | Entry::MethodType(descriptor) => {
descriptor_refs(pool.utf8(*descriptor)?, &mut refs)
}
_ => {}
}
}
let access = r.u2()?;
let name = pool.class(r.u2()?)?.to_owned();
let super_index = r.u2()?;
let super_name = if super_index == 0 { None } else { Some(pool.class(super_index)?.to_owned()) };
let mut interfaces = Vec::new();
for _ in 0..r.u2()? {
interfaces.push(pool.class(r.u2()?)?.to_owned());
}
let fields = members(&mut r, &pool, &mut refs)?;
let methods = members(&mut r, &pool, &mut refs)?;
let mut api = Fnv::new();
// ACC_SUPER and ACC_SYNTHETIC say nothing about what compiles against the class.
api.u16(access & !(0x0020 | ACC_SYNTHETIC));
api.str(&name);
api.str(super_name.as_deref().unwrap_or(""));
let mut sorted = interfaces.clone();
sorted.sort();
for i in &sorted {
api.str(i);
}
let mut class_attrs: Vec<(String, u64)> = Vec::new();
attributes(&mut r, &pool, |attr, body| {
let mut b = Bytes { data: body, pos: 0 };
let mut h = Fnv::new();
match attr {
"Signature" => {
if let Some(sig) = b.u2().and_then(|i| pool.utf8(i)) {
descriptor_refs(sig, &mut refs);
h.str(sig);
}
}
"PermittedSubclasses" => {
let mut names = Vec::new();
for _ in 0..b.u2().unwrap_or(0) {
if let Some(c) = b.u2().and_then(|i| pool.class(i)) {
names.push(c.to_owned());
}
}
names.sort();
names.iter().for_each(|n| h.str(n));
}
"Record" => {
for _ in 0..b.u2().unwrap_or(0) {
let (Some(n), Some(d)) = (b.u2().and_then(|i| pool.utf8(i)), b.u2().and_then(|i| pool.utf8(i)))
else {
break;
};
h.str(n);
h.str(d);
let mut component = |attr: &str, body: &[u8]| {
if attr == "Signature"
&& let Some(sig) = (Bytes { data: body, pos: 0 }).u2().and_then(|i| pool.utf8(i))
{
h.str(sig);
}
};
if attributes(&mut b, &pool, &mut component).is_none() {
break;
}
}
}
// Nested classes this class declares, and their access.
"InnerClasses" => {
let mut nested = Vec::new();
for _ in 0..b.u2().unwrap_or(0) {
let (Some(inner), Some(outer), Some(_), Some(flags)) = (b.u2(), b.u2(), b.u2(), b.u2()) else {
break;
};
let inner = pool.class(inner).unwrap_or("");
if outer != 0 && pool.class(outer) == Some(name.as_str()) && flags & ACC_PRIVATE == 0 {
nested.push(format!("{inner}:{flags}"));
}
}
nested.sort();
nested.iter().for_each(|n| h.str(n));
}
"RuntimeVisibleAnnotations" | "RuntimeInvisibleAnnotations" => {
// Annotation types are dependencies; their values aren't API.
annotation_types(body, &pool, &mut refs);
return;
}
_ => return,
}
class_attrs.push((attr.to_owned(), h.0));
})?;
class_attrs.sort();
for (attr, h) in &class_attrs {
api.str(attr);
api.bytes(&h.to_be_bytes());
}
let mut constants = Fnv::new();
let mut api_members: Vec<(u8, &str, &str, u16, u64)> = Vec::new();
for (kind, list) in [(0u8, &fields), (1u8, &methods)] {
for m in list.iter() {
if kind == 0
&& let Some(value) = &m.constant
{
// Private constants are inlined too, but only in their own class.
if m.access & ACC_PRIVATE == 0 {
constants.str(&m.name);
constants.str(&m.descriptor);
constants.bytes(value);
}
}
if m.access & (ACC_PRIVATE | ACC_SYNTHETIC) != 0 || m.name == "<clinit>" {
continue;
}
api_members.push((kind, &m.name, &m.descriptor, m.access & !ACC_SYNTHETIC, m.extra));
}
}
api_members.sort();
for (kind, name, descriptor, access, extra) in api_members {
api.bytes(&[kind]);
api.str(name);
api.str(descriptor);
api.u16(access);
api.bytes(&extra.to_be_bytes());
}
refs.remove(&name);
refs.retain(|r| !r.starts_with("java/"));
Some(ClassFile { name, super_name, interfaces, refs, api: api.0, constants: constants.0 })
}
/// Adds the types of the annotations in a `Runtime*Annotations` attribute.
fn annotation_types(body: &[u8], pool: &Pool, refs: &mut BTreeSet<String>) {
let mut b = Bytes { data: body, pos: 0 };
let Some(count) = b.u2() else { return };
let mut ignored = Fnv::new();
for _ in 0..count {
if annotation(&mut b, pool, refs, &mut ignored).is_none() {
return;
}
}
}
fn annotation(b: &mut Bytes, pool: &Pool, refs: &mut BTreeSet<String>, h: &mut Fnv) -> Option<()> {
let ty = pool.utf8(b.u2()?)?;
descriptor_refs(ty, refs);
h.str(ty);
for _ in 0..b.u2()? {
h.str(pool.utf8(b.u2()?)?);
element_value(b, pool, refs, h)?;
}
Some(())
}
/// An annotation element value: its class names go to `refs`, its value (resolved, not the
/// constant pool indices) to `h`.
fn element_value(b: &mut Bytes, pool: &Pool, refs: &mut BTreeSet<String>, h: &mut Fnv) -> Option<()> {
let tag = b.u1()?;
h.bytes(&[tag]);
match tag {
b'B' | b'C' | b'D' | b'F' | b'I' | b'J' | b'S' | b'Z' => h.bytes(&pool.constant(b.u2()?)?),
b's' => h.str(pool.utf8(b.u2()?)?),
b'e' => {
let ty = pool.utf8(b.u2()?)?;
descriptor_refs(ty, refs);
h.str(ty);
h.str(pool.utf8(b.u2()?)?);
}
b'c' => {
let ty = pool.utf8(b.u2()?)?;
descriptor_refs(ty, refs);
h.str(ty);
}
b'@' => annotation(b, pool, refs, h)?,
b'[' => {
for _ in 0..b.u2()? {
element_value(b, pool, refs, h)?;
}
}
_ => return None,
}
Some(())
}
/// The simple name of a class (`com/acme/Order$Line` → `Line`), which a new class can shadow.
pub fn simple_name(name: &str) -> &str {
let tail = name.rsplit('/').next().unwrap_or(name);
tail.rsplit('$').next().unwrap_or(tail)
}
@@ -1,145 +0,0 @@
// OpenIDEA's Java build of a Gradle build (ide_build::jbuild). With -Popenidea.build.output=<dir>,
// every Java source set writes its classes and resources to <dir>/[<group>.]<project>/classes|test-classes,
// so neither the language server nor a terminal `gradle` writes what the IDE runs. The task
// `openideaBuildModel` (-Popenidea.build.model=<file>) runs what generates sources, processes the
// resources and writes, as JSON, each source set's roots, classpaths and how JavaCompile compiles it:
// the same model the Maven extension writes (java/java-build, BuildModel).
import groovy.json.JsonOutput
import org.gradle.api.tasks.compile.AbstractCompile
import org.gradle.api.tasks.compile.JavaCompile
import org.gradle.jvm.tasks.Jar
def property = { String name -> gradle.startParameter.projectProperties[name] }
def outRoot = property('openidea.build.output')
if (outRoot == null || gradle.parent != null) return
// The project's name in the build: unique, unlike `name`.
def nameOf = { Project p -> p == p.rootProject ? p.name : p.path.substring(1).replace(':', '.') }
def outputOf = { Project p, String set ->
def folder = p.group ? "${p.group}.${nameOf(p)}" : nameOf(p)
new File(outRoot, folder + '/' + (set == 'main' ? 'classes' : 'test-classes'))
}
def javaSets = { Project p ->
def sets = p.extensions.findByName('sourceSets')
sets == null ? [] : ['main', 'test'].collect { sets.findByName(it) }.findAll { it != null }
}
gradle.projectsEvaluated {
def root = gradle.rootProject
root.allprojects.each { p ->
javaSets(p).each { ss ->
def out = outputOf(p, ss.name)
ss.java.destinationDirectory.set(out)
ss.output.resourcesDir = out
p.tasks.named(ss.processResourcesTaskName).configure { destinationDir = out }
}
}
root.tasks.register('openideaBuildModel') {
// What compiling needs from the same project (generated sources), and the resources.
dependsOn {
root.allprojects.collectMany { p ->
javaSets(p).collectMany { ss ->
def compile = p.tasks.getByName(ss.compileJavaTaskName)
def generators = compile.taskDependencies.getDependencies(compile).findAll {
it.project == p && !(it instanceof AbstractCompile) && !(it instanceof Jar)
}
generators + [p.tasks.getByName(ss.processResourcesTaskName)]
}
}
}
doLast {
// Project artifacts resolve to the projects' outputs.
def artifacts = [:]
root.allprojects.each { p ->
def main = javaSets(p).find { it.name == 'main' }
if (main == null) return
def jar = p.tasks.findByName('jar')
if (jar instanceof Jar) artifacts[jar.archiveFile.get().asFile.canonicalPath] = outputOf(p, 'main')
}
def files = { collection ->
def out = []
try {
collection?.files?.each { f ->
def mapped = artifacts[f.canonicalPath] ?: f
if (!out.contains(mapped.canonicalPath)) out << mapped.canonicalPath
}
} catch (e) {
out << "!${e.message}".toString()
}
out
}
def included = gradle.includedBuilds.collect { it.name }
def projects = root.allprojects.findAll { !javaSets(it).isEmpty() }.collect { p ->
def problems = included.isEmpty() ? [] : ["it is a composite build (${included.join(', ')})".toString()]
def others = p.tasks.withType(AbstractCompile).findAll {
!(it instanceof JavaCompile) && it.name ==~ /(?i)compile.*(Kotlin|Groovy|Scala|Aspectj).*/
}.collect { "${it.class.name.replace('_Decorated', '')}@${it.name}".toString() }
def setModel = { String name ->
def ss = javaSets(p).find { it.name == name }
if (ss == null) return [sourceRoots: [], output: outputOf(p, name).path, classpath: [], runtimeClasspath: []]
JavaCompile compile = p.tasks.getByName(ss.compileJavaTaskName)
def o = compile.options
def classpath = files(compile.classpath)
def runtime = files(ss.runtimeClasspath)
(classpath + runtime).findAll { it.startsWith('!') }.each { problems << "Cannot resolve the dependencies: ${it.substring(1)}".toString() }
def processorPath = files(o.annotationProcessorPath)
def processorProblems = processorPath.findAll { it.startsWith('!') }
def projectProcessors = processorPath.findAll { path -> artifacts.values().any { it.canonicalPath == path } }
def home = null
try { home = compile.javaCompiler.orNull?.metadata?.installationPath?.asFile?.canonicalPath } catch (ignored) {}
[
sourceRoots: ss.java.srcDirs.collect { it.canonicalPath },
output: outputOf(p, name).canonicalPath,
classpath: classpath.findAll { !it.startsWith('!') },
runtimeClasspath: runtime.findAll { !it.startsWith('!') },
resources: ss.resources.srcDirs.collect { [directory: it.canonicalPath, filtering: false] },
compiler: [
compilerId: 'javac',
source: compile.sourceCompatibility,
target: compile.targetCompatibility,
release: o.release.orNull?.toString(),
encoding: o.encoding,
debug: o.debug,
debuglevel: o.debugOptions.debugLevel,
showWarnings: o.warnings,
showDeprecation: o.deprecation,
fork: home != null,
executable: home == null ? null : new File(home, 'bin/javac').path,
generatedSourcesDirectory: o.generatedSourceOutputDirectory.asFile.orNull?.canonicalPath,
includes: ss.java.includes as List,
excludes: ss.java.excludes as List,
compilerArgs: o.allCompilerArgs.collect { it.toString() },
processorPath: processorProblems.isEmpty() && projectProcessors.isEmpty() ? processorPath : null,
processorPathError: !processorProblems.isEmpty()
? processorProblems[0].substring(1)
: (projectProcessors.isEmpty() ? null : 'its annotation processors are built in the same build'),
],
]
}
def mainModel = setModel('main')
def testModel = setModel('test')
// Gradle compiles tests against the main classes: they're the main output here.
[
dir: p.projectDir.canonicalPath,
groupId: (p.group ?: '').toString(),
artifactId: nameOf(p),
version: p.version.toString(),
packaging: 'jar',
main: mainModel,
test: testModel,
otherCompilers: others,
testGenerators: [],
problems: problems,
gradlePath: p.path,
]
}
def modelFile = property('openidea.build.model')
if (modelFile != null) {
def file = new File(modelFile)
def temporary = new File(file.parentFile, file.name + '.tmp')
temporary.text = JsonOutput.toJson([version: 1, projects: projects])
temporary.renameTo(file) || { file.delete(); temporary.renameTo(file) }()
}
}
}
}
-216
View File
@@ -1,216 +0,0 @@
//! Class-level incremental compilation (#4078 step 3). Each source set records, per class it
//! compiled, the source it came from, its supertypes, the classes its constant pool names and
//! fingerprints of its API and constants ([`super::classfile`]). A build compiles the changed
//! sources, then the sources of classes that refer to a class whose API changed (or to a
//! subclass of one), round after round until no API changes. Sets compiled against this one
//! read its log of API changes; a changed compile-time constant, which javac copies into the
//! classes that use it, recompiles the whole set and every set compiled against it.
use super::*;
use std::collections::BTreeSet;
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
pub(super) struct ClassRecord {
/// The source javac compiled it from; `None` for classes an annotation processor wrote
/// without naming an originating source.
pub source: Option<PathBuf>,
pub file: PathBuf,
pub super_name: Option<String>,
#[serde(default)]
pub interfaces: Vec<String>,
#[serde(default)]
pub refs: Vec<String>,
pub api: u64,
pub constants: u64,
}
impl ClassRecord {
pub fn new(class: classfile::ClassFile, file: PathBuf, source: Option<PathBuf>) -> (String, Self) {
let record = ClassRecord {
source,
file,
super_name: class.super_name,
interfaces: class.interfaces,
refs: class.refs.into_iter().collect(),
api: class.api,
constants: class.constants,
};
(class.name, record)
}
fn has_constants(&self) -> bool {
self.constants != NO_CONSTANTS
}
}
/// The constant fingerprint of a class without compile-time constants.
pub(super) const NO_CONSTANTS: u64 = 0xcbf2_9ce4_8422_2325;
/// The classes whose API one compilation of a set changed.
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
pub(super) struct ApiChange {
/// The set's generation before and after the compilation.
pub since: u64,
pub generation: u64,
pub classes: Vec<String>,
/// Everything counts as changed: a constant changed, or there was nothing to compare with.
pub all: bool,
}
/// How many compilations' API changes a set keeps for the sets compiled against it; one that
/// fell further behind compiles from scratch.
const CHANGE_LOG: usize = 64;
/// The inputs of a source set that, when changed, compile it from scratch.
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
pub(super) struct SetStamp {
pub options: Vec<String>,
/// Classpath entries outside the reactor's outputs, with their stamps (folders have none).
pub libraries: Vec<(PathBuf, Option<FileStamp>)>,
/// The reactor outputs on the classpath, in order.
pub reactor: Vec<PathBuf>,
pub processor_path: Vec<(PathBuf, Option<FileStamp>)>,
pub java_home: PathBuf,
}
#[derive(Debug, Default, Deserialize, Serialize)]
pub(super) struct SetState {
pub stamp: SetStamp,
/// The sources as of the last compilation.
pub sources: BTreeMap<PathBuf, FileStamp>,
/// Changes whenever the set's classes do.
pub generation: u64,
/// The generation of each reactor output it was compiled against.
pub upstream: BTreeMap<PathBuf, u64>,
pub classes: BTreeMap<String, ClassRecord>,
/// Sources a failed compilation left uncompiled.
pub dirty: BTreeSet<PathBuf>,
pub changes: Vec<ApiChange>,
/// Sources annotation processors wrote, and other files they wrote without an originating
/// source (`META-INF/services`…): processors that aggregate. While there are any, a change
/// compiles the set from scratch.
pub generated: Vec<PathBuf>,
pub unowned: Vec<PathBuf>,
pub success: bool,
}
impl SetState {
/// The classes whose API changed since generation `since`; `None` when unknown (the log
/// doesn't reach back that far) or when everything counts as changed.
pub fn changes_since(&self, since: u64) -> Option<BTreeSet<String>> {
let mut changed = BTreeSet::new();
let mut at = since;
while at != self.generation {
let change = self.changes.iter().find(|c| c.since == at)?;
if change.all {
return None;
}
changed.extend(change.classes.iter().cloned());
at = change.generation;
}
Some(changed)
}
pub fn log(&mut self, generation: u64, classes: BTreeSet<String>, all: bool) {
self.changes.push(ApiChange {
since: self.generation,
generation,
classes: classes.into_iter().collect(),
all,
});
if self.changes.len() > CHANGE_LOG {
self.changes.drain(..self.changes.len() - CHANGE_LOG);
}
self.generation = generation;
}
}
pub(super) fn load_state(path: &Path) -> Option<SetState> {
serde_json::from_slice(&std::fs::read(path).ok()?).ok()
}
/// `seeds` and the classes of `classes` that extend or implement one of them, transitively:
/// a class that inherits a changed member changes for the classes that use it.
pub(super) fn with_subclasses(classes: &BTreeMap<String, ClassRecord>, seeds: &BTreeSet<String>) -> BTreeSet<String> {
let mut out = seeds.clone();
loop {
let before = out.len();
for (name, record) in classes {
if !out.contains(name)
&& (record.super_name.as_ref().is_some_and(|s| out.contains(s))
|| record.interfaces.iter().any(|i| out.contains(i)))
{
out.insert(name.clone());
}
}
if out.len() == before {
return out;
}
}
}
/// The sources of the classes that refer to one of `affected`.
pub(super) fn dependent_sources(
classes: &BTreeMap<String, ClassRecord>,
affected: &BTreeSet<String>,
) -> BTreeSet<PathBuf> {
if affected.is_empty() {
return BTreeSet::new();
}
classes
.iter()
.filter(|(name, r)| affected.contains(*name) || r.refs.iter().any(|x| affected.contains(x)))
.filter_map(|(_, r)| r.source.clone())
.collect()
}
/// The sources of the classes that refer to a class with the same simple name as one of
/// `added`: a new class can take a simple name over from an on-demand import.
pub(super) fn shadowed_sources(classes: &BTreeMap<String, ClassRecord>, added: &BTreeSet<String>) -> BTreeSet<PathBuf> {
let names: BTreeSet<&str> = added.iter().map(|n| classfile::simple_name(n)).collect();
if names.is_empty() {
return BTreeSet::new();
}
classes
.iter()
.filter(|(name, r)| {
!added.contains(*name)
&& r.refs.iter().any(|x| !added.contains(x) && names.contains(classfile::simple_name(x)))
})
.filter_map(|(_, r)| r.source.clone())
.collect()
}
/// What one round's classes changed, compared with the classes the round replaced.
#[derive(Debug, Default)]
pub(super) struct RoundDiff {
pub api: BTreeSet<String>,
pub added: BTreeSet<String>,
pub constants: bool,
}
pub(super) fn diff(old: &BTreeMap<String, ClassRecord>, new: &BTreeMap<String, ClassRecord>) -> RoundDiff {
let mut out = RoundDiff::default();
for (name, record) in new {
match old.get(name) {
Some(before) => {
if before.api != record.api {
out.api.insert(name.clone());
}
if before.constants != record.constants {
out.constants = true;
}
}
None => {
out.api.insert(name.clone());
out.added.insert(name.clone());
}
}
}
for (name, before) in old {
if !new.contains_key(name) {
out.api.insert(name.clone());
out.constants |= before.has_constants();
}
}
out
}
-263
View File
@@ -1,263 +0,0 @@
//! Resident javac processes (`java/java-build`, `ai.openidea.javac.Server`): one JVM per JDK
//! and JVM options, kept warm between builds, compiling one request at a time in process.
use super::*;
use std::io::{BufRead, BufReader, Write};
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::mpsc;
use std::sync::{Arc, Mutex};
use std::time::Duration;
/// A message of the server about one request.
#[derive(Clone, Debug, Deserialize, PartialEq)]
#[serde(tag = "kind", rename_all = "kebab-case", rename_all_fields = "camelCase")]
pub enum Reply {
Diagnostic {
severity: String,
path: Option<PathBuf>,
/// 1-based.
line: Option<u32>,
/// 0-based UTF-16.
column: Option<u32>,
end_line: Option<u32>,
end_column: Option<u32>,
code: Option<String>,
message: String,
},
/// A class (or resource) file javac wrote, and the source it came from.
Output {
path: PathBuf,
source: Option<PathBuf>,
},
/// A source file an annotation processor wrote.
Generated {
path: PathBuf,
source: Option<PathBuf>,
},
OutputText {
text: String,
},
Done {
success: bool,
cancelled: bool,
},
}
#[derive(Debug, Serialize)]
struct Request<'a> {
id: u64,
op: &'static str,
options: &'a [String],
sources: &'a [PathBuf],
encoding: Option<&'a str>,
}
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct ServerKey {
pub java_home: PathBuf,
/// Options of the compiler's JVM (`.mvn/jvm.config`: `--add-opens` for processors).
pub jvm_args: Vec<String>,
}
type Pending = Arc<Mutex<HashMap<u64, mpsc::Sender<Reply>>>>;
pub struct JavacServer {
child: Mutex<Child>,
stdin: Mutex<ChildStdin>,
pending: Pending,
alive: Arc<AtomicBool>,
next: AtomicU64,
pub version: String,
}
impl JavacServer {
fn start(jar: &Path, key: &ServerKey) -> IdeResult<Self> {
let java = key.java_home.join("bin").join(if cfg!(windows) { "java.exe" } else { "java" });
let mut cmd = Command::new(&java);
cmd.args(&key.jvm_args)
.args(["-XX:+UseSerialGC", "-XX:TieredStopAtLevel=1", "-Dfile.encoding=UTF-8", "-cp"])
.arg(jar)
.arg("ai.openidea.javac.Server")
.env("JAVA_HOME", &key.java_home)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null());
ide_core::process::prepare(&mut cmd);
ide_core::process::own_group(&mut cmd);
let mut child =
cmd.spawn().map_err(|e| IdeError::unavailable(format!("Cannot start javac ({}): {e}", java.display())))?;
let stdin = child.stdin.take().expect("piped");
let stdout = child.stdout.take().expect("piped");
let pending: Pending = Arc::default();
let alive = Arc::new(AtomicBool::new(true));
let (ready_tx, ready_rx) = mpsc::channel::<Result<String, String>>();
{
let (pending, alive) = (pending.clone(), alive.clone());
std::thread::Builder::new()
.name("javac-server".into())
.spawn(move || {
let mut ready = Some(ready_tx);
for line in BufReader::new(stdout).lines() {
let Ok(line) = line else { break };
let Ok(value) = serde_json::from_str::<serde_json::Value>(&line) else { continue };
match value.get("kind").and_then(|k| k.as_str()) {
Some("ready") => {
let version = value.get("version").and_then(|v| v.as_str()).unwrap_or("").to_owned();
if let Some(ready) = ready.take() {
let _ = ready.send(Ok(version));
}
continue;
}
Some("fatal") => {
let message = value.get("message").and_then(|v| v.as_str()).unwrap_or("").to_owned();
if let Some(ready) = ready.take() {
let _ = ready.send(Err(message));
}
continue;
}
_ => {}
}
let Some(id) = value.get("id").and_then(|v| v.as_u64()) else { continue };
let Ok(reply) = serde_json::from_value::<Reply>(value) else { continue };
let done = matches!(reply, Reply::Done { .. });
let mut pending = pending.lock().unwrap();
if let Some(tx) = pending.get(&id) {
let _ = tx.send(reply);
}
if done {
pending.remove(&id);
}
}
alive.store(false, Ordering::SeqCst);
// Requests still waiting learn that the server is gone.
for (_, tx) in pending.lock().unwrap().drain() {
let _ = tx.send(Reply::Diagnostic {
severity: "error".into(),
path: None,
line: None,
column: None,
end_line: None,
end_column: None,
code: None,
message: "The javac process exited".into(),
});
let _ = tx.send(Reply::Done { success: false, cancelled: false });
}
if let Some(ready) = ready.take() {
let _ = ready.send(Err("The javac process exited while starting".into()));
}
})
.map_err(|e| IdeError::internal(e.to_string()))?;
}
let version = match ready_rx.recv_timeout(Duration::from_secs(60)) {
Ok(Ok(version)) => version,
Ok(Err(message)) => {
ide_core::process::kill_tree(&mut child);
return Err(IdeError::unavailable(format!("Cannot start javac ({}): {message}", java.display())));
}
Err(_) => {
ide_core::process::kill_tree(&mut child);
return Err(IdeError::unavailable(format!("javac ({}) did not start", java.display())));
}
};
Ok(JavacServer {
child: Mutex::new(child),
stdin: Mutex::new(stdin),
pending,
alive,
next: AtomicU64::new(1),
version,
})
}
fn alive(&self) -> bool {
self.alive.load(Ordering::SeqCst)
}
fn send(&self, value: &impl Serialize) -> IdeResult<()> {
let mut line = serde_json::to_vec(value).map_err(|e| IdeError::internal(e.to_string()))?;
line.push(b'\n');
let mut stdin = self.stdin.lock().unwrap();
stdin.write_all(&line).and_then(|()| stdin.flush()).map_err(|e| IdeError::internal(format!("javac: {e}")))
}
/// Compiles `sources` with javac `options`, passing each reply to `on_reply`, until the
/// compilation ends. Cancelling stops javac at its next phase.
pub fn compile(
&self,
options: &[String],
sources: &[PathBuf],
encoding: Option<&str>,
cancel: &CancellationToken,
mut on_reply: impl FnMut(&Reply),
) -> IdeResult<bool> {
let id = self.next.fetch_add(1, Ordering::SeqCst);
let (tx, rx) = mpsc::channel();
self.pending.lock().unwrap().insert(id, tx);
if let Err(e) = self.send(&Request { id, op: "compile", options, sources, encoding }) {
self.pending.lock().unwrap().remove(&id);
return Err(e);
}
let mut cancelled = false;
loop {
match rx.recv_timeout(Duration::from_millis(100)) {
Ok(reply) => {
if let Reply::Done { success, cancelled: stopped } = reply {
if stopped || cancelled {
return Err(IdeError::cancelled());
}
return Ok(success);
}
on_reply(&reply);
}
Err(mpsc::RecvTimeoutError::Timeout) => {
if cancel.is_cancelled() && !cancelled {
cancelled = true;
let _ = self.send(&serde_json::json!({ "op": "cancel", "id": id }));
}
}
Err(mpsc::RecvTimeoutError::Disconnected) => {
return Err(IdeError::internal("The javac process exited"));
}
}
}
}
}
impl Drop for JavacServer {
fn drop(&mut self) {
let _ = self.send(&serde_json::json!({ "op": "exit" }));
let mut child = self.child.lock().unwrap();
for _ in 0..20 {
if child.try_wait().ok().flatten().is_some() {
return;
}
std::thread::sleep(Duration::from_millis(50));
}
ide_core::process::kill_tree(&mut child);
}
}
/// The resident javac servers of one IDE process.
#[derive(Default)]
pub struct JavacPool {
servers: Mutex<HashMap<ServerKey, Arc<JavacServer>>>,
}
impl JavacPool {
/// The running server for `key`, started on first use (or after it died).
pub fn server(&self, jar: &Path, key: &ServerKey) -> IdeResult<Arc<JavacServer>> {
let mut servers = self.servers.lock().unwrap();
if let Some(server) = servers.get(key).filter(|s| s.alive()) {
return Ok(server.clone());
}
let server = Arc::new(JavacServer::start(jar, key)?);
servers.insert(key.clone(), server.clone());
Ok(server)
}
/// Stops every server (the project closed).
pub fn shutdown(&self) {
self.servers.lock().unwrap().clear();
}
}
File diff suppressed because it is too large. Load diff
-342
View File
@@ -1,342 +0,0 @@
//! The build model of a Maven reactor or Gradle build as the build tool itself configures it,
//! recorded by the prepare run (`java/java-build` `BuildModel`, `gradle-build.init.gradle`), and when that run is due.
use super::*;
use std::fs;
/// `model.json` of the prepare run (see `BuildModel.java`).
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ReactorModel {
pub version: u32,
pub projects: Vec<ProjectModel>,
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProjectModel {
/// Absolute project directory.
pub dir: PathBuf,
pub group_id: String,
pub artifact_id: String,
pub version: String,
pub packaging: String,
pub main: SourceSet,
pub test: SourceSet,
/// Executions in the compile phases that aren't javac (`group:artifact:goal@id`).
#[serde(default)]
pub other_compilers: Vec<String>,
/// Test source generators the prepare run doesn't reach.
#[serde(default)]
pub test_generators: Vec<String>,
#[serde(default)]
pub problems: Vec<String>,
/// The Gradle project path (`:`, `:app`); `None` for Maven.
#[serde(default)]
pub gradle_path: Option<String>,
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SourceSet {
pub source_roots: Vec<PathBuf>,
pub output: PathBuf,
pub classpath: Vec<PathBuf>,
pub runtime_classpath: Vec<PathBuf>,
#[serde(default)]
pub resources: Vec<ResourceRoot>,
pub compiler: Option<CompilerConfig>,
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ResourceRoot {
pub directory: PathBuf,
#[serde(default)]
pub filtering: bool,
pub target_path: Option<String>,
#[serde(default)]
pub includes: Vec<String>,
#[serde(default)]
pub excludes: Vec<String>,
}
/// maven-compiler-plugin's configuration of one source set, as its mojo was configured.
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct CompilerConfig {
pub compiler_id: Option<String>,
pub source: Option<String>,
pub target: Option<String>,
pub release: Option<String>,
pub encoding: Option<String>,
pub parameters: Option<bool>,
pub debug: Option<bool>,
pub debuglevel: Option<String>,
pub proc: Option<String>,
pub enable_preview: Option<bool>,
pub fork: Option<bool>,
pub executable: Option<String>,
pub skip: Option<bool>,
pub show_warnings: Option<bool>,
pub show_deprecation: Option<bool>,
pub generated_sources_directory: Option<PathBuf>,
#[serde(default)]
pub includes: Vec<String>,
#[serde(default)]
pub excludes: Vec<String>,
pub annotation_processors: Option<Vec<String>>,
#[serde(default)]
pub compiler_args: Vec<String>,
pub compiler_argument: Option<String>,
#[serde(default)]
pub compiler_arguments: BTreeMap<String, Option<String>>,
pub multi_release_output: Option<bool>,
pub processor_path: Option<Vec<PathBuf>>,
pub processor_path_error: Option<String>,
}
impl ProjectModel {
pub fn key(&self) -> String {
format!("{}:{}", self.group_id, self.artifact_id)
}
pub fn set(&self, test: bool) -> &SourceSet {
if test { &self.test } else { &self.main }
}
/// Why the IDE can't compile this project with javac itself, if it can't.
pub fn unsupported(&self, test: bool) -> Option<String> {
// What the build tool couldn't resolve or read: the model would be incomplete.
if let Some(problem) = self.problems.first() {
return Some(format!("{}: {problem}", self.artifact_id));
}
if !self.other_compilers.is_empty() {
return Some(format!("{} also compiles with {}", self.artifact_id, self.other_compilers.join(", ")));
}
if test && !self.test_generators.is_empty() {
return Some(format!(
"{} generates test sources with {}",
self.artifact_id,
self.test_generators.join(", ")
));
}
for set in [&self.main, &self.test] {
let Some(c) = &set.compiler else { continue };
if c.compiler_id.as_deref().is_some_and(|id| id != "javac") {
return Some(format!("{} compiles with {}", self.artifact_id, c.compiler_id.as_deref().unwrap()));
}
if c.multi_release_output == Some(true) {
return Some(format!("{} is a multi-release jar", self.artifact_id));
}
if let Some(error) = &c.processor_path_error {
return Some(format!("{}: {error}", self.artifact_id));
}
}
None
}
}
/// Where the IDE's build of the reactor at `top_dir` keeps its model and outputs.
pub(super) fn reactor_dir(cache: &Path, top_dir: &str) -> PathBuf {
let base = cache.join("java-build");
if top_dir.is_empty() { base.join("_root") } else { base.join(top_dir) }
}
/// The outputs of every project, `<out>/<groupId>.<artifactId>/classes`, as the extension
/// redirects them (`-Dopenidea.build.output=<out>`).
pub(super) fn output_root(cache: &Path, top_dir: &str) -> PathBuf {
reactor_dir(cache, top_dir).join("out")
}
/// What the recorded model was prepared from.
#[derive(Debug, Deserialize, Serialize)]
pub(super) struct PrepareRecord {
pub fingerprint: LaunchFingerprint,
pub model: ReactorModel,
}
const MODEL_VERSION: u32 = 1;
/// Files the model depends on: the POM chains, settings, toolchains, the Maven launcher,
/// and generator inputs (any `src/<set>/<dir>` that isn't Java sources or resources:
/// `proto`, `antlr4`, `avro`…), but not the Java sources and resources themselves.
pub(super) fn prepare_fingerprint(
root: &Path,
reactor: &[&maven::MavenProject],
step: &BuildStep,
local_repo: Option<PathBuf>,
jar_version: &str,
cancel: &CancellationToken,
) -> IdeResult<Option<LaunchFingerprint>> {
let Some(mut inputs) = maven::model_inputs(root, reactor, local_repo) else { return Ok(None) };
for project in reactor {
let src = subdir(root, &project.dir).join("src");
for set in fs::read_dir(&src).into_iter().flatten().flatten() {
for dir in fs::read_dir(set.path()).into_iter().flatten().flatten() {
let name = dir.file_name();
if dir.path().is_dir() && !matches!(name.to_str(), Some("java" | "resources")) {
inputs.push(dir.path());
}
}
}
}
for dir in step.cwd.ancestors() {
inputs.extend([dir.join(".mvn"), dir.join("mvnw"), dir.join("mvnw.cmd")]);
if dir == root {
break;
}
}
inputs.push(process::program_path(&step.program, &step.env, &step.cwd));
if let Some(home) = dirs::home_dir() {
inputs.extend([home.join(".m2/settings.xml"), home.join(".m2/toolchains.xml")]);
}
if let Some(home) = step.env.get("JAVA_HOME") {
inputs.push(Path::new(home).join("release"));
}
inputs.sort();
inputs.dedup();
let parameters = serde_json::to_string(&(MODEL_VERSION, jar_version, &step.program, &step.args, &step.env))
.map_err(|e| IdeError::internal(e.to_string()))?;
Ok(Some(LaunchFingerprint::new(parameters, fingerprint::scan_all(root, inputs, cancel)?)))
}
pub(super) fn load_record(dir: &Path) -> Option<PrepareRecord> {
let record: PrepareRecord = serde_json::from_slice(&fs::read(dir.join("prepare.json")).ok()?).ok()?;
(record.model.version == MODEL_VERSION).then_some(record)
}
pub(super) fn save_record(dir: &Path, record: &PrepareRecord) -> IdeResult<()> {
write_json(&dir.join("prepare.json"), record)
}
pub(super) fn write_json(path: &Path, value: &impl Serialize) -> IdeResult<()> {
let parent = path.parent().ok_or_else(|| IdeError::internal("no parent folder"))?;
fs::create_dir_all(parent)?;
let mut file = tempfile::NamedTempFile::new_in(parent)?;
serde_json::to_writer(file.as_file_mut(), value).map_err(|e| IdeError::internal(e.to_string()))?;
file.persist(path).map_err(|e| IdeError::from(e.error))?;
Ok(())
}
/// Whether the generated source roots the model lists still exist: `mvn clean` removes them.
pub(super) fn generated_roots_exist(model: &ReactorModel) -> bool {
model.projects.iter().all(|p| {
[&p.main, &p.test].iter().all(|set| {
set.source_roots.iter().all(|root| {
root.exists() || !root.components().any(|c| c.as_os_str() == "target") || is_processor_output(set, root)
})
})
})
}
/// The annotation processors' output folder, which javac writes into and never reads as a root.
pub(super) fn is_processor_output(set: &SourceSet, root: &Path) -> bool {
set.compiler.as_ref().and_then(|c| c.generated_sources_directory.as_deref()).is_some_and(|dir| dir == root)
}
/// A Maven step at the reactor root running `goals` with the IDE's extension loaded.
pub(super) fn maven_step(
root: &Path,
top: &maven::MavenProject,
jar: &Path,
output_root: &Path,
model_file: Option<&Path>,
extra: &[String],
) -> BuildStep {
let mut step = maven_build_step(
&top.command,
&["-B", "-Dstyle.color=never", maven::LOCAL_REPO_TRACKING_ARG],
&subdir(root, &top.dir),
);
step.args.extend(top.options.iter().cloned());
step.args.push(format!("-Dmaven.ext.class.path={}", jar.display()));
step.args.push(format!("-Dopenidea.build.output={}", output_root.display()));
if let Some(file) = model_file {
step.args.push(format!("-Dopenidea.build.model={}", file.display()));
}
step.args.extend(extra.iter().cloned());
step.env = top.env.clone();
step
}
/// The init script that gives a Gradle build the IDE's outputs and writes its model.
const GRADLE_INIT_SCRIPT: &str = include_str!("gradle-build.init.gradle");
/// Writes the init script into the build's state folder, and returns its path.
pub(super) fn gradle_init_script(dir: &Path) -> IdeResult<PathBuf> {
fs::create_dir_all(dir)?;
let path = dir.join("openidea-build.init.gradle");
if fs::read_to_string(&path).ok().as_deref() != Some(GRADLE_INIT_SCRIPT) {
fs::write(&path, GRADLE_INIT_SCRIPT)?;
}
Ok(path)
}
/// A Gradle step at the build's root running `tasks` with the IDE's init script.
pub(super) fn gradle_step(
root: &Path,
g: &crate::GradleModel,
init: &Path,
output_root: &Path,
model_file: Option<&Path>,
tasks: &[String],
) -> BuildStep {
let mut step = gradle_build_step(
&g.command,
// The init script configures the evaluated projects, which a configuration cache skips.
&["--console=plain", "--no-configuration-cache"],
&subdir(root, &g.dir),
);
step.args.extend(["--init-script".to_owned(), init.to_string_lossy().into_owned()]);
step.args.push(format!("-Popenidea.build.output={}", output_root.display()));
if let Some(file) = model_file {
step.args.push(format!("-Popenidea.build.model={}", file.display()));
}
step.args.extend(tasks.iter().cloned());
step.env = g.env.clone();
step
}
/// Files a Gradle build's model depends on: settings and build scripts (with what they apply),
/// properties, the wrapper and catalogs, `buildSrc`, and generator inputs.
pub(super) fn gradle_prepare_fingerprint(
root: &Path,
g: &crate::GradleModel,
step: &BuildStep,
jar_version: &str,
cancel: &CancellationToken,
) -> IdeResult<LaunchFingerprint> {
let mut inputs = crate::gradle::build_files(root, g);
let dir = subdir(root, &g.dir);
inputs.extend([dir.join("buildSrc"), dir.join("gradle"), dir.join("gradlew"), dir.join("gradlew.bat")]);
for project in &g.projects {
let src = subdir(root, &project.dir).join("src");
for set in fs::read_dir(&src).into_iter().flatten().flatten() {
for generator in fs::read_dir(set.path()).into_iter().flatten().flatten() {
let name = generator.file_name();
if generator.path().is_dir() && !matches!(name.to_str(), Some("java" | "resources")) {
inputs.push(generator.path());
}
}
}
}
inputs.push(process::program_path(&step.program, &step.env, &step.cwd));
if let Some(home) = dirs::home_dir() {
inputs.push(home.join(".gradle/gradle.properties"));
inputs.push(home.join(".gradle/init.d"));
}
if let Some(home) = step.env.get("JAVA_HOME") {
inputs.push(Path::new(home).join("release"));
}
inputs.sort();
inputs.dedup();
let parameters =
serde_json::to_string(&(MODEL_VERSION, jar_version, GRADLE_INIT_SCRIPT, &step.program, &step.args, &step.env))
.map_err(|e| IdeError::internal(e.to_string()))?;
Ok(LaunchFingerprint::new(parameters, fingerprint::scan_all(root, inputs, cancel)?))
}
pub(super) fn read_model(path: &Path) -> IdeResult<ReactorModel> {
let bytes = fs::read(path).map_err(|e| IdeError::internal(format!("The build wrote no model ({e})")))?;
serde_json::from_slice(&bytes).map_err(|e| IdeError::internal(format!("Unreadable build model: {e}")))
}
-544
View File
@@ -1,544 +0,0 @@
use super::*;
use crate::BuildModel;
use std::fs;
use std::sync::Mutex as StdMutex;
const JAR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../../java/java-build/openidea-java-build.jar");
fn write(root: &Path, rel: &str, text: &str) {
let path = root.join(rel);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, text).unwrap();
}
/// A JDK (`JAVA_HOME`) and Maven on the search path, else `None` (the test is skipped).
fn tools() -> Option<(PathBuf, PathBuf)> {
let home = std::env::var_os("JAVA_HOME").map(PathBuf::from).filter(|h| h.join("bin").is_dir())?;
let mvn = ide_core::process::find_executable("mvn", &ide_core::tool_path::search_path())?;
Some((home, mvn))
}
const ROOT_POM: &str = r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>root</artifactId><version>1</version><packaging>pom</packaging>
<modules><module>lib</module><module>app</module></modules>
<properties><maven.compiler.release>11</maven.compiler.release><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties>
<build><pluginManagement><plugins><plugin><artifactId>maven-compiler-plugin</artifactId><version>3.13.0</version>
<configuration><parameters>true</parameters></configuration></plugin></plugins></pluginManagement></build></project>"#;
const LIB_POM: &str = r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>lib</artifactId></project>"#;
const APP_POM: &str = r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>app</artifactId>
<dependencies><dependency><groupId>t</groupId><artifactId>lib</artifactId><version>1</version></dependency></dependencies>
<build><resources><resource><directory>src/main/resources</directory><filtering>true</filtering></resource></resources></build></project>"#;
/// A `lib` ← `app` reactor built by the IDE's Java build with a real Maven and JDK.
struct Fixture {
_tmp: tempfile::TempDir,
root: PathBuf,
cache: PathBuf,
model: BuildModel,
/// Where the build keeps its state under the cache (`Reactor::key`).
key: &'static str,
service: JavaBuildService,
events: StdMutex<Vec<BuildEvent>>,
}
impl Fixture {
fn new(files: &[(&str, &str)]) -> Option<Self> {
let Some((home, mvn)) = tools() else {
eprintln!("skipped: needs JAVA_HOME and mvn");
return None;
};
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
for (rel, text) in
[("pom.xml", ROOT_POM), ("lib/pom.xml", LIB_POM), ("app/pom.xml", APP_POM)].iter().chain(files)
{
write(&root, rel, text);
}
let cache = root.join(".cache");
let mut model = crate::load(&root, &cache, None);
for p in &mut model.maven.as_mut().unwrap().projects {
p.command = mvn.to_string_lossy().into_owned();
p.env.insert("JAVA_HOME".into(), home.to_string_lossy().into_owned());
}
Some(Fixture {
_tmp: tmp,
root,
cache,
model,
key: "",
service: JavaBuildService::default(),
events: StdMutex::default(),
})
}
/// The same `lib` ← `app` build with Gradle (`OPENIDEA_TEST_GRADLE`, else `gradle` on the
/// search path).
fn gradle(files: &[(&str, &str)]) -> Option<Self> {
let home = std::env::var_os("JAVA_HOME").map(PathBuf::from).filter(|h| h.join("bin").is_dir());
let gradle = std::env::var_os("OPENIDEA_TEST_GRADLE")
.map(PathBuf::from)
.or_else(|| ide_core::process::find_executable("gradle", &ide_core::tool_path::search_path()));
let (Some(home), Some(gradle)) = (home, gradle) else {
eprintln!("skipped: needs JAVA_HOME and gradle (OPENIDEA_TEST_GRADLE)");
return None;
};
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
let build = [
("settings.gradle", "rootProject.name = 'root'\ninclude 'lib', 'app'\n"),
(
"build.gradle",
"subprojects {\n apply plugin: 'java'\n group = 't'\n tasks.withType(JavaCompile).configureEach { options.release = 11; options.encoding = 'UTF-8' }\n}\n",
),
("lib/build.gradle", ""),
(
"app/build.gradle",
"dependencies { implementation project(':lib') }\nprocessResources { filesMatching('*.properties') { expand(version: '1') } }\n",
),
];
for (rel, text) in build.iter().chain(files) {
write(&root, rel, text);
}
let cache = root.join(".cache");
let mut model = crate::load(&root, &cache, None);
assert_eq!(model.gradle.len(), 1, "{model:?}");
let g = &mut model.gradle[0];
g.command = gradle.to_string_lossy().into_owned();
g.env.insert("JAVA_HOME".into(), home.to_string_lossy().into_owned());
Some(Fixture {
_tmp: tmp,
root,
cache,
model,
key: "_gradle",
service: JavaBuildService::default(),
events: StdMutex::default(),
})
}
fn write(&self, rel: &str, text: &str) {
write(&self.root, rel, text);
}
fn out(&self, rel: &str) -> PathBuf {
model::output_root(&self.cache, self.key).join(rel)
}
/// Builds the launch of `app` (its tests when `test`).
fn launch(&self, test: bool) -> LaunchOutputs {
self.build(Target::Launch { module: &self.root.join("app"), test })
}
fn build(&self, target: Target) -> LaunchOutputs {
let jdk = |_: Option<u32>| None;
let build = JavaBuild {
root: &self.root,
model: &self.model,
cache: &self.cache,
jar: Path::new(JAR),
jar_version: "test",
local_repo: None,
service: &self.service,
jdk: &jdk,
};
let on_event = |e: BuildEvent| self.events.lock().unwrap().push(e);
match build.build(target, BuildKind::Build, &CancellationToken::new(), &on_event) {
Ok(Built::Done(outputs)) => outputs,
Ok(Built::Unsupported(reason)) => panic!("unsupported: {reason}"),
Err(e) => panic!("{e:?}"),
}
}
/// The steps of the launch builds since the last call.
fn steps(&self) -> Vec<String> {
self.events
.lock()
.unwrap()
.drain(..)
.filter_map(|e| match e {
BuildEvent::Step { command, .. } => Some(command),
_ => None,
})
.collect()
}
/// Builds and returns the steps it took, which must succeed.
fn steps_of_launch(&self) -> Vec<String> {
self.steps();
let built = self.launch(false);
assert_eq!(built.failure, None, "{:?}", built.messages);
self.steps()
}
}
#[test]
fn builds_maven_modules_with_javac_and_only_what_changed() {
let Some(f) = Fixture::new(&[
(
"lib/src/main/java/l/L.java",
"package l;\npublic class L { public static String name() { return \"lib\"; } }\n",
),
(
"app/src/main/java/a/A.java",
"package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name()); } }\n",
),
("app/src/main/resources/app.properties", "version=${project.version}\n"),
("app/src/test/java/a/ATest.java", "package a;\npublic class ATest { String s = l.L.name(); }\n"),
]) else {
return;
};
// First build: Maven prepares the model, javac compiles lib then app into the IDE's outputs.
let first = f.launch(false);
assert_eq!(first.failure, None, "{:?}", first.messages);
assert_eq!(first.class_paths[0], f.out("t.app/classes"));
assert!(first.class_paths.contains(&f.out("t.lib/classes")), "{:?}", first.class_paths);
assert!(f.out("t.app/classes/a/A.class").is_file());
assert!(f.out("t.lib/classes/l/L.class").is_file());
assert!(!f.root.join("app/target/classes/a/A.class").exists());
assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\n");
let steps = f.steps();
assert!(steps[0].contains("process-resources"), "{steps:?}");
assert_eq!(steps[1..], ["javac lib (main, 1 file)", "javac app (main, 1 file)"]);
// Nothing changed: no Maven, no javac.
assert_eq!(f.steps_of_launch(), Vec::<String>::new());
// A change inside a method compiles that class only, without Maven.
f.write(
"lib/src/main/java/l/L.java",
"package l;\npublic class L { public static String name() { return \"lib 2\"; } }\n",
);
assert_eq!(f.steps_of_launch(), ["javac lib (main, 1 file)"]);
// A resource change is processed by Maven (it filters), and compiles nothing.
f.write("app/src/main/resources/app.properties", "version=${project.version}\nmore=1\n");
let steps = f.steps_of_launch();
assert_eq!(steps.len(), 1, "{steps:?}");
assert!(steps[0].contains("resources:resources") && steps[0].contains("-pl app"), "{steps:?}");
assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\nmore=1\n");
// A deleted source leaves no class behind.
f.write("app/src/main/java/a/Gone.java", "package a;\nclass Gone {}\n");
assert_eq!(f.steps_of_launch(), ["javac app (main, 1 of 2 files)"]);
assert!(f.out("t.app/classes/a/Gone.class").is_file());
fs::remove_file(f.root.join("app/src/main/java/a/Gone.java")).unwrap();
assert_eq!(f.steps_of_launch(), Vec::<String>::new());
assert!(!f.out("t.app/classes/a/Gone.class").exists());
// Compile errors fail the build with positioned messages.
f.write("app/src/main/java/a/A.java", "package a;\npublic class A { int x = \"s\"; }\n");
let failed = f.launch(false);
let failure = failed.failure.expect("fails");
assert!(failure.contains("incompatible types"), "{failure}");
let error = failed.messages.iter().find(|m| m.severity == Severity::Error).unwrap();
assert_eq!(error.path.as_deref(), Some(f.root.join("app/src/main/java/a/A.java").as_path()));
assert_eq!(error.range.unwrap().start, Pos::new(1, 25));
// It compiles again next time, even unchanged.
f.steps();
assert!(f.launch(false).failure.is_some());
assert_eq!(f.steps(), ["javac app (main, 1 file)"]);
// A test launch compiles the module's tests after its main classes.
f.write(
"app/src/main/java/a/A.java",
"package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name()); } }\n",
);
let tests = f.launch(true);
assert_eq!(tests.failure, None, "{:?}", tests.messages);
assert_eq!(tests.class_paths[..2], [f.out("t.app/test-classes"), f.out("t.app/classes")]);
assert!(f.out("t.app/test-classes/a/ATest.class").is_file());
// Recompile compiles the file even unchanged.
f.steps();
let file = f.root.join("app/src/main/java/a/A.java");
assert_eq!(f.build(Target::File(&file)).failure, None);
assert_eq!(f.steps(), ["javac app (main, 1 file)"]);
// Build Project builds every module's main and test classes.
f.write("lib/src/test/java/l/LTest.java", "package l;\nclass LTest { String s = L.name(); }\n");
assert_eq!(f.build(Target::Project).failure, None);
assert_eq!(f.steps(), ["javac lib (tests, 1 file)"]);
assert!(f.out("t.lib/test-classes/l/LTest.class").is_file());
}
#[test]
fn recompiles_the_classes_an_api_change_reaches() {
let Some(f) = Fixture::new(&[
("lib/src/main/java/l/Base.java", "package l;\npublic class Base { public int m() { return 1; } }\n"),
("lib/src/main/java/l/Sub.java", "package l;\npublic class Sub extends Base {}\n"),
("lib/src/main/java/l/User.java", "package l;\nclass User { int u(Sub s) { return s.m(); } }\n"),
("lib/src/main/java/l/Const.java", "package l;\npublic class Const { public static final int X = 1; }\n"),
("lib/src/main/java/l/ConstUser.java", "package l;\nclass ConstUser { int c() { return Const.X; } }\n"),
("lib/src/main/java/l/Other.java", "package l;\npublic class Other { public int o() { return 1; } }\n"),
("app/src/main/java/a/A.java", "package a;\nclass A { int a() { return new l.Other().o(); } }\n"),
("app/src/main/java/a/B.java", "package a;\nclass B { int b() { return l.Const.X; } }\n"),
]) else {
return;
};
assert_eq!(f.steps_of_launch()[1..], ["javac lib (main, 6 files)", "javac app (main, 2 files)"]);
// A body change: that class only, and nothing downstream.
f.write("lib/src/main/java/l/Other.java", "package l;\npublic class Other { public int o() { return 2; } }\n");
assert_eq!(f.steps_of_launch(), ["javac lib (main, 1 of 6 files)"]);
// An API change reaches the classes that use the class or a subclass of it.
f.write(
"lib/src/main/java/l/Base.java",
"package l;\npublic class Base { public int m() { return 1; } public int n() { return 2; } }\n",
);
assert_eq!(f.steps_of_launch(), ["javac lib (main, 1 of 6 files)", "javac lib (main, 2 of 6 files)"]);
// Across modules: only the classes that use it.
f.write(
"lib/src/main/java/l/Other.java",
"package l;\npublic class Other { public int o() { return 2; } public void p() {} }\n",
);
assert_eq!(f.steps_of_launch(), ["javac lib (main, 1 of 6 files)", "javac app (main, 1 of 2 files)"]);
// A compile-time constant is copied into its uses: everything compiled against it compiles again.
f.write("lib/src/main/java/l/Const.java", "package l;\npublic class Const { public static final int X = 2; }\n");
assert_eq!(
f.steps_of_launch(),
["javac lib (main, 1 of 6 files)", "javac lib (main, 5 of 6 files)", "javac app (main, 2 files)"]
);
// A removed method fails the classes that still call it.
f.write("lib/src/main/java/l/Base.java", "package l;\npublic class Base { public int n() { return 2; } }\n");
let failed = f.launch(false);
assert!(failed.failure.expect("fails").contains("User.java"));
}
#[test]
fn an_api_change_from_a_failed_build_still_reaches_other_modules() {
let Some(f) = Fixture::new(&[
("lib/src/main/java/l/L.java", "package l;\npublic class L { public static int m() { return 1; } }\n"),
("lib/src/main/java/l/U.java", "package l;\nclass U { int u() { return L.m(); } }\n"),
("app/src/main/java/a/A.java", "package a;\nclass A { int a() { return l.L.m(); } }\n"),
]) else {
return;
};
assert_eq!(f.launch(false).failure, None);
// L compiles, then U, which still calls the removed method, fails lib before app compiles.
f.write("lib/src/main/java/l/L.java", "package l;\npublic class L { public static int n() { return 1; } }\n");
assert!(f.launch(false).failure.expect("lib fails").contains("U.java"));
// Once lib compiles, app learns that L changed, and A fails too instead of keeping a class
// that calls a method L no longer has.
f.write("lib/src/main/java/l/U.java", "package l;\nclass U { int u() { return L.n(); } }\n");
let failed = f.launch(false);
assert!(failed.failure.expect("app fails").contains("A.java"), "{:?}", failed.messages);
// So does a changed constant: C compiles, then the whole set, where U fails.
f.write("app/src/main/java/a/A.java", "package a;\nclass A { int a() { return l.L.n() + l.C.X; } }\n");
let c = |x: u32, y: &str| format!("package l;\npublic class C {{ public static final int X = {x};{y} }}\n");
f.write("lib/src/main/java/l/C.java", &c(1, " public static int y() { return 0; }"));
f.write("lib/src/main/java/l/U.java", "package l;\nclass U { int u() { return L.n() + C.y(); } }\n");
assert_eq!(f.launch(false).failure, None);
f.write("lib/src/main/java/l/C.java", &c(2, ""));
assert!(f.launch(false).failure.expect("lib fails").contains("U.java"));
f.write("lib/src/main/java/l/U.java", "package l;\nclass U { int u() { return L.n(); } }\n");
f.steps();
assert_eq!(f.launch(false).failure, None);
let steps = f.steps();
assert!(steps.contains(&"javac app (main, 1 file)".to_owned()), "{steps:?}");
}
#[test]
fn reads_what_a_class_file_declares() {
let Some((home, _)) = tools() else { return };
let tmp = tempfile::tempdir().unwrap();
let compile = |text: &str| {
write(tmp.path(), "p/C.java", text);
let status = std::process::Command::new(home.join("bin/javac"))
.args(["-d", "out", "p/C.java"])
.current_dir(tmp.path())
.status()
.unwrap();
assert!(status.success());
classfile::parse(&fs::read(tmp.path().join("out/p/C.class")).unwrap()).unwrap()
};
let a = compile(
"package p;\nimport java.util.List;\npublic class C extends Thread implements Runnable {\n public static final String K = \"k\";\n @Deprecated public List<javax.swing.JButton> f;\n public x.Y g() { return null; }\n private int hidden() { return 1; }\n}\nclass Z {}\n"
.replace("x.Y", "Object")
.as_str(),
);
assert_eq!(a.name, "p/C");
assert_eq!(a.super_name.as_deref(), Some("java/lang/Thread"));
assert_eq!(a.interfaces, ["java/lang/Runnable"]);
assert!(a.refs.contains("javax/swing/JButton"), "{:?}", a.refs);
assert!(!a.refs.iter().any(|r| r.starts_with("java/")), "{:?}", a.refs);
// Private members and method bodies aren't API; constants have their own fingerprint.
let b = compile(
"package p;\nimport java.util.List;\npublic class C extends Thread implements Runnable {\n public static final String K = \"k\";\n @Deprecated public List<javax.swing.JButton> f;\n public Object g() { return \"x\"; }\n private long hidden2() { return 1; }\n}\nclass Z {}\n",
);
assert_eq!((a.api, a.constants), (b.api, b.constants));
let c = compile(
"package p;\nimport java.util.List;\npublic class C extends Thread implements Runnable {\n public static final String K = \"changed\";\n @Deprecated public List<javax.swing.JButton> f;\n public Object g() { return \"x\"; }\n}\nclass Z {}\n",
);
assert_eq!(a.api, c.api);
assert_ne!(a.constants, c.constants);
let d = compile(
"package p;\nimport java.util.List;\npublic class C extends Thread implements Runnable {\n public static final String K = \"k\";\n @Deprecated public List<javax.swing.JLabel> f;\n public Object g() { return \"x\"; }\n}\nclass Z {}\n",
);
assert_ne!(a.api, d.api);
}
#[test]
fn follows_api_changes_through_the_log() {
let mut state = SetState { generation: 1, ..Default::default() };
state.log(2, ["a/A".to_owned()].into(), false);
state.log(3, ["a/B".to_owned()].into(), false);
assert_eq!(state.changes_since(3), Some(BTreeSet::new()));
assert_eq!(state.changes_since(2), Some(["a/B".to_owned()].into()));
assert_eq!(state.changes_since(1), Some(["a/A".to_owned(), "a/B".to_owned()].into()));
// Unknown generations, and a log entry where everything changed, mean everything.
assert_eq!(state.changes_since(0), None);
state.log(4, BTreeSet::new(), true);
assert_eq!(state.changes_since(3), None);
}
#[test]
fn ant_patterns_match_like_maven() {
assert!(ant_match("**/*.java", "a/b/C.java"));
assert!(ant_match("**/*.java", "C.java"));
assert!(ant_match("com/acme/**", "com/acme/x/Y.java"));
assert!(!ant_match("com/acme/**", "com/other/Y.java"));
assert!(ant_match("**/generated/", "x/generated/Y.java"));
assert!(ant_match("**/*Test?.java", "a/FooTest1.java"));
assert!(!ant_match("*.java", "a/B.java"));
}
#[test]
fn javac_options_follow_the_compiler_configuration() {
let set = SourceSet {
output: PathBuf::from("/o"),
compiler: Some(CompilerConfig {
release: Some("17".into()),
source: Some("1.8".into()),
encoding: Some("UTF-8".into()),
parameters: Some(true),
debuglevel: Some("lines,vars".into()),
proc: Some("none".into()),
processor_path: Some(vec![PathBuf::from("/p.jar")]),
annotation_processors: Some(vec!["a.P".into()]),
compiler_args: vec!["-Xlint:unchecked".into()],
compiler_arguments: [("Akey=v".to_owned(), None)].into(),
show_warnings: Some(false),
..Default::default()
}),
..Default::default()
};
let args = javac_options(&set, &[PathBuf::from("/lib.jar")], Path::new("/gen"), Some(21));
let joined = args.join(" ");
let separator = if cfg!(windows) { ";" } else { ":" };
assert!(joined.starts_with(&format!("-d /o -classpath /o{separator}/lib.jar -sourcepath -s /gen")), "{joined}");
for expected in [
"-processorpath /p.jar",
"-processor a.P",
"-proc:none",
"-g:lines,vars",
"-parameters",
"-nowarn",
"-encoding UTF-8",
"--release 17",
"-Akey=v",
] {
assert!(joined.contains(expected), "{expected} in {joined}");
}
assert!(joined.ends_with("-Xlint:unchecked"), "{joined}");
// JDK 8 has no --release: source and target instead.
let old = javac_options(&set, &[], Path::new("/gen"), Some(8)).join(" ");
assert!(old.contains("-source 1.8") && !old.contains("--release"), "{old}");
}
#[test]
fn builds_gradle_projects_with_javac_and_only_what_changed() {
let Some(f) = Fixture::gradle(&[
(
"lib/src/main/java/l/L.java",
"package l;\npublic class L { public static String name() { return \"lib\"; } }\n",
),
(
"app/src/main/java/a/A.java",
"package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name()); } }\n",
),
("app/src/main/resources/app.properties", "version=${version}\n"),
("app/src/test/java/a/ATest.java", "package a;\npublic class ATest { String s = l.L.name(); }\n"),
]) else {
return;
};
let steps = f.steps_of_launch();
assert_eq!(steps.len(), 3, "{steps:?}");
assert!(steps[0].contains("openideaBuildModel"), "{steps:?}");
assert!(steps[1].starts_with("javac lib (main"), "{steps:?}");
assert!(steps[2].starts_with("javac app (main"), "{steps:?}");
assert!(f.out("t.lib/classes/l/L.class").is_file());
assert!(f.out("t.app/classes/a/A.class").is_file());
assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\n");
// Gradle's own outputs stay untouched.
assert!(!f.root.join("app/build/classes").exists());
let built = f.launch(false);
assert!(built.class_paths.iter().any(|p| p.ends_with("t.lib/classes")), "{:?}", built.class_paths);
assert!(!built.class_paths.iter().any(|p| p.extension().is_some_and(|e| e == "jar")), "{:?}", built.class_paths);
assert_eq!(f.steps(), Vec::<String>::new(), "nothing changed");
f.write(
"app/src/main/java/a/A.java",
"package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name() + 1); } }\n",
);
let steps = f.steps_of_launch();
assert_eq!(steps.len(), 1, "{steps:?}");
assert!(steps[0].starts_with("javac app (main"), "{steps:?}");
f.write("app/src/main/resources/app.properties", "version=${version}\nname=app\n");
let steps = f.steps_of_launch();
assert_eq!(steps.len(), 1, "{steps:?}");
assert!(steps[0].contains(":app:processResources"), "{steps:?}");
assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\nname=app\n");
// Tests compile against the main classes.
f.steps();
let built = f.launch(true);
assert_eq!(built.failure, None, "{:?}", built.messages);
assert!(f.out("t.app/test-classes/a/ATest.class").is_file());
// A changed build script prepares again.
f.write("lib/build.gradle", "// changed\n");
let steps = f.steps_of_launch();
assert!(steps[0].contains("openideaBuildModel"), "{steps:?}");
// An error is a javac diagnostic on the source.
f.write("lib/src/main/java/l/L.java", "package l;\npublic class L { public static String name() { return 1; } }\n");
let built = f.launch(false);
assert!(built.failure.is_some());
let error = built.messages.iter().find(|m| m.severity == Severity::Error).expect("an error");
assert_eq!(error.path.as_deref(), Some(f.root.join("lib/src/main/java/l/L.java").as_path()));
}
#[test]
fn leaves_gradle_projects_with_other_compilers_to_gradle() {
let Some(f) = Fixture::gradle(&[
("app/build.gradle", "apply plugin: 'groovy'\ndependencies { implementation project(':lib') }\n"),
("app/src/main/java/a/A.java", "package a;\npublic class A {}\n"),
]) else {
return;
};
let jdk = |_: Option<u32>| None;
let build = JavaBuild {
root: &f.root,
model: &f.model,
cache: &f.cache,
jar: Path::new(JAR),
jar_version: "test",
local_repo: None,
service: &f.service,
jdk: &jdk,
};
let target = Target::Launch { module: &f.root.join("app"), test: false };
match build.build(target, BuildKind::Build, &CancellationToken::new(), &|_| {}) {
Ok(Built::Unsupported(reason)) => assert!(reason.contains("GroovyCompile"), "{reason}"),
Ok(Built::Done(outputs)) => panic!("built: {outputs:?}"),
Err(e) => panic!("{e:?}"),
}
}
-1
View File
@@ -9,7 +9,6 @@ pub mod application_update;
pub mod compile;
pub mod gradle;
mod gradle_deps;
pub mod jbuild;
pub mod kotlin_bridge;
pub mod maven;
pub mod pom_edit;
+4 -97
View File
@@ -517,59 +517,6 @@ pub fn local_repository_of(settings: &Path) -> Option<PathBuf> {
Some(PathBuf::from(repo.replace("${user.home}", &home)))
}
/// The local repository a Maven run with these options resolves into: `-Dmaven.repo.local=`
/// first, then `<localRepository>` of the `-s` settings, then the user's default.
pub fn local_repository_for(options: &[String]) -> Option<PathBuf> {
if let Some(repo) = options.iter().find_map(|a| a.strip_prefix("-Dmaven.repo.local=")) {
return Some(PathBuf::from(repo));
}
let mut args = options.iter();
while let Some(arg) = args.next() {
let path = match arg.as_str() {
"-s" | "--settings" => args.next().map(String::as_str),
_ => arg.strip_prefix("-s=").or_else(|| arg.strip_prefix("--settings=")),
};
if let Some(path) = path {
return local_repository_of(Path::new(path)).or_else(default_local_repo);
}
}
default_local_repo()
}
/// A goal of the IDE's own (`help:evaluate`, `dependency:build-classpath`, …) by its plugin's
/// coordinates rather than its prefix: offline, Maven resolves a prefix only from group metadata
/// in the local repository, which a repository filled from a private mirror often lacks even when
/// the plugin itself is there. Uses the newest 3.x version already in `repo`, so nothing is
/// downloaded, else a pinned one.
pub fn plugin_goal(goal: &str, repo: Option<&Path>) -> String {
let (prefix, goal) = goal.split_once(':').expect("prefix:goal");
let (artifact, pinned) = match prefix {
"help" => ("maven-help-plugin", "3.5.1"),
"dependency" => ("maven-dependency-plugin", "3.8.1"),
_ => unreachable!("not a goal of the IDE's own: {prefix}"),
};
let version = repo.and_then(|repo| newest_local_plugin(repo, artifact, 3)).unwrap_or_else(|| pinned.to_owned());
format!("org.apache.maven.plugins:{artifact}:{version}:{goal}")
}
/// The newest release of `org.apache.maven.plugins:<artifact>` whose jar is in `repo`,
/// from major version `min_major` up.
pub(crate) fn newest_local_plugin(repo: &Path, artifact: &str, min_major: u64) -> Option<String> {
let dir = repo.join("org/apache/maven/plugins").join(artifact);
let parse = |v: &str| v.split('.').map(|n| n.parse::<u64>().ok()).collect::<Option<Vec<u64>>>();
std::fs::read_dir(&dir)
.ok()?
.flatten()
.filter_map(|e| e.file_name().into_string().ok())
.filter_map(|v| parse(&v).map(|n| (n, v)))
.filter(|(n, v)| {
n.first().is_some_and(|&major| major >= min_major)
&& dir.join(v).join(format!("{artifact}-{v}.jar")).is_file()
})
.max()
.map(|(_, v)| v)
}
impl Resolver {
fn new(local_repo: Option<PathBuf>, profiles: &[String]) -> Self {
Self::new_with_jdk(local_repo, profiles, None)
@@ -753,26 +700,7 @@ pub(crate) fn launch_inputs(
projects: &[&MavenProject],
local_repo: Option<PathBuf>,
) -> Option<Vec<PathBuf>> {
project_inputs(root, projects, local_repo, true)
}
/// The POM chains (with imported BOMs) of `projects` and the files their profiles activate
/// on: what Maven's model of them is built from, without their sources.
pub(crate) fn model_inputs(
root: &Path,
projects: &[&MavenProject],
local_repo: Option<PathBuf>,
) -> Option<Vec<PathBuf>> {
project_inputs(root, projects, local_repo, false)
}
fn project_inputs(
root: &Path,
projects: &[&MavenProject],
local_repo: Option<PathBuf>,
sources: bool,
) -> Option<Vec<PathBuf>> {
fn roots(el: &Element, parent: &str, dir: &Path, sources: bool, out: &mut Vec<PathBuf>) -> Option<()> {
fn roots(el: &Element, parent: &str, dir: &Path, out: &mut Vec<PathBuf>) -> Option<()> {
let input =
matches!(el.name.as_str(), "sourceDirectory" | "testSourceDirectory" | "sourceDir" | "testSourceDir")
|| (matches!(parent, "sources" | "sourceDirs" | "testSources" | "testSourceDirs")
@@ -781,7 +709,6 @@ fn project_inputs(
|| (parent == "filters" && el.name == "filter");
// Profile activation may depend on the presence of an otherwise unrelated file.
let activation = parent == "file" && matches!(el.name.as_str(), "exists" | "missing");
let input = input && sources;
if input || activation {
// A source root under Maven's build directory is generated by the build itself.
// Skip it without resolving the property: `<build><directory>` may be custom, and
@@ -807,7 +734,7 @@ fn project_inputs(
}
}
for child in &el.children {
roots(child, &el.name, dir, sources, out)?;
roots(child, &el.name, dir, out)?;
}
Some(())
}
@@ -816,9 +743,7 @@ fn project_inputs(
for project in projects {
let dir = root.join(&project.dir);
// Include all conventional language/resource roots, including nonstandard files under src.
if sources {
out.push(dir.join("src"));
}
out.push(dir.join("src"));
let pom = root.join(&project.pom);
resolver.context(&pom, 0);
let mut path = pom;
@@ -830,7 +755,7 @@ fn project_inputs(
}
out.push(path.clone());
let text = xml::read_text(&path)?;
roots(&xml::parse(&text)?, "", &dir, sources, &mut out)?;
roots(&xml::parse(&text)?, "", &dir, &mut out)?;
let raw = resolver.pom(&path)?;
let Some(parent) = raw.parent else { break };
path = resolver.parent_path(path.parent()?, &parent)?;
@@ -2632,24 +2557,6 @@ mod tests {
assert!(local_repository_of(&tmp.path().join("missing.xml")).is_none());
}
#[test]
fn ide_goals_resolve_from_the_repository_the_run_uses() {
let tmp = tempfile::tempdir().unwrap();
let settings = tmp.path().join("settings.xml");
std::fs::write(&settings, "<settings><localRepository>/srv/m2</localRepository></settings>").unwrap();
let s = settings.to_string_lossy().into_owned();
let opts = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::<Vec<_>>();
assert_eq!(local_repository_for(&opts(&["-s", &s])), Some(PathBuf::from("/srv/m2")));
assert_eq!(local_repository_for(&opts(&[&format!("--settings={s}")])), Some(PathBuf::from("/srv/m2")));
let explicit = opts(&["-s", &s, "-Dmaven.repo.local=/tmp/r"]);
assert_eq!(local_repository_for(&explicit), Some(PathBuf::from("/tmp/r")));
// No repository known: a pinned version, still by coordinates.
assert_eq!(
plugin_goal("dependency:build-classpath", None),
"org.apache.maven.plugins:maven-dependency-plugin:3.8.1:build-classpath"
);
}
#[test]
fn effective_pom_goals_come_from_the_local_repository_it_is_given() {
let tmp = tempfile::tempdir().unwrap();
+36 -54
View File
@@ -86,37 +86,22 @@ const MAVEN_CACHE_VERSION: u32 = 1;
/// `dependency:tree` of a plugin version whose `-Dverbose` lists the occurrences Maven
/// omitted (conflicts, duplicates): verbose output was dropped in 3.0 and is back since 3.2.
/// Offline, it is used only when an earlier sync downloaded it; otherwise the newest version
/// in the local repository is.
/// Offline, it is used only when an earlier sync downloaded it; otherwise the project's own
/// plugin version is, which may be cached instead.
const DEPENDENCY_TREE: &str = "org.apache.maven.plugins:maven-dependency-plugin:3.8.1:tree";
const DEPENDENCY_TREE_JAR: &str =
"org/apache/maven/plugins/maven-dependency-plugin/3.8.1/maven-dependency-plugin-3.8.1.jar";
/// The goals that read the effective POM into `effective` and the verbose dependency trees;
/// `repo` is the local repository the build resolves from. Both goals name their plugin by
/// coordinates: offline, a prefix resolves only from group metadata the repository may lack.
/// Offline without a cached 3.x `maven-help-plugin`, `effective-pom` is skipped so `mvn -o`
/// still resolves the dependency tree instead of failing to download the help plugin.
/// `repo` is the local repository the build resolves from.
fn maven_sync_goals(effective: &Path, offline: bool, repo: Option<&Path>) -> Vec<String> {
let pinned = !offline || repo.is_some_and(|repo| repo.join(DEPENDENCY_TREE_JAR).is_file());
let tree = if pinned {
DEPENDENCY_TREE.to_owned()
} else {
repo.and_then(|repo| maven::newest_local_plugin(repo, "maven-dependency-plugin", 2)).map_or_else(
|| "dependency:tree".to_owned(),
|v| format!("org.apache.maven.plugins:maven-dependency-plugin:{v}:tree"),
)
};
let has_help =
!offline || repo.is_some_and(|repo| maven::newest_local_plugin(repo, "maven-help-plugin", 3).is_some());
let mut goals = Vec::with_capacity(4);
if has_help {
goals.push(maven::plugin_goal("help:effective-pom", repo));
goals.push(format!("-Doutput={}", effective.to_string_lossy()));
}
goals.push(tree);
goals.push("-Dverbose".into());
goals
vec![
"help:effective-pom".into(),
format!("-Doutput={}", effective.to_string_lossy()),
if pinned { DEPENDENCY_TREE.into() } else { "dependency:tree".into() },
"-Dverbose".into(),
]
}
/// The settings' Maven options for the sync runs: the thread count (`-T`, also
@@ -382,8 +367,25 @@ pub fn sync_maven(
verbose: true,
..MavenCache::default()
};
// Where the build resolves its jars, and therefore where the plugin goals are read from.
let repo = maven::local_repository_for(&options.maven_options);
// Where the build resolves its jars, and therefore where the plugin goals are read
// from: `-Dmaven.repo.local=` first, then `<localRepository>` of the `-s` settings,
// then the user's default repository (which `plugin()` resolves itself).
let local_repo: Option<PathBuf> =
options.maven_options.iter().find_map(|a| a.strip_prefix("-Dmaven.repo.local=")).map(PathBuf::from).or_else(
|| {
let mut args = options.maven_options.iter();
while let Some(arg) = args.next() {
let path = match arg.as_str() {
"-s" | "--settings" => args.next().map(String::as_str),
_ => arg.strip_prefix("-s=").or_else(|| arg.strip_prefix("--settings=")),
};
if let Some(path) = path {
return maven::local_repository_of(Path::new(path));
}
}
None
},
);
let mut errors: Vec<String> = Vec::new();
for (n, top) in model.projects.iter().filter(|p| !p.aggregated).enumerate() {
let effective = cache_dir.join(format!("effective-pom-{n}.xml"));
@@ -405,6 +407,7 @@ pub fn sync_maven(
if !options.profiles.is_empty() {
args.push(format!("-P{}", options.profiles.join(",")));
}
let repo = local_repo.clone().or_else(maven::default_local_repo);
args.extend(maven_sync_goals(&effective, options.offline, repo.as_deref()));
progress(SyncProgress { message: format!("Reading {}", top.display_name), fraction: None });
let command = options.maven_command.as_deref().unwrap_or(&top.command);
@@ -422,7 +425,7 @@ pub fn sync_maven(
}
})?;
let effective_projects = std::fs::read_to_string(&effective)
.map(|t| maven::parse_effective_pom_in(&t, repo.as_deref()))
.map(|t| maven::parse_effective_pom_in(&t, local_repo.as_deref()))
.unwrap_or_default();
let trees = maven::parse_dependency_tree(&out.text);
for (key, plugins, deps) in effective_projects {
@@ -950,32 +953,11 @@ mod tests {
#[test]
fn sync_reads_verbose_trees_with_a_pinned_plugin_unless_offline_without_it() {
let tmp = tempfile::tempdir().unwrap();
let help = "org.apache.maven.plugins:maven-help-plugin:3.5.1:effective-pom";
let online = maven_sync_goals(Path::new("e.xml"), false, Some(tmp.path()));
assert_eq!(online, [help, "-Doutput=e.xml", DEPENDENCY_TREE, "-Dverbose"]);
// Offline with neither plugin cached: `effective-pom` is skipped so `mvn -o` does not fail
// on an uncached `maven-help-plugin`, and the tree falls back to the project's own version.
let online = maven_sync_goals(Path::new("e.xml"), false, None);
assert_eq!(online, ["help:effective-pom", "-Doutput=e.xml", DEPENDENCY_TREE, "-Dverbose"]);
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
assert_eq!(offline, ["dependency:tree", "-Dverbose"]);
// #5757 / #5844: offline, plugins in the local repository are named by their coordinates,
// since the prefix needs group metadata a repository filled from a private mirror may lack;
// a repository with `maven-dependency-plugin` but no 3.x `maven-help-plugin` runs only the tree.
for (artifact, version) in [("maven-help-plugin", "2.2"), ("maven-dependency-plugin", "3.6.1")] {
let jar =
tmp.path().join(format!("org/apache/maven/plugins/{artifact}/{version}/{artifact}-{version}.jar"));
std::fs::create_dir_all(jar.parent().unwrap()).unwrap();
std::fs::write(&jar, "").unwrap();
}
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
assert_eq!(offline, ["org.apache.maven.plugins:maven-dependency-plugin:3.6.1:tree", "-Dverbose"]);
let help_jar = tmp.path().join("org/apache/maven/plugins/maven-help-plugin/3.4.0/maven-help-plugin-3.4.0.jar");
std::fs::create_dir_all(help_jar.parent().unwrap()).unwrap();
std::fs::write(&help_jar, "").unwrap();
// A version folder without its jar (only the POM was fetched) doesn't count.
std::fs::create_dir_all(tmp.path().join("org/apache/maven/plugins/maven-help-plugin/3.10.0")).unwrap();
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
assert_eq!(offline[0], "org.apache.maven.plugins:maven-help-plugin:3.4.0:effective-pom");
assert_eq!(offline[2], "org.apache.maven.plugins:maven-dependency-plugin:3.6.1:tree");
assert_eq!(offline[2], "dependency:tree");
assert!(offline.contains(&"-Dverbose".to_owned()));
// Downloaded by an online sync: offline keeps using it, the project's version may be missing.
let jar = tmp.path().join(DEPENDENCY_TREE_JAR);
std::fs::create_dir_all(jar.parent().unwrap()).unwrap();
@@ -1047,7 +1029,7 @@ mod tests {
let cache = tmp.path().join("cache");
sync_maven(&root, &cache, &SyncOptions::default(), &CancellationToken::new(), &|_| {}).unwrap();
let args = std::fs::read_to_string(root.join("mvnw-args")).unwrap();
assert!(args.contains("maven-help-plugin:"), "args: {args}");
assert!(args.contains("help:effective-pom"), "args: {args}");
let loaded = crate::load_linked(&root, &cache, None, &Default::default(), &Default::default());
let maven = loaded.maven.unwrap();
assert!(maven.synced_at.is_some() && maven.sync_error.is_none(), "{:?}", maven.sync_error);
@@ -1072,6 +1054,6 @@ mod tests {
let args = std::fs::read_to_string(root.join("mvnd-args")).unwrap();
// `-T1` pins the daemon serial so the dependency trees stay parseable.
assert!(args.contains("-T1"), "args: {args}");
assert!(args.contains("maven-help-plugin:"), "args: {args}");
assert!(args.contains("help:effective-pom"), "args: {args}");
}
}
+7 -4
View File
@@ -137,16 +137,19 @@ pub fn build(root: &Path, model: &BuildModel, id: &str, cache: &Path) -> IdeResu
// POM's effective identity first; profiles and -D options can change its GAV.
let output = cache.join("artifact-project.txt");
let mut probe = top.options.clone();
let evaluate =
crate::maven::plugin_goal("help:evaluate", crate::maven::local_repository_for(&top.options).as_deref());
probe.extend([
"-f".into(),
root.join(&p.pom).to_string_lossy().into_owned(),
evaluate.clone(),
"help:evaluate".into(),
"-Dexpression=project.id".into(),
format!("-Doutput={}", output.display()),
]);
args.extend(["-DskipTests".into(), "package".into(), evaluate, format!("-Doutput={}", manifest.display())]);
args.extend([
"-DskipTests".into(),
"package".into(),
"help:evaluate".into(),
format!("-Doutput={}", manifest.display()),
]);
return Ok(WebBuild {
command: top.command.clone(),
args,
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "ide-clipboard"
description = "The OS clipboard's file list (file manager <-> project view) and pasted images: Windows CF_HDROP / PNG / CF_DIB, macOS NSPasteboard, Linux text/uri-list via GTK"
description = "The OS clipboard's file list (Explorer <-> project view) and pasted images: Windows CF_HDROP / PNG / CF_DIB or macOS NSPasteboard, no window or message loop"
version.workspace = true
edition.workspace = true
license.workspace = true
+4 -151
View File
@@ -16,12 +16,8 @@
//! thread: AppKit and WebKit also access the general pasteboard there, and its
//! mutable type cache cannot be protected by a mutex in this crate.
//!
//! Linux keeps it as `text/uri-list` (Dolphin, Nautilus and most file
//! managers) or GNOME's `x-special/gnome-copied-files` (`copy` or `cut`, then
//! one URI per line), read and written through the GTK clipboard on X11 and
//! Wayland alike; [`request_files`] reads it without blocking the main loop.
//! Other platforms are not wired up: [`files`] is empty and [`set_files`]
//! fails there.
//! Other platforms (`text/uri-list` on X11) are not wired up: [`files`] is
//! empty and [`set_files`] fails there.
//!
//! [`png`] reads an image (a screenshot) for the project view's Paste, which
//! saves it as a file: `public.png` or `public.tiff` on macOS, the registered
@@ -83,7 +79,6 @@ const HEADER: usize = 20;
/// The absolute paths on the clipboard, empty when it holds no file list.
/// Read failures remain errors so callers can retain an internal copy.
/// Empty on Linux, where [`request_files`] reads it.
pub fn files() -> std::io::Result<Vec<PathBuf>> {
imp::files()
}
@@ -106,7 +101,7 @@ pub fn set_files(paths: &[PathBuf]) -> bool {
/// line. An editor paste inserts names, not the absolute paths the file list
/// keeps for Explorer (#1878; IDEA's text flavor is names too). A path with no
/// file name (a root like `C:\`) keeps its whole path.
#[cfg(any(windows, target_os = "macos", target_os = "linux", test))]
#[cfg(any(windows, target_os = "macos", test))]
fn names_text(paths: &[PathBuf], separator: &str) -> String {
paths
.iter()
@@ -117,82 +112,6 @@ fn names_text(paths: &[PathBuf], separator: &str) -> String {
.join(separator)
}
/// The `file://` URIs in a `text/uri-list` or `x-special/gnome-copied-files`
/// payload as local paths: comments, the `copy`/`cut` line and URIs for other
/// hosts or schemes are skipped.
#[cfg(any(target_os = "linux", all(test, unix)))]
fn uri_list_paths(text: &str) -> Vec<PathBuf> {
text.lines().map(str::trim).filter(|line| !line.starts_with('#')).filter_map(uri_to_path).collect()
}
/// A local `file://` URI (`file:///a%20b` or `file://localhost/a%20b`) as a
/// path; its percent-escapes are raw bytes, as GLib writes them.
#[cfg(any(target_os = "linux", all(test, unix)))]
fn uri_to_path(uri: &str) -> Option<PathBuf> {
use std::os::unix::ffi::OsStringExt;
let rest = uri.strip_prefix("file://")?;
let path = if rest.starts_with('/') { rest } else { rest.strip_prefix("localhost")? };
let path = path.split(['?', '#']).next()?;
if !path.starts_with('/') {
return None;
}
let hex = |b: u8| (b as char).to_digit(16).map(|d| d as u8);
let bytes = path.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
let escaped =
(bytes[i] == b'%').then(|| Some((hex(*bytes.get(i + 1)?)? << 4) | hex(*bytes.get(i + 2)?)?)).flatten();
match escaped {
Some(b) => {
out.push(b);
i += 3;
}
None => {
out.push(bytes[i]);
i += 1;
}
}
}
Some(PathBuf::from(std::ffi::OsString::from_vec(out)))
}
/// `path` as a `file://` URI, every byte outside the unreserved set and `/`
/// percent-escaped.
#[cfg(any(target_os = "linux", all(test, unix)))]
fn file_uri(path: &std::path::Path) -> String {
use std::fmt::Write;
use std::os::unix::ffi::OsStrExt;
let mut uri = String::from("file://");
for &b in path.as_os_str().as_bytes() {
if b.is_ascii_alphanumeric() || b"/-._~".contains(&b) {
uri.push(b as char);
} else {
let _ = write!(uri, "%{b:02X}");
}
}
uri
}
/// Reads the clipboard's file list without blocking: `text/uri-list` first,
/// then GNOME's list, and calls `done` with the paths (empty without a list).
/// Call on the main thread; `done` runs there later.
#[cfg(target_os = "linux")]
pub fn request_files(done: impl FnOnce(Vec<PathBuf>) + 'static) {
use gtk::gdk::{Atom, SELECTION_CLIPBOARD};
fn paths_in(data: &gtk::SelectionData) -> Vec<PathBuf> {
// A failed request has a negative length and no data.
if data.length() <= 0 { Vec::new() } else { uri_list_paths(&String::from_utf8_lossy(&data.data())) }
}
gtk::Clipboard::get(&SELECTION_CLIPBOARD).request_contents(&Atom::intern(imp::URI_LIST), move |board, data| {
let paths = paths_in(data);
if !paths.is_empty() {
return done(paths);
}
board.request_contents(&Atom::intern(imp::GNOME_COPIED), move |_, data| done(paths_in(data)));
});
}
/// `DROPFILES` for `paths`, in the wide form so names outside the ANSI code
/// page survive. Empty paths are skipped.
pub fn encode(paths: &[PathBuf]) -> Vec<u8> {
@@ -809,25 +728,8 @@ mod imp {
}
}
#[cfg(target_os = "linux")]
pub const URI_LIST: &str = "text/uri-list";
#[cfg(target_os = "linux")]
pub const GNOME_COPIED: &str = "x-special/gnome-copied-files";
pub fn has_files() -> bool {
#[cfg(target_os = "linux")]
{
gtk::Clipboard::get(&gtk::gdk::SELECTION_CLIPBOARD).wait_for_targets().is_some_and(|targets| {
targets.into_iter().any(|target| {
let name = target.name();
name == URI_LIST || name == GNOME_COPIED
})
})
}
#[cfg(not(target_os = "linux"))]
{
false
}
false
}
pub fn has_image() -> bool {
@@ -845,33 +747,6 @@ mod imp {
Ok(Vec::new())
}
/// Offers `paths` as `text/uri-list` (KDE and most file managers), GNOME's
/// list (Nautilus, Thunar) and their names as text, rendered on request.
#[cfg(target_os = "linux")]
pub fn set_files(paths: &[PathBuf]) -> bool {
use gtk::{TargetEntry, TargetFlags};
let uris: Vec<String> = paths.iter().map(|p| super::file_uri(p)).collect();
let uri_list: String = uris.iter().map(|uri| format!("{uri}\r\n")).collect();
let gnome = format!("copy\n{}", uris.join("\n"));
let names = super::names_text(paths, "\n");
let entry = |name: &str, info: u32| TargetEntry::new(name, TargetFlags::empty(), info);
let targets = [
entry(URI_LIST, 0),
entry(GNOME_COPIED, 1),
entry("UTF8_STRING", 2),
entry("text/plain;charset=utf-8", 2),
entry("text/plain", 2),
];
gtk::Clipboard::get(&gtk::gdk::SELECTION_CLIPBOARD).set_with_data(&targets, move |_, data, info| match info {
0 => data.set(&data.target(), 8, uri_list.as_bytes()),
1 => data.set(&data.target(), 8, gnome.as_bytes()),
_ => {
let _ = data.set_text(&names);
}
})
}
#[cfg(not(target_os = "linux"))]
pub fn set_files(_paths: &[PathBuf]) -> bool {
false
}
@@ -894,28 +769,6 @@ mod tests {
list.iter().map(PathBuf::from).collect()
}
#[cfg(unix)]
#[test]
fn file_manager_uri_lists_become_paths() {
// Dolphin: CRLF-separated `text/uri-list`, with a comment line.
let kde = "# copied\r\nfile:///home/u/a%20b.txt\r\nfile://localhost/home/u/%E6%A1%8C%E9%9D%A2\r\n";
assert_eq!(uri_list_paths(kde), paths(&["/home/u/a b.txt", "/home/u/桌面"]));
// Nautilus/Thunar: `copy` or `cut`, then one URI per line.
assert_eq!(uri_list_paths("cut\nfile:///tmp/x\nfile:///tmp/y"), paths(&["/tmp/x", "/tmp/y"]));
// Other hosts and schemes are not local files.
assert!(uri_list_paths("file://server/share/x\nhttps://example.com/x\nsmb:///x").is_empty());
}
#[cfg(unix)]
#[test]
fn written_uris_read_back_as_the_same_paths() {
let list = paths(&["/home/u/a b#1%.txt", "/home/u/桌面/项目", "/tmp/plain-name_1.~"]);
let uris: Vec<String> = list.iter().map(|p| file_uri(p)).collect();
assert_eq!(uris[0], "file:///home/u/a%20b%231%25.txt");
assert_eq!(uris[2], "file:///tmp/plain-name_1.~");
assert_eq!(uri_list_paths(&uris.join("\r\n")), list);
}
#[test]
fn a_written_list_reads_back_unchanged() {
let list = paths(&["C:/work/project/a.txt", "C:/work/project/sub"]);
+1 -5
View File
@@ -15,16 +15,12 @@ specta.workspace = true
specta-typescript.workspace = true
thiserror.workspace = true
tokio-util.workspace = true
portable-pty.workspace = true
[dev-dependencies]
sha2 = "0.10"
tempfile.workspace = true
[target.'cfg(unix)'.dependencies]
libc = "0.2"
[target.'cfg(windows)'.dependencies]
dirs.workspace = true
tracing.workspace = true
windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading"] }
windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading"] }
-21
View File
@@ -1,21 +0,0 @@
Copyright (c) Microsoft Corporation. All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -1,39 +0,0 @@
# Bundled Windows console host
Unmodified files from Microsoft's MIT-licensed
[Microsoft.Windows.Console.ConPTY 1.25.260930003](https://www.nuget.org/packages/Microsoft.Windows.Console.ConPTY/1.25.260930003).
The system ConPTY on Windows 10 build 19045 consumes alternate-screen transitions; xterm then
puts full-screen applications' redraws in normal scrollback. A current console host
preserves those transitions, including while resizing and updating a running TUI.
The package is pinned, checked in and embedded by `ide-core`, so desktop, server,
Run and debugger builds work offline and do not depend on another installed IDE.
Only the target architecture is embedded, along with its MIT license. `src/pty.rs`
extracts them atomically to a versioned user cache and preloads the DLL's absolute
path before portable-pty initializes.
Windows reuses that module when portable-pty loads `conpty.dll` by name. Loading
failure is logged and falls back to the system backend. Windows builds before
19041 also retain the system backend.
Source archive:
`https://api.nuget.org/v3-flatcontainer/microsoft.windows.console.conpty/1.25.260930003/microsoft.windows.console.conpty.1.25.260930003.nupkg`
Archive SHA-256: `02b07b349af66d801159bdf9e440d4a1ce78bb951f37fc8609731665afdae7ee`
For each architecture, `conpty.dll` comes from
`runtimes/win-<arch>/native/conpty.dll`, and `OpenConsole.exe` from
`build/native/runtimes/<arch>/OpenConsole.exe` in that archive. Preserve the pair and
the license when updating; update `VERSION` in `src/pty.rs` and these checksums too.
| File | SHA-256 |
| --------------------- | ------------------------------------------------------------------ |
| arm64/conpty.dll | `151a02355227710c20c9f8f1eaf68ac4668aa09cdc921adc7ec661804d8eb1bf` |
| arm64/OpenConsole.exe | `4313825a3ba634d113cc6ed3bc8ce735e3c19d360cecd985794787479469f91f` |
| x64/conpty.dll | `feeef341d891643c62d30b6b07800bc70f0bc148f44cb8c3bee84aa557ae805a` |
| x64/OpenConsole.exe | `3d66b23d0a71bb8eed2b77edc8b9df9bf54ce6c8fb74c863a30e760997f80586` |
| x86/conpty.dll | `d145f621bf64a9da3b7395587ddef9831ca404805d8987ec8c9903d0c4603d93` |
| x86/OpenConsole.exe | `e3e475547d57da0689dc9fc5e0101d10390e2a4719a6eb5dcad569f6cb33c1a3` |
Verification: `cargo test -p ide-core pty::`. `pty::checksums` checks the embedded files against the table above on every platform. The native PTY test launches a child
console application and requires alternate-screen entry and exit to reach the
reader; a system ConPTY that consumes them fails this check.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
-1
View File
@@ -25,7 +25,6 @@ pub mod project_dir;
pub mod project_env;
pub mod project_roots;
pub mod proxy_settings;
pub mod pty;
pub mod real_path;
pub mod remote_settings;
pub mod settings;
-254
View File
@@ -1,254 +0,0 @@
//! The PTY backend shared by terminals, Run consoles and debugger launchers.
pub fn native_pty_system() -> Box<dyn portable_pty::PtySystem + Send> {
#[cfg(windows)]
windows::initialize();
portable_pty::native_pty_system()
}
#[cfg(windows)]
mod windows {
use std::fs;
use std::io::{self, Write};
use std::os::windows::ffi::OsStrExt;
use std::path::Path;
use std::sync::OnceLock;
use std::sync::atomic::{AtomicU64, Ordering};
use windows_sys::Win32::Foundation::FreeLibrary;
use windows_sys::Win32::System::LibraryLoader::{
GetProcAddress, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW,
};
const VERSION: &str = "1.25.260930003";
#[cfg(target_arch = "x86_64")]
const RUNTIME: (&str, &[u8], &[u8]) = (
"x64",
include_bytes!("../resources/conpty/x64/conpty.dll"),
include_bytes!("../resources/conpty/x64/OpenConsole.exe"),
);
#[cfg(target_arch = "aarch64")]
const RUNTIME: (&str, &[u8], &[u8]) = (
"arm64",
include_bytes!("../resources/conpty/arm64/conpty.dll"),
include_bytes!("../resources/conpty/arm64/OpenConsole.exe"),
);
#[cfg(target_arch = "x86")]
const RUNTIME: (&str, &[u8], &[u8]) = (
"x86",
include_bytes!("../resources/conpty/x86/conpty.dll"),
include_bytes!("../resources/conpty/x86/OpenConsole.exe"),
);
pub(super) fn initialize() -> bool {
static BUNDLED: OnceLock<bool> = OnceLock::new();
*BUNDLED.get_or_init(|| {
if !crate::platform::windows_build_number().is_some_and(|build| build >= 19041) {
return false;
}
match load() {
Ok(()) => true,
Err(error) => {
tracing::warn!(%error, "bundled ConPTY unavailable; using the system terminal backend");
false
}
}
})
}
fn load() -> io::Result<()> {
let cache = dirs::cache_dir().ok_or_else(|| io::Error::other("no user cache directory"))?;
let directory = cache.join("OpenIDEA").join("conpty").join(VERSION).join(RUNTIME.0);
fs::create_dir_all(&directory)?;
install(&directory.join("LICENSE.txt"), include_bytes!("../resources/conpty/LICENSE"))?;
install(&directory.join("OpenConsole.exe"), RUNTIME.2)?;
let library = directory.join("conpty.dll");
install(&library, RUNTIME.1)?;
let wide: Vec<u16> = library.as_os_str().encode_wide().chain(Some(0)).collect();
// portable-pty 0.9 opens conpty.dll by name. Preload our verified absolute path:
// Windows reuses this module, without adding the project directory to DLL search.
// SAFETY: the path is terminated and the module is retained for the process lifetime.
let module = unsafe {
LoadLibraryExW(
wide.as_ptr(),
std::ptr::null_mut(),
LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32,
)
};
if module.is_null() {
return Err(io::Error::last_os_error());
}
for name in [c"CreatePseudoConsole", c"ResizePseudoConsole", c"ClosePseudoConsole"] {
// SAFETY: `module` is loaded and each name is a terminated export name.
if unsafe { GetProcAddress(module, name.as_ptr().cast()) }.is_none() {
// SAFETY: no PTY uses this rejected module yet; release our load reference.
unsafe { FreeLibrary(module) };
return Err(io::Error::other("bundled ConPTY lacks the portable-pty exports"));
}
}
// Keep this reference for the process lifetime, including between PTY sessions.
tracing::info!(path = %library.display(), version = VERSION, "loaded bundled ConPTY");
Ok(())
}
fn install(path: &Path, data: &[u8]) -> io::Result<()> {
if fs::read(path).is_ok_and(|existing| existing == data) {
return Ok(());
}
static NEXT: AtomicU64 = AtomicU64::new(0);
let pending =
path.with_extension(format!("{}-{}.tmp", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
let result = (|| {
let mut file = fs::OpenOptions::new().write(true).create_new(true).open(&pending)?;
file.write_all(data)?;
file.sync_all()?;
drop(file);
match fs::rename(&pending, path) {
Ok(()) => Ok(()),
Err(_) if fs::read(path).is_ok_and(|existing| existing == data) => Ok(()),
Err(error) => Err(error),
}
})();
let _ = fs::remove_file(pending);
result
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn installs_atomically_and_repairs_incomplete_files() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("conpty.dll");
fs::write(&path, b"partial").unwrap();
std::thread::scope(|scope| {
for _ in 0..8 {
let path = &path;
scope.spawn(move || install(path, b"complete runtime").unwrap());
}
});
assert_eq!(fs::read(&path).unwrap(), b"complete runtime");
assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
}
#[test]
fn loads_the_bundled_backend() {
assert!(initialize());
}
#[test]
fn conpty_output_child() {
if std::env::var_os("OPENIDEA_CONPTY_TEST_CHILD").is_none() {
return;
}
use windows_sys::Win32::System::Console::{
ENABLE_VIRTUAL_TERMINAL_PROCESSING, GetConsoleMode, GetStdHandle, STD_OUTPUT_HANDLE, SetConsoleMode,
};
// SAFETY: the inherited console output handle and a local writable mode word.
unsafe {
let output = GetStdHandle(STD_OUTPUT_HANDLE);
let mut mode = 0;
assert_ne!(GetConsoleMode(output, &mut mode), 0);
assert_ne!(SetConsoleMode(output, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING), 0);
}
std::io::stdout()
.write_all(b"\x1b[?1049h\x1b[2J\x1b[HWorking (3m 19s)\x1b[1;1H\x1b[2KWorking (2m 59s)\x1b[?1049l\r\nVT_DONE\r\n")
.unwrap();
std::io::stdout().flush().unwrap();
}
#[test]
fn conpty_preserves_alternate_screen_transitions() {
use std::io::Read;
use std::sync::mpsc;
use std::time::{Duration, Instant};
let pair = super::super::native_pty_system().openpty(portable_pty::PtySize::default()).unwrap();
let mut reader = pair.master.try_clone_reader().unwrap();
let mut writer = pair.master.take_writer().unwrap();
let mut command = portable_pty::CommandBuilder::new(std::env::current_exe().unwrap());
command.args(["--exact", "pty::windows::tests::conpty_output_child", "--nocapture"]);
command.env("OPENIDEA_CONPTY_TEST_CHILD", "1");
let mut child = pair.slave.spawn_command(command).unwrap();
drop(pair.slave);
let (tx, rx) = mpsc::channel();
let reading = std::thread::spawn(move || {
let mut bytes = [0; 4096];
while let Ok(count) = reader.read(&mut bytes) {
if count == 0 || tx.send(bytes[..count].to_vec()).is_err() {
break;
}
}
});
let deadline = Instant::now() + Duration::from_secs(10);
let mut output = Vec::new();
let mut cursor_replied = false;
while Instant::now() < deadline {
if let Ok(bytes) = rx.recv_timeout(Duration::from_millis(50)) {
output.extend_from_slice(&bytes);
if !cursor_replied && output.windows(4).any(|s| s == b"\x1b[6n") {
writer.write_all(b"\x1b[1;1R").unwrap();
cursor_replied = true;
}
if output.windows(7).any(|s| s == b"VT_DONE") {
break;
}
}
}
let _ = child.kill();
let _ = child.wait();
drop(writer);
drop(pair.master);
reading.join().unwrap();
let output = String::from_utf8_lossy(&output);
assert!(output.contains("\x1b[?1049h"), "alternate screen entry missing: {output:?}");
assert!(output.contains("\x1b[?1049l"), "alternate screen exit missing: {output:?}");
}
}
}
/// The embedded runtime is the pinned NuGet package's files (`resources/conpty/README.md`).
#[cfg(test)]
mod checksums {
use sha2::{Digest, Sha256};
const FILES: [(&str, &[u8], &str); 6] = [
(
"arm64/conpty.dll",
include_bytes!("../resources/conpty/arm64/conpty.dll"),
"151a02355227710c20c9f8f1eaf68ac4668aa09cdc921adc7ec661804d8eb1bf",
),
(
"arm64/OpenConsole.exe",
include_bytes!("../resources/conpty/arm64/OpenConsole.exe"),
"4313825a3ba634d113cc6ed3bc8ce735e3c19d360cecd985794787479469f91f",
),
(
"x64/conpty.dll",
include_bytes!("../resources/conpty/x64/conpty.dll"),
"feeef341d891643c62d30b6b07800bc70f0bc148f44cb8c3bee84aa557ae805a",
),
(
"x64/OpenConsole.exe",
include_bytes!("../resources/conpty/x64/OpenConsole.exe"),
"3d66b23d0a71bb8eed2b77edc8b9df9bf54ce6c8fb74c863a30e760997f80586",
),
(
"x86/conpty.dll",
include_bytes!("../resources/conpty/x86/conpty.dll"),
"d145f621bf64a9da3b7395587ddef9831ca404805d8987ec8c9903d0c4603d93",
),
(
"x86/OpenConsole.exe",
include_bytes!("../resources/conpty/x86/OpenConsole.exe"),
"e3e475547d57da0689dc9fc5e0101d10390e2a4719a6eb5dcad569f6cb33c1a3",
),
];
#[test]
fn embedded_runtime_matches_the_pinned_package() {
for (name, bytes, expected) in FILES {
let actual: String = Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect();
assert_eq!(actual, expected, "{name}");
}
}
}
-11
View File
@@ -1218,7 +1218,6 @@ pub struct LanguagesSettings {
pub markdown: MarkdownSettings,
pub arduino: ArduinoSettings,
pub zig: ZigSettings,
pub flutter: FlutterSettings,
}
impl Default for LanguagesSettings {
@@ -1250,7 +1249,6 @@ impl Default for LanguagesSettings {
markdown: MarkdownSettings::default(),
arduino: ArduinoSettings::default(),
zig: ZigSettings::default(),
flutter: FlutterSettings::default(),
}
}
}
@@ -1517,15 +1515,6 @@ pub struct ZigSettings {
pub zig: String,
}
/// The Flutter plugin's "Flutter SDK path".
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct FlutterSettings {
/// Flutter SDK root (holding `bin/flutter`); its `flutter` and Dart replace the ones on
/// `PATH`. Empty = `PATH`.
pub sdk: String,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct GoSettings {
+14 -15
View File
@@ -897,21 +897,6 @@ impl DebugManager {
if config.adapter == "rdbg" {
rdbg_command_line(&mut spec, &config, &cwd)?;
}
// Flutter: a project depending on the Flutter SDK needs `flutter debug_adapter`
// (the Dart adapter cannot start a program importing `dart:ui`, and hot reload
// is Flutter-only). Plain Dart projects keep the configured `dart`. Before
// `custom_command`, which picks the Flutter SDK setting's `flutter`.
if config.adapter == "dart" {
let program = arguments.get("program").and_then(Value::as_str).map(Path::new);
if force_flutter || is_flutter_project(&cwd, program) {
if spec.command == "dart" {
spec.command = "flutter".into();
}
if let Some(device) = flutter_device {
add_flutter_device(&mut arguments, device);
}
}
}
if let Some(command) = custom_command(&spec.command) {
spec.command = command;
}
@@ -927,6 +912,20 @@ impl DebugManager {
spec.command = python;
}
}
// Flutter: a project depending on the Flutter SDK needs `flutter debug_adapter`
// (the Dart adapter cannot start a program importing `dart:ui`, and hot reload
// is Flutter-only). Plain Dart projects keep the configured `dart`.
if config.adapter == "dart" {
let program = arguments.get("program").and_then(Value::as_str).map(Path::new);
if force_flutter || is_flutter_project(&cwd, program) {
if spec.command == "dart" {
spec.command = "flutter".into();
}
if let Some(device) = flutter_device {
add_flutter_device(&mut arguments, device);
}
}
}
let id = DebugSessionId::next();
let debug_server = take_debug_server(&mut arguments)?;
if let Some(server) = &debug_server {
+1 -2
View File
@@ -1061,8 +1061,7 @@ fn reap_on_exit(mut child: Box<dyn portable_pty::Child + Send + Sync>, exited: A
/// starts a launcher that gives the program its terminal, and the program reads input only from
/// a terminal), forwards its output to the console, and keeps the terminal for typed input.
pub(crate) fn run_in_terminal(s: &Arc<Session>, args: &Value) -> Result<Value, String> {
use ide_core::pty::native_pty_system;
use portable_pty::{CommandBuilder, PtySize};
use portable_pty::{CommandBuilder, PtySize, native_pty_system};
let argv: Vec<String> = args
.get("args")
.and_then(Value::as_array)
+3 -4
View File
@@ -658,7 +658,8 @@ impl DbManager {
let config = self.sources()?.into_iter().find(|s| s.id == id).and_then(|s| s.ssh).map(|s| s.config);
if let Some(c) = config.filter(|c| !c.trim().is_empty()) {
let save = self.ssh.config(&c).map(|c| c.save_secret).unwrap_or(save);
return self.ssh.set_secret(&c, secret, save);
self.ssh.set_secret(&c, secret, save);
return Ok(());
}
self.remember(self.saved_for(id), secrets::ssh_key(id), secret, save).await
}
@@ -759,9 +760,7 @@ impl DbManager {
} else {
if let Some(s) = ssh_secret {
let save = self.ssh.config(config)?.save_secret;
if let Err(e) = self.ssh.set_secret(config, Some(s), save) {
tracing::warn!("could not save the SSH credential: {}", e.message);
}
self.ssh.set_secret(config, Some(s), save);
}
self.ssh.session(config).await?
})
+194 -43
View File
@@ -1,34 +1,23 @@
//! One `dart devtools` server per project window. In `--machine` mode it reports its port as a
//! `server.started` line on stdout.
//! One `dart devtools` server per project window, started when first asked for. In `--machine`
//! mode it reports its port as a `server.started` line on stdout. A server that fails or exits
//! is not restarted on its own: the next request starts a new one.
use crate::flutter_executable;
use crate::server::{Line, Spec, ToolServer};
use crate::{KILL_GRACE, OUTPUT_TAIL, keep_output, read_lines, spawn_watched};
use ide_core::process::{kill_tree, terminate_tree};
use ide_core::tool_path::{find_command, search_path_in};
use parking_lot::{Condvar, Mutex};
use serde_json::Value;
use std::collections::VecDeque;
use std::path::{Path, PathBuf};
use std::time::Duration;
use std::process::Child;
use std::sync::Arc;
use std::time::{Duration, Instant};
const START_TIMEOUT: Duration = Duration::from_secs(60);
/// The address embedded pages are allowed to come from, so never `localhost`.
pub(crate) const HOST: &str = "127.0.0.1";
const HOST: &str = "127.0.0.1";
const ARGS: [&str; 7] = ["devtools", "--machine", "--allow-embedding", "--host", HOST, "--port", "0"];
pub(crate) static DEVTOOLS: Spec = Spec {
name: "Flutter DevTools",
args: &ARGS,
timeout: Duration::from_secs(60),
executable: dart_executable,
not_found: "Dart SDK not found: install Flutter or add it to PATH",
line,
failed: |message| if message.is_empty() { "dart devtools exited".into() } else { message },
};
impl ToolServer {
/// `dart` is the configured one, else the one of the `flutter` on the search path.
pub fn devtools(root: PathBuf, dart: crate::Configured) -> Self {
Self::new(root, &DEVTOOLS, dart)
}
}
fn started_port(line: &str) -> Option<u16> {
let message: Value = serde_json::from_str(line.trim()).ok()?;
if message.get("event")?.as_str()? != "server.started" {
@@ -37,23 +26,186 @@ fn started_port(line: &str) -> Option<u16> {
u16::try_from(message.get("params")?.get("port")?.as_u64()?).ok()
}
fn line(line: &str) -> Line {
match started_port(line) {
Some(port) => Line::Url(format!("http://{HOST}:{port}")),
None => Line::Output(line.to_owned()),
}
}
/// The `dart` of the SDK `flutter` belongs to, so that DevTools matches the debugged app.
fn dart_executable(root: &Path) -> Option<PathBuf> {
flutter_executable(root)
let path = search_path_in(root);
find_command("flutter", &path, root)
.and_then(|flutter| {
// On the search path `flutter` is often a link into the SDK.
let flutter = if cfg!(unix) { std::fs::canonicalize(&flutter).unwrap_or(flutter) } else { flutter };
let dart = flutter.with_file_name(if cfg!(windows) { "dart.bat" } else { "dart" });
dart.is_file().then_some(dart)
})
.or_else(|| find_command("dart", &search_path_in(root), root))
.or_else(|| find_command("dart", &path, root))
}
#[derive(Default)]
enum Status {
#[default]
Stopped,
Starting,
Ready(String),
Failed(String),
}
#[derive(Default)]
struct State {
/// Bumped by every start and stop: a reader of an older process no longer has a say.
generation: u64,
child: Option<Child>,
status: Status,
}
impl State {
fn shut_down(&mut self) {
self.generation += 1;
if let Some(mut child) = self.child.take() {
std::thread::spawn(move || terminate_tree(&mut child, KILL_GRACE));
}
}
}
struct Shared {
root: PathBuf,
/// Replaces the lookup on the search path (tests).
executable: Option<PathBuf>,
timeout: Duration,
state: Mutex<State>,
changed: Condvar,
}
impl Shared {
/// Applies `status` unless this process was replaced or stopped; false if it was.
fn set(&self, generation: u64, status: Status) -> bool {
let mut state = self.state.lock();
if state.generation != generation {
return false;
}
state.status = status;
self.changed.notify_all();
true
}
}
pub struct DevToolsServer(Arc<Shared>);
impl DevToolsServer {
pub fn new(root: PathBuf) -> Self {
Self::with_executable(root, None, START_TIMEOUT)
}
fn with_executable(root: PathBuf, executable: Option<PathBuf>, timeout: Duration) -> Self {
Self(Arc::new(Shared { root, executable, timeout, state: Mutex::default(), changed: Condvar::new() }))
}
/// The server's address, starting it if none runs. Blocks until it is known.
pub fn url(&self) -> Result<String, String> {
let shared = &self.0;
let deadline = Instant::now() + shared.timeout;
let mut state = shared.state.lock();
if matches!(state.status, Status::Stopped | Status::Failed(_)) {
state.generation += 1;
state.status = Status::Starting;
let (shared, generation) = (shared.clone(), state.generation);
std::thread::spawn(move || run(&shared, generation));
}
loop {
match &state.status {
Status::Ready(url) => return Ok(url.clone()),
Status::Failed(message) => return Err(message.clone()),
Status::Stopped => return Err("Flutter DevTools was stopped".into()),
Status::Starting => {}
}
if shared.changed.wait_until(&mut state, deadline).timed_out() {
state.shut_down();
let message = "Flutter DevTools did not start in time".to_owned();
state.status = Status::Failed(message.clone());
shared.changed.notify_all();
return Err(message);
}
}
}
/// Ends the server (project closed, or no longer trusted).
pub fn stop(&self) {
let mut state = self.0.state.lock();
state.shut_down();
state.status = Status::Stopped;
self.0.changed.notify_all();
}
/// Ends the server before returning, for a process about to exit.
pub fn kill(&self) {
let mut state = self.0.state.lock();
state.generation += 1;
state.status = Status::Stopped;
if let Some(mut child) = state.child.take() {
kill_tree(&mut child);
}
self.0.changed.notify_all();
}
}
/// One server's whole life, on its own thread.
fn run(shared: &Arc<Shared>, generation: u64) {
let fail = |message: String| {
shared.set(generation, Status::Failed(message));
};
let Some(executable) = shared.executable.clone().or_else(|| dart_executable(&shared.root)) else {
return fail("Dart SDK not found: install Flutter or add it to PATH".into());
};
let mut child = match spawn_watched(&executable, &ARGS, &shared.root) {
Ok(child) => child,
Err(e) => return fail(format!("could not run {}: {e}", executable.display())),
};
let (Some(stdout), Some(stderr)) = (child.stdout.take(), child.stderr.take()) else {
terminate_tree(&mut child, Duration::ZERO);
return fail("no output pipe".into());
};
{
let mut state = shared.state.lock();
if state.generation != generation {
drop(state);
terminate_tree(&mut child, KILL_GRACE);
return;
}
state.child = Some(child);
}
let tail = Arc::new(Mutex::new(VecDeque::with_capacity(OUTPUT_TAIL)));
let errors = {
let tail = tail.clone();
std::thread::spawn(move || {
read_lines(stderr, |line| {
keep_output(&tail, line);
true
});
})
};
read_lines(stdout, |line| match started_port(line) {
Some(port) => shared.set(generation, Status::Ready(format!("http://{HOST}:{port}"))),
None => {
keep_output(&tail, line);
true
}
});
let _ = errors.join();
let mut state = shared.state.lock();
if state.generation != generation {
return;
}
let child = state.child.take();
state.status = if matches!(state.status, Status::Ready(_)) {
Status::Stopped
} else {
let message = Vec::from(std::mem::take(&mut *tail.lock())).join("\n");
Status::Failed(if message.is_empty() { "dart devtools exited".into() } else { message })
};
shared.changed.notify_all();
drop(state);
if let Some(mut child) = child {
std::thread::spawn(move || terminate_tree(&mut child, Duration::ZERO));
}
}
#[cfg(test)]
@@ -73,15 +225,14 @@ mod tests {
mod process {
use super::*;
use std::os::unix::fs::PermissionsExt;
use std::time::Instant;
const STARTED: &str = r#"echo '{"event":"server.started","params":{"port":4242}}'"#;
fn server(dir: &Path, script: &str, timeout: Duration) -> ToolServer {
fn server(dir: &Path, script: &str, timeout: Duration) -> DevToolsServer {
let path = dir.join("dart");
std::fs::write(&path, format!("#!/bin/sh\necho run >> runs\n{script}")).unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
ToolServer::with_executable(dir.to_owned(), &DEVTOOLS, Box::new(move || Some(path.clone())), timeout)
DevToolsServer::with_executable(dir.to_owned(), Some(path), timeout)
}
fn runs(dir: &Path) -> usize {
@@ -101,8 +252,8 @@ mod tests {
let dir = tempfile::tempdir().unwrap();
let script = format!("echo \"$*\" > args\necho $$ > pid\n{STARTED}\nexec sleep 30");
let devtools = server(dir.path(), &script, Duration::from_secs(10));
assert_eq!(devtools.url(&[]).unwrap(), "http://127.0.0.1:4242");
assert_eq!(devtools.url(&[]).unwrap(), "http://127.0.0.1:4242");
assert_eq!(devtools.url().unwrap(), "http://127.0.0.1:4242");
assert_eq!(devtools.url().unwrap(), "http://127.0.0.1:4242");
assert_eq!(runs(dir.path()), 1);
let args = std::fs::read_to_string(dir.path().join("args")).unwrap();
assert_eq!(args.trim(), ARGS.join(" "));
@@ -120,10 +271,10 @@ mod tests {
fn a_failure_is_reported_and_only_a_new_request_retries() {
let dir = tempfile::tempdir().unwrap();
let devtools = server(dir.path(), "echo boom >&2\nexit 3", Duration::from_secs(10));
assert_eq!(devtools.url(&[]).unwrap_err(), "boom");
assert_eq!(devtools.url().unwrap_err(), "boom");
std::thread::sleep(Duration::from_millis(100));
assert_eq!(runs(dir.path()), 1);
assert_eq!(devtools.url(&[]).unwrap_err(), "boom");
assert_eq!(devtools.url().unwrap_err(), "boom");
assert_eq!(runs(dir.path()), 2);
}
@@ -131,10 +282,10 @@ mod tests {
fn a_server_that_exits_is_not_restarted_until_asked() {
let dir = tempfile::tempdir().unwrap();
let devtools = server(dir.path(), STARTED, Duration::from_secs(10));
devtools.url(&[]).unwrap();
wait_for("the exit to be noticed", || devtools.is_stopped());
devtools.url().unwrap();
wait_for("the exit to be noticed", || matches!(devtools.0.state.lock().status, Status::Stopped));
assert_eq!(runs(dir.path()), 1);
devtools.url(&[]).unwrap();
devtools.url().unwrap();
assert_eq!(runs(dir.path()), 2);
}
@@ -142,7 +293,7 @@ mod tests {
fn a_server_that_never_reports_times_out() {
let dir = tempfile::tempdir().unwrap();
let devtools = server(dir.path(), "exec sleep 30", Duration::from_millis(200));
assert_eq!(devtools.url(&[]).unwrap_err(), "Flutter DevTools did not start in time");
assert_eq!(devtools.url().unwrap_err(), "Flutter DevTools did not start in time");
}
}
}
+8 -27
View File
@@ -10,10 +10,8 @@
//! daemon that fails stays failed until the user restarts it.
mod devtools;
mod server;
mod widget_preview;
pub use server::ToolServer;
pub use devtools::DevToolsServer;
use ide_android::AndroidDevice;
use ide_core::event::{FlutterDaemonStatus, FlutterDevice, FlutterDeviceList, FlutterEmulator};
@@ -191,7 +189,8 @@ impl State {
struct Shared {
root: PathBuf,
sink: SharedSink,
executable: Configured,
/// Replaces the lookup on the search path (tests).
executable: Option<PathBuf>,
state: Mutex<State>,
}
@@ -201,21 +200,16 @@ impl Shared {
}
}
/// The configured `flutter` / `dart` (the Flutter SDK setting), asked at each start; `None`
/// looks it up on the search path.
pub type Configured = Box<dyn Fn() -> Option<PathBuf> + Send + Sync>;
/// One project window's `flutter daemon`, started on first use.
pub struct FlutterDaemon(Arc<Shared>);
impl FlutterDaemon {
pub fn new(root: PathBuf, sink: SharedSink, executable: Configured) -> Self {
Self(Arc::new(Shared { root, sink, executable, state: Mutex::default() }))
pub fn new(root: PathBuf, sink: SharedSink) -> Self {
Self::with_executable(root, sink, None)
}
#[cfg(all(test, unix))]
fn with_executable(root: PathBuf, sink: SharedSink, executable: Option<PathBuf>) -> Self {
Self::new(root, sink, Box::new(move || executable.clone()))
Self(Arc::new(Shared { root, sink, executable, state: Mutex::default() }))
}
/// The current list; starts the daemon unless it already ran. Never blocks on the process.
@@ -277,15 +271,6 @@ impl FlutterDaemon {
}
}
/// Starts a running daemon again, with the SDK the settings now choose.
pub fn sdk_changed(&self) {
let mut state = self.0.state.lock();
if state.status != FlutterDaemonStatus::Stopped {
state.shut_down();
start(&self.0, &mut state);
}
}
/// Ends the daemon (project closed, or no longer trusted).
pub fn stop(&self) {
let mut state = self.0.state.lock();
@@ -400,14 +385,10 @@ fn read_lines(pipe: impl Read, mut on_line: impl FnMut(&str) -> bool) {
}
}
/// The `flutter` that commands run in `root` use.
fn flutter_executable(root: &Path) -> Option<PathBuf> {
find_command("flutter", &search_path_in(root), root)
}
/// One daemon's whole life, on its own thread.
fn run(shared: &Arc<Shared>, generation: u64) {
let executable = (shared.executable)().or_else(|| flutter_executable(&shared.root));
let executable =
shared.executable.clone().or_else(|| find_command("flutter", &search_path_in(&shared.root), &shared.root));
let Some(executable) = executable else {
return finish(shared, generation, FlutterDaemonStatus::NotInstalled);
};
-218
View File
@@ -1,218 +0,0 @@
//! A Flutter tool serving pages for the IDE to embed, one per project window, started when first
//! asked for. It reports its address on stdout. A server that fails or exits is not restarted on
//! its own: the next request starts a new one.
use crate::{KILL_GRACE, OUTPUT_TAIL, keep_output, read_lines, spawn_watched};
use ide_core::process::{kill_tree, terminate_tree};
use parking_lot::{Condvar, Mutex};
use std::collections::VecDeque;
use std::path::{Path, PathBuf};
use std::process::Child;
use std::sync::Arc;
use std::time::{Duration, Instant};
/// What one line of the tool's output says.
pub(crate) enum Line {
/// The page's address: the server is ready.
Url(String),
/// Text worth showing if the server fails.
Output(String),
/// Nothing worth keeping.
Skip,
}
/// How to run one kind of server.
pub(crate) struct Spec {
/// For messages, e.g. "Flutter DevTools".
pub name: &'static str,
pub args: &'static [&'static str],
pub timeout: Duration,
pub executable: fn(&Path) -> Option<PathBuf>,
pub not_found: &'static str,
pub line: fn(&str) -> Line,
/// The failure to report, from the output kept until the tool exited.
pub failed: fn(String) -> String,
}
#[derive(Default)]
enum Status {
#[default]
Stopped,
Starting,
Ready(String),
Failed(String),
}
#[derive(Default)]
struct State {
/// Bumped by every start and stop: a reader of an older process no longer has a say.
generation: u64,
child: Option<Child>,
status: Status,
}
impl State {
fn shut_down(&mut self) {
self.generation += 1;
if let Some(mut child) = self.child.take() {
std::thread::spawn(move || terminate_tree(&mut child, KILL_GRACE));
}
}
}
struct Shared {
root: PathBuf,
spec: &'static Spec,
/// The configured executable; the spec's lookup on the search path without one.
executable: crate::Configured,
timeout: Duration,
state: Mutex<State>,
changed: Condvar,
}
impl Shared {
/// Applies `status` unless this process was replaced or stopped; false if it was.
fn set(&self, generation: u64, status: Status) -> bool {
let mut state = self.state.lock();
if state.generation != generation {
return false;
}
state.status = status;
self.changed.notify_all();
true
}
}
pub struct ToolServer(Arc<Shared>);
impl ToolServer {
pub(crate) fn new(root: PathBuf, spec: &'static Spec, executable: crate::Configured) -> Self {
Self::with_executable(root, spec, executable, spec.timeout)
}
pub(crate) fn with_executable(
root: PathBuf,
spec: &'static Spec,
executable: crate::Configured,
timeout: Duration,
) -> Self {
Self(Arc::new(Shared { root, spec, executable, timeout, state: Mutex::default(), changed: Condvar::new() }))
}
/// The server's address, starting it with `extra` arguments if none runs. Blocks until it is known.
pub fn url(&self, extra: &[String]) -> Result<String, String> {
let shared = &self.0;
let deadline = Instant::now() + shared.timeout;
let mut state = shared.state.lock();
if matches!(state.status, Status::Stopped | Status::Failed(_)) {
state.generation += 1;
state.status = Status::Starting;
let (shared, generation, extra) = (shared.clone(), state.generation, extra.to_vec());
std::thread::spawn(move || run(&shared, generation, &extra));
}
loop {
match &state.status {
Status::Ready(url) => return Ok(url.clone()),
Status::Failed(message) => return Err(message.clone()),
Status::Stopped => return Err(format!("{} was stopped", shared.spec.name)),
Status::Starting => {}
}
if shared.changed.wait_until(&mut state, deadline).timed_out() {
state.shut_down();
let message = format!("{} did not start in time", shared.spec.name);
state.status = Status::Failed(message.clone());
shared.changed.notify_all();
return Err(message);
}
}
}
/// Ends the server (project closed, or no longer trusted).
pub fn stop(&self) {
let mut state = self.0.state.lock();
state.shut_down();
state.status = Status::Stopped;
self.0.changed.notify_all();
}
/// Ends the server before returning, for a process about to exit.
pub fn kill(&self) {
let mut state = self.0.state.lock();
state.generation += 1;
state.status = Status::Stopped;
if let Some(mut child) = state.child.take() {
kill_tree(&mut child);
}
self.0.changed.notify_all();
}
#[cfg(all(test, unix))]
pub(crate) fn is_stopped(&self) -> bool {
matches!(self.0.state.lock().status, Status::Stopped)
}
}
/// One server's whole life, on its own thread.
fn run(shared: &Arc<Shared>, generation: u64, extra: &[String]) {
let spec = shared.spec;
let fail = |message: String| {
shared.set(generation, Status::Failed(message));
};
let Some(executable) = (shared.executable)().or_else(|| (spec.executable)(&shared.root)) else {
return fail(spec.not_found.into());
};
let args: Vec<&str> = spec.args.iter().copied().chain(extra.iter().map(String::as_str)).collect();
let mut child = match spawn_watched(&executable, &args, &shared.root) {
Ok(child) => child,
Err(e) => return fail(format!("could not run {}: {e}", executable.display())),
};
let (Some(stdout), Some(stderr)) = (child.stdout.take(), child.stderr.take()) else {
terminate_tree(&mut child, Duration::ZERO);
return fail("no output pipe".into());
};
{
let mut state = shared.state.lock();
if state.generation != generation {
drop(state);
terminate_tree(&mut child, KILL_GRACE);
return;
}
state.child = Some(child);
}
let tail = Arc::new(Mutex::new(VecDeque::with_capacity(OUTPUT_TAIL)));
let errors = {
let tail = tail.clone();
std::thread::spawn(move || {
read_lines(stderr, |line| {
keep_output(&tail, line);
true
});
})
};
read_lines(stdout, |line| match (spec.line)(line) {
Line::Url(url) => shared.set(generation, Status::Ready(url)),
Line::Output(text) => {
keep_output(&tail, &text);
true
}
Line::Skip => true,
});
let _ = errors.join();
let mut state = shared.state.lock();
if state.generation != generation {
return;
}
let child = state.child.take();
state.status = if matches!(state.status, Status::Ready(_)) {
Status::Stopped
} else {
let message = Vec::from(std::mem::take(&mut *tail.lock())).join("\n");
Status::Failed((spec.failed)(message))
};
shared.changed.notify_all();
drop(state);
if let Some(mut child) = child {
std::thread::spawn(move || terminate_tree(&mut child, Duration::ZERO));
}
}
-118
View File
@@ -1,118 +0,0 @@
//! One `flutter widget-preview` server per project window: the `@Preview` widgets of the project,
//! served as a web page that reloads as they change. Like the Flutter plugins of Android Studio
//! and VS Code it runs on the `web-server` device, in `--machine` mode, where it reports events
//! as bracketed JSON lines and the page's address with `widget_preview.started`. Without
//! `--dtd-url` it starts its own analysis server and Dart Tooling Daemon to find the previews.
use crate::devtools::HOST;
use crate::flutter_executable;
use crate::server::{Line, Spec, ToolServer};
use serde_json::Value;
use std::path::PathBuf;
use std::time::Duration;
/// The release whose `widget-preview start` has the options used here.
const MIN_FLUTTER: &str = "3.38";
static WIDGET_PREVIEW: Spec = Spec {
name: "Flutter Widget Preview",
args: &["widget-preview", "start", "--machine", "--web-server"],
// The first start runs `pub get` and compiles the preview environment.
timeout: Duration::from_secs(300),
executable: flutter_executable,
not_found: "Flutter SDK not found: install Flutter or add it to PATH",
line,
failed,
};
impl ToolServer {
/// `flutter` is the configured one, else the one on the search path.
pub fn widget_preview(root: PathBuf, flutter: crate::Configured) -> Self {
Self::new(root, &WIDGET_PREVIEW, flutter)
}
}
fn line(line: &str) -> Line {
let Ok(Value::Array(messages)) = serde_json::from_str(line.trim()) else {
return Line::Output(line.to_owned());
};
let Some(message) = messages.first() else { return Line::Skip };
let params = &message["params"];
match message["event"].as_str() {
// The server listens on every interface; embedded pages may only come from `HOST`.
Some("widget_preview.started") => params["url"]
.as_str()
.map_or(Line::Skip, |url| Line::Url(url.replacen("//localhost:", &format!("//{HOST}:"), 1))),
Some("widget_preview.logMessage") if matches!(params["level"].as_str(), Some("error" | "warning")) => {
params["message"].as_str().map_or(Line::Skip, |text| Line::Output(text.to_owned()))
}
_ => Line::Skip,
}
}
fn failed(message: String) -> String {
// What an older `flutter` says of a command or an option it doesn't know.
if message.contains("Could not find a") && message.contains(" named \"") {
format!(
"Flutter Widget Preview needs Flutter {MIN_FLUTTER} or later. Upgrade Flutter, then refresh the window."
)
} else if message.is_empty() {
"flutter widget-preview exited".into()
} else {
message
}
}
#[cfg(test)]
mod tests {
use super::*;
fn url(line: &str) -> Option<String> {
match super::line(line) {
Line::Url(url) => Some(url),
_ => None,
}
}
fn output(line: &str) -> Option<String> {
match super::line(line) {
Line::Output(text) => Some(text),
_ => None,
}
}
#[test]
fn started_gives_the_address_on_the_embeddable_host() {
let line = r#"[{"event":"widget_preview.started","params":{"url":"http://localhost:56207"}}]"#;
assert_eq!(url(line).as_deref(), Some("http://127.0.0.1:56207"));
let launch =
r#"[{"event":"widget_preview.app.webLaunchUrl","params":{"url":"http://localhost:1","launched":false}}]"#;
assert_eq!(url(launch), None);
}
#[test]
fn only_errors_warnings_and_plain_text_are_kept() {
let log = |level: &str| {
format!(r#"[{{"event":"widget_preview.logMessage","params":{{"level":"{level}","message":"m"}}}}]"#)
};
assert_eq!(output(&log("error")).as_deref(), Some("m"));
assert_eq!(output(&log("warning")).as_deref(), Some("m"));
assert_eq!(output(&log("status")), None);
assert_eq!(output(r#"[{"event":"widget_preview.initializing","params":{"pid":1}}]"#), None);
assert_eq!(
output("Could not find a command named \"widget-preview\".").as_deref(),
Some("Could not find a command named \"widget-preview\".")
);
}
#[test]
fn an_older_flutter_is_named_as_the_cause() {
for message in
[r#"Could not find a command named "widget-preview"."#, r#"Could not find an option named "--web-server"."#]
{
assert!(failed(message.into()).starts_with("Flutter Widget Preview needs Flutter 3.38"));
}
assert_eq!(failed("pub get failed".into()), "pub get failed");
assert_eq!(failed(String::new()), "flutter widget-preview exited");
}
}
+9 -121
View File
@@ -27,21 +27,17 @@ pub fn data_dir(identifier: &str) -> Result<PathBuf, String> {
}
/// `$OPENIDEA_LOG_DIR/<identifier>` when set, else `~/Library/Logs/<identifier>` on macOS and
/// `logs` in the local data directory elsewhere (Tauri's `app_log_dir`), so a custom location
/// from Settings › System Settings › Caches moves the logs too.
/// `<local data>/<identifier>/logs` elsewhere (Tauri's `app_log_dir`).
pub fn log_dir(identifier: &str) -> Result<PathBuf, String> {
if let Some(var) = std::env::var_os(LOG_ENV).filter(|v| !v.is_empty()) {
return resolve_env(LOG_ENV, Some(var), None, identifier);
let os = if cfg!(target_os = "macos") {
dirs::home_dir().map(|home| home.join("Library/Logs").join(identifier))
} else {
dirs::data_local_dir().map(|dir| dir.join(identifier).join("logs"))
};
match std::env::var_os(LOG_ENV).filter(|v| !v.is_empty()) {
Some(var) => resolve_env(LOG_ENV, Some(var), None, identifier),
None => os.ok_or_else(|| "cannot find the log directory".into()),
}
if cfg!(target_os = "macos") {
return dirs::home_dir()
.map(|home| home.join("Library/Logs").join(identifier))
.ok_or_else(|| "cannot find the log directory".into());
}
startup_local_data_dir(identifier)
.or_else(|_| local_data_dir(identifier))
.map(|dir| dir.join("logs"))
.map_err(|_| "cannot find the log directory".into())
}
/// The directory under `$<env>` when set (absolute, not created here), else under the OS directory.
@@ -221,74 +217,6 @@ fn apply_custom_migration_in(path: &Path, local: &Path) {
}
}
/// WebView2's profile (localStorage, IndexedDB, cookies) inside the directory the windows
/// are given, which on Windows is the local data directory.
pub const WEBVIEW_PROFILE: &str = "EBWebView";
/// Browser caches in a WebView2 profile: rebuilt on demand, so not copied across volumes.
const WEBVIEW_CACHES: [&str; 6] = ["Cache", "Code Cache", "GPUCache", "DawnCache", "GrShaderCache", "ShaderCache"];
/// Brings WebView2's profile into `local` before the first window opens: from a scheduled
/// move's source (Settings › System Settings › Caches), else from the default directory, where
/// windows kept it before they followed a custom location. Runs synchronously, as a window
/// started meanwhile would create an empty profile; a profile already in `local` is never
/// merged into or replaced, and a failed move leaves the old one in place.
pub fn adopt_webview_profile(identifier: &str, local: &Path) {
let scheduled = migration_path(identifier)
.and_then(|path| fs::read(path).ok())
.and_then(|bytes| serde_json::from_slice::<CustomMigration>(&bytes).ok())
.filter(|job| job.to == local)
.map(|job| job.from);
adopt_webview_profile_from(scheduled.into_iter().chain(local_data_dir(identifier).ok()), local);
}
fn adopt_webview_profile_from(sources: impl IntoIterator<Item = PathBuf>, local: &Path) {
let target = local.join(WEBVIEW_PROFILE);
if target.try_exists().unwrap_or(true) {
return;
}
let Some(source) = sources
.into_iter()
.filter(|dir| dir != local)
.map(|dir| dir.join(WEBVIEW_PROFILE))
.find(|profile| fs::symlink_metadata(profile).is_ok_and(|m| m.is_dir()))
else {
return;
};
let result = fs::create_dir_all(local).and_then(|()| match rename_missing(&source, &target) {
Err(error) if rename_failure(&error) == RenameFailure::Copy => {
let staging = local.join(format!(".migration-{}", uuid::Uuid::new_v4()));
let copied = copy_profile(&source, &staging).and_then(|()| rename_missing(&staging, &target));
if staging.exists() {
let _ = remove_entry(&staging);
}
copied.and_then(|()| remove_entry(&source))
}
other => other,
});
match result {
Ok(()) => tracing::info!(?source, ?target, "moved the WebView profile to the local data directory"),
Err(error) => tracing::warn!(?source, ?target, %error, "cannot move the WebView profile; starting a new one"),
}
}
/// [`copy_tree`] without the profile's browser caches.
fn copy_profile(source: &Path, target: &Path) -> io::Result<()> {
let metadata = fs::symlink_metadata(source)?;
if !metadata.is_dir() {
return copy_tree(source, target);
}
fs::create_dir(target)?;
for entry in fs::read_dir(source)? {
let entry = entry?;
if WEBVIEW_CACHES.iter().any(|name| entry.file_name() == *name) {
continue;
}
copy_profile(&entry.path(), &target.join(entry.file_name()))?;
}
Ok(())
}
/// Entries of a local-data tree that move to a newly chosen directory.
/// Non-relocatable tool installs (virtual environments with absolute interpreter
/// paths) stay behind and are reinstalled on demand, as in `migrate_entries`;
@@ -624,46 +552,6 @@ fn relative_wrapper(text: &str, source: &Path) -> String {
mod tests {
use super::*;
#[test]
fn the_webview_profile_moves_into_a_custom_local_directory_once() {
let tmp = tempfile::tempdir().unwrap();
let (default, custom) = (tmp.path().join("default"), tmp.path().join("custom"));
let storage = default.join(WEBVIEW_PROFILE).join("Default/Local Storage");
fs::create_dir_all(&storage).unwrap();
fs::write(storage.join("leveldb"), "history").unwrap();
adopt_webview_profile_from([default.clone()], &custom);
let moved = custom.join(WEBVIEW_PROFILE).join("Default/Local Storage/leveldb");
assert_eq!(fs::read_to_string(&moved).unwrap(), "history");
assert!(!default.join(WEBVIEW_PROFILE).exists());
// A profile already in place is never replaced by an older one.
fs::create_dir_all(default.join(WEBVIEW_PROFILE)).unwrap();
adopt_webview_profile_from([default.clone()], &custom);
assert!(default.join(WEBVIEW_PROFILE).exists());
assert_eq!(fs::read_to_string(&moved).unwrap(), "history");
}
#[test]
fn the_default_directory_keeps_its_own_profile() {
let tmp = tempfile::tempdir().unwrap();
let profile = tmp.path().join(WEBVIEW_PROFILE);
fs::create_dir_all(&profile).unwrap();
adopt_webview_profile_from([tmp.path().to_path_buf()], tmp.path());
assert!(profile.is_dir());
}
#[test]
fn a_copied_profile_leaves_the_browser_caches_behind() {
let tmp = tempfile::tempdir().unwrap();
let source = tmp.path().join("source");
fs::create_dir_all(source.join("Default/Cache/Cache_Data")).unwrap();
fs::create_dir_all(source.join("Default/IndexedDB")).unwrap();
fs::write(source.join("Default/Cache/Cache_Data/f_1"), "x").unwrap();
fs::write(source.join("Default/IndexedDB/db"), "kept").unwrap();
copy_profile(&source, &tmp.path().join("copy")).unwrap();
assert_eq!(fs::read_to_string(tmp.path().join("copy/Default/IndexedDB/db")).unwrap(), "kept");
assert!(!tmp.path().join("copy/Default/Cache").exists());
}
#[test]
fn config_data_and_log_dirs_follow_the_os_unless_their_variable_is_set() {
let os = Some(PathBuf::from("/os"));
+48 -118
View File
@@ -118,8 +118,6 @@ pub struct Host {
pub(crate) heap_windows: Mutex<HashMap<ide_heap::HeapSnapshotId, String>>,
pub(crate) heap_requests: ops::heap::HeapRequests,
pub(crate) rebase_editors: Arc<ops::vcs::RebaseEditors>,
/// The IDE's Java build: resident javac processes shared by every window's launches.
pub(crate) java_build: Arc<ide_build::jbuild::JavaBuildService>,
/// SSH connections of Settings › SSH Configurations.
pub ssh: Arc<ide_ssh::SshManager>,
/// SFTP deployment, remote file editing and runs on run targets.
@@ -146,31 +144,11 @@ pub struct Host {
requests: requests::Requests,
project_requests: RwLock<HashMap<String, Vec<RequestId>>>,
/// Shutdowns of projects closed with [`Host::close_project_detached`].
closing: parking_lot::Mutex<Vec<DetachedClose>>,
closing: parking_lot::Mutex<Vec<std::thread::JoinHandle<()>>>,
/// One open at a time per window (see [`Host::opening`]).
open_locks: parking_lot::Mutex<HashMap<String, Arc<parking_lot::Mutex<()>>>>,
}
struct DetachedClose {
root: Option<std::path::PathBuf>,
handle: std::thread::JoinHandle<()>,
}
struct ShutdownWork {
notebooks: Vec<Arc<notebook::NotebookService>>,
bridges: Vec<Arc<kotlin_bridge::KotlinBridge>>,
lsp: Option<Arc<ide_lsp::LspManager>>,
debug: Option<(Arc<ide_dap::DebugManager>, String, Option<std::path::PathBuf>)>,
agents: Vec<Arc<ide_agent::AgentManager>>,
terminals: Option<ide_terminal::DetachedTerminals>,
processes: Option<ide_run::DetachedProcessKills>,
retired: Option<Arc<Project>>,
}
fn roots_overlap(a: &std::path::Path, b: &std::path::Path) -> bool {
a == b || a.starts_with(b) || b.starts_with(a)
}
/// How long exit waits for project shutdown before giving up.
const EXIT_SHUTDOWN_WAIT: std::time::Duration = std::time::Duration::from_secs(10);
@@ -212,8 +190,6 @@ impl Host {
let sink_for: SinkFactory = diagnostics_store::recording_sink_factory(diagnostics.clone(), sink_for);
let global_settings = SettingsStore::load(&config_dir, None);
let ssh = Arc::new(ide_ssh::SshManager::new(data_dir.join("ssh-passwords.json")));
let migration = ssh.clone();
runtime.spawn_blocking(move || migration.start_password_migration());
ssh.set_configs(global_settings.effective().ssh.configs);
let host = Self {
plugin_host: RwLock::default(),
@@ -249,7 +225,6 @@ impl Host {
heap_windows: Mutex::default(),
heap_requests: Default::default(),
rebase_editors: Default::default(),
java_build: Default::default(),
languages,
syntax,
config_dir,
@@ -356,7 +331,7 @@ impl Host {
/// [`Self::close_project_detached`] there.
pub fn close_project(&self, window: &str) {
if let Some(shutdown) = self.begin_close(window) {
self.wait_blocking(shutdown.handle);
self.wait_blocking(shutdown);
}
}
@@ -366,15 +341,15 @@ impl Host {
pub fn close_project_detached(&self, window: &str) {
if let Some(shutdown) = self.begin_close(window) {
let mut closing = self.closing.lock();
closing.retain(|entry| !entry.handle.is_finished());
closing.retain(|handle| !handle.is_finished());
closing.push(shutdown);
}
}
/// Detaches the project from `window` synchronously so the caller (including the UI
/// event-loop thread) never blocks on disk I/O or process shutdown, and returns the
/// background handle that stops its workers, agents, terminals and processes.
fn begin_close(&self, window: &str) -> Option<DetachedClose> {
/// Detaches the project from `window` and stops what it started, synchronously,
/// so the window can open another project at once. Returns the thread that
/// finishes shutting down its workers.
fn begin_close(&self, window: &str) -> Option<std::thread::JoinHandle<()>> {
self.mcp_reports.forget_window(window);
self.mcp_requests.forget_window(window);
self.mcp_agent_runs.forget_window(window);
@@ -421,115 +396,77 @@ impl Host {
phpstan.stop();
}
project.documents.clear_workspace_edit_history();
project.agents.detach_sinks();
project.agents.shutdown();
project.flutter.stop();
project.devtools.stop();
project.widget_preview.stop();
project.notebooks.stop_admission();
// Detach runs and terminals synchronously so a new project opened in the same window
// never collides with them, then terminate them and shut down agents on the background thread.
let processes = self.processes.detach_project_kills(&project.root);
let terminals = self.terminals.detach_key(self.owner_window(window));
let root = (!project.light).then(|| project.root.clone());
let handle = self.spawn_project_shutdown(ShutdownWork {
notebooks: vec![project.notebooks.clone()],
bridges: project.kotlin_bridge.iter().cloned().collect(),
lsp: Some(project.lsp.clone()),
// What the closing window started goes with it — the builds and searches it
// asked for, its runs, its shells and its debug sessions — and its language
// servers shut down.
self.processes.kill_project(&project.root);
self.terminals.kill_key(self.owner_window(window));
Some(self.spawn_project_shutdown(
vec![project.notebooks.clone()],
project.kotlin_bridge.iter().cloned().collect(),
Some(project.lsp.clone()),
// Debug sessions under the root belong to windows: a project served without one starts none.
debug: Some((self.debugger.clone(), window.to_owned(), (!background).then(|| project.root.clone()))),
agents: vec![project.agents.clone()],
terminals: Some(terminals),
processes: Some(processes),
retired: Some(project),
});
Some(DetachedClose { root, handle })
Some((self.debugger.clone(), window.to_owned(), (!background).then(|| project.root.clone()))),
Some(project),
))
}
/// Project/window destruction must finish owned kernel and agent cleanup, not enqueue
/// Project/window destruction must finish owned kernel cleanup, not enqueue
/// work which can be lost as the desktop runtime exits: the returned thread is
/// joined by the closer or, for a detached close, before exit.
fn spawn_project_shutdown(&self, work: ShutdownWork) -> std::thread::JoinHandle<()> {
for bridge in &work.bridges {
fn spawn_project_shutdown(
&self,
notebooks: Vec<Arc<notebook::NotebookService>>,
bridges: Vec<Arc<kotlin_bridge::KotlinBridge>>,
lsp: Option<Arc<ide_lsp::LspManager>>,
debug: Option<(Arc<ide_dap::DebugManager>, String, Option<std::path::PathBuf>)>,
retired: Option<Arc<Project>>,
) -> std::thread::JoinHandle<()> {
for bridge in &bridges {
bridge.stop();
}
for service in &work.notebooks {
for service in &notebooks {
service.stop_admission();
}
let runtime = self.runtime.clone();
std::thread::spawn(move || {
if let Some(processes) = work.processes {
processes.kill();
}
if let Some(terminals) = work.terminals {
terminals.terminate();
}
let agents = (!work.agents.is_empty()).then(|| {
let agents = work.agents;
std::thread::spawn(move || {
for manager in agents {
manager.shutdown();
}
})
});
// Dropping the project stops its file watcher and index worker, which first finish the
// batch they are applying (many file events while a build writes its output), so it
// isn't done on the closing caller's thread (the UI thread for a window close).
let retired = work.retired.map(|project| std::thread::spawn(move || drop(project)));
let retired = retired.map(|project| std::thread::spawn(move || drop(project)));
runtime.block_on(async move {
for bridge in work.bridges {
for bridge in bridges {
bridge.shutdown().await;
}
for service in work.notebooks {
for service in notebooks {
service.shutdown().await;
}
if let Some(lsp) = work.lsp {
if let Some(lsp) = lsp {
lsp.shutdown_all().await;
}
if let Some((debug, key, root)) = work.debug {
if let Some((debug, key, root)) = debug {
debug.stop_key(&key).await;
if let Some(root) = root {
debug.stop_under(&root).await;
}
}
});
if let Some(agents) = agents {
let _ = agents.join();
}
if let Some(retired) = retired {
let _ = retired.join();
}
})
}
/// Waits for every detached close to finish.
#[cfg(test)]
/// Waits for detached closes, so a project opened next never races the
/// language servers of one still shutting down (e.g. over a shared workspace).
pub(crate) fn wait_detached_closes(&self) {
let pending: Vec<_> = self.closing.lock().drain(..).collect();
for shutdown in pending {
self.wait_blocking(shutdown.handle);
}
}
/// Waits only for detached closes whose root overlaps `root`, so opening an unrelated project
/// never blocks on another project's background shutdown.
pub(crate) fn wait_detached_closes_for(&self, root: &std::path::Path) {
let matching = {
let mut closing = self.closing.lock();
closing.retain(|entry| !entry.handle.is_finished());
let mut wait = Vec::new();
let mut keep = Vec::new();
for entry in closing.drain(..) {
if entry.root.as_deref().is_some_and(|other| roots_overlap(other, root)) {
wait.push(entry.handle);
} else {
keep.push(entry);
}
}
*closing = keep;
wait
};
for handle in matching {
self.wait_blocking(handle);
self.wait_blocking(shutdown);
}
}
@@ -555,23 +492,18 @@ impl Host {
/// Called before the desktop runtime exits, including update/restart exits, on
/// the event-loop thread: waits for detached closes and the open projects'
/// kernels and agents, but no longer than [`EXIT_SHUTDOWN_WAIT`], so a runtime worker
/// kernels, but no longer than [`EXIT_SHUTDOWN_WAIT`], so a runtime worker
/// stuck on the event loop cannot keep the process from exiting.
pub fn shutdown_notebooks_on_exit(&self) {
let projects = self.projects();
let mut pending: Vec<_> = self.closing.lock().drain(..).map(|entry| entry.handle).collect();
if !projects.is_empty() {
pending.push(self.spawn_project_shutdown(ShutdownWork {
notebooks: projects.iter().map(|project| project.notebooks.clone()).collect(),
bridges: projects.iter().filter_map(|project| project.kotlin_bridge.clone()).collect(),
lsp: None,
debug: None,
agents: projects.iter().map(|project| project.agents.clone()).collect(),
terminals: None,
processes: None,
retired: None,
}));
}
let mut pending: Vec<_> = self.closing.lock().drain(..).collect();
pending.push(self.spawn_project_shutdown(
projects.iter().map(|project| project.notebooks.clone()).collect(),
projects.iter().filter_map(|project| project.kotlin_bridge.clone()).collect(),
None,
None,
None,
));
let deadline = std::time::Instant::now() + EXIT_SHUTDOWN_WAIT;
while pending.iter().any(|handle| !handle.is_finished()) {
if std::time::Instant::now() >= deadline {
@@ -596,7 +528,6 @@ impl Host {
for project in self.projects() {
project.flutter.kill();
project.devtools.kill();
project.widget_preview.kill();
}
}
@@ -639,7 +570,6 @@ impl Host {
project.files_events_active.store(false, std::sync::atomic::Ordering::Release);
project.flutter.kill();
project.devtools.kill();
project.widget_preview.kill();
}
for project in &projects {
project.plugin_diagnostics.close();
+2 -4
View File
@@ -33,10 +33,8 @@ fn get_workspace_roots() -> Tool {
"get_workspace_roots",
"Returns the root directories of the IDE workspace: this project and the trusted projects attached to it
in the same window, as absolute paths. A task works in one directory, but its workspace can hold several projects.
Call this before the first project-related operation in a session, and when asked about the workspace, project or
working directories. `projectRoot` is the project this connection serves, the default base for paths; `roots` is
every project in the workspace, the scope to search and read, not a list of projects to change. It doesn't change the
working directory or permissions. Other tools reach an attached project by its root as `projectPath`.",
Call this when asked about the workspace, project or working directories, and before planning a change that may span
projects. Other tools reach an attached project by its root as `projectPath`.",
|call| async move {
let root = call.root().to_path_buf();
let mut roots = vec![root.clone()];
-1
View File
@@ -513,7 +513,6 @@ async fn resolve_jvm_application(
call.window(),
std::path::PathBuf::from(&module),
test == Some(true),
false,
policy,
&cancel,
None,
+4 -97
View File
@@ -9,7 +9,6 @@ use crate::{Host, Project};
use ide_command::command;
use ide_build::compile::{self, BuildEvent, BuildKind, BuildResult};
use ide_build::jbuild::Target;
use ide_build::maven::completion::{PomCompletion, PomCompletionOption};
use ide_build::maven::sources;
use ide_build::maven::{PomGoto, PomManagedDeclaration, PomNavigationOptions};
@@ -976,38 +975,11 @@ pub async fn build_run(
let config_dir = host.config_dir.clone();
let token = host.begin_project_request(window, request);
let launch_project = project.clone();
let (service, data_dir) = (host.java_build.clone(), host.local_data_dir.clone());
let result = blocking(move || {
let single = cmake.is_none() && ide_workspace::workspace::Workspace::load(&root)?.is_none();
// A Maven or Gradle project builds with the IDE's Java build (#4078), unless its
// settings ask for the build tool, or it can't.
if single {
let model = with_profiles(load(&root, &cache, &settings), &cache);
let served = match file.as_deref() {
Some(module) => super::java::served_by_service(&root, &model, &settings, module),
None => super::java::project_served_by_service(&model, &settings),
};
if served {
let service = super::java::ServiceBuild {
service: &service,
data_dir: &data_dir,
root: &root,
cache: &cache,
settings: &settings,
model: &model,
};
let target = match file.as_deref() {
Some(file) => Target::Module(file),
None => Target::Project,
};
if let Some(result) = service_build_result(&service, target, kind, &clear, &sink, &token, &on_event)? {
return Ok(result);
}
}
}
// Fast path (#2476): an unchanged single-project Maven build skips
// Maven entirely. Previous diagnostics stay: nothing changed, so they
// are still accurate.
let single = cmake.is_none() && ide_workspace::workspace::Workspace::load(&root)?.is_none();
if single && kind == BuildKind::Build {
let model = with_profiles(load(&root, &cache, &settings), &cache);
if compile::menu_up_to_date(&cache, &root, &model, file.as_deref(), &token) {
@@ -1130,59 +1102,13 @@ pub async fn build_run(
let outcome = result?;
// Maven generated sources (protobuf, gRPC) stay invisible to jdtls until the
// folders the build wrote are attached. An up-to-date build skips Maven and
// still needs this: the classes can already be on disk. The IDE's Java build
// generates them with Maven too.
if matches!(outcome.system, ide_build::compile::BuildSystem::Maven | ide_build::compile::BuildSystem::Javac) {
// still needs this: the classes can already be on disk.
if outcome.system == ide_build::compile::BuildSystem::Maven {
project.lsp.sync_maven_generated_sources(&project.root).await;
}
Ok(outcome)
}
/// A menu build by the IDE's Java build, as the Build window shows it; `None` when Maven builds.
/// Diagnostics of `clear` are cleared once the service builds; its messages are published.
#[allow(clippy::too_many_arguments)]
fn service_build_result(
service: &super::java::ServiceBuild,
target: Target,
kind: BuildKind,
clear: &[std::path::PathBuf],
sink: &ide_core::SharedSink,
token: &CancellationToken,
on_event: &Channel<BuildEvent>,
) -> IdeResult<Option<BuildResult>> {
let started = std::time::Instant::now();
let title = std::sync::Mutex::new(String::new());
let forward = |event: BuildEvent| {
if let BuildEvent::Started { title: t, .. } = &event {
*title.lock().unwrap() = t.clone();
}
let _ = on_event.send(event);
};
let built = service.build(target, kind, token, &forward)?;
let Some(outputs) = built else { return Ok(None) };
for path in clear {
sink.emit(IdeEvent::Diagnostics {
path: path.clone().into(),
source: compile::DIAGNOSTICS_SOURCE.into(),
items: Vec::new(),
});
}
for (path, items) in compile::diagnostics(&outputs.messages) {
sink.emit(IdeEvent::Diagnostics { path: path.into(), source: compile::DIAGNOSTICS_SOURCE.into(), items });
}
let count =
|severity: ide_core::Severity| outputs.messages.iter().filter(|m| m.severity == severity).count() as u32;
Ok(Some(BuildResult {
system: compile::BuildSystem::Javac,
title: title.into_inner().unwrap(),
success: outputs.failure.is_none(),
errors: count(ide_core::Severity::Error),
warnings: count(ide_core::Severity::Warning),
duration_ms: started.elapsed().as_secs_f64() * 1000.0,
messages: outputs.messages,
}))
}
fn plan_compile_file(
root: &Path,
cache: &Path,
@@ -1241,26 +1167,7 @@ pub async fn build_compile_file(
};
let sink = project.sink.clone();
let token = host.begin_project_request(window, request);
let (service, data_dir) = (host.java_build.clone(), host.local_data_dir.clone());
let result = blocking(move || {
{
let model = with_profiles(load(&scope.root, &scope.cache, &scope.settings), &scope.cache);
if super::java::served_by_service(&scope.root, &model, &scope.settings, &file) {
let service = super::java::ServiceBuild {
service: &service,
data_dir: &data_dir,
root: &scope.root,
cache: &scope.cache,
settings: &scope.settings,
model: &model,
};
let target = Target::File(&file);
let kind = BuildKind::Build;
if let Some(result) = service_build_result(&service, target, kind, &clear, &sink, &token, &on_event)? {
return Ok(result);
}
}
}
for path in clear {
sink.emit(IdeEvent::Diagnostics {
path: path.into(),
@@ -1283,7 +1190,7 @@ pub async fn build_compile_file(
.await;
host.end_request(request);
let outcome = result?;
if matches!(outcome.system, ide_build::compile::BuildSystem::Maven | ide_build::compile::BuildSystem::Javac) {
if outcome.system == ide_build::compile::BuildSystem::Maven {
project.lsp.sync_maven_generated_sources(&scope_root).await;
}
Ok(outcome)
+2 -18
View File
@@ -40,27 +40,11 @@ pub async fn flutter_emulator_launch(host: &Host, window: &str, id: String) -> I
#[command(trust = trusted)]
pub async fn flutter_devtools_url(host: &Host, window: &str) -> IdeResult<String> {
let project = host.project(window)?;
tokio::task::spawn_blocking(move || project.devtools.url(&[]))
tokio::task::spawn_blocking(move || project.devtools.url())
.await
.map_err(|e| IdeError::internal(e.to_string()))?
.map_err(IdeError::unavailable)
}
/// The address of the project's Widget Preview page, its server started on first use with the
/// project's DevTools for its inspector. A server that failed or exited is only started again by
/// the next request.
#[command(trust = trusted)]
pub async fn flutter_widget_preview_url(host: &Host, window: &str) -> IdeResult<String> {
let project = host.project(window)?;
tokio::task::spawn_blocking(move || {
// Without it the tool starts a DevTools of its own.
let devtools = project.devtools.url(&[]).map(|url| format!("--devtools-server-address={url}"));
project.widget_preview.url(&Vec::from_iter(devtools.ok()))
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
.map_err(IdeError::unavailable)
}
ide_command::domain!(flutter: flutter_devices, flutter_devices_refresh, flutter_daemon_restart, flutter_emulator_launch,
flutter_devtools_url, flutter_widget_preview_url);
flutter_devtools_url);
+12 -231
View File
@@ -9,7 +9,6 @@ use super::build::{load, with_profiles, workspace};
use cache::LaunchEvents;
use ide_build::BuildModel;
use ide_build::compile::{self, BuildEvent};
use ide_build::jbuild::{Built, JavaBuild, JavaBuildService, LaunchOutputs, Target};
use ide_core::error::ErrorKind;
use ide_core::settings::Settings;
use ide_core::{CancellationToken, IdeError, IdeResult, RequestId};
@@ -23,16 +22,12 @@ use std::path::{Path, PathBuf};
/// A module with Kotlin / Groovy / Scala sources is built by its build system, whose class directories come first.
/// The build streams its console, messages and progress on `on_event` while it runs; a launch
/// whose build another launch's build joins receives that build's events.
/// A Maven module is built by the IDE's Java build, except for a `debug` launch the language
/// server serves: java-debug's HotSwap reloads the classes the language server compiles.
#[allow(clippy::too_many_arguments)]
#[command(trust = trusted)]
pub async fn java_resolve_launch(
host: &Host,
window: &str,
module: PathBuf,
test: bool,
debug: bool,
policy: BuildPolicy,
request: RequestId,
on_event: Channel<BuildEvent>,
@@ -44,18 +39,16 @@ pub async fn java_resolve_launch(
let events: LaunchEvents = std::sync::Arc::new(move |event| {
let _ = on_event.send(event);
});
let result = resolve_launch(host, window, module, test, debug, policy, &cancel, Some(events)).await;
let result = resolve_launch(host, window, module, test, policy, &cancel, Some(events)).await;
host.end_request(request);
result
}
#[allow(clippy::too_many_arguments)]
pub(crate) async fn resolve_launch(
host: &Host,
window: &str,
module: PathBuf,
test: bool,
debug: bool,
policy: BuildPolicy,
cancel: &CancellationToken,
events: Option<LaunchEvents>,
@@ -80,12 +73,13 @@ pub(crate) async fn resolve_launch(
}
let scope = std::sync::Arc::new(scope);
let launches = project.java_launches.for_cache(&scope.cache);
let waiting = launches.waiting.add(module.clone(), test, policy, events.clone());
let prefer_maven = scope.settings.languages.java.maven.delegate_build;
// A launch builds incrementally unless the configuration asks for Rebuild or NoBuild.
let build = policy != BuildPolicy::NoBuild;
let full = policy == BuildPolicy::Rebuild;
let build_kind = if full { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
let (model, external, mut delegated, is_maven, non_java, served) = {
let (model, external, mut delegated, is_maven) = {
let scope = scope.clone();
let launches = launches.clone();
let module = module.clone();
@@ -95,7 +89,6 @@ pub(crate) async fn resolve_launch(
let model = load_launch_model(&scope);
let non_java = build && compile::launch_has_non_java_sources(root, &model, &module, test);
let is_maven = is_maven_module(root, &model, &module);
let served = served_by_service(root, &model, &scope.settings, &module);
let delegated = build
&& delegates_to_external_build(
is_maven,
@@ -105,65 +98,11 @@ pub(crate) async fn resolve_launch(
prefer_maven,
);
let external = non_java || delegated;
(std::sync::Arc::new(model), external, delegated, is_maven, non_java, served)
(model, external, delegated, is_maven)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
};
// A Maven or Gradle module is built by the IDE's Java build ([`served_by_service`]), unless
// the launch debugs with java-debug, whose HotSwap reloads what jdtls compiles (ecj's
// classes differ from javac's: lambda names). jdtls keeps building for its diagnostics
// either way.
if served && !non_java && !debug {
let built = {
let (service, data_dir, scope, model, module, cancel, events) = (
host.java_build.clone(),
host.local_data_dir.clone(),
scope.clone(),
model.clone(),
module.clone(),
cancel.clone(),
events.clone(),
);
tokio::task::spawn_blocking(move || {
let on_event = |event: BuildEvent| {
if let Some(events) = &events {
events(event);
}
};
let kind = build.then_some(build_kind);
build_with_service(&service, &data_dir, &scope, &model, &module, test, kind, &cancel, &on_event)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))??
};
if let Some(outputs) = built {
progress("Resolving the classpath");
let mut info = project.lsp.java_launch(&module, test, false, false, false, cancel).await?;
let data_dir = host.local_data_dir.clone();
let cancel = cancel.clone();
return tokio::task::spawn_blocking(move || {
// javac's verdict replaces JDT's, as a Maven build's does.
if build {
apply_external_build_result(&mut info, outputs.failure, true);
}
info.class_paths = outputs.class_paths.iter().map(|p| p.to_string_lossy().into_owned()).collect();
apply_library_classpath(&mut info, &scope.root, &scope.settings.project_structure.libraries, test);
finish_launch(&mut info, &scope.root, &module, &scope.settings, &model, &data_dir);
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
tracing::info!(
total_ms = started.elapsed().as_millis(),
"Java launch resolved with the IDE's Java build"
);
Ok(info)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?;
}
}
let waiting = launches.waiting.add(module.clone(), test, policy, events.clone());
let mut external_build =
if delegated { Some(project.lsp.java_external_build(&module, cancel).await?) } else { None };
if build && !delegated {
@@ -185,6 +124,7 @@ pub(crate) async fn resolve_launch(
drop_processor_recreate_errors(&mut info);
}
}
let model = std::sync::Arc::new(model);
let members = if delegated {
build_members(&project, &scope, &model, &module, test, &waiting, cancel).await?
} else {
@@ -277,104 +217,6 @@ pub(crate) async fn resolve_launch(
.map_err(|e| IdeError::internal(e.to_string()))?
}
/// Builds the launch of a Maven module with the IDE's Java build (#4078): javac in a resident
/// process with the configuration Maven gives the compiler, into outputs in the project cache
/// that neither the language server nor a terminal `mvn` writes. `None` when the module needs
/// Maven's own build (another compiler, a multi-release jar, a Java module…), which then runs.
/// Without `kind` (no build before launch), the outputs of its last build, if any.
#[allow(clippy::too_many_arguments)]
fn build_with_service(
service: &JavaBuildService,
data_dir: &Path,
scope: &workspace::Scope,
model: &BuildModel,
module: &Path,
test: bool,
kind: Option<compile::BuildKind>,
cancel: &CancellationToken,
on_event: &(dyn Fn(BuildEvent) + Sync),
) -> IdeResult<Option<LaunchOutputs>> {
let service =
ServiceBuild { service, data_dir, root: &scope.root, cache: &scope.cache, settings: &scope.settings, model };
match kind {
Some(kind) => service.build(Target::Launch { module, test }, kind, cancel, on_event),
// No build: the outputs of the last one, when there was one.
None => Ok(service
.with(module, |build| build.recorded_launch(module, test))
.flatten()
.map(|class_paths| LaunchOutputs { class_paths, ..Default::default() })),
}
}
/// A build of the IDE's Java build service in one project (or workspace member).
pub(crate) struct ServiceBuild<'a> {
pub service: &'a JavaBuildService,
pub data_dir: &'a Path,
pub root: &'a Path,
pub cache: &'a Path,
pub settings: &'a Settings,
pub model: &'a BuildModel,
}
impl ServiceBuild<'_> {
/// Runs `f` with the build, its JDKs resolved for `module`; `None` when the build jar
/// can't be installed.
fn with<R>(&self, module: &Path, f: impl FnOnce(&JavaBuild) -> R) -> Option<R> {
let jar = ide_sdk::java::java_build_jar(self.data_dir)?;
let (root, settings) = (self.root, self.settings);
let jdk = |release: Option<u32>| {
ide_sdk::apply::module_jdk(root, module, settings)
.or_else(|| ide_sdk::java::pick_jdk(&ide_sdk::java::installed_jdks(), release).cloned())
.map(|jdk| jdk.home)
};
let version = ide_sdk::java::java_build_version();
let build = JavaBuild {
root,
model: self.model,
cache: self.cache,
jar: &jar,
jar_version: &version,
local_repo: ide_sdk::apply::maven_local_repository(root, settings),
service: self.service,
jdk: &jdk,
};
Some(f(&build))
}
/// Builds `target`; `None` when the build tool has to (the service doesn't build it, or failed).
pub fn build(
&self,
target: Target,
kind: compile::BuildKind,
cancel: &CancellationToken,
on_event: &(dyn Fn(BuildEvent) + Sync),
) -> IdeResult<Option<LaunchOutputs>> {
let module = match target {
Target::Launch { module, .. } | Target::Module(module) | Target::File(module) => module,
Target::Project => self.root,
};
let Some(built) = self.with(module, |build| build.build(target, kind, cancel, on_event)) else {
return Ok(None);
};
match built {
Ok(Built::Done(outputs)) => Ok(Some(outputs)),
Ok(Built::Unsupported(reason)) => {
tracing::info!(module = %module.display(), reason, "Building with the build tool");
Ok(None)
}
Err(e) if e.kind == ErrorKind::Cancelled => Err(e),
Err(e) => {
tracing::warn!(module = %module.display(), "The IDE's Java build failed: {}", e.message);
on_event(BuildEvent::Output {
text: format!("The IDE's Java build failed, so the build tool builds it: {}\n", e.message),
stderr: true,
});
Ok(None)
}
}
}
}
fn load_launch_model(scope: &workspace::Scope) -> BuildModel {
with_profiles(load(&scope.root, &scope.cache, &scope.settings), &scope.cache)
}
@@ -383,39 +225,6 @@ fn is_maven_module(root: &Path, model: &BuildModel, module: &Path) -> bool {
model.maven.as_ref().is_some_and(|m| m.projects.iter().any(|p| root.join(&p.dir) == module))
}
/// Whether the IDE's Java build builds the module holding `path` (#4078): a Maven module unless
/// Settings › Maven › Delegate IDE build/run actions to Maven asks for Maven; a Gradle module
/// when Settings › Gradle › Build and run using asks for the IDE.
pub(crate) fn served_by_service(root: &Path, model: &BuildModel, settings: &Settings, path: &Path) -> bool {
let maven = model.maven.iter().flat_map(|m| m.projects.iter().map(|p| (root.join(&p.dir), true)));
let gradle = model.gradle.iter().flat_map(|g| g.projects.iter().map(|p| (root.join(&p.dir), false)));
// The deepest module holding it; Maven's when both build the folder.
let module = maven
.chain(gradle)
.filter(|(dir, _)| path.starts_with(dir))
.max_by_key(|(dir, maven)| (dir.components().count(), *maven));
match module {
Some((_, true)) => !settings.languages.java.maven.delegate_build,
Some((_, false)) => gradle_served(settings),
None => false,
}
}
/// Whether the IDE's Java build builds the whole project: it has Maven or Gradle builds, and
/// builds them all.
pub(crate) fn project_served_by_service(model: &BuildModel, settings: &Settings) -> bool {
let maven = model.maven.as_ref().map(|_| !settings.languages.java.maven.delegate_build);
let gradle = (!model.gradle.is_empty()).then(|| gradle_served(settings));
match (maven, gradle) {
(None, None) => false,
(maven, gradle) => maven.unwrap_or(true) && gradle.unwrap_or(true),
}
}
fn gradle_served(settings: &Settings) -> bool {
settings.languages.java.gradle.run_using == ide_core::settings::GradleRunUsing::Ide
}
/// 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.
#[allow(clippy::too_many_arguments)]
@@ -432,9 +241,8 @@ async fn resolve_launch_without_jdtls(
let started = std::time::Instant::now();
let scope = std::sync::Arc::new(scope);
let kind = if policy == BuildPolicy::Rebuild { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
let (model, built, by_service) = {
let (model, built) = {
let (scope, module, cancel, events) = (scope.clone(), module.clone(), cancel.clone(), events.clone());
let (service, data_dir) = (host.java_build.clone(), host.local_data_dir.clone());
tokio::task::spawn_blocking(move || {
let model = load_launch_model(&scope);
let on_event = |event: BuildEvent| {
@@ -442,33 +250,12 @@ async fn resolve_launch_without_jdtls(
events(event);
}
};
if policy == BuildPolicy::NoBuild {
return (model, None, false);
}
if served_by_service(&scope.root, &model, &scope.settings, &module)
&& !compile::launch_has_non_java_sources(&scope.root, &model, &module, test)
{
match build_with_service(
&service,
&data_dir,
&scope,
&model,
&module,
test,
Some(kind),
&cancel,
&on_event,
) {
Ok(Some(outputs)) => {
let built = compile::LaunchBuild { class_dirs: outputs.class_paths, failure: outputs.failure };
return (model, Some(Ok(built)), true);
}
Ok(None) => {}
Err(e) => return (model, Some(Err(e)), false),
}
}
let built = compile::build_for_launch(&scope.root, &model, &module, test, kind, &cancel, &on_event);
(model, Some(built), false)
let built = if policy == BuildPolicy::NoBuild {
None
} else {
Some(compile::build_for_launch(&scope.root, &model, &module, test, kind, &cancel, &on_event))
};
(model, built)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
@@ -507,12 +294,6 @@ async fn resolve_launch_without_jdtls(
tokio::task::spawn_blocking(move || {
let (root, cache, settings) = (&scope.root, &scope.cache, &scope.settings);
match from_server {
// The IDE's Java build gave the whole classpath; the server adds its JDK.
Some(server) if by_service => {
info.project_root = server.classpath.project_root;
info.java_home = server.jdk_home.map(Into::into);
}
None if by_service => {}
Some(server) => {
info.project_root = server.classpath.project_root;
info.module_paths = server.classpath.module_paths;
-27
View File
@@ -413,31 +413,6 @@ pub async fn lsp_signature_help(host: &Host, window: &str, doc: DocId, pos: Pos)
}
}
/// The Flutter Property Editor's arguments of the call at `pos`.
#[command(trust = trusted)]
pub async fn lsp_editable_arguments(
host: &Host,
window: &str,
doc: DocId,
pos: Pos,
) -> IdeResult<Option<EditableArguments>> {
host.project(window)?.lsp.editable_arguments(doc, pos).await
}
/// Sets an argument of the call at `pos`; the edit reaches the document as the server's
/// `workspace/applyEdit`, undoable like any other.
#[command(trust = trusted)]
pub async fn lsp_edit_argument(
host: &Host,
window: &str,
doc: DocId,
pos: Pos,
name: String,
value: Option<ArgumentValue>,
) -> IdeResult<()> {
host.project(window)?.lsp.edit_argument(doc, pos, name, value).await
}
#[command(trust = trusted)]
pub async fn lsp_goto(host: &Host, window: &str, doc: DocId, pos: Pos, kind: GotoKind) -> IdeResult<Vec<Location>> {
let target = position_document(host, window, doc, pos).await?;
@@ -3225,8 +3200,6 @@ ide_command::domain!(
lsp_completion,
lsp_document_colors,
lsp_document_highlights,
lsp_edit_argument,
lsp_editable_arguments,
lsp_document_links,
lsp_exception_class_at,
lsp_execute_code_action,
-7
View File
@@ -407,13 +407,6 @@ pub fn set_settings(
if key == "vcs" || key == "vcs.git" || key == "vcs.git.executable" {
host.apply_git_executable();
}
// `flutter daemon` and DevTools run on the Flutter SDK; the next request starts DevTools again.
if ["languages", "languages.flutter", "languages.flutter.sdk"].contains(&key) {
for project in affected() {
project.flutter.sdk_changed();
project.devtools.stop();
}
}
if is_proxy {
host.apply_proxy();
}
+6 -20
View File
@@ -391,10 +391,8 @@ async fn start_inner(
if config.command.is_empty() {
return Err(IdeError::invalid("run configuration has no command"));
}
// A JVM on a run target gets no plugin agents; a local one gets them once its JDK is resolved.
if config.extras.target.as_deref().is_some_and(|t| !t.is_empty()) {
add_java_agents(&mut config, &on_output, None);
}
let on_target = config.extras.target.as_deref().is_some_and(|t| !t.is_empty());
add_java_agents(&mut config, &on_output, !on_target);
// Settings › Run Targets: over SSH, or in a container.
if config.kind == "tomcat" && config.extras.target.as_deref().is_some_and(|t| !t.is_empty()) {
return Err(IdeError::invalid("Tomcat Local requires the local machine"));
@@ -485,8 +483,6 @@ async fn start_inner(
);
ide_sdk::go::apply_to_run(&mut config, &settings.languages.go.build_tags);
}
let run_dir = project.root.join(config.cwd.as_deref().unwrap_or(Path::new("")));
add_java_agents(&mut config, &on_output, Some(&run_dir));
if config.command == ide_sdk::godot::COMMAND {
return Err(IdeError::unavailable(ide_sdk::godot::NOT_FOUND));
}
@@ -559,24 +555,14 @@ async fn start_inner(
/// Plugins' Java agents (`[[contributes.javaAgents]]`, granted `java.agent`) for the JVM of an
/// Application, Spring Boot or JAR Application configuration started on this machine. A JVM on a
/// run target gets none; the console says so, and why an approved agent was left out.
fn add_java_agents(config: &mut RunConfig, on_output: &Emit<OutputChunk>, run_dir: Option<&Path>) {
fn add_java_agents(config: &mut RunConfig, on_output: &Emit<OutputChunk>, local: bool) {
if !ide_run::java_agent::applies(&config.kind) {
return;
}
// The JVM the launch starts: a bare `java` (what generated configurations name) is looked
// up the way the process start finds it, so the `jdk` filter of `vmOptions` sees that JDK.
let java = run_dir.and_then(|dir| {
let search = ide_run::wrap::search_path_in(config, dir);
let home = config
.env
.get("JAVA_HOME")
.map(std::path::PathBuf::from)
.or_else(|| std::env::var_os("JAVA_HOME").map(std::path::PathBuf::from));
ide_run::java_agent::launched_java(&config.command, &search, home.as_deref())
});
let agents = ide_run::java_agent::current_for(java.as_deref());
let java = std::path::Path::new(&config.command);
let agents = ide_run::java_agent::current_for(Some(java));
let say = |text: &str| on_output(OutputChunk::System { text: format!("{text}\n") });
if run_dir.is_none() {
if !local {
if !agents.options.is_empty() {
say(
"Plugin Java agents were not added: they load only into JVMs started on this machine, not on a run target.",
-22
View File
@@ -470,27 +470,6 @@ pub async fn sdk_jdk_at(path: String) -> IdeResult<Option<Sdk>> {
blocking_value(move || ide_sdk::java::jdk_at(std::path::Path::new(&path)).map(|j| ide_sdk::jdk_sdk(&j))).await
}
/// `flutter --version --machine` of the Flutter SDK at `path`, or of the `flutter` on the
/// search path when `path` is empty; `None` when there is no Flutter SDK.
#[command(trust = trusted)]
pub async fn sdk_flutter_at(
host: &Host,
window: &str,
path: String,
) -> IdeResult<Option<ide_sdk::flutter::FlutterVersion>> {
let root = host.project(window).ok().map(|p| p.root.clone());
blocking_value(move || {
let root = root.unwrap_or_default();
let sdk = match ide_sdk::apply::setting_path(&root, &path) {
Some(sdk) => Some(sdk),
None => ide_core::tool_path::find_command("flutter", &ide_core::tool_path::search_path_in(&root), &root)
.and_then(|f| ide_sdk::flutter::sdk_of(&f)),
};
sdk.and_then(|sdk| ide_sdk::flutter::version(&sdk))
})
.await
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
@@ -649,7 +628,6 @@ mod tests {
ide_command::domain!(
sdk:
sdk_detect,
sdk_flutter_at,
sdk_jdk_at,
sdk_locate_tools,
sdk_php_composer_install,
+3 -21
View File
@@ -4,10 +4,8 @@
//! given belong to the server's [`ide_ssh::SshManager`], not the desktop's.
use crate::Host;
use ide_command::command;
use ide_core::event::NotifyLevel;
use ide_core::IdeResult;
use ide_core::remote_settings::SshConfiguration;
use ide_core::{IdeError, IdeEvent, IdeResult};
use ide_ssh::secrets::LegacyPasswordAction;
/// Test Connection: connects with `config` as edited (not necessarily saved).
#[command(trust = always)]
@@ -17,23 +15,8 @@ pub async fn ssh_test(host: &Host, config: SshConfiguration, secret: Option<Stri
/// Remembers the password / passphrase of configuration `id` (`None` forgets it).
#[command(trust = always)]
pub fn ssh_set_secret(host: &Host, window: &str, id: String, secret: Option<String>, save: bool) {
if let Err(e) = host.ssh.set_secret(&id, secret, save) {
host.window_sink(window).emit(IdeEvent::Notify {
level: NotifyLevel::Warning,
title: "Could not save credential".into(),
body: Some(e.message),
});
}
}
/// `Some` means legacy credentials remain in plaintext on this host.
#[command(trust = always)]
pub async fn ssh_legacy_passwords(host: &Host, action: LegacyPasswordAction) -> IdeResult<Option<String>> {
let ssh = host.ssh.clone();
tokio::task::spawn_blocking(move || ssh.resolve_legacy_passwords(action))
.await
.map_err(|e| IdeError::internal(e.to_string()))?
pub fn ssh_set_secret(host: &Host, id: String, secret: Option<String>, save: bool) {
host.ssh.set_secret(&id, secret, save);
}
/// Whether a password is saved under `key` (an FTP deployment server's).
@@ -69,7 +52,6 @@ ide_command::domain!(
ssh:
ssh_connected,
ssh_disconnect,
ssh_legacy_passwords,
ssh_needs_secret,
ssh_password_saved,
ssh_set_secret,
+9 -35
View File
@@ -68,9 +68,7 @@ pub struct Project {
/// Flutter's devices; its daemon starts when the UI first asks for them.
pub(crate) flutter: ide_flutter::FlutterDaemon,
/// Flutter DevTools; its server starts when the UI first asks for it.
pub(crate) devtools: ide_flutter::ToolServer,
/// Flutter Widget Preview; its server starts when its tool window first opens.
pub(crate) widget_preview: ide_flutter::ToolServer,
pub(crate) devtools: ide_flutter::DevToolsServer,
pub(crate) kotlin_bridge: Option<Arc<crate::kotlin_bridge::KotlinBridge>>,
pub(crate) phpstan: Option<Arc<crate::phpstan::Phpstan>>,
pub(crate) watcher: Arc<Watcher>,
@@ -125,8 +123,8 @@ impl Host {
// A window takes the root over from the MCP server's background project, whose
// shutdown the wait below sits out; none opens until this open is over.
let _claim = (!crate::mcp::BackgroundProjects::is_key(window)).then(|| self.mcp_background.claim(self, &root));
self.close_project_detached(window);
self.wait_detached_closes_for(&root);
self.close_project(window);
self.wait_detached_closes();
let sink: SharedSink = (self.sink_for)(window);
// Before anything the project starts: its children get the project's environment.
let trusted = Arc::new(AtomicBool::new(self.trust.window_trusted(&root)?));
@@ -646,16 +644,8 @@ impl Host {
let project = Arc::new(Project {
plugin_diagnostics,
trusted,
flutter: ide_flutter::FlutterDaemon::new(
root.clone(),
sink.clone(),
flutter_tool(&root, &settings, "flutter"),
),
devtools: ide_flutter::ToolServer::devtools(root.clone(), flutter_tool(&root, &settings, "dart")),
widget_preview: ide_flutter::ToolServer::widget_preview(
root.clone(),
flutter_tool(&root, &settings, "flutter"),
),
flutter: ide_flutter::FlutterDaemon::new(root.clone(), sink.clone()),
devtools: ide_flutter::DevToolsServer::new(root.clone()),
root,
sink,
languages,
@@ -867,10 +857,8 @@ impl Host {
}
return Ok(current);
}
self.close_project_detached(window);
if let Some(dir) = watch_dir {
self.wait_detached_closes_for(dir);
}
self.close_project(window);
self.wait_detached_closes();
let sink: SharedSink = (self.sink_for)(window);
let settings = Arc::new(SettingsStore::load(&self.config_dir, None));
let effective = settings.effective();
@@ -907,16 +895,8 @@ impl Host {
let project = Arc::new(Project {
plugin_diagnostics,
trusted: Arc::new(AtomicBool::new(false)),
flutter: ide_flutter::FlutterDaemon::new(
dir.clone(),
sink.clone(),
flutter_tool(&dir, &settings, "flutter"),
),
devtools: ide_flutter::ToolServer::devtools(dir.clone(), flutter_tool(&dir, &settings, "dart")),
widget_preview: ide_flutter::ToolServer::widget_preview(
dir.clone(),
flutter_tool(&dir, &settings, "flutter"),
),
flutter: ide_flutter::FlutterDaemon::new(dir.clone(), sink.clone()),
devtools: ide_flutter::DevToolsServer::new(dir.clone()),
sink,
languages,
settings,
@@ -1044,12 +1024,6 @@ fn light_watcher(
)
}
/// `flutter` / `dart` as Settings › Flutter chooses them, read each time the daemon or DevTools starts.
fn flutter_tool(root: &Path, settings: &Arc<SettingsStore>, command: &'static str) -> ide_flutter::Configured {
let (root, settings) = (root.to_path_buf(), settings.clone());
Box::new(move || ide_sdk::apply::tool_command(&root, &settings.effective(), command))
}
/// Looks for repositories nested below the project (and the one containing it);
/// emits `VcsChanged` when the set of roots changed.
fn scan_repositories(
-1
View File
@@ -287,7 +287,6 @@ impl crate::Host {
project.agents.shutdown();
project.flutter.stop();
project.devtools.stop();
project.widget_preview.stop();
self.processes.kill_project(&project.root);
project.notebooks.restrict().await;
let windows: Vec<_> = self
-20
View File
@@ -2,26 +2,6 @@ mod common;
use ide_host::{Host, HostConfig, ops};
#[tokio::test]
async fn startup_moves_legacy_ssh_credentials_without_opening_a_project_or_connection() {
use ide_ssh::secrets::testing::{files_containing, use_memory_store};
use_memory_store();
let tmp = tempfile::tempdir().unwrap();
let config = common::host_config(tmp.path());
std::fs::create_dir_all(&config.data_dir).unwrap();
std::fs::write(config.data_dir.join("ssh-passwords.json"), r#"{"box":"legacy-fixture"}"#).unwrap();
let host = Host::new(config);
tokio::time::timeout(std::time::Duration::from_secs(5), async {
while !files_containing(tmp.path(), "legacy-fixture").is_empty() {
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
})
.await
.expect("startup migration");
assert_eq!(host.ssh.password("box").as_deref(), Some("legacy-fixture"));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn split_storage_keeps_user_history_and_uses_local_tools_and_caches() {
let tmp = tempfile::tempdir().unwrap();
-215
View File
@@ -1,215 +0,0 @@
mod common;
use ide_build::compile::BuildEvent;
use ide_core::RequestId;
use ide_host::{Host, ops};
use ide_run::BuildPolicy;
use ide_workspace::{SettingsStore, settings::SettingsScope};
use std::fs;
use std::path::Path;
use std::sync::{Arc, Mutex};
fn write(root: &Path, rel: &str, text: &str) {
let path = root.join(rel);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, text).unwrap();
}
/// A Maven launch compiles with the IDE's Java build (javac, outputs in the project cache)
/// and runs from its outputs. Needs `mvn` and a JDK (`JAVA_HOME`), else it is skipped.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn maven_launch_compiles_with_the_ides_java_build() {
let has_jdk = std::env::var_os("JAVA_HOME").is_some_and(|h| Path::new(&h).join("bin").is_dir());
if !has_jdk || ide_core::process::find_executable("mvn", &ide_core::tool_path::search_path()).is_none() {
eprintln!("skipped: needs JAVA_HOME and mvn");
return;
}
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
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>app</module></modules>
<properties><maven.compiler.release>11</maven.compiler.release><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties></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,
"app/pom.xml",
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>app</artifactId>
<dependencies><dependency><groupId>t</groupId><artifactId>lib</artifactId><version>1</version></dependency></dependencies></project>"#,
);
write(
&root,
"lib/src/main/java/l/L.java",
"package l;\npublic class L { public static String name() { return \"lib\"; } }\n",
);
write(
&root,
"app/src/main/java/a/A.java",
"package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name()); } }\n",
);
// No language server: the build tool compiles the launch.
let global = SettingsStore::load(&base.join("config"), None);
for server in ["jdtls", "java-analyzer", "kmp-lsp"] {
global
.set(SettingsScope::Global, &format!("languageServers.{server}.enabled"), serde_json::json!(false))
.unwrap();
}
let host = Host::new(common::host_config(&base));
host.trust.decide(&root, true, false).unwrap();
host.open_project("main", &root).unwrap();
let events = Arc::new(Mutex::new(Vec::new()));
let sink = events.clone();
let channel = ops::Channel::new(move |event: BuildEvent| sink.lock().unwrap().push(event));
let info = ops::java::java_resolve_launch(
&host,
"main",
root.join("app"),
false,
false,
BuildPolicy::Make,
RequestId::next(),
channel,
)
.await
.unwrap();
let steps: Vec<String> = events
.lock()
.unwrap()
.iter()
.filter_map(|e| match e {
BuildEvent::Step { command, .. } => Some(command.clone()),
_ => None,
})
.collect();
assert!(steps.iter().any(|s| s.starts_with("javac lib")), "{steps:?}");
assert!(steps.iter().any(|s| s.starts_with("javac app")), "{steps:?}");
assert!(!steps.iter().any(|s| s.contains("-am")), "{steps:?}");
let first = Path::new(&info.class_paths[0]);
assert!(first.ends_with("out/t.app/classes"), "{:?}", info.class_paths);
assert!(first.join("a/A.class").is_file());
assert!(info.class_paths.iter().any(|p| Path::new(p).ends_with("out/t.lib/classes")), "{:?}", info.class_paths);
assert!(!root.join("app/target/classes").exists());
// Build › Build Project compiles with it too, and reports javac's errors.
write(&root, "lib/src/main/java/l/L.java", "package l;\npublic class L { }\n");
let built = ops::build::build_run(
&host,
"main",
ide_build::compile::BuildKind::Build,
None,
None,
RequestId::next(),
Vec::new(),
ops::Channel::new(|_: BuildEvent| {}),
)
.await
.unwrap();
assert_eq!(built.system, ide_build::compile::BuildSystem::Javac);
assert!(!built.success);
assert_eq!(built.errors, 1, "{:?}", built.messages);
assert!(built.messages[0].path.as_deref().is_some_and(|p| p.ends_with("a/A.java")), "{:?}", built.messages);
assert!(!root.join("lib/target/classes").exists());
host.shutdown().await;
}
/// With Settings › Gradle › Build and run using: IDE, a Gradle launch and Build Project compile
/// with the IDE's Java build too. Needs a JDK (`JAVA_HOME`) and Gradle (`OPENIDEA_TEST_GRADLE`).
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn gradle_launch_compiles_with_the_ides_java_build() {
let has_jdk = std::env::var_os("JAVA_HOME").is_some_and(|h| Path::new(&h).join("bin").is_dir());
let Some(gradle) = std::env::var_os("OPENIDEA_TEST_GRADLE").filter(|_| has_jdk) else {
eprintln!("skipped: needs JAVA_HOME and OPENIDEA_TEST_GRADLE");
return;
};
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
write(&root, "settings.gradle", "rootProject.name = 'root'\ninclude 'lib', 'app'\n");
write(&root, "build.gradle", "subprojects {\n apply plugin: 'java'\n group = 't'\n}\n");
write(&root, "lib/build.gradle", "");
write(&root, "app/build.gradle", "dependencies { implementation project(':lib') }\n");
write(&root, "gradlew", &format!("#!/bin/sh\nexec '{}' \"$@\"\n", Path::new(&gradle).display()));
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(root.join("gradlew"), fs::Permissions::from_mode(0o755)).unwrap();
write(
&root,
"lib/src/main/java/l/L.java",
"package l;\npublic class L { public static String name() { return \"lib\"; } }\n",
);
write(
&root,
"app/src/main/java/a/A.java",
"package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name()); } }\n",
);
let global = SettingsStore::load(&base.join("config"), None);
for server in ["jdtls", "java-analyzer", "kmp-lsp"] {
global
.set(SettingsScope::Global, &format!("languageServers.{server}.enabled"), serde_json::json!(false))
.unwrap();
}
global.set(SettingsScope::Global, "languages.java.gradle.runUsing", serde_json::json!("ide")).unwrap();
let host = Host::new(common::host_config(&base));
host.trust.decide(&root, true, false).unwrap();
host.open_project("main", &root).unwrap();
let events = Arc::new(Mutex::new(Vec::new()));
let sink = events.clone();
let channel = ops::Channel::new(move |event: BuildEvent| sink.lock().unwrap().push(event));
let info = ops::java::java_resolve_launch(
&host,
"main",
root.join("app"),
false,
false,
BuildPolicy::Make,
RequestId::next(),
channel,
)
.await
.unwrap();
let steps: Vec<String> = events
.lock()
.unwrap()
.iter()
.filter_map(|e| match e {
BuildEvent::Step { command, .. } => Some(command.clone()),
_ => None,
})
.collect();
assert!(steps.iter().any(|s| s.contains("openideaBuildModel")), "{steps:?}");
assert!(steps.iter().any(|s| s.starts_with("javac lib")), "{steps:?}");
assert!(steps.iter().any(|s| s.starts_with("javac app")), "{steps:?}");
let first = Path::new(&info.class_paths[0]);
assert!(first.ends_with("out/t.app/classes"), "{:?}", info.class_paths);
assert!(first.join("a/A.class").is_file());
assert!(info.class_paths.iter().any(|p| Path::new(p).ends_with("out/t.lib/classes")), "{:?}", info.class_paths);
assert!(!root.join("app/build/classes").exists());
write(&root, "lib/src/main/java/l/L.java", "package l;\npublic class L { }\n");
let built = ops::build::build_run(
&host,
"main",
ide_build::compile::BuildKind::Build,
None,
None,
RequestId::next(),
Vec::new(),
ops::Channel::new(|_: BuildEvent| {}),
)
.await
.unwrap();
assert_eq!(built.system, ide_build::compile::BuildSystem::Javac);
assert_eq!(built.errors, 1, "{:?}", built.messages);
assert!(built.messages[0].path.as_deref().is_some_and(|p| p.ends_with("a/A.java")), "{:?}", built.messages);
host.shutdown().await;
}
+1 -2
View File
@@ -136,8 +136,7 @@ async fn ssh_server(home: &Path, server_home: &Path, project: &Path) -> Arc<ide_
save_secret: true,
..Default::default()
}]);
ide_ssh::secrets::testing::use_memory_store();
ssh.set_secret("local-test", Some("secret".into()), true).unwrap();
ssh.set_secret("local-test", Some("secret".into()), true);
assert!(ssh.session("local-test").await.is_err(), "unknown host key first");
ssh.trust_host("local-test").await.unwrap();
ssh.session("local-test").await.unwrap()
+1 -26
View File
@@ -10,30 +10,6 @@ use std::path::Path;
use std::sync::{Arc, Mutex, mpsc};
use std::time::Duration;
#[tokio::test]
async fn a_failed_credential_save_warns_the_window_but_keeps_the_session_password() {
let tmp = tempfile::tempdir().unwrap();
let config = common::host_config(tmp.path());
std::fs::create_dir_all(config.data_dir.join("ssh-passwords.json")).unwrap();
let (tx, rx) = mpsc::channel();
let host = Host::new(HostConfig {
sink_for: Box::new(move |_| {
let tx = tx.clone();
Arc::new(move |e| tx.send(e).unwrap())
}),
..config
});
ide_host::ops::ssh::ssh_set_secret(&host, "main", "box".into(), Some("test-value".into()), true);
let warning = rx.try_iter().find_map(|e| match e {
IdeEvent::Notify { level: ide_core::event::NotifyLevel::Warning, body, .. } => body,
_ => None,
});
let warning = warning.expect("the window should be told saving failed");
assert!(warning.contains("session only"));
assert!(!warning.contains("test-value"));
assert_eq!(host.ssh.password("box").as_deref(), Some("test-value"));
}
fn read_until(rx: &mpsc::Receiver<String>, needle: &str) -> String {
let mut all = String::new();
while !all.contains(needle) {
@@ -62,8 +38,7 @@ async fn host_with_ssh_box(tmp: &Path, exec: ide_ssh::testing::ExecFn) -> (Arc<H
save_secret: true,
..Default::default()
}]);
ide_ssh::secrets::testing::use_memory_store();
ssh.set_secret("box", Some("secret".into()), true).unwrap();
ssh.set_secret("box", Some("secret".into()), true);
assert!(ssh.session("box").await.is_err(), "unknown host key first");
ssh.trust_host("box").await.unwrap();
+1 -1
View File
@@ -80,7 +80,7 @@ async fn welcome_window_browses_selected_ssh_host_without_executing_commands() {
auth: SshAuth::Password,
..Default::default()
}]);
ssh.set_secret("selected-host", Some("secret".into()), false).unwrap();
ssh.set_secret("selected-host", Some("secret".into()), false);
assert!(ssh.session("selected-host").await.is_err());
ssh.trust_host("selected-host").await.unwrap();
+6 -16
View File
@@ -88,18 +88,10 @@ done
let events = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
let sink = events.clone();
let channel = ops::Channel::new(move |event: ide_build::compile::BuildEvent| sink.lock().unwrap().push(event));
let info = ops::java::java_resolve_launch(
&host,
"main",
module,
test,
false,
BuildPolicy::Make,
RequestId::next(),
channel,
)
.await
.unwrap();
let info =
ops::java::java_resolve_launch(&host, "main", module, test, BuildPolicy::Make, RequestId::next(), channel)
.await
.unwrap();
// The build streams its command and progress while it runs.
use ide_build::compile::BuildEvent;
let events = events.lock().unwrap();
@@ -118,11 +110,9 @@ done
assert!(info.class_paths.iter().any(|p| std::path::Path::new(p) == out));
assert!(info.class_paths.iter().any(|p| std::path::Path::new(p) == jar));
let calls = fs::read_to_string(root.join("calls")).unwrap();
// This Maven records no build model for the IDE's Java build, so Maven builds the module.
assert!(calls.lines().next().unwrap().contains("-Dopenidea.build.model="), "{calls}");
assert!(calls.lines().nth(1).unwrap().contains("-pl app -am"), "{calls}");
assert!(calls.lines().next().unwrap().contains("-pl app -am"), "{calls}");
assert!(calls.lines().all(|line| line.contains(&format!("-P member-{index}"))), "{calls}");
assert!(calls.contains(":build-classpath"), "{calls}");
assert!(calls.contains("dependency:build-classpath"), "{calls}");
}
}
-12
View File
@@ -305,18 +305,6 @@ impl PathFilter {
builder.build().flatten().filter(|e| e.file_type().is_some_and(|t| t.is_dir())).map(|e| e.into_path()).collect()
}
/// The folders directly in `dir` that the index would walk.
pub(crate) fn child_dirs(&self, dir: &Path) -> Vec<PathBuf> {
let Some(mut builder) = self.walker(dir) else { return Vec::new() };
builder
.max_depth(Some(1))
.build()
.flatten()
.filter(|e| e.depth() == 1 && e.file_type().is_some_and(|t| t.is_dir()))
.map(|e| e.into_path())
.collect()
}
pub(crate) fn directories_with_names(&self, names: &HashSet<&OsStr>) -> Vec<PathBuf> {
let matches = parking_lot::Mutex::new(Vec::new());
for root in self.roots() {
-7
View File
@@ -26,12 +26,6 @@ pub use filter::walk_skips;
pub use worker::MAX_SYMBOL_FILE;
use worker::{Job, MAX_RECENT, Shared};
/// Stack of the indexing threads. Parsing and outlining a deeply nested file (generated
/// code, a big JSON or minified script) recurse as deep as the file nests; the 2 MiB a Rust
/// thread gets by default overflowed on Windows and took the whole IDE down (#5739). Only
/// what a thread touches is committed, so the reservation costs address space, not memory.
const INDEX_STACK: usize = 32 * 1024 * 1024;
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct FileMatch {
@@ -156,7 +150,6 @@ impl ProjectIndex {
let shared = shared.clone();
std::thread::Builder::new()
.name("openidea-index".into())
.stack_size(INDEX_STACK)
.spawn(move || shared.run(scan))
.map_err(|e| ide_core::IdeError::internal(format!("cannot start indexer: {e}")))?
};
-63
View File
@@ -1246,66 +1246,3 @@ fn queries_during_streaming_scan_do_not_deadlock() {
done_rx.recv_timeout(Duration::from_secs(60)).expect("concurrent index queries deadlocked with streaming scan");
}
#[test]
fn reconciling_a_few_changed_files_does_not_show_indexing() {
let fx = sample();
let events = Arc::new(Mutex::new(Vec::new()));
let sink: SharedSink = {
let events = events.clone();
Arc::new(move |e: IdeEvent| events.lock().push(e))
};
let idx = fx.open_with(sink);
let announced = |events: &Mutex<Vec<IdeEvent>>| {
events
.lock()
.iter()
.filter(|e| matches!(e, IdeEvent::IndexState { indexing: true, .. } | IdeEvent::Task { done: false, .. }))
.count()
};
let settle = || {
assert!(idx.wait_idle(WAIT));
// The touched folders are reconciled once the snapshot delay has passed.
std::thread::sleep(Duration::from_millis(300));
assert!(idx.wait_idle(WAIT));
};
// A program appending to its log in the project, as a debugged Spring app does.
events.lock().clear();
let log = fx.write("logs/app.log", "start\n");
for i in 0..3 {
std::fs::write(&log, format!("line {i}\n").repeat(i + 1)).unwrap();
idx.update(std::slice::from_ref(&log), &[]);
settle();
}
assert_eq!(announced(&events), 0, "a log being written must not show Indexing");
assert!(files(&idx, "app.log").contains(&"logs/app.log".to_owned()), "the log is still indexed");
}
/// #5749: a file at the project root changing must not re-walk the whole project when the
/// touched folders are reconciled, yet folders that appear or vanish there are still picked up.
#[test]
fn reconciling_a_root_change_lists_only_that_folder() {
let fx = sample();
let idx = fx.open();
// Written behind the index's back, deep in a folder it already knows.
fx.write("src/order/Unreported.java", "class Unreported {}\n");
// A new folder, a vanished one and an unreported file next to the changed root file.
fx.write("fresh/deep/Fresh.java", "class Fresh {}\n");
std::fs::remove_dir_all(fx.root.join("docs")).unwrap();
fx.write("Unlisted.txt", "x\n");
let log = fx.write("app.log", "line\n");
idx.update(std::slice::from_ref(&log), &[]);
assert!(idx.wait_idle(WAIT));
// The touched folders are reconciled once the snapshot delay has passed.
std::thread::sleep(Duration::from_millis(300));
assert!(idx.wait_idle(WAIT));
assert!(files(&idx, "app.log").contains(&"app.log".to_owned()), "the changed file is indexed");
assert!(files(&idx, "Unlisted").contains(&"Unlisted.txt".to_owned()), "the root folder is listed");
assert!(files(&idx, "Fresh").contains(&"fresh/deep/Fresh.java".to_owned()), "a new folder is walked");
assert!(files(&idx, "maintenance").is_empty(), "a vanished folder's files are dropped");
assert!(files(&idx, "main.rs").contains(&"src/main.rs".to_owned()), "other folders keep their files");
assert!(files(&idx, "Unreported").is_empty(), "known subfolders are not re-walked");
}
+32 -128
View File
@@ -22,7 +22,6 @@ use std::time::{Duration, Instant, SystemTime};
static INDEX_POOL: LazyLock<rayon::ThreadPool> = LazyLock::new(|| {
rayon::ThreadPoolBuilder::new()
.thread_name(|i| format!("openidea-index-{i}"))
.stack_size(crate::INDEX_STACK)
.build()
.expect("cannot build index thread pool")
});
@@ -37,15 +36,6 @@ const PROGRESS_EVERY: Duration = Duration::from_millis(250);
const SNAPSHOT_DELAY: Duration = Duration::from_secs(2);
#[cfg(test)]
const SNAPSHOT_DELAY: Duration = Duration::from_millis(50);
/// The shortest gap between two snapshot refreshes. Any index write drops the snapshot (see
/// `Store::apply`), so a later refresh only makes the next startup faster; a project whose files
/// keep changing (a log written inside it) would otherwise rewrite it every couple of seconds.
#[cfg(not(test))]
const SNAPSHOT_EVERY: Duration = Duration::from_secs(10);
#[cfg(test)]
const SNAPSHOT_EVERY: Duration = Duration::ZERO;
/// A subtree scan with fewer files to parse runs without showing "Indexing" (see `scan`).
const QUIET_SCAN_FILES: usize = 200;
pub(crate) const MAX_RECENT: usize = 50;
pub(crate) enum Job {
@@ -85,8 +75,6 @@ pub(crate) struct Shared {
idle: Condvar,
/// Coalesced post-update snapshot refresh.
snapshot_due: Mutex<Option<Instant>>,
/// When the snapshot was last refreshed (see [`SNAPSHOT_EVERY`]).
snapshot_saved: Mutex<Option<Instant>>,
/// Directories whose watcher events still need reconciliation before a
/// refreshed snapshot can be trusted.
pending_dirs: Mutex<HashSet<PathBuf>>,
@@ -115,7 +103,6 @@ impl Shared {
wake: Condvar::new(),
idle: Condvar::new(),
snapshot_due: Mutex::default(),
snapshot_saved: Mutex::default(),
pending_dirs: Mutex::default(),
}
}
@@ -457,8 +444,7 @@ impl Shared {
}
/// A cancelled scan (project closed) still ends its progress task and the indexing state.
fn end_scan(&self, task: Option<TaskId>) {
let Some(task) = task else { return };
fn end_scan(&self, task: TaskId) {
self.indexing.store(false, Ordering::SeqCst);
self.sink.emit(IdeEvent::Task {
id: task,
@@ -485,13 +471,13 @@ impl Shared {
}
fn full_scan(&self, found: Option<Vec<Found>>, guard: SystemTime) {
self.scan(None, &[], found, guard);
self.scan(None, found, guard);
// Parsing every file churns through far more memory than the index keeps.
ide_core::memory::release_free_pages();
}
/// Shows "Indexing" (the status flag and a background task) for a scan.
fn start_scan(&self) -> TaskId {
fn scan(&self, dirs: Option<&[PathBuf]>, prewalked: Option<Vec<Found>>, guard: SystemTime) -> Option<ScanCounts> {
let started = Instant::now();
self.indexing.store(true, Ordering::SeqCst);
self.emit_state();
let task = TaskId::next();
@@ -503,25 +489,6 @@ impl Shared {
done: false,
cancellable: false,
});
task
}
/// A full scan shows "Indexing" from the start. A subtree scan (folders the watcher reported,
/// reconciled after each burst of changes) shows it only once it has
/// [`QUIET_SCAN_FILES`] or more files to parse: a program writing its log inside the project
/// would otherwise keep "Indexing" in the status bar for as long as it runs.
///
/// Indexed files the walk didn't see are dropped when they are below one of `dirs` (all of
/// them for a full scan) or directly in one of `shallow`.
fn scan(
&self,
dirs: Option<&[PathBuf]>,
shallow: &[PathBuf],
prewalked: Option<Vec<Found>>,
guard: SystemTime,
) -> Option<ScanCounts> {
let started = Instant::now();
let mut task = dirs.is_none().then(|| self.start_scan());
let filter = self.filter();
let walk_started = Instant::now();
@@ -540,10 +507,7 @@ impl Shared {
found.iter().filter_map(|f| prev_hash_if_stale(&d, f).map(|h| (f, h))).collect();
let stale: Vec<PathBuf> = d
.paths()
.filter(|p| {
dirs.is_none_or(|dirs| dirs.iter().any(|dir| p.starts_with(dir)))
|| p.parent().is_some_and(|parent| shallow.iter().any(|dir| dir == parent))
})
.filter(|p| dirs.is_none_or(|dirs| dirs.iter().any(|dir| p.starts_with(dir))))
.filter(|p| !seen.contains(p.as_path()))
.cloned()
.collect();
@@ -560,9 +524,6 @@ impl Shared {
self.persist(&[], &stale, false);
let total = todo.len();
if task.is_none() && total >= QUIET_SCAN_FILES {
task = Some(self.start_scan());
}
let update_started = Instant::now();
let mut laps = ChunkLaps::default();
{
@@ -603,9 +564,7 @@ impl Shared {
}
done += batch.len();
laps.add(self.publish(batch.drain(..)));
if let Some(task) = task
&& last_progress.elapsed() >= PROGRESS_EVERY
{
if last_progress.elapsed() >= PROGRESS_EVERY {
last_progress = Instant::now();
self.sink.emit(IdeEvent::Task {
id: task,
@@ -647,19 +606,15 @@ impl Shared {
}
let snapshot_elapsed = snapshot_started.elapsed();
*self.snapshot_due.lock() = None;
*self.snapshot_saved.lock() = Some(Instant::now());
if let Some(task) = task {
self.indexing.store(false, Ordering::SeqCst);
self.sink.emit(IdeEvent::Task {
id: task,
title: "Indexing".into(),
message: None,
fraction: Some(1.0),
done: true,
cancellable: false,
});
}
// The counts may have changed either way.
self.indexing.store(false, Ordering::SeqCst);
self.sink.emit(IdeEvent::Task {
id: task,
title: "Indexing".into(),
message: None,
fraction: Some(1.0),
done: true,
cancellable: false,
});
self.emit_state();
if self.is_cancelled() {
return None;
@@ -802,67 +757,17 @@ impl Shared {
}
let mut due = self.snapshot_due.lock();
if due.is_none() {
let soonest = self.snapshot_saved.lock().map(|saved| saved + SNAPSHOT_EVERY);
*due = Some((Instant::now() + SNAPSHOT_DELAY).max(soonest.unwrap_or(Instant::now())));
*due = Some(Instant::now() + SNAPSHOT_DELAY);
}
}
/// Reconciles the folders the watcher reported since the last snapshot, then refreshes it.
/// A folder the index already has files below is listed one level deep: its own files, plus
/// any subfolder that appeared (walked whole) or is gone (its files dropped). A folder it
/// knows nothing below is walked whole. Walking known folders whole would re-read the entire
/// project after every change to a file at its root.
fn reconcile(&self, dirs: &[PathBuf]) {
let filter = self.filter();
// The subfolders each reported folder has indexed files in; absent when it has none.
let mut known: HashMap<&Path, HashSet<PathBuf>> = HashMap::new();
{
let d = self.data.read();
for path in d.paths() {
for dir in dirs {
let Ok(rest) = path.strip_prefix(dir) else { continue };
let subdirs = known.entry(dir.as_path()).or_default();
let mut parts = rest.components();
if let (Some(first), Some(_)) = (parts.next(), parts.next()) {
subdirs.insert(dir.join(first));
}
}
}
}
let mut found = Vec::new();
let mut trees = Vec::new();
let mut shallow = Vec::new();
for dir in dirs {
let Some(indexed) = known.get(dir.as_path()) else {
found.extend(filter.walk(dir, &self.cancelled));
trees.push(dir.clone());
continue;
};
found.extend(filter.list_dir(dir));
shallow.push(dir.clone());
for sub in filter.child_dirs(dir) {
if !indexed.contains(&sub) {
found.extend(filter.walk(&sub, &self.cancelled));
trees.push(sub);
}
}
// Gone from disk; a subfolder only hidden from the listing (an extra content root
// or a newly excluded folder) is handled by its own root or the rule-change rescan.
trees.extend(indexed.iter().filter(|sub| std::fs::symlink_metadata(sub).is_err()).cloned());
}
// Reported folders may nest; parse each file once.
let mut unique = HashSet::new();
found.retain(|f| unique.insert(f.path.clone()));
self.scan(Some(&trees), &shallow, Some(found), SystemTime::now());
}
fn save_snapshot_now(&self) {
let dirs: Vec<PathBuf> = self.pending_dirs.lock().drain().collect();
if !dirs.is_empty() {
// Reconcile the directories touched since the last scan before
// recording their mtimes; otherwise a missed watcher event could be
// blessed into the manifest.
self.reconcile(&dirs);
self.scan(Some(&dirs), None, SystemTime::now());
return;
}
if let Some(store) = &self.store {
@@ -874,7 +779,6 @@ impl Shared {
}
}
*self.snapshot_due.lock() = None;
*self.snapshot_saved.lock() = Some(Instant::now());
}
fn persist(&self, puts: &[(String, FileRecord)], deletes: &[String], durable: bool) {
@@ -980,7 +884,7 @@ impl Shared {
}
}
if !rescan {
self.scan(Some(&roots), &[], None, SystemTime::now());
self.scan(Some(&roots), None, SystemTime::now());
changed.retain(|p| !roots.iter().any(|root| p.starts_with(root)));
removed.retain(|p| !roots.iter().any(|root| p.starts_with(root)));
}
@@ -1270,7 +1174,7 @@ mod metric_tests {
batch.extend([sub.join(format!("f{i}.txt")), sub, root.join("gone")]);
}
std::fs::write(root.join("keep.txt"), "x").unwrap();
shared.scan(None, &[], None, SystemTime::now()).unwrap();
shared.scan(None, None, SystemTime::now()).unwrap();
assert_eq!(shared.data.read().file_count, 41);
std::fs::remove_dir_all(root.join("gone")).unwrap();
@@ -1294,7 +1198,7 @@ mod metric_tests {
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(p, "x").unwrap();
}
shared.scan(None, &[], None, SystemTime::now()).unwrap();
shared.scan(None, None, SystemTime::now()).unwrap();
assert_eq!(shared.data.read().file_count, 7);
std::fs::remove_dir_all(root.join("gone")).unwrap();
@@ -1329,11 +1233,11 @@ mod metric_tests {
for i in 0..count {
std::fs::write(root.join(format!("file_{i}.unknown")), "plain").unwrap();
}
let cold = shared.scan(None, &[], None, SystemTime::now()).unwrap();
let cold = shared.scan(None, None, SystemTime::now()).unwrap();
assert_eq!((cold.discovered, cold.metadata_reused, cold.scheduled), (count, 0, count));
assert_eq!(cold.outcomes, ExtractionCounts { unsupported: count, ..Default::default() });
assert_eq!(shared.data.read().file_count as usize, count);
let hot = shared.scan(None, &[], None, SystemTime::now()).unwrap();
let hot = shared.scan(None, None, SystemTime::now()).unwrap();
assert_eq!((hot.discovered, hot.metadata_reused, hot.scheduled), (count, count, 0));
assert_eq!(hot.outcomes.total(), 0);
}
@@ -1345,7 +1249,7 @@ mod metric_tests {
let shared = shared(&root);
let path = root.join("main.rs");
std::fs::write(&path, "fn main() {}").unwrap();
shared.scan(None, &[], None, SystemTime::now()).unwrap();
shared.scan(None, None, SystemTime::now()).unwrap();
let (found, hash) = {
let data = shared.data.read();
let e = data.get(&path).unwrap();
@@ -1365,10 +1269,10 @@ mod metric_tests {
let path = root.join("main.rs");
std::fs::write(&path, "fn main() {}\n").unwrap();
let shared = shared(&root);
let cold = shared.scan(None, &[], None, SystemTime::now()).unwrap();
let cold = shared.scan(None, None, SystemTime::now()).unwrap();
assert_eq!((cold.discovered, cold.metadata_reused, cold.scheduled), (1, 0, 1));
assert_eq!(cold.outcomes, ExtractionCounts { symbol_extractions: 1, ..Default::default() });
let hot = shared.scan(None, &[], None, SystemTime::now()).unwrap();
let hot = shared.scan(None, None, SystemTime::now()).unwrap();
assert_eq!((hot.discovered, hot.metadata_reused, hot.scheduled), (1, 1, 0));
assert_eq!(hot.outcomes, ExtractionCounts::default());
// Force a metadata mismatch without a timestamp-resolution-dependent sleep.
@@ -1379,7 +1283,7 @@ mod metric_tests {
rec.mtime = rec.mtime.wrapping_add(1);
let (entry, symbols) = FileEntry::new(path.clone(), "main.rs".into(), rec);
shared.data.write().insert(entry, symbols);
let touched = shared.scan(None, &[], None, SystemTime::now()).unwrap();
let touched = shared.scan(None, None, SystemTime::now()).unwrap();
assert_eq!((touched.discovered, touched.metadata_reused, touched.scheduled), (1, 0, 1));
assert_eq!(touched.outcomes, ExtractionCounts { hash_reused: 1, ..Default::default() });
assert_eq!(shared.data.read().symbol_count, 1);
@@ -1435,13 +1339,13 @@ mod metric_tests {
{
let mut index = shared(&root);
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
assert_eq!(index.scan(None, &[], None, SystemTime::now()).unwrap().outcomes.symbol_extractions, 1);
assert_eq!(index.scan(None, None, SystemTime::now()).unwrap().outcomes.symbol_extractions, 1);
}
let mut index = shared(&root);
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
let found = index.walk_roots(None);
index.load_persisted(&found);
let counts = index.scan(None, &[], Some(found), SystemTime::now()).unwrap();
let counts = index.scan(None, Some(found), SystemTime::now()).unwrap();
assert_eq!((counts.discovered, counts.metadata_reused, counts.scheduled), (1, 1, 0));
assert_eq!(counts.outcomes, ExtractionCounts::default());
assert_eq!(index.data.read().symbol_count, 1);
@@ -1458,7 +1362,7 @@ mod metric_tests {
{
let mut index = shared(&root);
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
assert_eq!(index.scan(None, &[], None, SystemTime::now()).unwrap().outcomes.symbol_extractions, 1);
assert_eq!(index.scan(None, None, SystemTime::now()).unwrap().outcomes.symbol_extractions, 1);
}
let mut index = shared(&root);
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
@@ -1507,7 +1411,7 @@ mod metric_tests {
{
let mut index = shared(&root);
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
index.scan(None, &[], None, SystemTime::now()).unwrap();
index.scan(None, None, SystemTime::now()).unwrap();
}
let mut index = shared(&root);
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
@@ -1558,7 +1462,7 @@ mod metric_tests {
});
index
});
assert!(index.scan(None, &[], None, SystemTime::now()).is_none());
assert!(index.scan(None, None, SystemTime::now()).is_none());
assert!(index.is_cancelled());
assert!(!index.indexing.load(Ordering::Relaxed));
assert_eq!(index.data.read().file_count, 1);
@@ -1569,7 +1473,7 @@ mod metric_tests {
let dir = tempfile::tempdir().unwrap();
let shared = shared(dir.path());
shared.cancel();
assert!(shared.scan(None, &[], None, SystemTime::now()).is_none());
assert!(shared.scan(None, None, SystemTime::now()).is_none());
assert!(!shared.indexing.load(Ordering::Relaxed));
}
}
+1 -1
View File
@@ -320,7 +320,7 @@ mod tests {
})
.unwrap();
assert_eq!(json, "{\"threadDump\":{}}");
let prefix = format!("Thread.dump_to_file -format=json \"{}", dir.join("threads-42-").display());
let prefix = format!("Thread.dump_to_file -format=json \"{}/threads-42-", dir.display());
assert!(sent.starts_with(&prefix) && sent.ends_with(".json\""), "{sent}");
assert!(is_empty(&dir));
}
-29
View File
@@ -87,7 +87,6 @@ use std::time::Duration;
use text::{DocText, Encoding};
use types::*;
const DART_SERVER: &str = "dart";
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10);
const COMPLETION_TIMEOUT: Duration = Duration::from_secs(5);
const LONG_TIMEOUT: Duration = Duration::from_secs(30);
@@ -2449,34 +2448,6 @@ impl LspManager {
.then(|| outline.items.clone())
}
/// The arguments of the call at `pos` the Flutter Property Editor shows; `None` outside a
/// call, or when no Dart server serves the document.
pub async fn editable_arguments(&self, doc: DocId, pos: Pos) -> IdeResult<Option<EditableArguments>> {
let (snap, targets) = self.doc_targets(doc, "the property editor", |_| true).await?;
let Some(t) = targets.iter().find(|t| t.server.name == DART_SERVER) else { return Ok(None) };
self.call(t, "dart/textDocument/editableArguments", snap.pos_params(t, pos), None, DEFAULT_TIMEOUT).await
}
/// Sets the argument `name` of the call at `pos` to `value` (`None` passes null). The server
/// sends the edit back as `workspace/applyEdit`, which the apply-edit hook applies.
pub async fn edit_argument(
&self,
doc: DocId,
pos: Pos,
name: String,
value: Option<ArgumentValue>,
) -> IdeResult<()> {
let (snap, targets) = self.doc_targets(doc, "the property editor", |_| true).await?;
let t = targets
.iter()
.find(|t| t.server.name == DART_SERVER)
.ok_or_else(|| IdeError::unavailable("no Dart language server serves this document"))?;
let mut params = snap.pos_params(t, pos);
params["edit"] = json!({ "name": name, "newValue": value });
let _: Value = self.call(t, "dart/textDocument/editArgument", params, None, DEFAULT_TIMEOUT).await?;
Ok(())
}
/// Records a published outline; whether what the open documents of `path` show changed.
fn set_flutter_outline(
&self,
-54
View File
@@ -654,57 +654,3 @@ pub struct ClassifiedReference {
#[specta(optional)]
pub text: Option<String>,
}
/// The arguments the Flutter Property Editor edits: those of the widget (or other) call at a
/// position, as the Dart server's `dart/textDocument/editableArguments` reports them.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct EditableArguments {
/// The widget's (or callee's) name.
pub name: Option<String>,
pub documentation: Option<String>,
pub arguments: Vec<EditableArgument>,
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct EditableArgument {
pub name: String,
pub documentation: Option<String>,
/// How to edit it: `string`, `int`, `double`, `bool` or `enum`.
#[serde(rename = "type")]
pub kind: String,
/// The literal value in the code (only while `has_argument`); an expression has `display_value`.
pub value: Option<ArgumentValue>,
#[serde(default)]
pub has_argument: bool,
pub default_value: Option<ArgumentValue>,
pub display_value: Option<String>,
// Absent from older Dart SDKs (`isDeprecated` came later): read as false rather than
// failing the whole list.
#[serde(default)]
pub is_required: bool,
#[serde(default)]
pub is_nullable: bool,
#[serde(default)]
pub is_deprecated: bool,
#[serde(default = "editable_by_default")]
pub is_editable: bool,
pub not_editable_reason: Option<String>,
/// An enum's values, as `EnumName.value`.
pub options: Option<Vec<String>>,
}
fn editable_by_default() -> bool {
true
}
/// A literal argument value. Ints stay ints: the server rejects `1.0` for an `int` parameter.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(untagged)]
pub enum ArgumentValue {
Bool(bool),
Int(i64),
Double(f64),
Text(String),
}
-79
View File
@@ -1549,85 +1549,6 @@ async fn flutter_outline_follows_the_document_and_the_server_instance() {
assert!(h.mgr.flutter_outline(reopened).is_none());
}
#[tokio::test(flavor = "multi_thread")]
async fn property_editor_lists_the_dart_servers_arguments_and_applies_its_edit() {
let h = harness(&[("dart", incremental_caps())]);
let (doc, path) = h.open("a.mk", "Text('x')\n");
h.wait_status("dart", ServerStatus::Ready).await;
let s = h.launcher.state("dart");
let arg = |name: &str, extra: Value| {
let mut a = json!({ "name": name, "hasArgument": false, "isRequired": false, "isNullable": true,
"isDeprecated": false, "isEditable": true });
a.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
a
};
let at = json!({"start":{"line":0,"character":0},"end":{"line":0,"character":9}});
s.respond(
"dart/textDocument/editableArguments",
json!({ "textDocument": { "uri": uri_of(&path), "version": 1 }, "name": "Text", "range": at, "arguments": [
arg("data", json!({ "type": "string", "value": "x", "hasArgument": true, "isRequired": true, "isNullable": false })),
arg("textAlign", json!({ "type": "enum", "options": ["TextAlign.left", "TextAlign.center"] })),
arg("maxLines", json!({ "type": "int", "value": 2, "hasArgument": true })),
// An older SDK leaves out flags it doesn't know yet.
json!({ "name": "softWrap", "type": "bool", "hasArgument": false }),
]}),
);
let args = h.mgr.editable_arguments(doc, Pos::new(0, 2)).await.unwrap().unwrap();
assert_eq!(args.name.as_deref(), Some("Text"));
assert_eq!(
(args.arguments[0].kind.as_str(), args.arguments[0].value.clone()),
("string", Some(ArgumentValue::Text("x".into())))
);
assert_eq!(args.arguments[1].options.as_ref().unwrap()[1], "TextAlign.center");
assert_eq!(args.arguments[1].value, None);
assert!(args.arguments[3].is_editable && !args.arguments[3].is_deprecated && !args.arguments[3].is_required);
assert_eq!(args.arguments[2].value, Some(ArgumentValue::Int(2)));
let asked = s.requested("dart/textDocument/editableArguments");
assert_eq!(asked[0]["position"], json!({"line":0,"character":2}));
// The server answers editArgument with null and sends the edit as workspace/applyEdit.
let applied: Arc<Mutex<Vec<WorkspaceEdit>>> = Arc::default();
let received = applied.clone();
h.mgr.set_apply_edit_hook(Box::new(move |e| {
received.lock().push(e);
true
}));
let uri = uri_of(&path);
*s.responder.lock() = Some(Arc::new(move |s, method, _| {
(method == "dart/textDocument/editArgument").then(|| {
let edit = json!({ "changes": { uri.clone(): [{ "range":
{"start":{"line":0,"character":5},"end":{"line":0,"character":8}}, "newText": "'y'" }] } });
let reply: Value = tokio::task::block_in_place(|| {
tokio::runtime::Handle::current().block_on(s.peer().request(
"workspace/applyEdit",
json!({ "edit": edit }),
None,
))
})
.unwrap();
assert_eq!(reply, json!({"applied": true}));
Value::Null
})
}));
h.mgr.edit_argument(doc, Pos::new(0, 2), "data".into(), Some(ArgumentValue::Text("y".into()))).await.unwrap();
let sent = s.requested("dart/textDocument/editArgument");
assert_eq!(sent[0]["edit"], json!({ "name": "data", "newValue": "y" }));
assert_eq!(sent[0]["position"], json!({"line":0,"character":2}));
let edits = applied.lock().clone();
assert!(
matches!(&edits[..], [e] if matches!(&e.files[0], FileEdit::Edit { edits, .. } if edits[0].new_text == "'y'"))
);
}
#[tokio::test(flavor = "multi_thread")]
async fn property_editor_has_nothing_without_a_dart_server() {
let h = harness(&[("mock", incremental_caps())]);
let (doc, _) = h.open("a.mk", "Text('x')\n");
h.wait_status("mock", ServerStatus::Ready).await;
assert!(h.mgr.editable_arguments(doc, Pos::new(0, 2)).await.unwrap().is_none());
assert!(h.launcher.state("mock").requested("dart/textDocument/editableArguments").is_empty());
}
#[tokio::test(flavor = "multi_thread")]
async fn closing_labels_join_the_inlay_hints_until_the_next_edit() {
let h = harness(&[("mock", incremental_caps())]);
-104
View File
@@ -1188,107 +1188,3 @@ async fn phoxite_pulls_a_member_up_end_to_end() {
assert!(!refused.message.is_empty() && !refused.message.starts_with("phoxite:"), "{refused:?}");
mgr.shutdown_all().await;
}
/// jdtls keeps building incrementally even though the IDE's Java build compiles what runs:
/// its build is what reports an API change in one Maven module in the files of the modules
/// that use it, open or not. With `java.autobuild.enabled: false` (and
/// `validateAllOpenBuffersOnChanges`), neither updates.
#[tokio::test(flavor = "multi_thread")]
#[ignore = "requires jdtls on PATH (or OPENIDEA_TEST_JDTLS) and a compatible JDK"]
async fn jdtls_build_reports_cross_module_errors_in_open_and_closed_files() {
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap().join("project");
let write = |rel: &str, text: &str| {
let path = root.join(rel);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(&path, text).unwrap();
path
};
let parent = r#"<parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent>"#;
write(
"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>app</module></modules><properties><maven.compiler.release>11</maven.compiler.release></properties></project>"#,
);
write(
"lib/pom.xml",
&format!("<project><modelVersion>4.0.0</modelVersion>{parent}<artifactId>lib</artifactId></project>"),
);
write(
"app/pom.xml",
&format!(
"<project><modelVersion>4.0.0</modelVersion>{parent}<artifactId>app</artifactId><dependencies><dependency><groupId>t</groupId><artifactId>lib</artifactId><version>1</version></dependency></dependencies></project>"
),
);
let lib_source = "package l;\npublic class L { public static String name() { return \"lib\"; } }\n";
let app_source = "package a;\npublic class A { String s = l.L.name(); }\n";
let lib = write("lib/src/main/java/l/L.java", lib_source);
let app = write("app/src/main/java/a/A.java", app_source);
let closed = write("app/src/main/java/a/B.java", "package a;\nclass B { String s = l.L.name(); }\n");
let mut java = LanguageRegistry::load(None).unwrap().get(&LanguageId::new("java")).unwrap();
java.language_servers.retain(|s| s.name == "jdtls");
let server = &mut java.language_servers[0];
if let Ok(bin) = std::env::var("OPENIDEA_TEST_JDTLS") {
server.command = bin;
}
server.args.extend(["-data".into(), dir.path().join("jdtls-data").to_string_lossy().into_owned()]);
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![java]));
let (lib_doc, app_doc) = (DocId::next(), DocId::next());
mgr.did_open(lib_doc, &lib, &LanguageId::new("java"), 1, lib_source);
mgr.did_open(app_doc, &app, &LanguageId::new("java"), 1, app_source);
let errors = |path: &Path| {
events.lock().iter().rev().find_map(|e| match e {
IdeEvent::Diagnostics { path: p, items, .. } if p.0 == path => Some(
items
.iter()
.filter(|d| d.severity == ide_core::Severity::Error)
.map(|d| d.message.clone())
.collect::<Vec<_>>(),
),
_ => None,
})
};
// The import resolves `lib` from source: the open editor of `app` has no errors.
retry("app imported", Duration::from_secs(300), || {
let status = last_status(&events, "jdtls");
if let Some((ServerStatus::Crashed | ServerStatus::Missing | ServerStatus::Misconfigured, message)) = &status {
panic!("jdtls failed: {message:?}");
}
let clean = errors(&app).is_some_and(|e| e.is_empty());
let mgr = mgr.clone();
let app = app.clone();
async move {
let cp =
tokio::time::timeout(Duration::from_secs(10), mgr.java_classpath(&app, false, &Default::default()))
.await
.ok()?
.ok()?;
(clean && cp.class_paths.iter().any(|p| p.contains("/lib/"))).then_some(())
}
})
.await;
// Rename the method in the editor of `lib`, and save.
let renamed = lib_source.replace("name()", "title()");
let line = lib_source.lines().nth(1).unwrap();
mgr.did_change(
lib_doc,
2,
&[AppliedChange {
range: Range::new(Pos::new(1, 0), Pos::new(1, line.len() as u32)),
text: renamed.lines().nth(1).unwrap().to_owned(),
}],
&|| renamed.clone(),
);
std::fs::write(&lib, &renamed).unwrap();
mgr.did_save(lib_doc, &renamed);
retry("the open editor of app reports the removed method", Duration::from_secs(120), || {
let found = errors(&app).is_some_and(|e| e.iter().any(|m| m.contains("name()")));
async move { found.then_some(()) }
})
.await;
retry("the closed file of app reports it too", Duration::from_secs(60), || {
let found = errors(&closed).is_some_and(|e| e.iter().any(|m| m.contains("name()")));
async move { found.then_some(()) }
})
.await;
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
}
+2 -7
View File
@@ -168,13 +168,8 @@ impl Session<'_> {
"instructions": format!(
"Built-in OpenIDEA tools for {about}: they see the files as the IDE has them and, \
for a project open in a window, its editors. The project's workspace can include other \
projects attached to it, which a session's working directory doesn't show. Before the \
first project-related operation in a session, call `get_workspace_roots`: its \
`projectRoot` is the project this connection serves and the default base for paths, and \
its `roots` are every project in the IDE workspace. That is the scope to search and read, \
not a list of projects to change; it doesn't change your working directory or \
permissions. Pass another root as `projectPath` to reach that project. Call it again \
when the user switches projects or attaches one."
projects attached to it: call `get_workspace_roots` to list them before answering about \
workspace directories or planning a change across projects."
),
})
}
-2
View File
@@ -282,8 +282,6 @@ async fn a_folder_served_in_the_background_answers_initialize_list_and_call() {
let init = rpc_for(&s, &inside, "initialize", json!({})).await;
let instructions = init["result"]["instructions"].as_str().unwrap();
assert!(instructions.contains(inventory.to_str().unwrap()), "{instructions}");
// Clients that load tool descriptions lazily still learn to establish the workspace first (#5751).
assert!(instructions.contains("first project-related operation in a session, call `get_workspace_roots`"));
let list = rpc_for(&s, &inside, "tools/list", json!({})).await;
assert_eq!(list["result"]["tools"][0]["description"], format!("Names {}", inventory.display()), "{list}");
let call = rpc_for(&s, &inside, "tools/call", json!({ "name": "where" })).await;
-57
View File
@@ -123,27 +123,6 @@ fn is_jetbrains_jdk(java: &Path) -> bool {
release_field(java, "IMPLEMENTOR").is_some_and(|v| v.to_ascii_lowercase().contains("jetbrains"))
}
/// The JVM a configuration whose command is `command` starts, for the JDK filter. A path is
/// itself. A bare `java` is the first one on `search`, as the launch finds it; when that is
/// no JDK's own launcher (macOS's `/usr/bin/java` stub, which runs `JAVA_HOME`'s), it is
/// `java_home`'s. `None` when neither is found.
pub fn launched_java(command: &str, search: &std::ffi::OsStr, java_home: Option<&Path>) -> Option<PathBuf> {
let path = Path::new(command);
if path.components().count() > 1 {
return Some(path.to_path_buf());
}
let windows = cfg!(windows);
let found =
ide_core::process::find_executable_in(command, search, windows, std::env::var("PATHEXT").ok().as_deref());
if let Some(java) = &found
&& release_field(java, "JAVA_VERSION").is_some()
{
return found;
}
let java = java_home.map(|home| home.join("bin").join(if windows { "java.exe" } else { "java" }));
java.filter(|java| java.is_file()).or(found)
}
/// `KEY="value"` from the JDK `release` file next to `bin/java` (or JDK 8's `jre/bin/java`).
fn release_field(java: &Path, key: &str) -> Option<String> {
let java = std::fs::canonicalize(java).unwrap_or_else(|_| java.to_path_buf());
@@ -247,42 +226,6 @@ fn split_text(text: &str) -> Vec<String> {
mod tests {
use super::*;
/// A JDK home with `bin/java` and a `release` file naming `implementor`.
#[cfg(unix)]
fn jdk(root: &Path, name: &str, implementor: &str) -> PathBuf {
let home = root.join(name);
std::fs::create_dir_all(home.join("bin")).unwrap();
std::fs::write(home.join("bin/java"), "#!/bin/sh\n").unwrap();
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(home.join("bin/java"), std::fs::Permissions::from_mode(0o755)).unwrap();
std::fs::write(home.join("release"), format!("JAVA_VERSION=\"21\"\nIMPLEMENTOR=\"{implementor}\"\n")).unwrap();
home
}
#[cfg(unix)]
#[test]
fn a_bare_java_is_the_one_the_launch_finds() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let jbr = jdk(dir.path(), "jbr", "JetBrains s.r.o.");
let openjdk = jdk(dir.path(), "openjdk", "Eclipse Adoptium");
// A JDK's own launcher on the search path is what runs, whatever JAVA_HOME says.
let search = std::env::join_paths([jbr.join("bin")]).unwrap();
let java = launched_java("java", &search, Some(&openjdk)).unwrap();
assert!(jdk_allows(Some(&java), Some("jetbrains")));
// A stub outside any JDK (macOS /usr/bin/java) runs JAVA_HOME's.
let stub = dir.path().join("usr/bin");
std::fs::create_dir_all(&stub).unwrap();
std::fs::write(stub.join("java"), "#!/bin/sh\n").unwrap();
std::fs::set_permissions(stub.join("java"), std::fs::Permissions::from_mode(0o755)).unwrap();
let search = std::env::join_paths([stub]).unwrap();
let java = launched_java("java", &search, Some(&jbr)).unwrap();
assert!(jdk_allows(Some(&java), Some("jetbrains")));
assert!(!jdk_allows(launched_java("java", &search, Some(&openjdk)).as_deref(), Some("jetbrains")));
// A path is itself.
assert_eq!(launched_java("/opt/jdk/bin/java", &search, Some(&jbr)), Some(PathBuf::from("/opt/jdk/bin/java")));
}
fn strings(a: &[&str]) -> Vec<String> {
a.iter().map(|s| (*s).to_owned()).collect()
}
+1 -1
View File
@@ -21,7 +21,7 @@ mod utf8;
pub mod wrap;
pub use detect::cmake::{build_configs as cmake_build_configs, prepare as prepare_cmake};
pub use process::{DetachedProcessKills, ProcessManager, StartOptions};
pub use process::{ProcessManager, StartOptions};
use ide_core::{IdeResult, RunId};
use serde::{Deserialize, Serialize};
+4 -28
View File
@@ -3,10 +3,9 @@
use crate::utf8::OutputDecoder;
use crate::{OutputChunk, RunAttach, RunConfig, RunInfo};
use ide_core::pty::native_pty_system;
use ide_core::{IdeError, IdeEvent, IdeResult, RunId, SharedSink};
use parking_lot::Mutex;
use portable_pty::{CommandBuilder, MasterPty, PtySize};
use portable_pty::{CommandBuilder, MasterPty, PtySize, native_pty_system};
use std::collections::{BTreeMap, VecDeque};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
@@ -888,25 +887,15 @@ impl ProcessManager {
}
}
/// Collects every running process tree for `root` and marks it stopping so the actual
/// termination can run on a background thread without blocking the UI thread or racing
/// processes started later.
pub fn detach_project_kills(&self, root: &Path) -> DetachedProcessKills {
let mut targets = Vec::new();
/// Kills every running process tree at once (shutting down).
pub fn kill_project(&self, root: &Path) {
for entry in self.runs.lock().values().filter(|e| e.project_root == root) {
if !entry.exited.load(Ordering::Acquire)
&& let Some(pid) = *entry.pid.lock()
{
entry.stopping.store(true, Ordering::Release);
targets.push((entry.clone(), pid));
kill_tree(entry, pid, true);
}
}
DetachedProcessKills(targets)
}
/// Kills every running process tree at once (shutting down).
pub fn kill_project(&self, root: &Path) {
self.detach_project_kills(root).kill();
}
pub fn kill_all(&self) {
@@ -949,19 +938,6 @@ impl ProcessManager {
}
}
/// Running process trees snapshotted from [`ProcessManager`] to be killed off the caller's thread.
pub struct DetachedProcessKills(Vec<(Arc<Entry>, u32)>);
impl DetachedProcessKills {
pub fn kill(self) {
for (entry, pid) in self.0 {
if !entry.exited.load(Ordering::Acquire) {
kill_tree(&entry, pid, true);
}
}
}
}
impl Drop for ProcessManager {
fn drop(&mut self) {
self.kill_all();
-1
View File
@@ -127,7 +127,6 @@ pub(crate) fn info(def: &Def) -> GeneratorInfo {
description: def.description.clone(),
git: def.git,
fields: def.fields.iter().map(field).collect(),
directory: def.directory.clone(),
dynamic: def.service.is_some(),
}
}
+4 -18
View File
@@ -57,16 +57,6 @@ fn with_defaults(def: &Def, name: &str, values: &Values) -> Values {
out
}
/// The project folder's name: the generator's `directory` template (the solution name of a
/// .NET project with a solution), or the project name.
fn project_folder(def: &Def, name: &str, values: &Values) -> String {
def.directory
.as_deref()
.map(|t| render(t, values).trim().to_owned())
.filter(|folder| !folder.is_empty())
.unwrap_or_else(|| name.to_owned())
}
/// The fields a project service adds to the form (its metadata); empty for other generators.
pub fn options(id: &str, values: &Values, cancel: &CancellationToken) -> IdeResult<Vec<Field>> {
let def = def(id).ok_or_else(|| unknown(id))?;
@@ -408,19 +398,15 @@ pub(crate) fn create_with(
if let Some(e) = name_error(name) {
return Err(IdeError::invalid(e));
}
let values = with_defaults(def, name, &req.values);
let folder = project_folder(def, name, &values);
if let Some(e) = name_error(&folder) {
return Err(IdeError::invalid(e));
}
let location = req.location.to_path_buf();
if !location.is_dir() {
std::fs::create_dir_all(&location)?;
}
let target = location.join(&folder);
let target = location.join(name);
if target_taken(&target) {
return Err(IdeError::invalid(format!("{} already exists and is not empty", target.display())));
}
let values = with_defaults(def, name, &req.values);
let search = search_path();
let mut missing = def
@@ -434,10 +420,10 @@ pub(crate) fn create_with(
return Err(IdeError::unavailable(format!("`{}`{need} is required to create this project", r.program)));
}
let staging = Staging(location.join(format!(".{folder}.openidea-new-{}", std::process::id())));
let staging = Staging(location.join(format!(".{name}.openidea-new-{}", std::process::id())));
let _ = std::fs::remove_dir_all(&staging.0);
std::fs::create_dir_all(&staging.0)?;
let project = staging.0.join(&folder);
let project = staging.0.join(name);
download_service(def, &values, &staging.0, &project, cancel, emit)?;
let creates_dir = def.steps.iter().any(|s| s.cwd == Cwd::Parent && s.applies(&values));
-16
View File
@@ -169,17 +169,6 @@ fn dotnet_pins_the_sdk_and_creates_a_solution() {
let (pin, lines) = render(&[("solution", "false")]);
assert_eq!(pin, None);
assert_eq!(lines, ["dotnet new console --name Shop --output . --language C#", "dotnet new gitignore"]);
// #5732: the top folder is the solution's (Store/Store.slnx, Store/Shop/Shop.csproj), as in
// Rider and Visual Studio; without a solution `solution-name` isn't sent and it is the project's.
let folder = |pairs: &[(&str, &str)]| {
let given = pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
project_folder(def, "Shop", &with_defaults(def, "Shop", &given))
};
assert_eq!(folder(&[("solution-name", "Store")]), "Store");
assert_eq!(folder(&[]), "Shop");
assert_eq!(folder(&[("solution", "false")]), "Shop");
assert_eq!(folder(&[("solution-name", " ")]), "Shop");
}
#[cfg(unix)]
@@ -209,11 +198,6 @@ fn dotnet_templates_see_the_selected_sdk_before_running() {
let pin: serde_json::Value = serde_json::from_slice(&std::fs::read(project.join("global.json")).unwrap()).unwrap();
assert_eq!(pin["sdk"]["version"], "10.0.400");
assert_eq!(std::fs::read_to_string(parent_pin).unwrap(), inherited);
// A solution named apart from the project names the folder.
let req = request("dotnet", tmp.path(), "Api", &[("sdk", "10.0.400"), ("solution-name", "Store")]);
let project = create_with(&def, &req, &CancellationToken::new(), &|_| {}).unwrap();
assert_eq!(project, tmp.path().join("Store"));
assert!(project.join("global.json").is_file());
}
/// `dotnet` of a runtime-only install: `--version` fails ("No .NET SDKs were found").
-8
View File
@@ -30,11 +30,6 @@ pub(crate) struct Def {
pub requires: Vec<RequireDef>,
#[serde(default)]
pub fields: Vec<FieldDef>,
/// The project folder's name, when it isn't the project name: a template over the fields
/// (.NET's solution name). Steps that create the folder themselves (`cwd = "parent"`) can't
/// use it.
#[serde(default)]
pub directory: Option<String>,
#[serde(default)]
pub service: Option<ServiceDef>,
/// Generation runs: the service's zip, `steps`, `files`, then `after`.
@@ -285,9 +280,6 @@ pub struct GeneratorInfo {
/// Offer "Create Git repository".
pub git: bool,
pub fields: Vec<Field>,
/// The project folder's name when it isn't the project name: a template over the fields
/// shown (a hidden field has its default), like [`Field::default`]; empty renders the name.
pub directory: Option<String>,
/// More fields come from `scaffold_options` (a project service's metadata).
pub dynamic: bool,
}
+6 -27
View File
@@ -1184,31 +1184,13 @@ pub fn tool_command(root: &Path, s: &Settings, command: &str) -> Option<PathBuf>
if command == godot::COMMAND {
return godot::find(custom);
}
custom.or_else(|| flutter_sdk_tool(root, s, command))
}
/// `flutter` / `dart` of the Flutter SDK in Settings › Languages & Frameworks › Flutter, else
/// `None` (the search path). Dart is the SDK's own (`bin/cache/dart-sdk`), else its `bin/dart`
/// wrapper, which downloads it on first use.
pub fn flutter_sdk_tool(root: &Path, s: &Settings, command: &str) -> Option<PathBuf> {
let bin = setting_path(root, &s.languages.flutter.sdk)?.join("bin");
let script = |name: &str| bin.join(if cfg!(windows) { format!("{name}.bat") } else { name.to_owned() });
match command {
"flutter" => Some(script("flutter")),
"dart" => Some(
Some(bin.join("cache/dart-sdk/bin").join(exe("dart")))
.filter(|d| d.is_file())
.unwrap_or_else(|| script("dart")),
),
_ => None,
}
custom
}
/// Points a run configuration launching a bare tool name at the executable from
/// [`tool_command`] (Godot apps live outside the search path; `flutter` / `dart` follow the
/// Flutter SDK setting).
/// [`tool_command`] (Godot apps live outside the search path).
pub fn resolve_run_command(config: &mut RunConfig, root: &Path, s: &Settings) {
if matches!(config.command.as_str(), godot::COMMAND | "flutter" | "dart")
if config.command == godot::COMMAND
&& let Some(path) = tool_command(root, s, &config.command)
{
config.command = path.to_string_lossy().into_owned();
@@ -2225,12 +2207,9 @@ pub fn without_derived_in(config: &RunConfig, root: &Path, fallback: Option<&Pat
&& let Some(name) = path.file_name().map(|n| n.to_string_lossy().into_owned())
{
// Generated configurations name the bare program (`java`), also on Windows where the
// derived path ends in `java.exe` (`flutter.bat`).
let bare = name
.len()
.checked_sub(4)
.filter(|&at| name[at..].eq_ignore_ascii_case(".exe") || name[at..].eq_ignore_ascii_case(".bat"))
.map(|at| &name[..at]);
// derived path ends in `java.exe`.
let bare =
name.len().checked_sub(4).filter(|&at| name[at..].eq_ignore_ascii_case(".exe")).map(|at| &name[..at]);
for candidate in bare.into_iter().chain([name.as_str()]) {
let mut probe = out.clone();
probe.command = candidate.to_owned();
+1 -7
View File
@@ -32,7 +32,6 @@ pub fn detect(kind: SdkKind, root: Option<&Path>) -> Vec<Sdk> {
SdkKind::Ruby => crate::ruby::detect(root),
SdkKind::Zig => zig(),
SdkKind::Dotnet => dotnet(),
SdkKind::Flutter => crate::flutter::detect(),
};
if let Some(root) = root {
pinned_first(&mut out, kind, root);
@@ -49,12 +48,7 @@ fn tool_of(kind: SdkKind) -> Option<Tool> {
SdkKind::Maven => Some(Tool::Maven),
SdkKind::Ruby => Some(Tool::Ruby),
SdkKind::Zig => Some(Tool::Zig),
SdkKind::Php
| SdkKind::PackageManager
| SdkKind::Rust
| SdkKind::TypeScript
| SdkKind::Dotnet
| SdkKind::Flutter => None,
SdkKind::Php | SdkKind::PackageManager | SdkKind::Rust | SdkKind::TypeScript | SdkKind::Dotnet => None,
}
}
-121
View File
@@ -1,121 +0,0 @@
//! Flutter SDKs: Settings › Languages & Frameworks › Flutter (the Flutter plugin's "Flutter SDK path").
use crate::exec::query_in;
use crate::{Sdk, home_dir};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::path::{Path, PathBuf};
use std::time::Duration;
/// `flutter --version` may first unpack the Dart SDK or print the analytics notice.
const VERSION_TIMEOUT: Duration = Duration::from_secs(60);
/// What `flutter --version --machine` reports of an SDK.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase", default)]
pub struct FlutterVersion {
/// SDK root (not part of Flutter's answer).
pub root: String,
pub framework_version: String,
pub channel: Option<String>,
pub dart_sdk_version: Option<String>,
}
pub(crate) fn flutter_script(sdk: &Path) -> PathBuf {
sdk.join("bin").join(if cfg!(windows) { "flutter.bat" } else { "flutter" })
}
/// The SDK root of a `flutter` executable; on the search path it is often a link into the SDK.
pub fn sdk_of(flutter: &Path) -> Option<PathBuf> {
let real = dunce::canonicalize(flutter).ok()?;
let root = real.parent()?.parent()?;
flutter_script(root).is_file().then(|| root.to_path_buf())
}
/// `flutter --version --machine` of the SDK at `sdk`. `None` when `sdk` holds no `bin/flutter`;
/// an empty `framework_version` when it did not answer.
pub fn version(sdk: &Path) -> Option<FlutterVersion> {
let flutter = flutter_script(sdk);
if !flutter.is_file() {
return None;
}
let out = query_in(&flutter, &["--version", "--machine"], Some(sdk), &[], VERSION_TIMEOUT).unwrap_or_default();
let mut version = parse_version(&out).unwrap_or_default();
version.root = sdk.to_string_lossy().into_owned();
Some(version)
}
/// The JSON object of `flutter --version --machine`, after anything it printed first.
fn parse_version(out: &str) -> Option<FlutterVersion> {
let json = &out[out.find('{')?..=out.rfind('}')?];
serde_json::from_str(json).ok()
}
/// The framework version an SDK records, without running it.
fn recorded_version(sdk: &Path) -> Option<String> {
let json = std::fs::read_to_string(sdk.join("bin/cache/flutter.version.json")).ok();
json.and_then(|j| parse_version(&j))
.map(|v| v.framework_version)
.or_else(|| std::fs::read_to_string(sdk.join("version")).ok().map(|v| v.trim().to_owned()))
.filter(|v| !v.is_empty())
}
/// Flutter SDKs: the one on the search path, fvm's and the usual install folders.
pub(crate) fn detect() -> Vec<Sdk> {
let mut roots: Vec<(PathBuf, &str)> = Vec::new();
if let Some(sdk) = crate::exec::which("flutter").and_then(|f| sdk_of(&f)) {
roots.push((sdk, "path"));
}
if let Some(home) = home_dir() {
for dir in ["flutter", "development/flutter", "sdk/flutter"] {
roots.push((home.join(dir), "system"));
}
if let Ok(versions) = std::fs::read_dir(home.join("fvm/versions")) {
roots.extend(versions.flatten().map(|e| (e.path(), "fvm")));
}
}
let mut seen = std::collections::HashSet::new();
roots
.into_iter()
.filter(|(sdk, _)| flutter_script(sdk).is_file())
.filter(|(sdk, _)| seen.insert(dunce::canonicalize(sdk).unwrap_or_else(|_| sdk.clone())))
.map(|(sdk, source)| {
let version = recorded_version(&sdk);
Sdk {
path: sdk.clone().into(),
name: format!("Flutter {}", version.as_deref().unwrap_or_default()).trim().to_owned(),
version,
source: source.to_owned(),
home: Some(sdk.into()),
extra: None,
}
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reads_the_version_after_what_flutter_printed_first() {
let out = "Downloading Dart SDK…\n{\n \"frameworkVersion\": \"3.38.1\",\n \"channel\": \"stable\",\n \"dartSdkVersion\": \"3.10.0\"\n}\n";
let v = parse_version(out).unwrap();
assert_eq!(
(v.framework_version.as_str(), v.channel.as_deref(), v.dart_sdk_version.as_deref()),
("3.38.1", Some("stable"), Some("3.10.0"))
);
assert_eq!(parse_version("flutter: command not found"), None);
}
#[test]
fn a_folder_without_bin_flutter_is_no_sdk() {
let dir = tempfile::tempdir().unwrap();
assert_eq!(version(dir.path()), None);
std::fs::create_dir_all(dir.path().join("bin/cache")).unwrap();
std::fs::write(flutter_script(dir.path()), "").unwrap();
std::fs::write(dir.path().join("bin/cache/flutter.version.json"), r#"{"frameworkVersion":"3.35.0"}"#).unwrap();
assert_eq!(recorded_version(dir.path()).as_deref(), Some("3.35.0"));
assert_eq!(sdk_of(&flutter_script(dir.path())), Some(dunce::canonicalize(dir.path()).unwrap()));
}
}
-17
View File
@@ -1654,23 +1654,6 @@ pub fn junit_runner_jar(data_dir: &Path) -> Option<PathBuf> {
)
}
/// The IDE's Java build (`java/java-build`): the resident javac server and the Maven
/// extension that records the build model.
const JAVA_BUILD: &[u8] = include_bytes!("../../../java/java-build/openidea-java-build.jar");
/// Extracts the Java build jar into the application's data directory.
pub fn java_build_jar(data_dir: &Path) -> Option<PathBuf> {
install_bundle(data_dir, "java-build", "1.0.0", JAVA_BUILD)
}
/// Changes whenever the embedded Java build jar does (FNV-1a of its bytes), so build models
/// recorded by an older extension are prepared again.
pub fn java_build_version() -> String {
let hash =
JAVA_BUILD.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x100_0000_01b3));
format!("{hash:016x}")
}
/// The JUnit Platform launcher a test classpath needs to start the runner.
#[derive(Debug, PartialEq)]
pub enum JunitLauncher {
-3
View File
@@ -12,7 +12,6 @@ mod astro;
pub mod container_python;
mod discover;
mod exec;
pub mod flutter;
pub mod go;
pub mod godot;
pub mod java;
@@ -58,8 +57,6 @@ pub enum SdkKind {
Zig,
/// .NET SDKs of the `dotnet` on the search path; `version` is what `global.json` pins.
Dotnet,
/// Flutter SDK roots.
Flutter,
}
/// One installed interpreter / toolchain.
-50
View File
@@ -2058,56 +2058,6 @@ fn the_godot_setting_applies_to_server_debugger_and_run_configurations() {
assert_eq!(crate::apply::tool_command(tmp.path(), &s, "zls"), None);
}
#[test]
fn the_flutter_sdk_setting_picks_flutter_and_dart_for_server_and_run_configurations() {
let tmp = tempfile::tempdir().unwrap();
let sdk = tmp.path().join("flutter");
let run = |command: &str| RunConfig {
id: "dart:pub get".into(),
name: "pub get".into(),
kind: "dart-command".into(),
command: command.into(),
args: vec!["pub".into(), "get".into()],
cwd: None,
env: BTreeMap::new(),
detected: true,
is_test: false,
debug_adapter: None,
allow_parallel: false,
extras: Default::default(),
};
// No setting: the names stay for the search path.
let mut s = Settings::default();
let mut plain = run("flutter");
apply_to_run_configs(std::slice::from_mut(&mut plain), tmp.path(), &s);
assert_eq!(plain.command, "flutter");
assert_eq!(crate::apply::tool_command(tmp.path(), &s, "dart"), None);
// A project-relative SDK: `bin/flutter`, and `bin/dart` until the Dart SDK is unpacked.
s.languages.flutter.sdk = "flutter".into();
let flutter = sdk.join("bin").join(if cfg!(windows) { "flutter.bat" } else { "flutter" });
let wrapper = sdk.join("bin").join(if cfg!(windows) { "dart.bat" } else { "dart" });
assert_eq!(crate::apply::tool_command(tmp.path(), &s, "dart"), Some(wrapper));
let dart = sdk.join("bin/cache/dart-sdk/bin").join(exe("dart"));
std::fs::create_dir_all(dart.parent().unwrap()).unwrap();
std::fs::write(&dart, "").unwrap();
let mut cfg = server("dart");
configure_server(&mut cfg, tmp.path(), tmp.path(), &s);
assert_eq!(Path::new(&cfg.command), dart);
let mut configs = [run("flutter"), run("dart"), run("/usr/bin/flutter")];
apply_to_run_configs(&mut configs, tmp.path(), &s);
assert_eq!(Path::new(&configs[0].command), flutter);
assert_eq!(Path::new(&configs[1].command), dart);
assert_eq!(configs[2].command, "/usr/bin/flutter");
// Saved configurations keep the bare name.
assert_eq!(crate::apply::without_derived(&configs[0], tmp.path(), &s).command, "flutter");
// An explicit tool path still wins.
let explicit = tmp.path().join("opt").join("dart");
s.tools.insert("dart".into(), ide_core::settings::ToolSettings { path: explicit.to_string_lossy().into_owned() });
assert_eq!(crate::apply::tool_command(tmp.path(), &s, "dart"), Some(explicit));
}
#[test]
fn python_library_paths_are_parsed_and_deduplicated() {
let tmp = tempfile::tempdir().unwrap();
+8 -24
View File
@@ -1,7 +1,7 @@
//! App-wide SSH connections, one per SSH configuration, shared by every
//! feature that works on that host (deployment, run targets, data sources).
use crate::secrets::{LegacyPasswordAction, SecretFile};
use crate::secrets::SecretFile;
use crate::session::{ConnectError, Session, UnknownHostKey};
use crate::target::{SshFiles, SshTarget};
use ide_core::remote_settings::{SshAuth, SshConfiguration};
@@ -14,7 +14,6 @@ use std::sync::Arc;
pub struct SshManager {
files: SshFiles,
saved: SecretFile,
startup_migration: std::sync::Once,
/// Secrets entered this session (not saved, or not yet), by configuration id.
entered: Mutex<HashMap<String, String>>,
configs: RwLock<Vec<SshConfiguration>>,
@@ -35,8 +34,7 @@ impl SshManager {
pub fn with_files(secrets: PathBuf, files: SshFiles) -> Self {
Self {
files,
saved: SecretFile::ssh_passwords(secrets),
startup_migration: std::sync::Once::new(),
saved: SecretFile::new(secrets),
entered: Mutex::default(),
configs: RwLock::default(),
sessions: Mutex::default(),
@@ -49,19 +47,6 @@ impl SshManager {
&self.files
}
pub fn start_password_migration(&self) {
self.startup_migration.call_once(|| match self.saved.resolve_legacy(LegacyPasswordAction::Retry) {
Ok(None) => {}
Ok(Some(why)) => tracing::warn!("ssh-passwords.json still contains legacy plaintext credentials: {why}"),
Err(e) => tracing::warn!("could not check ssh-passwords.json: {}", e.message),
});
}
pub fn resolve_legacy_passwords(&self, action: LegacyPasswordAction) -> IdeResult<Option<String>> {
self.start_password_migration();
self.saved.resolve_legacy(action)
}
/// Replaces the configurations (Settings › SSH Configurations); sessions of
/// changed or removed ones are closed, secrets of removed ones forgotten.
pub fn set_configs(&self, configs: Vec<SshConfiguration>) {
@@ -101,7 +86,7 @@ impl SshManager {
/// Remembers the password / passphrase of configuration `id` for the session,
/// and in the saved passwords with `save` (`None` forgets it).
pub fn set_secret(&self, id: &str, secret: Option<String>, save: bool) -> IdeResult<()> {
pub fn set_secret(&self, id: &str, secret: Option<String>, save: bool) {
match &secret {
Some(s) => {
self.entered.lock().insert(id.to_owned(), s.clone());
@@ -111,13 +96,12 @@ impl SshManager {
}
}
match (secret, save) {
(Some(s), true) => self.saved.set(id, &s).map_err(|e| {
IdeError::unavailable(format!("The credential was kept for this session only. {}", e.message))
}),
_ => {
self.saved.delete(id);
Ok(())
(Some(s), true) => {
if let Err(e) = self.saved.set(id, &s) {
tracing::warn!("could not save the SSH password: {}", e.message);
}
}
_ => self.saved.delete(id),
}
}
+17 -164
View File
@@ -25,14 +25,6 @@ static LOCK: Mutex<()> = Mutex::new(());
/// Reads the secrets of an older version's file, by key (`None`: not that format).
pub type Legacy = fn(serde_json::Value) -> Option<BTreeMap<String, String>>;
#[derive(Clone, Copy, Deserialize, Serialize, specta::Type)]
#[serde(rename_all = "camelCase")]
pub enum LegacyPasswordAction {
Check,
Retry,
RemovePlaintext,
}
/// Where the secrets are kept: the default credential store, or a stand-in in tests.
pub trait Vault: Send + Sync {
fn available(&self) -> bool;
@@ -85,7 +77,6 @@ pub struct SecretFile {
path: PathBuf,
legacy: Legacy,
vault: Arc<dyn Vault>,
keep_legacy_until_moved: bool,
}
/// The file's contents. `id` keeps the credentials of different data directories
@@ -96,11 +87,6 @@ struct Index {
keys: BTreeSet<String>,
}
enum Stored {
Index(Index),
Legacy(BTreeMap<String, String>),
}
enum Contents {
Index(Index),
/// An older version's file that could not be moved, and why.
@@ -136,17 +122,12 @@ impl SecretFile {
Self::with_legacy(path, |v| serde_json::from_value(v).ok())
}
/// For the startup migration with a user-visible choice to retry or discard.
pub(crate) fn ssh_passwords(path: PathBuf) -> Self {
Self { keep_legacy_until_moved: true, ..Self::new(path) }
}
pub fn with_legacy(path: PathBuf, legacy: Legacy) -> Self {
Self::with_vault(path, legacy, Arc::new(DefaultStore))
}
pub fn with_vault(path: PathBuf, legacy: Legacy, vault: Arc<dyn Vault>) -> Self {
Self { path, legacy, vault, keep_legacy_until_moved: false }
Self { path, legacy, vault }
}
pub fn get(&self, key: &str) -> Option<String> {
@@ -241,73 +222,21 @@ impl SecretFile {
})
}
fn read(&self) -> std::io::Result<Stored> {
use std::io::{Error, ErrorKind};
let bytes = match std::fs::read(&self.path) {
Err(e) if e.kind() == ErrorKind::NotFound => {
return Ok(Stored::Index(Index { id: new_id(), keys: BTreeSet::new() }));
}
other => other?,
};
let value = serde_json::from_slice::<serde_json::Value>(&bytes)
.map_err(|_| Error::new(ErrorKind::InvalidData, "invalid JSON"))?;
if let Ok(index) = serde_json::from_value::<Index>(value.clone()) {
return Ok(Stored::Index(index));
}
(self.legacy)(value).map(Stored::Legacy).ok_or_else(|| Error::new(ErrorKind::InvalidData, "unknown format"))
}
fn load(&self) -> Contents {
match self.read() {
Ok(Stored::Index(index)) => Contents::Index(index),
Ok(Stored::Legacy(old)) => self.migrate(old),
Err(e) if e.kind() == std::io::ErrorKind::InvalidData => self.set_aside(&e.to_string()),
Err(e) => Contents::Plaintext(BTreeMap::new(), format!("{}: {e}", self.path.display())),
let value = match std::fs::read(&self.path) {
Err(_) => return Contents::Index(Index { id: new_id(), keys: BTreeSet::new() }),
Ok(bytes) => match serde_json::from_slice::<serde_json::Value>(&bytes) {
Ok(v) => v,
Err(e) => return self.set_aside(&e.to_string()),
},
};
if let Ok(index) = serde_json::from_value::<Index>(value.clone()) {
return Contents::Index(index);
}
match (self.legacy)(value) {
Some(old) => self.migrate(old),
None => self.set_aside("unknown format"),
}
}
/// `Some` means plaintext remains. Never overwrite an index that another window
/// already migrated; an unreadable file is set aside, as on any other access.
pub(crate) fn resolve_legacy(&self, action: LegacyPasswordAction) -> IdeResult<Option<String>> {
off_runtime(|| {
let _g = LOCK.lock();
let old = match self.read() {
Ok(Stored::Legacy(old)) => old,
Ok(Stored::Index(_)) => return Ok(None),
Err(e) if e.kind() == std::io::ErrorKind::InvalidData => {
return match self.set_aside(&e.to_string()) {
Contents::Index(_) => Ok(None),
Contents::Plaintext(_, why) => Err(unavailable(&why)),
};
}
Err(e) => return Err(unavailable(&format!("{}: {e}", self.path.display()))),
};
if matches!(action, LegacyPasswordAction::Check) && !old.is_empty() {
return Ok(Some("Migration is incomplete.".into()));
}
if matches!(action, LegacyPasswordAction::RemovePlaintext) || old.is_empty() {
// A partial move may already have secured some keys. Preserve their
// namespace without needing the vault to be unlocked to remove plaintext.
let pending = self.pending_path();
let index = match std::fs::read_to_string(&pending) {
Ok(id) if !id.trim().is_empty() => Index { id: id.trim().into(), keys: old.into_keys().collect() },
Ok(_) => return Err(unavailable("empty migration id")),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Index { id: new_id(), keys: BTreeSet::new() },
Err(e) => return Err(unavailable(&format!("{}: {e}", pending.display()))),
};
self.write(&index)?;
if let Err(e) = std::fs::remove_file(&pending)
&& e.kind() != std::io::ErrorKind::NotFound
{
tracing::warn!("saved passwords: could not remove {}: {e}", pending.display());
}
return Ok(None);
}
Ok(match self.migrate(old) {
Contents::Index(_) => None,
Contents::Plaintext(_, why) => Some(why),
})
})
}
/// An unreadable file is renamed rather than overwritten (it may index
@@ -333,8 +262,8 @@ impl SecretFile {
}
/// Moves an older version's secrets to the credential store, key by key; a secret
/// the store refuses for good (too long, say) is forgotten unless the caller
/// offers explicit recovery. The old file is replaced only when everything else was moved.
/// the store refuses for good (too long, say) is forgotten, and the user is asked
/// for it again. The old file is replaced only when everything else was moved.
/// Until then the id waits in `<file>.migrating`, so a retry after a failure or a
/// crash overwrites the same credentials instead of copying them again.
fn migrate(&self, old: BTreeMap<String, String>) -> Contents {
@@ -358,7 +287,7 @@ impl SecretFile {
Ok(()) => {
index.keys.insert(key.clone());
}
Err(e @ (StoreError::TooLong(..) | StoreError::Invalid(..))) if !self.keep_legacy_until_moved => {
Err(e @ (StoreError::TooLong(..) | StoreError::Invalid(..))) => {
tracing::warn!("saved passwords: {key} does not fit the credential store and is forgotten: {e}");
}
Err(e) => {
@@ -496,82 +425,6 @@ mod tests {
const OLD: &str = r#"{"https://a.example": "me\nold-a", "https://b.example": "me\nold-b"}"#;
#[test]
fn a_pending_plaintext_migration_can_be_retried_or_explicitly_discarded() {
use LegacyPasswordAction::{Check, RemovePlaintext, Retry};
for discard in [false, true] {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("ssh-passwords.json");
let vault = Arc::new(FakeVault::default());
let file = with_fake(&path, &vault);
assert!(file.resolve_legacy(Check).unwrap().is_none());
assert!(!path.exists());
std::fs::write(&path, OLD).unwrap();
vault.fail("https://b.example", platform);
assert!(file.resolve_legacy(Retry).unwrap().is_some());
assert!(file.resolve_legacy(Check).unwrap().is_some());
assert_eq!(std::fs::read_to_string(&path).unwrap(), OLD);
if discard {
assert!(file.resolve_legacy(RemovePlaintext).unwrap().is_none());
}
vault.heal();
assert!(file.resolve_legacy(Retry).unwrap().is_none());
// A stale action from another window cannot erase a migrated index.
assert!(file.resolve_legacy(RemovePlaintext).unwrap().is_none());
assert_eq!(files_containing(tmp.path(), "old-"), Vec::<PathBuf>::new());
assert_eq!(file.get("https://a.example").as_deref(), Some("me\nold-a"));
assert_eq!(file.get("https://b.example").as_deref(), (!discard).then_some("me\nold-b"));
}
}
#[test]
fn removing_plaintext_needs_no_vault_and_sets_an_unknown_format_aside() {
use LegacyPasswordAction::{RemovePlaintext, Retry};
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("ssh-passwords.json");
let vault = Arc::new(FakeVault { absent: true, ..Default::default() });
let file = with_fake(&path, &vault);
std::fs::write(&path, OLD).unwrap();
assert!(file.resolve_legacy(Retry).unwrap().is_some());
assert!(file.resolve_legacy(RemovePlaintext).unwrap().is_none());
assert!(files_containing(tmp.path(), "old-").is_empty());
assert!(file.keys().is_empty());
std::fs::write(&path, "unknown-format").unwrap();
assert!(file.resolve_legacy(RemovePlaintext).unwrap().is_none());
let aside = files_containing(tmp.path(), "unknown-format");
assert_eq!(aside.len(), 1);
assert_ne!(aside[0], path);
}
#[test]
fn ssh_keeps_the_only_copy_until_the_user_can_choose_what_to_do() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("ssh-passwords.json");
let vault = Arc::new(FakeVault::default());
let file = SecretFile { vault: vault.clone(), ..SecretFile::ssh_passwords(path.clone()) };
vault.fail("box", || StoreError::TooLong("password".into(), 2560));
std::fs::write(&path, r#"{"box":"legacy-value"}"#).unwrap();
assert!(file.resolve_legacy(LegacyPasswordAction::Retry).unwrap().is_some());
assert_eq!(file.get("box").as_deref(), Some("legacy-value"));
assert_eq!(files_containing(tmp.path(), "legacy-value"), std::slice::from_ref(&path));
}
#[test]
fn a_malformed_ssh_file_is_set_aside_instead_of_blocking_new_saves() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("ssh-passwords.json");
let vault = Arc::new(FakeVault::default());
let file = SecretFile { vault: vault.clone(), ..SecretFile::ssh_passwords(path.clone()) };
std::fs::write(&path, "{ malformed").unwrap();
assert!(file.resolve_legacy(LegacyPasswordAction::Check).unwrap().is_none());
let aside = files_containing(tmp.path(), "{ malformed");
assert_eq!(aside.len(), 1);
assert_ne!(aside[0], path);
file.set("box", "new-value").unwrap();
assert_eq!(file.get("box").as_deref(), Some("new-value"));
assert!(files_containing(tmp.path(), "new-value").is_empty());
}
#[test]
fn saved_secrets_never_reach_disk() {
use_memory_store();
+6 -22
View File
@@ -4,11 +4,10 @@
mod integration;
mod scrollback;
use ide_core::pty::native_pty_system;
use ide_core::utf8::Utf8Decoder;
use ide_core::{IdeError, IdeEvent, IdeResult, SharedSink, TerminalId};
use parking_lot::{Condvar, Mutex};
use portable_pty::{ChildKiller, CommandBuilder, MasterPty, PtySize};
use portable_pty::{ChildKiller, CommandBuilder, MasterPty, PtySize, native_pty_system};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::{BTreeMap, HashMap};
@@ -510,17 +509,13 @@ impl TerminalManager {
}
}
/// Detaches every terminal opened by `key` so it can be terminated on a background thread
/// without blocking the caller or racing a new project opened in the same window.
pub fn detach_key(&self, key: &str) -> DetachedTerminals {
let mut sessions = self.sessions.lock();
let ids: Vec<TerminalId> = sessions.iter().filter(|(_, s)| s.key == key).map(|(id, _)| *id).collect();
DetachedTerminals(ids.into_iter().filter_map(|id| sessions.remove(&id)).collect())
}
/// Closes the terminals `key` opened: the project of that window is closing.
pub fn kill_key(&self, key: &str) {
self.detach_key(key).terminate();
let ids: Vec<TerminalId> =
self.sessions.lock().iter().filter(|(_, s)| s.key == key).map(|(id, _)| *id).collect();
for id in ids {
let _ = self.kill(id);
}
}
pub fn kill(&self, id: TerminalId) -> IdeResult<()> {
@@ -737,17 +732,6 @@ mod win {
}
}
/// Terminal sessions detached from [`TerminalManager`] to be terminated off the caller's thread.
pub struct DetachedTerminals(Vec<Arc<Session>>);
impl DetachedTerminals {
pub fn terminate(self) {
for session in self.0 {
terminate(&session);
}
}
}
/// Hangs up the shell (and its process group), escalating to SIGKILL if it lingers.
fn terminate(session: &Session) {
let (writer, killer) = match &session.io {
+1 -1
View File
@@ -164,7 +164,7 @@ Each form has **Host** and **Port** fields and shows the command to start the re
- **Java HotSwap**: **Run › Debugging Actions › Reload Changed Classes** compiles your changes and reloads the changed classes into the running Java debug session. Active frames keep running the old code until they return. When JDT LS finishes a build after a save, the IDE offers the reload.
- **JavaScript in the browser**: a **JavaScript Debug** configuration opens a URL in Chrome or Edge and debugs the page's scripts in their sources through source maps. See [JavaScript and TypeScript](/en/languages/javascript#debugging).
- **Maven and Gradle**: debugging a Maven or Gradle configuration starts the JVM with a JDWP agent and attaches java-debug to it.
- **Dart / Flutter**: **Settings › Languages & Frameworks › Flutter › Flutter SDK path** chooses the Flutter SDK whose `flutter` and Dart the language server, the debugger, run configurations, pub commands, the device list and **Build › Flutter** use; empty uses the ones on `PATH`. **Hot Reload** and **Hot Restart** are available while a Dart session is running. In a Flutter project, the device selector next to the run configuration chooses where Run and Debug start the app; a run configuration's **Device** field pins it to one device. A Flutter configuration also sets the **Build mode** (Debug, Profile or Release; Profile and Release run without the debugger or hot reload), **Build flavor** and **Additional run args** (such as `--dart-define=KEY=value`); **Run › Flutter Attach** attaches the debugger to the app of the selected Flutter configuration that was started elsewhere (an add-to-app host), passing its **Additional attach args** to `flutter attach`. Saving a Dart file of a running Flutter debug session also hot reloads the app, unless the file has errors. Turn this off with **Hot reload on save** in **Settings › Build, Execution, Deployment › Debugger**.
- **Dart / Flutter**: **Hot Reload** and **Hot Restart** are available while a Dart session is running. In a Flutter project, the device selector next to the run configuration chooses where Run and Debug start the app; a run configuration's **Device** field pins it to one device. A Flutter configuration also sets the **Build mode** (Debug, Profile or Release; Profile and Release run without the debugger or hot reload), **Build flavor** and **Additional run args** (such as `--dart-define=KEY=value`); **Run › Flutter Attach** attaches the debugger to the app of the selected Flutter configuration that was started elsewhere (an add-to-app host), passing its **Additional attach args** to `flutter attach`. Saving a Dart file of a running Flutter debug session also hot reloads the app, unless the file has errors. Turn this off with **Hot reload on save** in **Settings › Build, Execution, Deployment › Debugger**.
- **PHP**: if the PHP interpreter does not load Xdebug, breakpoints are skipped; the IDE warns about this when the session starts.
- **Python**: **Settings › Build, Execution, Deployment › Python Debugger** has **Attach to subprocess automatically while debugging** and **Gevent compatible**.
-5
View File
@@ -46,11 +46,6 @@ through the app-wide SSH configurations.
Saved passwords and passphrases go to the macOS Keychain, Windows Credential Manager or the Secret Service on Linux,
never to a settings file. The **+**, **−** and copy buttons above the list add, remove and duplicate configurations.
Older versions stored saved credentials in plaintext in `ssh-passwords.json`. On startup, OpenIDEA moves them into
the OS credential store. If the file still contains passwords, unlock the store and choose **Retry migration**, or
choose **Remove plaintext copy** and re-enter any credentials that were not migrated. New credentials that cannot
be saved are kept only for the session. Migration does not change old backups: rotate any exposed password.
### `~/.ssh/config` support
OpenIDEA has its own SSH client and reads `~/.ssh/config` itself. It understands `Host`, `Match`, `Include`,
+1 -1
View File
@@ -166,7 +166,7 @@ C 和 C++ 的配置也可以改用 GDB 14 及以上版本(`gdb -i dap`):
- **Java HotSwap**:**运行 › 调试操作 › 重新加载已更改的类** 编译改动,并把变化的类重新加载到正在运行的 Java 调试会话中。已经在执行的帧要等返回后才会用上新代码。保存后 JDT LS 自动完成构建时,IDE 也会提示是否重新加载。
- **浏览器中的 JavaScript**:**JavaScript 调试** 配置在 Chrome 或 Edge 中打开一个 URL,通过 source map 在源码中调试页面脚本。见 [JavaScript 与 TypeScript](/zh/languages/javascript)。
- **Maven 和 Gradle**:调试 Maven 或 Gradle 配置时,IDE 会让 JVM 带上 JDWP agent 启动,再用 java-debug 附加上去。
- **Dart / Flutter**:**设置 › 语言和框架 › Flutter › Flutter SDK 路径** 选择 Flutter SDK,语言服务器、调试器、运行配置、pub 命令、设备列表和 **构建 › Flutter** 都使用它的 `flutter` 和 Dart;留空则使用 `PATH` 中的。Dart 会话运行时可以用 **热重载** 和 **热重启**。在 Flutter 项目中,运行配置旁边的设备选择器决定运行和调试在哪台设备上启动应用;运行配置的 **设备** 字段可以固定使用某台设备。Flutter 配置还可以设置 **构建模式**(调试、性能分析或发布;后两者不带调试器,也不能热重载)、**构建 flavor** 和 **附加 run 参数**(例如 `--dart-define=KEY=value`);**运行 › Flutter 附加** 把调试器附加到所选 Flutter 配置在别处启动的应用(例如 add-to-app 的宿主应用),并把 **附加 attach 参数** 传给 `flutter attach`。保存正在运行的 Flutter 调试会话里的 Dart 文件时也会自动热重载,文件有错误时跳过。可在 **设置 › 构建、执行、部署 › 调试器** 中关闭 **保存时热重载**。
- **Dart / Flutter**:Dart 会话运行时可以用 **热重载** 和 **热重启**。在 Flutter 项目中,运行配置旁边的设备选择器决定运行和调试在哪台设备上启动应用;运行配置的 **设备** 字段可以固定使用某台设备。Flutter 配置还可以设置 **构建模式**(调试、性能分析或发布;后两者不带调试器,也不能热重载)、**构建 flavor** 和 **附加 run 参数**(例如 `--dart-define=KEY=value`);**运行 › Flutter 附加** 把调试器附加到所选 Flutter 配置在别处启动的应用(例如 add-to-app 的宿主应用),并把 **附加 attach 参数** 传给 `flutter attach`。保存正在运行的 Flutter 调试会话里的 Dart 文件时也会自动热重载,文件有错误时跳过。可在 **设置 › 构建、执行、部署 › 调试器** 中关闭 **保存时热重载**。
- **PHP**:如果 PHP 解释器没有加载 Xdebug,断点会被跳过;会话启动时 IDE 会提示。
- **Python**:**设置 › 构建、执行、部署 › Python 调试器** 中有 **调试时自动附加到子进程** 和 **兼容 Gevent**。
-4
View File
@@ -38,10 +38,6 @@ OpenIDEA 通过 SSH 连接;在 Windows 上也可以直接连入 WSL 发行版
保存的密码和密码短语存放在 macOS 钥匙串、Windows 凭据管理器或 Linux 的 Secret Service 中,不会写进设置文件。列表上方的
**+**、**−** 和复制按钮用于添加、移除和复制配置。
旧版本会在 `ssh-passwords.json` 中明文保存凭据。OpenIDEA 会在启动时将它们迁移到系统凭据库。
如果文件中仍有密码,可以解锁凭据库后选择**重试迁移**,也可以选择**移除明文副本**,并在下次使用时重新输入未迁移的凭据。
无法保存的新凭据仅在当前会话中有效。迁移不会更改旧备份;如果备份中的密码已泄露,请更换密码。
### `~/.ssh/config` 支持
OpenIDEA 自带 SSH 客户端,自行读取 `~/.ssh/config`,支持 `Host`、`Match`、`Include`、`HostName`、`User`、`Port`、
+10 -10
View File
@@ -313,8 +313,8 @@ for (const surface of ["new", "task"] as const) {
const settings = page.getByRole("button", { name: /^Model settings:/ });
await settings.click();
await expect(page.getByRole("button", { name: "Back to models" })).toHaveCount(0);
await page.getByRole("option", { name: "Thorough" }).click();
await page.getByRole("option", { name: "1M" }).click();
await page.getByRole("radio", { name: "Thorough" }).click();
await page.getByRole("radio", { name: "1M" }).click();
await expect(settings).toHaveText("Thorough · 1M");
await page.keyboard.press("Escape");
await expect(box(page)).toHaveText("Review the project structure");
@@ -418,7 +418,7 @@ test("Settings and effort popup exclude the agent shortcut", async ({ workbench:
await expect(search).toHaveValue("keymap");
await settings.getByRole("button", { name: "Cancel", exact: true }).click();
await effortLabel(page).click();
const popup = page.getByRole("listbox", { name: "Effort Level", exact: true });
const popup = page.getByRole("radiogroup", { name: "Effort Level", exact: true });
await expect(popup).toBeVisible();
await page.keyboard.press("Alt+t");
expect(await ipcCalls(page, "agent_set_config")).toEqual([]);
@@ -642,10 +642,10 @@ test("New Task discovers uncached model effort before the first prompt", async (
await page.evaluate(() => document.dispatchEvent(new Event("test:model-settings-ready")));
await expectEffort(page, "Quick");
await effortLabel(page).click();
const efforts = page.getByRole("listbox", { name: "Effort Level", exact: true });
await expect(efforts.getByRole("option", { name: "Quick", exact: true })).toBeVisible();
await expect(efforts.getByRole("option", { name: "Thorough", exact: true })).toBeVisible();
await expect(efforts.getByRole("option", { name: "Gentle", exact: true })).toHaveCount(0);
const efforts = page.getByRole("radiogroup", { name: "Effort Level", exact: true });
await expect(efforts.getByRole("radio", { name: "Quick", exact: true })).toBeVisible();
await expect(efforts.getByRole("radio", { name: "Thorough", exact: true })).toBeVisible();
await expect(efforts.getByRole("radio", { name: "Gentle", exact: true })).toHaveCount(0);
await page.keyboard.press("Escape");
await expect(box(page)).toHaveText("Keep this first task unsent");
await expectNoSubmission(page);
@@ -675,9 +675,9 @@ test("an existing chat can choose effort for a refreshed model before sending",
await expect(modelButton(page)).toHaveAttribute("title", /^Model: Swift\b/);
await expectEffort(page, "Quick");
await effortLabel(page).click();
const efforts = page.getByRole("listbox", { name: "Effort Level", exact: true });
await expect(efforts.getByRole("option", { name: "Gentle", exact: true })).toHaveCount(0);
await efforts.getByRole("option", { name: "Thorough", exact: true }).click();
const efforts = page.getByRole("radiogroup", { name: "Effort Level", exact: true });
await expect(efforts.getByRole("radio", { name: "Gentle", exact: true })).toHaveCount(0);
await efforts.getByRole("radio", { name: "Thorough", exact: true }).click();
await page.keyboard.press("Escape");
await expectEffort(page, "Thorough");
await expect(send).toBeEnabled();
+7 -6
View File
@@ -413,7 +413,8 @@ test("keeps chat history readable and selections free of timestamps and status l
expect(selected).not.toMatch(/AM|PM|5s|Reasoning|Requesting task context/);
await page.keyboard.press("ControlOrMeta+c");
expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(selected);
// The latest turn stays open: its reasoning shows as its own collapsed row.
// The finished turn's reasoning is folded with its work.
await stream.locator("[class*='_turnFold_'] > summary").click();
await stream.locator("[class*='_thought_'] > summary").click();
await expect(stream.locator("[class*='_thoughtPreview_']")).toHaveText("Requesting task context");
await expect(stream.locator("[class*='_thoughtBody_'] strong")).toHaveText("Requesting task context");
@@ -794,7 +795,8 @@ test("Find in Conversation skips user-select:none summaries and closed <details>
}, TASK);
const stream = page.locator("[class*='_stream_']:visible");
// A command is its own row, outside the reasoning's run.
const runSummary = stream.locator("details[class*='_processRun_'] > summary");
await runSummary.click();
await expect(stream.getByText("stop_bash")).toBeVisible();
await stream.focus();
@@ -892,14 +894,13 @@ test("indents process-run thoughts and tool calls clearly and aligns output-less
entries: new Map([
[
task.id,
// Reasoning and read-only calls group into one run; commands and edits would be rows of their own.
[
{ type: "thought", text: "**Checking CI Status**\n\nInspecting workflow runs." },
{
type: "tool",
id: "t1",
title: "gh pr checks 3631 --repo l0ng-ai/openidea",
kind: "fetch",
kind: "execute",
status: "completed",
locations: [],
output: "All checks pending",
@@ -910,7 +911,7 @@ test("indents process-run thoughts and tool calls clearly and aligns output-less
type: "tool",
id: "t2",
title: "read_bash",
kind: "read",
kind: "other",
status: "completed",
locations: [],
output: "E2E pass",
@@ -920,7 +921,7 @@ test("indents process-run thoughts and tool calls clearly and aligns output-less
type: "tool",
id: "t3",
title: "read_bash",
kind: "read",
kind: "other",
status: "running",
locations: [],
output: "",
+9 -14
View File
@@ -40,17 +40,13 @@ const entries: AgentEntry[] = Array.from({ length: 80 }, (_, turn): AgentEntry[]
},
]).flat();
/** Opens the 80-turn chat; `foldTurns` folds each earlier turn's work into one row. */
async function openHistory(page: Page, foldTurns = false) {
async function openHistory(page: Page) {
await page.goto("/");
await page.getByRole("tree", { name: "Project" }).waitFor();
await page.evaluate(
async ({ task, entries, foldTurns }) => {
async ({ task, entries }) => {
const path = "/src/features/agents/store.ts";
const projectPath = "/src/platform/project.ts";
const store = await import(path);
const { useProject } = await import(projectPath);
useProject.setState({ settings: { agents: { foldTurns } } });
store.useAgents.setState({
loaded: true,
error: null,
@@ -62,12 +58,10 @@ async function openHistory(page: Page, foldTurns = false) {
});
store.openTaskInEditorLocation(task.id);
},
{ task, entries, foldTurns },
{ task, entries },
);
const stream = page.locator("[class*='_stream_']:visible");
// A turn shows its request, the read and the reasoning runs, the command, the edit and the reply;
// folded, its work is one row. The latest turn stays open.
await expect(stream.locator(":scope > *")).toHaveCount(foldTurns ? 79 * 3 + 6 : 80 * 6);
await expect(stream.locator(":scope > *")).toHaveCount(80 * 3);
await page.evaluate(() => document.fonts.ready);
return stream;
}
@@ -91,7 +85,7 @@ for (const placement of ["editor", "toolWindow"] as const) {
);
// The working indicator ends the conversation, after its rows; the turn ends with a reply.
await expect(stream.getByRole("status").getByText("Writing…", { exact: true })).toBeVisible();
await expect(stream.locator(":scope > *")).toHaveCount(80 * 6 + 1);
await expect(stream.locator(":scope > *")).toHaveCount(80 * 3 + 1);
await expect.poll(() => stream.evaluate((el) => el.scrollHeight - el.clientHeight - el.scrollTop)).toBeLessThan(2);
const timer = await page.evaluate(async (id) => {
const path = "/src/features/agents/store.ts";
@@ -192,7 +186,7 @@ for (const selected of [false, true]) {
}
test("opens a folded turn with the keyboard and jumps back to the latest reply", async ({ page }) => {
const stream = await openHistory(page, true);
const stream = await openHistory(page);
await stream.evaluate((el) => {
el.scrollTop = 0;
});
@@ -203,8 +197,9 @@ test("opens a folded turn with the keyboard and jumps back to the latest reply",
await summary.focus();
await page.keyboard.press("Enter");
await expect(fold).toHaveAttribute("open", "");
// A folded turn lists its work without nesting runs.
await expect(fold.locator("[class*='_processRun_']")).toHaveCount(0);
const run = fold.locator("[class*='_processRun_']").first();
await expect(run).toBeVisible();
await run.locator(":scope > summary").click();
await expect(fold.getByText("read src/module-0.ts", { exact: true })).toBeVisible();
await summary.focus();
await page.keyboard.press("Space");
+1 -8
View File
@@ -63,14 +63,7 @@ test("the chosen device is used for Run, and replaced while it is disconnected",
await page.keyboard.press("Control+r");
await expect.poll(async () => (await ipcCalls(page, "run_start")).length).toBe(1);
const [started] = await ipcCalls(page, "run_start");
expect((started!.config as { args: string[] }).args).toEqual([
"run",
"-t",
"lib/main.dart",
"-d",
"chrome",
"--machine",
]);
expect((started!.config as { args: string[] }).args).toEqual(["run", "-t", "lib/main.dart", "-d", "chrome"]);
const emit = (devices: unknown[]) =>
page.evaluate(
-43
View File
@@ -476,46 +476,3 @@ test("difference navigation focuses and centres the merge result caret with sync
await page.keyboard.press("Shift+F7");
await check(101);
});
test("scrolling one pane sideways scrolls the other two to the same offset", async ({ page }) => {
await page.setViewportSize({ width: 900, height: 600 });
const long = (tag: string) => `const ${tag} = "${"x".repeat(400)}";`;
await mountMerge(page, [
lines(long("base"), "a", "b"),
lines(long("ours"), "a", "b"),
lines(long("theirs"), "a", "b"),
]);
const lefts = () =>
page
.locator("#merge-host .cm-scroller")
.evaluateAll((els) => els.map((el) => Math.round((el as HTMLElement).scrollLeft)));
for (const pane of ["Your version", "Result", "Their version"]) {
const offset = pane === "Result" ? 240 : pane === "Your version" ? 120 : 60;
await page
.getByRole("region", { name: pane })
.locator(".cm-scroller")
.evaluate((el, x) => (el.scrollLeft = x), offset);
await expect.poll(lefts).toEqual([offset, offset, offset]);
}
});
test("says when every change is processed and saves the result from the notice", async ({ page }) => {
await mountMerge(page);
await captureWrites(page);
const notice = page.locator("#merge-host").getByText("All changes have been processed.");
await expect(notice).toBeHidden();
await page.getByRole("button", { name: "Resolve Simple Conflicts" }).click();
await expect(status(page)).toHaveText("1 change left, 1 conflict");
await expect(notice).toBeHidden();
// The conflict left takes both sides.
await page.getByRole("region", { name: "Your version" }).locator(".cm-merge-accept").first().click();
await expect(notice).toBeHidden();
await page.getByRole("region", { name: "Their version" }).locator(".cm-merge-accept").first().click();
await expect(status(page)).toHaveText("All changes processed");
await expect(notice).toBeVisible();
await page.screenshot({ path: process.env.MERGE_SHOT, animations: "disabled" }).catch(() => undefined);
await page.getByRole("button", { name: "Save changes and finish merging" }).click();
// Nothing is left to confirm: the result is written and staged.
await expect.poll(async () => (await writes(page)).some((call) => call.command === "vcsStage")).toBe(true);
await expect(page.getByRole("dialog")).toHaveCount(0);
});
-1
View File
@@ -9,7 +9,6 @@ const java: GeneratorInfo = {
order: 1,
description: "A plain Java application built with Maven or Gradle.",
git: true,
directory: null,
dynamic: false,
fields: [
{
-3
View File
@@ -44,9 +44,6 @@ async function requestClose(
idlePolicy: { overrideSeconds },
});
window.__ipc.handlers.window_close_context = () => ({ windows, quitting });
window.__ipc.handlers.window_begin_prompt = () => true;
window.__ipc.handlers.window_end_prompt = () => null;
window.__ipc.handlers.window_ready_to_close = () => true;
window.__ipc.handlers.close_project = () => null;
window.__ipc.handlers.remote_invoke = ({ cmd }) => {
if (cmd === "remote_idle_timeout_minutes") {
+2 -9
View File
@@ -23,7 +23,7 @@ for (const theme of ["light", "dark"] as const) {
await page.getByRole("option", { name: "Current File", exact: true }).click();
const project = page.getByRole("region", { name: "Project", exact: true });
const buttons = [
...["Select Opened File", "Expand Selected", "Collapse All", "Options", "Hide"].map((name) =>
...["Select Opened File", "Expand All", "Collapse All", "Options", "Hide"].map((name) =>
project.getByRole("button", { name, exact: true }),
),
...[
@@ -66,8 +66,7 @@ for (const theme of ["light", "dark"] as const) {
await expect(button).toHaveCSS("outline-width", "2px");
}
const expand = project.getByRole("button", { name: "Expand Selected", exact: true });
await project.getByRole("treeitem", { name: "src", exact: true }).click();
const expand = project.getByRole("button", { name: "Expand All", exact: true });
await expand.hover();
const hover = await expand.evaluate((button) => getComputedStyle(button).backgroundColor);
await page.mouse.down();
@@ -75,12 +74,6 @@ for (const theme of ["light", "dark"] as const) {
await page.mouse.up();
await expect(project.getByRole("treeitem", { name: "src", exact: true })).toHaveAttribute("aria-expanded", "true");
await project.getByRole("button", { name: "Collapse All", exact: true }).click();
const projectRoot = project.getByRole("treeitem", { name: /^acme-api/ });
await expect(projectRoot).toHaveAttribute("aria-expanded", "false");
await expect(project.getByRole("treeitem", { name: "src", exact: true })).toHaveCount(0);
await projectRoot.click();
await project.getByRole("tree", { name: "Project" }).press("ArrowRight");
await expect(projectRoot).toHaveAttribute("aria-expanded", "true");
await expect(project.getByRole("treeitem", { name: "src", exact: true })).toHaveAttribute("aria-expanded", "false");
await project.getByRole("button", { name: "Options", exact: true }).click();
Loaded 100 of 306 files, more files were not shown because too many files have changed in this diff. Show more