Compare commits

..
Author SHA1 Message Date
l0ng-ai fd5f95760f docs: record product and design-system context
PRODUCT.md records the users, positioning, constraints and evidence the UI must respect.
DESIGN.md documents the visual system from src/styles/tokens.css and the src/ui primitives:
colour roles, the type scale, density and compact mode, tonal layering with shadows only on
floating surfaces, and component rules. .impeccable/ holds the design tool's config and the
machine-readable form of DESIGN.md.

The UI guidelines now say Islands Light is the default theme and list the built-in themes,
instead of describing the style as dark.
2026-11-25 09:18:36 +08:00
628 changed files with 3539 additions and 21839 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
+1 -11
View File
@@ -158,17 +158,7 @@
"src/features/run/**/*.ts",
"src/features/run/**/*.tsx",
"src/features/database/**/*.ts",
"src/features/database/**/*.tsx",
"src/features/analysis/**/*.ts",
"src/features/analysis/**/*.tsx",
"src/features/project-tree/**/*.ts",
"src/features/project-tree/**/*.tsx",
"src/features/http-client/**/*.ts",
"src/features/http-client/**/*.tsx",
"src/platform/**/*.ts",
"src/platform/**/*.tsx",
"src/features/debugger/**/*.ts",
"src/features/debugger/**/*.tsx"
"src/features/database/**/*.tsx"
],
"rules": {
"no-await-in-loop": "error"
Generated
-5
View File
@@ -4189,7 +4189,6 @@ dependencies = [
"ide-core",
"serde",
"specta",
"tempfile",
"which",
]
@@ -4252,20 +4251,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 -8
View File
@@ -6,13 +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).
## 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
@@ -73,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.
+2 -2
View File
@@ -196,11 +196,11 @@ fn levels_for_model_from_slice(options: &[AgentConfigOption]) -> Vec<AgentConfig
.filter(|o| config::is_per_model_option(o))
.cloned()
.map(|mut o| {
if config::is_context_option(&o.id) || config::is_fast_option(&o.id) {
if config::is_context_option(&o.id) {
if o.category.is_none() {
o.category = Some("model_config".into());
}
} else if o.category.is_none() {
} else if o.category.as_deref() != Some("thought_level") {
o.category = Some("thought_level".into());
}
o
+3 -4
View File
@@ -168,12 +168,11 @@ async fn discovery_reads_effort_and_fast_from_session_new_then_stops_the_agent()
assert_eq!(calls.iter().map(|(m, _)| m.as_str()).collect::<Vec<_>>(), ["initialize", "session/new"]);
assert_eq!(calls[1].1["mcpServers"], json!([]));
let cursor = mgr.providers().into_iter().find(|p| p.id == "cursor").unwrap();
// Per-model options (`effort`, `fast`, `context`) belong to the session's model, not provider-wide config.
assert!(!cursor.config.iter().any(|o| o.id == "fast"));
assert_eq!(cursor.thought_levels.keys().collect::<Vec<_>>(), ["m1"]);
let fast = cursor.thought_levels["m1"].iter().find(|o| o.id == "fast").expect("fast option");
let fast = cursor.config.iter().find(|o| o.id == "fast").expect("fast option");
assert_eq!(fast.category.as_deref(), Some("model_config"));
assert_eq!(fast.current.as_deref(), Some("false"));
// The effort option belongs to the session's model; m2 may offer other levels.
assert_eq!(cursor.thought_levels.keys().collect::<Vec<_>>(), ["m1"]);
assert!(cursor.thought_levels["m1"].iter().any(|o| o.category.as_deref() == Some("thought_level")));
}
+6 -24
View File
@@ -15,8 +15,6 @@ use tokio::time::Instant;
const FRESH_FOR: Duration = Duration::from_secs(15 * 60);
const COOLDOWN: Duration = Duration::from_secs(30);
/// Persisted catalog layout version; bump when option classification changes so stale per-model entries re-discover.
const CATALOG_SCHEMA: u8 = 2;
type Store = Arc<Mutex<HashMap<String, Known>>>;
type Key = (PathBuf, PathBuf, String);
@@ -82,8 +80,6 @@ impl CatalogData {
pub(crate) struct SavedCatalog {
/// An opaque cryptographic digest, never raw launch arguments or credentials.
fingerprint: String,
#[serde(default)]
schema: u8,
#[serde(flatten)]
catalog: CatalogData,
}
@@ -115,7 +111,7 @@ impl LaunchContext {
hash.update(&(value.len() as u64).to_le_bytes());
hash.update(value);
}
field(&mut hash, b"openidea-model-catalog-v2");
field(&mut hash, b"openidea-model-catalog-v1");
field(
&mut hash,
match self.spec.driver {
@@ -204,14 +200,7 @@ impl AgentCatalogs {
cache
.get(provider)
.and_then(|known| known.catalogs.get(&shared.root_key()))
.map(|saved| {
let mut catalog = saved.catalog.clone();
if saved.schema < CATALOG_SCHEMA {
catalog.refreshed_at_ms = None;
catalog.thought_levels.clear();
}
catalog
})
.map(|saved| saved.catalog.clone())
.unwrap_or_default()
}
@@ -239,8 +228,7 @@ impl AgentCatalogs {
}
drop(state);
let cache = shared.known.lock();
let saved = cache.get(provider)?.catalogs.get(&shared.root_key())?;
(saved.schema >= CATALOG_SCHEMA).then(|| saved.catalog.thought_levels.get(model).cloned()).flatten()
cache.get(provider)?.catalogs.get(&shared.root_key())?.catalog.thought_levels.get(model).cloned()
}
pub(super) async fn load_levels(
@@ -293,7 +281,7 @@ impl AgentCatalogs {
AgentModelCatalog {
provider: provider.to_owned(),
config: shared.config_for_new_task(catalog.config, provider),
thought_levels: shared.thought_levels_for_new_task(catalog.thought_levels, provider),
thought_levels: catalog.thought_levels,
refreshing: entry.flight.is_some(),
refreshed_at_ms: catalog.refreshed_at_ms,
retry_at_ms: model_failure
@@ -330,9 +318,7 @@ impl AgentCatalogs {
let generation = state.generation;
let saved =
shared.known.lock().get(&spec.id).and_then(|known| known.catalogs.get(&shared.root_key())).cloned();
let matching = saved
.as_ref()
.is_some_and(|saved| saved.schema >= CATALOG_SCHEMA && saved.fingerprint == context.fingerprint());
let matching = saved.as_ref().is_some_and(|saved| saved.fingerprint == context.fingerprint());
let age = saved
.as_ref()
.filter(|_| matching)
@@ -503,11 +489,7 @@ impl AgentCatalogs {
}
known.catalogs.insert(
shared.root_key(),
SavedCatalog {
fingerprint: entry.context.fingerprint(),
schema: CATALOG_SCHEMA,
catalog: catalog.clone(),
},
SavedCatalog { fingerprint: entry.context.fingerprint(), catalog: catalog.clone() },
);
entry.catalog = Some(catalog);
shared.persist_known(&cache);
+27 -99
View File
@@ -65,7 +65,7 @@ fn bypass_value(category: &str) -> Option<fn(&str) -> bool> {
}
/// Moves options that approve everything without asking to a value that asks: the agent's
/// own default (when it asks), else `default` or `ask`, else its first one that asks.
/// default or ask mode, else its first one that asks.
pub(crate) fn ask_for_approvals(config: &mut [AgentConfigOption]) {
for option in config {
let Some(bypass) = option.category.as_deref().and_then(bypass_value) else { continue };
@@ -73,15 +73,9 @@ pub(crate) fn ask_for_approvals(config: &mut [AgentConfigOption]) {
continue;
}
let asks = |v: &&AgentConfigValue| !bypass(&v.value);
let value = option
.default_value
.as_deref()
.and_then(|def| option.values.iter().filter(asks).find(|v| v.value == def))
.or_else(|| {
["default", "ask"]
.iter()
.find_map(|preferred| option.values.iter().filter(asks).find(|v| v.value == *preferred))
})
let value = ["default", "ask"]
.iter()
.find_map(|preferred| option.values.iter().filter(asks).find(|v| v.value == *preferred))
.or_else(|| option.values.iter().find(asks));
if let Some(value) = value {
option.current = Some(value.value.clone());
@@ -89,26 +83,11 @@ pub(crate) fn ask_for_approvals(config: &mut [AgentConfigOption]) {
}
}
/// Moves approval-bearing options (`mode`, `permissions`, `approval`) to their approving value.
pub(crate) fn apply_bypass_approvals(config: &mut [AgentConfigOption]) {
for option in config {
let Some(bypass) = option.category.as_deref().and_then(bypass_value) else { continue };
if let Some(value) = option.values.iter().find(|v| bypass(&v.value)) {
option.current = Some(value.value.clone());
}
}
}
/// Applies provider-specific defaults to per-model options for new tasks without altering `default_value`.
pub(crate) fn apply_model_defaults(provider: &str, options: &mut [AgentConfigOption]) {
if provider != "cursor" {
return;
}
if let Some(fast) = options.iter_mut().find(|o| is_fast_option(&o.id))
&& fast.values.iter().any(|v| v.value == "false")
{
fast.current = Some("false".into());
}
/// The mode that approves everything without asking (`bypassPermissions`, `yolo`, `full-access`…), if the agent has one.
pub(crate) fn bypass_mode(options: &[AgentConfigOption]) -> Option<(&AgentConfigOption, &AgentConfigValue)> {
let option = options.iter().find(|o| o.category.as_deref() == Some("mode"))?;
let value = option.values.iter().find(|v| is_bypass_mode(&v.value))?;
Some((option, value))
}
fn is_bypass_mode(mode: &str) -> bool {
@@ -147,20 +126,14 @@ pub(crate) fn options_of(result: &Value) -> Vec<AgentConfigOption> {
}
pub(crate) fn is_context_option(id: &str) -> bool {
matches!(id, "context" | "context_tier" | "contextTier")
}
pub(crate) fn is_fast_option(id: &str) -> bool {
id == "fast"
matches!(id, "context_tier" | "contextTier")
}
/// Whether an option's available values and default belong to the selected model
/// (`thought_level`, `context_tier`, and `model_config` options like `context` and `fast`)
/// rather than the provider as a whole.
/// (`thought_level` and model context-tier options) rather than the provider as a whole.
pub(crate) fn is_per_model_option(o: &AgentConfigOption) -> bool {
matches!(o.category.as_deref(), Some("thought_level" | "context_tier" | "model_config"))
matches!(o.category.as_deref(), Some("thought_level" | "context_tier"))
|| matches!(o.id.as_str(), "effort" | "reasoning_effort" | "thinking" | "reasoning")
|| is_fast_option(&o.id)
|| is_context_option(&o.id)
}
@@ -191,7 +164,7 @@ pub(crate) fn parse_options(options: &Value) -> Vec<AgentConfigOption> {
matches!(id.as_str(), "effort" | "reasoning_effort" | "thinking" | "reasoning")
.then(|| "thought_level".into())
})
.or_else(|| (is_fast_option(&id) || is_context_option(&id)).then(|| "model_config".into()))
.or_else(|| (id == "fast" || is_context_option(&id)).then(|| "model_config".into()))
}),
current,
default_value,
@@ -364,11 +337,6 @@ fn legacy(
}
}
fn clean_label(s: String, fallback: &str) -> String {
let trimmed = s.trim_matches(|c: char| c.is_whitespace() || matches!(c, '\u{200B}'..='\u{200D}' | '\u{FEFF}'));
if trimmed.is_empty() { fallback.to_owned() } else { trimmed.to_owned() }
}
fn value_of(v: &Value) -> Option<AgentConfigValue> {
let value = v.get("value")?.as_str()?.to_owned();
let meta = v.get("_meta");
@@ -384,7 +352,7 @@ fn value_of(v: &Value) -> Option<AgentConfigValue> {
.filter(|s| !s.is_empty())
.map(str::to_owned);
Some(AgentConfigValue {
name: str_of(v, "name").map(|n| clean_label(n, &value)).unwrap_or_else(|| value.clone()),
name: str_of(v, "name").unwrap_or_else(|| value.clone()),
description: str_of(v, "description"),
cost_category,
usage_multiplier,
@@ -466,16 +434,19 @@ mod tests {
]}
}));
assert!(bypass_approvals(&full_access));
assert_eq!(bypass_mode(&full_access).map(|(_, v)| v.value.as_str()), Some("full-access"));
let mut asking = options_of(&json!({
let asking = options_of(&json!({
"modes": {"currentModeId": "ask", "availableModes": [
{"id": "ask", "name": "Ask"}, {"id": "full-access", "name": "Full Access"}
]}
}));
assert!(!bypass_approvals(&asking));
apply_bypass_approvals(&mut asking);
assert_eq!(asking[0].current.as_deref(), Some("full-access"));
assert!(bypass_approvals(&asking));
assert_eq!(
bypass_mode(&asking).map(|(_, v)| v.value.as_str()),
Some("full-access"),
"the offered bypass mode stays available"
);
let permissions = |current: &str| {
options_of(&json!({"configOptions": [{
@@ -532,7 +503,7 @@ mod tests {
}
#[test]
fn effort_context_and_fast_are_per_model_options() {
fn effort_and_fast_categories_are_inferred_from_ids() {
let mut c = options_of(&json!({
"configOptions": [
{"id": "model", "type": "select", "currentValue": "gemini-4-carbon",
@@ -541,39 +512,19 @@ mod tests {
"_meta": {"copilotPriceCategory": "Medium", "copilotUsage": "1x"}}]},
{"id": "effort", "type": "select", "currentValue": "medium",
"options": [{"value": "low"}, {"value": "medium"}, {"value": "high"}]},
{"id": "context", "type": "select", "currentValue": "256k",
"options": [{"value": "256k", "name": "256K"}, {"value": "500k", "name": "500K"}]},
{"id": "contextTier", "type": "select", "currentValue": "default",
"options": [{"value": "default", "name": "200K"}, {"value": "long_context", "name": "1M"}]},
{"id": "fast", "type": "select", "currentValue": "true",
"options": [{"value": "false", "name": "Off"}, {"value": "true", "name": "Fast\u{200b}\u{200b}"}]}
{"id": "fast", "type": "select", "currentValue": "false",
"options": [{"value": "false", "name": "Off"}, {"value": "true", "name": "On"}]}
]
}));
assert_eq!(c.len(), 5);
assert_eq!(c.len(), 4);
assert_eq!(c[0].values[0].cost_category.as_deref(), Some("medium"));
assert_eq!(c[0].values[0].usage_multiplier.as_deref(), Some("1x"));
assert_eq!(c[1].category.as_deref(), Some("thought_level"));
assert_eq!(c[1].default_value.as_deref(), Some("medium"));
assert_eq!(c[2].category.as_deref(), Some("model_config"));
assert_eq!(c[3].category.as_deref(), Some("model_config"));
assert_eq!(c[4].category.as_deref(), Some("model_config"));
assert_eq!(c[4].values[1].name, "Fast");
assert!(
is_per_model_option(&c[1])
&& is_per_model_option(&c[2])
&& is_per_model_option(&c[3])
&& is_per_model_option(&c[4])
);
assert!(!is_per_model_option(&c[0]));
// Cursor defaults fast off for new tasks while preserving the agent's own default_value.
let mut cursor_opts = c.clone();
apply_model_defaults("cursor", &mut cursor_opts);
let fast = cursor_opts.iter().find(|o| o.id == "fast").unwrap();
assert_eq!((fast.current.as_deref(), fast.default_value.as_deref()), (Some("false"), Some("true")));
let mut other_opts = c.clone();
apply_model_defaults("claude", &mut other_opts);
assert_eq!(other_opts.iter().find(|o| o.id == "fast").unwrap().current.as_deref(), Some("true"));
assert!(is_per_model_option(&c[1]) && is_per_model_option(&c[2]) && !is_per_model_option(&c[3]));
// Editing effort on the same model preserves its initial `default_value` for Reset.
merge_update(
@@ -595,34 +546,11 @@ mod tests {
{"id": "model", "type": "select", "currentValue": "gpt-6-sol",
"options": [{"value": "gemini-4-carbon"}, {"value": "gpt-6-sol"}]},
{"id": "effort", "type": "select", "currentValue": "low",
"options": [{"value": "low"}, {"value": "medium"}, {"value": "high"}]},
{"id": "context", "type": "select", "currentValue": "1m",
"options": [{"value": "300k", "name": "300K"}, {"value": "1m", "name": "1M"}]}
"options": [{"value": "low"}, {"value": "medium"}, {"value": "high"}]}
]),
);
let effort = c.iter().find(|o| o.id == "effort").unwrap();
assert_eq!((effort.current.as_deref(), effort.default_value.as_deref()), (Some("low"), Some("low")));
let context = c.iter().find(|o| o.id == "context").unwrap();
assert_eq!((context.current.as_deref(), context.default_value.as_deref()), (Some("1m"), Some("1m")));
}
#[test]
fn apply_bypass_approvals_covers_mode_permissions_and_approval() {
let mut c = options_of(&json!({"configOptions": [
{"id": "mode", "category": "mode", "type": "select", "currentValue": "ask",
"options": [{"value": "ask"}, {"value": "full-access"}]},
{"id": "allow_all", "category": "permissions", "type": "select", "currentValue": "off",
"options": [{"value": "off"}, {"value": "on"}]},
{"id": "approval", "category": "approval", "type": "select", "currentValue": "ask",
"options": [{"value": "ask"}, {"value": "bypass"}]}
]}));
apply_bypass_approvals(&mut c);
assert_eq!(ids(&c), [("mode", Some("full-access")), ("allow_all", Some("on")), ("approval", Some("bypass"))]);
// Original agent default_values stay intact.
assert_eq!(
c.iter().map(|o| o.default_value.as_deref()).collect::<Vec<_>>(),
[Some("ask"), Some("off"), Some("ask")]
);
}
#[test]
-143
View File
@@ -1,143 +0,0 @@
//! Images in agent content: ACP content blocks, `data:` URLs and image files on disk.
use crate::model::AgentImage;
use base64::Engine;
use serde_json::{Value, json};
use std::path::Path;
/// Image files larger than this are not inlined into the conversation.
const MAX_FILE_BYTES: u64 = 10 * 1024 * 1024;
/// The image an ACP content block shows: an `image` (inline or by URI), a `resource` with an
/// image blob, or a `resource_link` to an image file.
pub(crate) fn from_content(content: &Value) -> Option<AgentImage> {
match str_of(content, "type")? {
"image" => {
if let (Some(data), Some(mime)) = (str_of(content, "data"), str_of(content, "mimeType"))
&& mime.starts_with("image/")
{
return Some(AgentImage { mime_type: mime.into(), data: data.into(), name: None });
}
from_uri(str_of(content, "uri")?)
}
"resource" => {
let resource = content.get("resource")?;
let (data, mime) = (str_of(resource, "blob")?, str_of(resource, "mimeType")?);
mime.starts_with("image/").then(|| AgentImage { mime_type: mime.into(), data: data.into(), name: None })
}
"resource_link" => {
let uri = str_of(content, "uri")?;
let declared = str_of(content, "mimeType").is_some_and(|m| m.starts_with("image/"));
if !declared && mime_of(Path::new(&uri_path(uri))).is_none() {
return None;
}
let mut image = from_uri(uri)?;
image.name = str_of(content, "name").map(str::to_owned);
Some(image)
}
_ => None,
}
}
fn str_of<'a>(v: &'a Value, key: &str) -> Option<&'a str> {
v.get(key).and_then(Value::as_str).filter(|s| !s.is_empty())
}
/// The image at a `data:` URL or a `file://` URI.
pub(crate) fn from_uri(uri: &str) -> Option<AgentImage> {
if let Some(rest) = uri.strip_prefix("data:") {
let (mime, data) = rest.split_once(";base64,")?;
return (mime.starts_with("image/") && !data.is_empty()).then(|| AgentImage {
mime_type: mime.into(),
data: data.into(),
name: None,
});
}
uri.starts_with("file://").then(|| from_file(Path::new(&uri_path(uri))))?
}
/// The image file at `path`, when it has an image extension and isn't too large.
pub(crate) fn from_file(path: &Path) -> Option<AgentImage> {
let mime = mime_of(path)?;
if std::fs::metadata(path).ok()?.len() > MAX_FILE_BYTES {
return None;
}
let bytes = std::fs::read(path).ok()?;
(!bytes.is_empty()).then(|| AgentImage {
mime_type: mime.into(),
data: base64::engine::general_purpose::STANDARD.encode(bytes),
name: path.file_name().and_then(|n| n.to_str()).map(str::to_owned),
})
}
/// `image` as an ACP image content block.
pub(crate) fn content(image: &AgentImage) -> Value {
json!({ "type": "image", "mimeType": image.media_type(), "data": image.data })
}
fn mime_of(path: &Path) -> Option<&'static str> {
let ext = path.extension()?.to_str()?.to_ascii_lowercase();
Some(match ext.as_str() {
"png" => "image/png",
"jpg" | "jpeg" => "image/jpeg",
"gif" => "image/gif",
"webp" => "image/webp",
"bmp" => "image/bmp",
"svg" => "image/svg+xml",
_ => return None,
})
}
/// The path of a `file://` URI (percent-decoded); other URIs as they are.
pub(crate) fn uri_path(uri: &str) -> String {
let Some(rest) = uri.strip_prefix("file://") else { return uri.to_owned() };
let bytes = rest.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%'
&& let Some(b) = rest.get(i + 1..i + 3).and_then(|h| u8::from_str_radix(h, 16).ok())
{
out.push(b);
i += 3;
} else {
out.push(bytes[i]);
i += 1;
}
}
let path = String::from_utf8_lossy(&out).into_owned();
// `file:///C:/x` on Windows.
match path.as_bytes() {
[b'/', drive, b':', ..] if drive.is_ascii_alphabetic() => path[1..].to_owned(),
_ => path,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn content_blocks_inline_data_urls_blobs_and_image_files() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("shot 1.png");
std::fs::write(&file, b"\x89PNG\r\n").unwrap();
std::fs::write(dir.path().join("notes.txt"), b"hi").unwrap();
let uri = crate::file_uri(&file);
let inline = json!({"type": "image", "mimeType": "image/png", "data": "aW1n"});
assert_eq!(from_content(&inline).unwrap().data, "aW1n");
let by_url = json!({"type": "image", "uri": "data:image/jpeg;base64,AAA"});
assert_eq!(from_content(&by_url).unwrap().mime_type, "image/jpeg");
let by_file = from_content(&json!({"type": "image", "uri": uri})).unwrap();
assert_eq!(by_file.data, base64::engine::general_purpose::STANDARD.encode(b"\x89PNG\r\n"));
let blob = json!({"type": "resource", "resource": {"uri": "x", "mimeType": "image/gif", "blob": "R0lG"}});
assert_eq!(from_content(&blob).unwrap().mime_type, "image/gif");
let link = from_content(&json!({"type": "resource_link", "uri": uri, "name": "shot"})).unwrap();
assert_eq!((link.mime_type.as_str(), link.name.as_deref()), ("image/png", Some("shot")));
let text = crate::file_uri(&dir.path().join("notes.txt"));
assert!(from_content(&json!({"type": "resource_link", "uri": text, "name": "notes"})).is_none());
assert!(from_content(&json!({"type": "resource", "resource": {"uri": "x", "text": "t"}})).is_none());
assert!(from_content(&json!({"type": "image", "uri": "https://example.com/a.png"})).is_none());
assert!(from_file(&dir.path().join("missing.png")).is_none());
}
}
+48 -215
View File
@@ -16,7 +16,6 @@ mod conversation;
mod elicitation;
mod external;
pub mod hermes;
mod images;
pub mod mcp;
mod model;
mod native;
@@ -331,23 +330,19 @@ impl Shared {
let hook = self.new_task_approvals.read().clone();
if hook.is_some_and(|ask| ask() == ide_core::settings::NewTaskApprovals::Ask) {
config::ask_for_approvals(&mut config);
} else {
config::apply_bypass_approvals(&mut config);
return config;
}
if let Some((o, v)) = config::bypass_mode(&config).map(|(o, v)| (o.id.clone(), v.value.clone()))
&& let Some(o) = config.iter_mut().find(|c| c.id == o)
{
o.current = Some(v);
}
if let Some(o) = config.iter_mut().find(|o| o.id == config::CURSOR_APPROVAL) {
o.current = Some("bypass".into());
}
config
}
pub(crate) fn thought_levels_for_new_task(
&self,
mut levels: BTreeMap<String, Vec<AgentConfigOption>>,
provider: &str,
) -> BTreeMap<String, Vec<AgentConfigOption>> {
for options in levels.values_mut() {
config::apply_model_defaults(provider, options);
}
levels
}
/// The commands the agent offered last time in this project.
fn known_commands(&self, provider: &str) -> Vec<AgentCommand> {
let cache = self.known.lock();
@@ -379,19 +374,8 @@ impl Shared {
}
}
// Discovery reads one model's options; a session on another model reports that model's.
// Restore each option's agent default so a session's manual overrides never pollute the catalog.
if acp && let Some((model, config)) = model.zip(config) {
let levels: Vec<_> = config
.iter()
.filter(|o| config::is_per_model_option(o))
.cloned()
.map(|mut o| {
if let Some(def) = o.default_value.clone().filter(|d| o.values.iter().any(|v| v.value == *d)) {
o.current = Some(def);
}
o
})
.collect();
let levels: Vec<_> = config.iter().filter(|o| config::is_per_model_option(o)).cloned().collect();
if !levels.is_empty() {
self.paths.catalogs.learn_levels(self, provider, model, levels);
}
@@ -435,13 +419,9 @@ struct TaskFile {
/// `None` for a worktree task, and a task saved before these were recorded.
#[serde(default, skip_serializing_if = "Option::is_none")]
touched: Option<BTreeSet<String>>,
/// The checkout as the last turn started, in task files saved before every turn's was kept.
#[serde(default, skip_serializing)]
/// The checkout as the last turn started, its copies in the store's `<id>.turn` folder.
#[serde(default, skip_serializing_if = "Option::is_none")]
turn: Option<worktree::TurnStart>,
/// The checkout as each turn of the conversation started (by turn, `None` where it wasn't
/// recorded), the copies in the store's `<id>.turn` folder.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
turns: Vec<Option<worktree::TurnStart>>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
subagents: Vec<SavedSubagent>,
/// Turns to drop from the session once it is loaded (a fork of an earlier point).
@@ -475,16 +455,6 @@ impl PendingModel {
/// The changed files of a checkout, stamped.
type Snapshot = BTreeMap<String, worktree::Stamp>;
/// Holds `TaskState::busy` for the duration of an operation so concurrent prompts or rollbacks
/// wait until it finishes.
struct BusyGuard(Arc<Task>);
impl Drop for BusyGuard {
fn drop(&mut self) {
self.0.state.lock().busy = false;
}
}
struct TaskState {
task: AgentTask,
session_id: Option<String>,
@@ -497,8 +467,8 @@ struct TaskState {
saved: Option<String>,
/// See `TaskFile::touched`.
touched: Option<Arc<BTreeSet<String>>>,
/// See `TaskFile::turns`.
turns: Vec<Option<Arc<worktree::TurnStart>>>,
/// See `TaskFile::turn`.
turn: Option<Arc<worktree::TurnStart>>,
pending_rollback: u32,
/// The user named the task; see `TaskFile::title_renamed`.
title_renamed: bool,
@@ -751,7 +721,7 @@ impl AgentManager {
let mut info = provider::describe(p);
let catalog = self.shared.paths.catalogs.cached(&self.shared, &p.id);
info.config = self.shared.config_for_new_task(catalog.config, &p.id);
info.thought_levels = self.shared.thought_levels_for_new_task(catalog.thought_levels, &p.id);
info.thought_levels = catalog.thought_levels;
info.commands = self.shared.known_commands(&p.id);
info
})
@@ -1019,7 +989,6 @@ impl AgentManager {
saved: None,
touched: Some(BTreeSet::new()),
turn: None,
turns: Vec::new(),
subagents: Vec::new(),
pending_rollback: 0,
title_renamed: true,
@@ -1074,7 +1043,7 @@ impl AgentManager {
};
// Until the session reports its own, show what the agent offered last time with the choices applied.
let catalog = self.shared.paths.catalogs.cached(&self.shared, &spec.id);
let mut levels = self.shared.thought_levels_for_new_task(catalog.thought_levels, &spec.id);
let mut levels = catalog.thought_levels;
let mut config = self.shared.config_for_new_task(catalog.config, &spec.id);
for choice in &req.config {
if let Some(o) = config.iter_mut().find(|o| o.id == choice.id) {
@@ -1147,7 +1116,6 @@ impl AgentManager {
saved,
touched: (req.isolation == Isolation::Local).then(BTreeSet::new),
turn: None,
turns: Vec::new(),
subagents: Vec::new(),
pending_rollback: 0,
title_renamed: false,
@@ -1510,9 +1478,8 @@ impl AgentManager {
before: (*s.before).clone(),
saved: s.saved.clone(),
touched: s.touched.as_deref().cloned(),
// The copies are the source's: the fork's turns are recorded as it runs them.
// The source's next turn replaces its copies: the fork's last turn is one of its own.
turn: None,
turns: Vec::new(),
subagents: s.conversation.saved_subagents(),
pending_rollback: total - keep,
title_renamed: s.title_renamed,
@@ -1529,31 +1496,21 @@ impl AgentManager {
}
/// Drops the task's turns after its first `turns`, in the agent's session and in the
/// conversation; returns the message that started the first dropped turn. With `files`,
/// the files the dropped turns changed go back as they were when the first of them
/// started; otherwise they stay as they are.
pub async fn rollback(&self, id: &str, turns: u32, files: bool) -> IdeResult<Option<AgentPrompt>> {
/// conversation; returns the message that started the first dropped turn. Files the
/// agent changed stay as they are.
pub async fn rollback(&self, id: &str, turns: u32) -> IdeResult<Option<AgentPrompt>> {
let task = self.task(id)?;
let (starts, cut) = {
let mut s = task.state.lock();
if s.busy {
return Err(IdeError::invalid("wait until the agent is done"));
}
let starts = turn_starts(&s.conversation.main.entries);
let Some(&cut) = starts.get(turns as usize) else { return Ok(None) };
s.busy = true;
(starts, cut)
};
let guard = BusyGuard(task.clone());
// Read and checked before anything changes: a file that can't go back stops it all.
let planned = if files { self.plan_rewind(&task, turns as usize, starts.len()).await? } else { Vec::new() };
if task.state.lock().busy {
return Err(IdeError::invalid("wait until the agent is done"));
}
let starts = turn_starts(&task.state.lock().conversation.main.entries);
let Some(&cut) = starts.get(turns as usize) else { return Ok(None) };
// Dropping every turn starts the conversation over, which needs no agent-side
// rewind — and some agents cannot rewind past their first turn (a resumed
// Claude Code session). A fresh session avoids both.
if turns == 0 {
task.kill();
let restamped = self.write_rewind(&task, planned).await?;
let (first, dir, kept) = {
let first = {
let mut s = task.state.lock();
let first = match s.conversation.main.entries.get(cut) {
Some(AgentEntry::User { text, .. }) => {
@@ -1570,29 +1527,25 @@ impl AgentManager {
s.task.usage = None;
s.pending_rollback = 0;
s.task.updated_ms = now_ms();
Self::finish_rewind(&mut s, 0, restamped);
(first, task.turn_dir(), s.turns.clone())
first
};
drop(guard);
task.streamed.lock().clear();
task.persist();
self.shared.emit(AgentEvent::Truncated { task: id.to_owned(), length: 0 });
task.emit_task();
self.prune_turn_copies(dir, kept).await;
return Ok(first);
}
let live = task.ensure_session().await.map_err(IdeError::internal)?;
if !live.capabilities.rollback {
return Err(IdeError::invalid("this agent can't undo turns"));
}
let drop_turns = (starts.len() - turns as usize) as u32;
let drop = (starts.len() - turns as usize) as u32;
let _: Value = live
.peer
.request("_openidea/rollback", json!({ "sessionId": live.session, "turns": drop_turns }), None)
.request("_openidea/rollback", json!({ "sessionId": live.session, "turns": drop }), None)
.await
.map_err(|e| IdeError::internal(task.describe(e)))?;
let restamped = self.write_rewind(&task, planned).await?;
let (first, dir, kept) = {
let first = {
let mut s = task.state.lock();
let first = match s.conversation.main.entries.get(cut) {
Some(AgentEntry::User { text, .. }) => Some(AgentPrompt { text: text.clone(), ..Default::default() }),
@@ -1600,15 +1553,12 @@ impl AgentManager {
};
s.conversation.truncate(cut);
s.task.updated_ms = now_ms();
Self::finish_rewind(&mut s, turns as usize, restamped);
(first, task.turn_dir(), s.turns.clone())
first
};
drop(guard);
task.streamed.lock().clear();
task.persist();
self.shared.emit(AgentEvent::Truncated { task: id.to_owned(), length: cut as u32 });
task.emit_task();
self.prune_turn_copies(dir, kept).await;
// Undoing may have started the agent: it stops again once idle.
task.release_when_idle();
Ok(first)
@@ -1966,98 +1916,6 @@ impl AgentManager {
.await
}
/// What rolling the task's files back to the start of its turn `turn` writes.
async fn plan_rewind(
&self,
task: &Arc<Task>,
turn: usize,
total_turns: usize,
) -> IdeResult<Vec<worktree::PutBack>> {
let (cwd, start, before, saved, touched, dropped_changed) = {
let s = task.state.lock();
let start = s.turns.get(turn).cloned().flatten();
let dropped = s.turns.get(turn..).unwrap_or(&[]);
let dropped_changed = (dropped.len() == total_turns - turn
&& dropped.iter().all(|t| t.as_ref().is_some_and(|t| t.changed.is_some())))
.then(|| {
dropped
.iter()
.flatten()
.filter_map(|t| t.changed.as_ref())
.flatten()
.cloned()
.collect::<BTreeSet<String>>()
});
(
s.task.cwd.0.clone(),
start,
s.before.clone(),
s.saved.as_ref().map(|name| self.shared.paths.store_dir.join(name)),
s.touched.clone(),
dropped_changed,
)
};
let Some(start) = start else {
// The task's own start is the first turn's.
if turn == 0 {
let at = task.base();
return vcs(&self.shared, move || {
worktree::plan_restore(&at, &before, saved.as_deref(), touched.as_deref())
})
.await;
}
return Err(IdeError::invalid(
"the files weren't recorded as this message was sent: roll them back in the Changes view instead",
));
};
let dir = task.turn_dir();
vcs(&self.shared, move || {
let mut changed = worktree::changed_in_turn(&cwd, &start)?.1;
// In the project's own checkout, only files the rolled-back turns changed are put back.
if let Some(touched) = &touched {
let scope = dropped_changed.as_ref().unwrap_or(touched);
changed.retain(|rel| scope.contains(rel));
}
worktree::rewind(&cwd, &start, &dir, &changed)
})
.await
}
/// Writes what `plan_rewind` planned on the blocking VCS pool and computes any `before`
/// restamps off-lock.
async fn write_rewind(
&self,
task: &Arc<Task>,
planned: Vec<worktree::PutBack>,
) -> IdeResult<Vec<(String, worktree::Stamp)>> {
if planned.is_empty() {
return Ok(Vec::new());
}
let (before, saved) = {
let s = task.state.lock();
(s.before.clone(), s.saved.as_ref().map(|name| self.shared.paths.store_dir.join(name)))
};
vcs(&self.shared, move || worktree::put_back(planned, &before, saved.as_deref())).await
}
/// Drops the records of the turns from `turn` on and applies any restamps to `before`.
fn finish_rewind(s: &mut TaskState, turn: usize, restamped: Vec<(String, worktree::Stamp)>) {
s.turns.truncate(turn);
if !restamped.is_empty() {
let mut before = (*s.before).clone();
before.extend(restamped);
s.before = Arc::new(before);
}
}
async fn prune_turn_copies(&self, dir: PathBuf, kept: Vec<Option<Arc<worktree::TurnStart>>>) {
let _ = vcs(&self.shared, move || {
worktree::prune_turn_copies(&dir, kept.iter().flatten().map(|t| &**t));
Ok(())
})
.await;
}
/// Rollback: puts the task's changed files among `rel_paths` (all with `None`) back as
/// `view` compares them: as they were when it started, as they are in `HEAD`, or as they
/// were when its last turn started.
@@ -2114,12 +1972,12 @@ impl AgentManager {
s.before = Arc::new(before);
}
// Rolled back further than the last turn: what it changed there is gone, not the turn's to list.
if let Some(Some(turn)) = s.turns.last_mut()
if let Some(turn) = &s.turn
&& let Some(changed) = &turn.changed
&& restored.iter().any(|rel| changed.contains(rel))
{
let changed = changed.iter().filter(|rel| !restored.contains(rel)).cloned().collect();
*turn = Arc::new(worktree::TurnStart { changed: Some(changed), ..(**turn).clone() });
s.turn = Some(Arc::new(worktree::TurnStart { changed: Some(changed), ..(**turn).clone() }));
}
}
task.persist();
@@ -2366,14 +2224,6 @@ impl Task {
config::add_client_options(&task.provider, &mut task.config);
let adopt = file.entries.is_empty() && file.session_id.is_some();
let conversation = Conversation::restore(file.entries, file.subagents);
let mut turns: Vec<_> = file.turns.into_iter().map(|t| t.map(Arc::new)).collect();
// Saved with the last turn's only: the turns before it have none.
if turns.is_empty()
&& let Some(last) = file.turn
{
turns.resize(turn_starts(&conversation.main.entries).len().saturating_sub(1), None);
turns.push(Some(Arc::new(last)));
}
let mut wanted = file.wanted;
let pending_model = file.pending_switch.or_else(|| {
let id = file.pending_model?;
@@ -2406,7 +2256,7 @@ impl Task {
before: Arc::new(file.before),
saved: file.saved,
touched: file.touched.map(Arc::new),
turns,
turn: file.turn.map(Arc::new),
pending_rollback: file.pending_rollback,
title_renamed: file.title_renamed,
busy: false,
@@ -2445,7 +2295,7 @@ impl Task {
(s.before.clone(), s.touched.clone())
}
/// Where the copies of the files already changed as the turns started are kept.
/// Where the copies of the files already changed as the last turn started are kept.
fn turn_dir(&self) -> PathBuf {
self.shared.paths.store_dir.join(format!("{}.turn", self.id))
}
@@ -2453,38 +2303,20 @@ impl Task {
/// The checkout as the last turn started, with the folder of its copies.
fn last_turn(&self) -> (PathBuf, Option<Arc<worktree::TurnStart>>, PathBuf) {
let s = self.state.lock();
(s.task.cwd.0.clone(), s.turns.last().cloned().flatten(), self.turn_dir())
(s.task.cwd.0.clone(), s.turn.clone(), self.turn_dir())
}
/// Records the checkout as a turn starts (its message shown): what the turn's changes are
/// compared with, and what rolling back to its message puts back.
/// Records the checkout as a turn starts: what the turn's changes are compared with.
async fn checkout_before_turn(self: &Arc<Self>) {
let (cwd, dir, index, earlier) = {
let s = self.state.lock();
let index = turn_starts(&s.conversation.main.entries).len().saturating_sub(1);
let earlier: Vec<_> = s.turns.iter().take(index).cloned().collect();
(s.task.cwd.0.clone(), self.turn_dir(), index, earlier)
};
let kept = earlier.clone();
let turn = match vcs(&self.shared, move || {
let turn = worktree::start_turn(&cwd, &dir)?;
worktree::prune_turn_copies(&dir, kept.iter().flatten().map(|t| &**t).chain([&turn]));
Ok(turn)
})
.await
{
let (cwd, previous, dir) = self.last_turn();
let turn = match vcs(&self.shared, move || worktree::start_turn(&cwd, &dir, previous.as_deref())).await {
Ok(turn) => Some(Arc::new(turn)),
Err(e) => {
tracing::warn!("recording the checkout as a turn of agent task {} starts: {e}", self.id);
None
}
};
{
let mut s = self.state.lock();
s.turns = earlier;
s.turns.resize(index, None);
s.turns.push(turn);
}
self.state.lock().turn = turn;
self.persist_soon();
}
@@ -2506,9 +2338,7 @@ impl Task {
touched.extend(in_worktree);
s.touched = Some(Arc::new(touched));
}
if let Some(last) = s.turns.last_mut() {
*last = Some(Arc::new(worktree::TurnStart { changed: Some(all), ..(*turn).clone() }));
}
s.turn = Some(Arc::new(worktree::TurnStart { changed: Some(all), ..(*turn).clone() }));
}
self.persist_soon();
}
@@ -2679,8 +2509,7 @@ impl Task {
before: (*s.before).clone(),
saved: s.saved.clone(),
touched: s.touched.as_deref().cloned(),
turn: None,
turns: s.turns.iter().map(|t| t.as_deref().cloned()).collect(),
turn: s.turn.as_deref().cloned(),
subagents: s.conversation.saved_subagents(),
pending_rollback: s.pending_rollback,
title_renamed: s.title_renamed,
@@ -3837,8 +3666,12 @@ impl Task {
/// A user message of the adopted history: live turns show the user's own, so only a replay's count.
fn adopt_user_chunk(self: &Arc<Self>, update: &Value) {
let content = update.get("content");
let image = content.and_then(images::from_content);
let text = if image.is_some() { String::new() } else { timeline::content_text(content).unwrap_or_default() };
let image = content.filter(|c| c.get("type").and_then(Value::as_str) == Some("image")).map(|c| AgentImage {
mime_type: c.get("mimeType").and_then(Value::as_str).unwrap_or_default().to_owned(),
data: c.get("data").and_then(Value::as_str).unwrap_or_default().to_owned(),
name: None,
});
let text = timeline::content_text(content).unwrap_or_default();
if text.is_empty() && image.is_none() {
return;
}
@@ -473,39 +473,6 @@ fn history_replays_turns() {
assert_eq!(updates[4]["status"], "completed");
}
#[test]
fn viewed_generated_and_attached_images_carry_their_pixels() {
let dir = tempfile::tempdir().unwrap();
let png = dir.path().join("shot.png");
std::fs::write(&png, b"\x89PNG\r\n").unwrap();
let png_path = png.to_str().unwrap();
let encoded = "iVBORw0K";
let view = json!({"id": "v", "type": "imageView", "path": png_path});
assert!(tool_call(&view, false, None, None).unwrap().get("content").is_none());
let image = &tool_call(&view, true, None, None).unwrap()["content"][0]["content"];
assert_eq!((image["type"].as_str(), image["data"].as_str()), (Some("image"), Some(encoded)));
let missing = json!({"id": "v", "type": "imageView", "path": dir.path().join("gone.png")});
assert!(tool_call(&missing, true, None, None).unwrap().get("content").is_none());
let inline = json!({"id": "g", "type": "imageGeneration", "status": "completed", "result": encoded});
let image = &tool_call(&inline, true, None, None).unwrap()["content"][0]["content"];
assert_eq!((image["mimeType"].as_str(), image["data"].as_str()), (Some("image/png"), Some(encoded)));
let saved =
json!({"id": "g", "type": "imageGeneration", "status": "completed", "fileId": "f", "savedPath": png_path});
assert_eq!(tool_call(&saved, true, None, None).unwrap()["content"][0]["content"]["data"], encoded);
let thread = json!({"turns": [{"items": [{"type": "userMessage", "id": "u", "content": [
{"type": "image", "url": "data:image/jpeg;base64,/9j/"},
{"type": "image", "url": "https://example.com/a.png"},
{"type": "localImage", "path": png_path},
{"type": "localImage", "path": "/gone.png"}
]}]}]});
let contents: Vec<Value> = history(&thread, None).into_iter().map(|u| u["content"].clone()).collect();
assert_eq!(contents[0], json!({"type": "image", "mimeType": "image/jpeg", "data": "/9j/"}));
assert_eq!(contents[1]["type"], "resource_link");
assert_eq!(contents[2], json!({"type": "image", "mimeType": "image/png", "data": encoded}));
assert_eq!(contents[3], json!({"type": "text", "text": "/gone.png"}));
}
#[test]
fn history_preserves_async_questions_with_stable_answer_ids() {
let updates = history(
+26 -43
View File
@@ -348,18 +348,36 @@ pub(super) fn user_input(prompt: &Value) -> Vec<Value> {
}
"resource" => {
let r = b.get("resource")?;
let path = crate::images::uri_path(r.get("uri").and_then(Value::as_str).unwrap_or_default());
let path = uri_path(r.get("uri").and_then(Value::as_str).unwrap_or_default());
let text = r.get("text").and_then(Value::as_str)?;
Some(json!({ "type": "text", "text": format!("<file path=\"{path}\">\n{text}\n</file>") }))
}
"resource_link" => {
Some(json!({ "type": "text", "text": crate::images::uri_path(b.get("uri")?.as_str()?) }))
}
"resource_link" => Some(json!({ "type": "text", "text": uri_path(b.get("uri")?.as_str()?) })),
_ => None,
})
.collect()
}
/// The path of a `file://` URI (percent-decoded); other URIs as they are.
fn uri_path(uri: &str) -> String {
let Some(rest) = uri.strip_prefix("file://") else { return uri.to_owned() };
let bytes = rest.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%'
&& let Some(b) = rest.get(i + 1..i + 3).and_then(|h| u8::from_str_radix(h, 16).ok())
{
out.push(b);
i += 3;
} else {
out.push(bytes[i]);
i += 1;
}
}
String::from_utf8_lossy(&out).into_owned()
}
/// A `session/update` notification's `update` for content.
pub(super) fn chunk(kind: &str, text: &str) -> Value {
json!({ "sessionUpdate": kind, "content": { "type": "text", "text": text } })
@@ -449,9 +467,6 @@ pub(super) fn tool_call(item: &Value, done: bool, cwd: Option<&str>, output: Opt
"imageView" => {
let path = item.get("path").and_then(Value::as_str).unwrap_or_default();
call.insert("locations".into(), json!([{ "path": path }]));
if done && let Some(image) = crate::images::from_file(std::path::Path::new(path)) {
call.insert("content".into(), json!([image_content(&image)]));
}
(format!("View {}", display_path(path, cwd)), "read")
}
"collabAgentToolCall" => {
@@ -467,12 +482,7 @@ pub(super) fn tool_call(item: &Value, done: bool, cwd: Option<&str>, output: Opt
}
"contextCompaction" => ("Compact the conversation".to_owned(), "other"),
"sleep" => ("Wait".to_owned(), "other"),
"imageGeneration" => {
if done && let Some(image) = generated_image(item) {
call.insert("content".into(), json!([image_content(&image)]));
}
("Generate an image".to_owned(), "other")
}
"imageGeneration" => ("Generate an image".to_owned(), "other"),
_ => return None,
};
call.insert("sessionUpdate".into(), json!(if done { "tool_call_update" } else { "tool_call" }));
@@ -483,19 +493,6 @@ pub(super) fn tool_call(item: &Value, done: bool, cwd: Option<&str>, output: Opt
Some(Value::Object(call))
}
fn image_content(image: &crate::model::AgentImage) -> Value {
json!({ "type": "content", "content": crate::images::content(image) })
}
/// A generated image: inline (base64 PNG) or, when codex saved it, the file.
fn generated_image(item: &Value) -> Option<crate::model::AgentImage> {
if let Some(data) = item.get("result").and_then(Value::as_str).filter(|d| !d.is_empty()) {
let image = crate::model::AgentImage { mime_type: "image/png".into(), data: data.into(), name: None };
return Some(crate::model::AgentImage { mime_type: image.media_type().into(), ..image });
}
crate::images::from_file(std::path::Path::new(item.get("savedPath")?.as_str()?))
}
/// The output of a running command, as a `tool_call_update`.
pub(super) fn command_output(id: &str, output: &str) -> Value {
json!({ "sessionUpdate": "tool_call_update", "toolCallId": id, "content": [text_content(&tail(output))] })
@@ -859,23 +856,9 @@ pub(super) fn history(thread: &Value, cwd: Option<&str>) -> Vec<Value> {
"user_message_chunk",
c.get("text").and_then(Value::as_str).unwrap_or_default(),
)),
Some("image") => {
let url = c.get("url").and_then(Value::as_str).unwrap_or_default();
let content = crate::images::from_uri(url).map_or_else(
|| json!({ "type": "resource_link", "uri": url, "name": "image" }),
|image| crate::images::content(&image),
);
out.push(json!({ "sessionUpdate": "user_message_chunk", "content": content }));
}
Some("localImage") => {
let path = c.get("path").and_then(Value::as_str).unwrap_or_default();
out.push(match crate::images::from_file(std::path::Path::new(path)) {
Some(image) => json!({ "sessionUpdate": "user_message_chunk",
"content": crate::images::content(&image) }),
None => chunk("user_message_chunk", path),
});
}
Some("mention" | "skill") => {
Some("image") => out.push(json!({ "sessionUpdate": "user_message_chunk",
"content": { "type": "resource_link", "uri": c.get("url"), "name": "image" } })),
Some("localImage" | "mention" | "skill") => {
let path = c.get("path").and_then(Value::as_str).unwrap_or_default();
out.push(chunk("user_message_chunk", path));
}
+11 -158
View File
@@ -2688,7 +2688,7 @@ async fn forks_rollbacks_and_steering() {
}
// Undoing the last turn hands its message back.
let undone = mgr.rollback(&task.id, 1, false).await.unwrap().unwrap();
let undone = mgr.rollback(&task.id, 1).await.unwrap().unwrap();
assert_eq!(undone.text, "again");
assert_eq!(turn_starts(&mgr.entries(&task.id, None).unwrap()).len(), 1);
assert!(agent.calls.lock().iter().any(|c| c == "_openidea/rollback 1"));
@@ -2715,7 +2715,7 @@ async fn forks_rollbacks_and_steering() {
}
handle.state.lock().conversation.main.entries.insert(0, AgentEntry::Agent { text: "Welcome".into() });
let rewinds = agent.calls.lock().iter().filter(|c| c.starts_with("_openidea/rollback")).count();
let first = mgr.rollback(&task.id, 0, false).await.unwrap().unwrap();
let first = mgr.rollback(&task.id, 0).await.unwrap().unwrap();
assert_eq!(first.text, "again");
assert!(mgr.entries(&task.id, None).unwrap().is_empty());
assert!(mgr.task(&task.id).unwrap().state.lock().session_id.is_none());
@@ -3654,7 +3654,7 @@ async fn idle_agents_stop_and_resume_their_session_on_the_next_message() {
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
tokio::time::sleep(Duration::from_millis(600)).await;
assert!(!live(&mgr, &task.id));
mgr.rollback(&task.id, 1, false).await.unwrap();
mgr.rollback(&task.id, 1).await.unwrap();
assert!(live(&mgr, &task.id));
tokio::time::sleep(Duration::from_millis(600)).await;
assert!(!live(&mgr, &task.id), "an agent started to undo turns stops too");
@@ -3942,10 +3942,14 @@ async fn composer_commands_discover_cursor_effort_and_fast() {
assert!(calls.iter().any(|m| m.as_str() == "session/new"));
assert_eq!(calls.iter().filter(|m| m.as_str() == "initialize").count(), 1);
let cursor = mgr.providers().into_iter().find(|p| p.id == "cursor").unwrap();
assert!(!cursor.config.iter().any(|o| o.id == "fast"));
let levels = cursor.thought_levels.values().next().expect("discovered model options");
assert_eq!(levels.iter().find(|o| o.id == "fast").unwrap().current.as_deref(), Some("false"));
assert!(levels.iter().any(|o| o.category.as_deref() == Some("thought_level")));
assert_eq!(cursor.config.iter().find(|o| o.id == "fast").unwrap().current.as_deref(), Some("false"));
assert!(
cursor
.thought_levels
.values()
.next()
.is_some_and(|levels| { levels.iter().any(|o| o.category.as_deref() == Some("thought_level")) })
);
}
#[tokio::test(flavor = "multi_thread")]
@@ -4661,157 +4665,6 @@ async fn the_last_turn_lists_and_rolls_back_only_its_own_changes() {
}
}
#[tokio::test(flavor = "multi_thread")]
async fn rolling_back_to_a_message_puts_back_the_files_as_it_was_sent() {
for isolation in [Isolation::Local, Isolation::Worktree] {
let repo = Checkout::new(Eol::Lf);
repo.write("a.txt", "base\n");
repo.write("gone.txt", "base\n");
repo.commit("init");
let mgr = manager(&repo.dir, Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask { prompt: text("Hello"), provider: "claude".into(), isolation, ..Default::default() })
.await
.unwrap();
let cwd = task.cwd.0.clone();
let write = |rel: &str, text: &str| std::fs::write(cwd.join(rel), text).unwrap();
let read = |rel: &str| std::fs::read_to_string(cwd.join(rel)).ok();
let case = format!("{isolation:?}");
one_turn(&mgr, &task.id, None, || write("a.txt", "base\nturn 1\n")).await;
// The user's own work between the turns.
write("mine.txt", "mine\n");
one_turn(&mgr, &task.id, Some("more"), || {
write("a.txt", "base\nturn 1\nturn 2\n");
write("two.txt", "two\n");
})
.await;
one_turn(&mgr, &task.id, Some("last"), || {
write("a.txt", "base\nturn 1\nturn 2\nturn 3\n");
std::fs::remove_file(cwd.join("gone.txt")).unwrap();
})
.await;
// And after the last one.
write("later.txt", "later\n");
// After a restart: the turns' records are kept with the task.
mgr.shutdown();
let mgr = manager(&repo.dir, Arc::new(FakeAgent::default()));
let undone = mgr.rollback(&task.id, 1, true).await.unwrap().unwrap();
assert_eq!(undone.text, "more", "{case}");
assert_eq!(turn_starts(&mgr.entries(&task.id, None).unwrap()).len(), 1, "{case}");
assert_eq!(read("a.txt").as_deref(), Some("base\nturn 1\n"), "{case}");
assert_eq!(read("gone.txt").as_deref(), Some("base\n"), "{case}");
assert_eq!(read("two.txt"), None, "{case}");
// There before the message was sent.
assert_eq!(read("mine.txt").as_deref(), Some("mine\n"), "{case}");
let later = match isolation {
// In the project's own checkout, a file no turn of the task changed is the user's.
Isolation::Local => Some("later\n"),
// In its own worktree, everything changed there since is the task's.
Isolation::Worktree => None,
};
assert_eq!(read("later.txt").as_deref(), later, "{case}");
assert_eq!(mgr.task(&task.id).unwrap().state.lock().turns.len(), 1, "{case}");
// Without `files` they stay; the first message takes the task back to its start.
one_turn(&mgr, &task.id, Some("retry"), || write("a.txt", "again\n")).await;
mgr.rollback(&task.id, 1, false).await.unwrap();
assert_eq!(read("a.txt").as_deref(), Some("again\n"), "{case}");
mgr.rollback(&task.id, 0, true).await.unwrap();
assert_eq!(read("a.txt").as_deref(), Some("base\n"), "{case}");
assert!(mgr.task(&task.id).unwrap().state.lock().turns.is_empty(), "{case}");
let left = std::fs::read_dir(repo.dir.join("store").join(format!("{}.turn", task.id)));
assert!(left.map_or(true, |mut d| d.next().is_none()), "{case}: no copies left");
mgr.delete(&task.id, true).await.unwrap();
}
}
#[tokio::test(flavor = "multi_thread")]
async fn a_message_sent_before_turns_were_recorded_cannot_take_the_files_back() {
let repo = Checkout::new(Eol::Lf);
repo.write("a.txt", "base\n");
repo.commit("init");
let mgr = manager(&repo.dir, Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask { prompt: text("Hello"), provider: "claude".into(), ..Default::default() })
.await
.unwrap();
one_turn(&mgr, &task.id, None, || repo.write("a.txt", "base\nturn 1\n")).await;
one_turn(&mgr, &task.id, Some("more"), || repo.write("a.txt", "base\nturn 1\nturn 2\n")).await;
one_turn(&mgr, &task.id, Some("last"), || repo.write("a.txt", "base\nturn 1\nturn 2\nturn 3\n")).await;
// As a task saved with its last turn's record only.
mgr.task(&task.id).unwrap().state.lock().turns[1] = None;
assert!(mgr.rollback(&task.id, 1, true).await.is_err());
assert_eq!(turn_starts(&mgr.entries(&task.id, None).unwrap()).len(), 3, "nothing changed");
assert_eq!(repo.read("a.txt"), "base\nturn 1\nturn 2\nturn 3\n");
mgr.rollback(&task.id, 2, true).await.unwrap();
assert_eq!(repo.read("a.txt"), "base\nturn 1\nturn 2\n");
}
#[tokio::test(flavor = "multi_thread")]
async fn rolling_back_to_first_message_without_turn_record_checks_before_changing_anything() {
let repo = Checkout::new(Eol::Lf);
repo.write("a.txt", "base\n");
repo.write("b.txt", "base\n");
repo.commit("init");
repo.write("a.txt", "user edit\n");
let mgr = manager(&repo.dir, Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask { prompt: text("Hello"), provider: "claude".into(), ..Default::default() })
.await
.unwrap();
one_turn(&mgr, &task.id, None, || {
repo.write("a.txt", "agent edit\n");
repo.write("b.txt", "agent edit\n");
})
.await;
{
let handle = mgr.task(&task.id).unwrap();
let mut s = handle.state.lock();
s.turns[0] = None;
s.saved = None;
}
assert!(mgr.rollback(&task.id, 0, true).await.is_err());
assert_eq!(turn_starts(&mgr.entries(&task.id, None).unwrap()).len(), 1, "conversation stays intact");
assert!(mgr.task(&task.id).unwrap().state.lock().session_id.is_some(), "session stays intact");
assert_eq!(repo.read("a.txt"), "agent edit\n");
assert_eq!(repo.read("b.txt"), "agent edit\n");
}
#[tokio::test(flavor = "multi_thread")]
async fn local_turn_rollback_keeps_user_edits_to_other_turns_files_and_reverts_committed_files() {
let repo = Checkout::new(Eol::Lf);
repo.write("turn1.txt", "base\n");
repo.write("turn2.txt", "base\n");
repo.commit("init");
let mgr = manager(&repo.dir, Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask {
prompt: text("Hello"),
provider: "claude".into(),
isolation: Isolation::Local,
..Default::default()
})
.await
.unwrap();
one_turn(&mgr, &task.id, None, || repo.write("turn1.txt", "turn 1\n")).await;
one_turn(&mgr, &task.id, Some("more"), || {
repo.write("turn2.txt", "turn 2\n");
repo.write("committed.txt", "from turn 2\n");
repo.git(&["add", "committed.txt"]);
repo.git(&["commit", "-q", "-m", "turn 2 commit"]);
})
.await;
// User edits a file from turn 1 after turn 2 finishes.
repo.write("turn1.txt", "turn 1 + user edit\n");
mgr.rollback(&task.id, 1, true).await.unwrap();
assert_eq!(repo.read("turn1.txt"), "turn 1 + user edit\n");
assert_eq!(repo.read("turn2.txt"), "base\n");
assert!(!repo.dir.join("committed.txt").exists());
}
#[tokio::test(flavor = "multi_thread")]
async fn rolling_back_the_whole_task_leaves_the_last_turn_nothing_to_list() {
let repo = Checkout::new(Eol::Lf);
+44 -103
View File
@@ -8,9 +8,6 @@ use std::collections::HashMap;
/// Tool output kept per call; longer output keeps its tail.
const MAX_OUTPUT: usize = 64 * 1024;
/// Image files a read tool names that are shown when it reports none itself.
const MAX_READ_IMAGES: usize = 4;
#[derive(Default)]
pub(crate) struct Timeline {
pub entries: Vec<AgentEntry>,
@@ -174,17 +171,51 @@ impl Timeline {
if update.get("locations").is_some_and(Value::is_array) {
*locs = locations(update.get("locations"));
}
if let Some(content) = update.get("content").and_then(Value::as_array) {
merge_content(content, output, images, diffs);
let Some(content) = update.get("content").and_then(Value::as_array) else { return };
let mut text = String::new();
let mut new_diffs = Vec::new();
let mut new_images = Vec::new();
for item in content {
match item.get("type").and_then(Value::as_str) {
Some("content") => {
let content = item.get("content");
if let Some(image) = content.filter(|c| c.get("type").and_then(Value::as_str) == Some("image"))
&& let (Some(data), Some(mime)) =
(image.get("data").and_then(Value::as_str), image.get("mimeType").and_then(Value::as_str))
&& !data.is_empty()
&& mime.starts_with("image/")
{
new_images.push(AgentImage { mime_type: mime.into(), data: data.into(), name: None });
}
if let Some(t) = content_text(content) {
if !text.is_empty() {
text.push('\n');
}
text.push_str(&t);
}
}
Some("diff") => {
let old = item.get("oldText").and_then(Value::as_str).unwrap_or_default();
let new = item.get("newText").and_then(Value::as_str).unwrap_or_default();
let (added, removed) = line_stats(old, new);
new_diffs.push(AgentToolDiff { path: IpcPath(str_field(item, "path").into()), added, removed });
}
_ => {}
}
}
// Agents that only name the image a read tool opened (Cursor): show the file itself.
if *status == AgentToolStatus::Completed && kind == "read" && images.is_empty() {
images.extend(
locs.iter()
.filter(|p| p.0.is_absolute())
.take(MAX_READ_IMAGES)
.filter_map(|p| crate::images::from_file(&p.0)),
);
if !text.is_empty() {
// The command a call announced (`$ cmd`) stays above the result that replaces it.
let command = output.as_deref().and_then(|o| o.lines().next()).filter(|l| l.starts_with("$ "));
if let Some(command) = command.filter(|c| !text.starts_with(c)) {
text = format!("{command}\n{text}");
}
*output = Some(tail(text));
}
if !new_diffs.is_empty() {
*diffs = new_diffs;
}
if !new_images.is_empty() {
*images = new_images;
}
}
@@ -351,54 +382,6 @@ fn subagent_status(state: &Value) -> Option<(AgentSubagentStatus, Option<String>
})
}
/// Folds a tool update's content into its output, diffs and images.
fn merge_content(
content: &[Value],
output: &mut Option<String>,
images: &mut Vec<AgentImage>,
diffs: &mut Vec<AgentToolDiff>,
) {
let mut text = String::new();
let mut new_diffs = Vec::new();
let mut new_images = Vec::new();
for item in content {
match item.get("type").and_then(Value::as_str) {
Some("content") => {
let content = item.get("content");
if let Some(image) = content.and_then(crate::images::from_content) {
new_images.push(image);
} else if let Some(t) = content_text(content) {
if !text.is_empty() {
text.push('\n');
}
text.push_str(&t);
}
}
Some("diff") => {
let old = item.get("oldText").and_then(Value::as_str).unwrap_or_default();
let new = item.get("newText").and_then(Value::as_str).unwrap_or_default();
let (added, removed) = line_stats(old, new);
new_diffs.push(AgentToolDiff { path: IpcPath(str_field(item, "path").into()), added, removed });
}
_ => {}
}
}
if !text.is_empty() {
// The command a call announced (`$ cmd`) stays above the result that replaces it.
let command = output.as_deref().and_then(|o| o.lines().next()).filter(|l| l.starts_with("$ "));
if let Some(command) = command.filter(|c| !text.starts_with(c)) {
text = format!("{command}\n{text}");
}
*output = Some(tail(text));
}
if !new_diffs.is_empty() {
*diffs = new_diffs;
}
if !new_images.is_empty() {
*images = new_images;
}
}
/// The text of a list of content blocks, one per line.
pub(crate) fn blocks_text(content: Option<&Value>) -> String {
let blocks = content.and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
@@ -449,7 +432,6 @@ fn tail(mut text: String) -> String {
#[cfg(test)]
mod tests {
use super::*;
use crate::model::AgentImage;
use serde_json::json;
#[test]
@@ -496,47 +478,6 @@ mod tests {
assert_eq!(serde_json::from_str::<AgentEntry>(&saved).unwrap(), t.entries[0]);
}
#[test]
fn tool_images_come_from_linked_files_and_resource_blobs() {
let dir = tempfile::tempdir().unwrap();
let png = dir.path().join("out.png");
std::fs::write(&png, b"\x89PNG\r\n").unwrap();
let mut t = Timeline::default();
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "r", "title": "Read", "kind": "read"}));
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "r", "content": [
{"type": "content", "content": {"type": "text", "text": "Read the image"}},
{"type": "content", "content": {"type": "resource_link", "uri": crate::file_uri(&png), "name": "out.png"}},
{"type": "content", "content": {"type": "resource", "resource": {"uri": "mem:1", "mimeType": "image/gif", "blob": "R0lG"}}}
]}));
let AgentEntry::Tool { images, output, .. } = &t.entries[0] else { panic!() };
let types: Vec<&str> = images.iter().map(|i| i.mime_type.as_str()).collect();
assert_eq!(types, ["image/png", "image/gif"]);
assert_eq!(output.as_deref(), Some("Read the image"));
}
#[test]
fn a_completed_read_shows_the_image_file_it_names() {
let dir = tempfile::tempdir().unwrap();
let png = dir.path().join("icon.png");
std::fs::write(&png, b"\x89PNG\r\n").unwrap();
let text = dir.path().join("a.rs");
std::fs::write(&text, b"fn main() {}").unwrap();
let mut t = Timeline::default();
for (id, path) in [("img", &png), ("src", &text)] {
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": id, "title": "Read", "kind": "read",
"locations": [{"path": path}]}));
}
let images = |t: &Timeline, i: usize| match &t.entries[i] {
AgentEntry::Tool { images, .. } => images.len(),
_ => panic!(),
};
assert_eq!(images(&t, 0), 0, "not before the read completes");
for id in ["img", "src"] {
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": id, "status": "completed"}));
}
assert_eq!((images(&t, 0), images(&t, 1)), (1, 0));
}
#[test]
fn chunks_merge_into_one_message_until_another_entry_comes() {
let mut t = Timeline::default();
+62 -240
View File
@@ -697,24 +697,12 @@ pub(crate) fn snapshot(cwd: &Path) -> IdeResult<BTreeMap<String, Stamp>> {
if let Some(rel) = nested_rel(&base, repo, &roots, &s.path) {
out.insert(rel, stamp(&s.path));
}
if let Some(old) = &s.renamed_from
&& let Some(rel) = nested_rel(&base, repo, &roots, &repo.root().join(old))
{
out.entry(rel).or_insert(None);
}
}
}
return Ok(out);
}
let Some(repo) = Repo::discover(cwd)? else { return Ok(BTreeMap::new()) };
let mut out = BTreeMap::new();
for s in repo.status()? {
out.insert(s.rel_path, stamp(&s.path));
if let Some(old) = s.renamed_from {
out.entry(old).or_insert(None);
}
}
Ok(out)
Ok(repo.status()?.into_iter().map(|s| (s.rel_path, stamp(&s.path))).collect())
}
/// The files whose state changed between two snapshots of a checkout: edited, new, deleted,
@@ -775,36 +763,6 @@ pub(crate) fn save_before(cwd: &Path, before: &BTreeMap<String, Stamp>, dir: &Pa
Ok(saved)
}
fn restore_content(
cwd: &Path,
rev: Option<&str>,
change: &AgentChange,
before: &BTreeMap<String, Stamp>,
saved: Option<&Path>,
) -> IdeResult<Option<Vec<u8>>> {
match before.get(&change.rel_path) {
Some(None) => Ok(None),
Some(Some(_)) => {
let copy =
saved.map(|d| d.join(saved_name(&change.rel_path))).filter(|p| p.is_file()).ok_or_else(|| {
IdeError::invalid(format!(
"{} had changes of yours when the task started that weren't saved; roll it back in Git instead",
change.rel_path
))
})?;
Ok(Some(std::fs::read(copy)?))
}
None => match rev {
Some(rev) => {
let at = change.repo.as_ref().map_or(cwd, |r| r.0.as_path());
let repo = Repo::discover(at)?.ok_or_else(|| IdeError::invalid("not in a git repository"))?;
repo.file_bytes_at(&change.path.0, Some(rev))
}
None => Ok(None),
},
}
}
/// Rolls `change` back: to the copy saved when the task started when the file had changes
/// then (`before`, `saved` holding the copies), otherwise to `rev` (removed when `rev` lacks
/// it, or when there is no `rev`: the repository had no commits).
@@ -815,35 +773,28 @@ pub(crate) fn restore(
before: &BTreeMap<String, Stamp>,
saved: Option<&Path>,
) -> IdeResult<()> {
put(&change.path.0, restore_content(cwd, rev, change, before, saved)?)
}
/// The files the task changed since it started, with what to put back. Fails, changing
/// nothing, when one can't be put back.
pub(crate) fn plan_restore(
at: &TaskBase,
before: &BTreeMap<String, Stamp>,
saved: Option<&Path>,
touched: Option<&BTreeSet<String>>,
) -> IdeResult<Vec<PutBack>> {
let changes = made_by_task(at.changes(before, None)?, touched);
let rev = at.rev()?;
let sources = match rev.as_deref() {
Some(rev) => rename_sources(at.cwd(), rev)?,
None => Default::default(),
};
let mut seen = BTreeSet::new();
let mut out = Vec::new();
for change in &changes {
for change in std::iter::once(change).chain(sources.get(&change.rel_path)) {
if !seen.insert(change.rel_path.clone()) {
continue;
}
let content = restore_content(at.cwd(), rev.as_deref(), change, before, saved)?;
out.push(PutBack { rel: change.rel_path.clone(), path: change.path.0.clone(), content });
let content = match before.get(&change.rel_path) {
Some(None) => None,
Some(Some(_)) => {
let copy =
saved.map(|d| d.join(saved_name(&change.rel_path))).filter(|p| p.is_file()).ok_or_else(|| {
IdeError::invalid(format!(
"{} had changes of yours when the task started that weren't saved; roll it back in Git instead",
change.rel_path
))
})?;
Some(std::fs::read(copy)?)
}
}
Ok(out)
None => match rev {
Some(rev) => {
let at = change.repo.as_ref().map_or(cwd, |r| r.0.as_path());
let repo = Repo::discover(at)?.ok_or_else(|| IdeError::invalid("not in a git repository"))?;
repo.file_bytes_at(&change.path.0, Some(rev))?
}
None => None,
},
};
put(&change.path.0, content)
}
/// Writes `content` to `path`, or removes the file when there is none.
@@ -868,7 +819,7 @@ pub(crate) fn saved_copy(dir: &Path, rel: &str) -> Option<Vec<u8>> {
std::fs::read(dir.join(saved_name(rel))).ok()
}
/// The checkout as one of the task's turns started: what that turn's changes are compared with
/// The checkout as the task's last turn started: what that turn's changes are compared with
/// and rolled back to. Recorded like the task's own start: `HEAD`, the files already changed,
/// and copies of those.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
@@ -889,45 +840,13 @@ pub(crate) struct TurnStart {
/// The files that changed while the turn ran, recorded as it ended (`None` while it runs).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub changed: Option<BTreeSet<String>>,
/// The copies are named by file and stamp, so the turns share them; the turn recorded
/// before that named them by file alone.
#[serde(default, skip_serializing_if = "is_false")]
pub stamped: bool,
}
fn is_false(b: &bool) -> bool {
!*b
}
/// The name of the copy of `rel` as stamped `stamp`: the same while the file is unchanged.
fn turn_copy_name(rel: &str, stamp: &Stamp) -> String {
let mut hasher = blake3::Hasher::new();
hasher.update(rel.as_bytes());
hasher.update(&[0]);
if let Some((len, modified)) = stamp {
hasher.update(&[1]);
hasher.update(&len.to_le_bytes());
hasher.update(&modified.to_le_bytes());
}
let hex = hasher.finalize().to_hex();
format!("t{}", &hex[..16])
}
impl TurnStart {
/// The name of the copy saved of `rel` as the turn began.
fn copy_name(&self, rel: &str) -> Option<String> {
if !self.stamped {
return Some(saved_name(rel));
}
Some(turn_copy_name(rel, self.before.get(rel)?))
}
}
/// Records the checkout at `cwd` as a turn starts, with copies of its changed files in `dir`.
/// A copy an earlier turn saved of a file unchanged since is used rather than made again, so
/// The copies `previous` saved of files unchanged since are kept rather than made again, so
/// starting a turn copies little more than what the turn before it changed.
pub(crate) fn start_turn(cwd: &Path, dir: &Path) -> IdeResult<TurnStart> {
let Some(at) = TurnRepos::of(cwd)? else { return Ok(TurnStart { stamped: true, ..Default::default() }) };
pub(crate) fn start_turn(cwd: &Path, dir: &Path, previous: Option<&TurnStart>) -> IdeResult<TurnStart> {
let Some(at) = TurnRepos::of(cwd)? else { return Ok(TurnStart::default()) };
let mut heads = BTreeMap::new();
let head = if at.nested {
for repo in &at.repos {
@@ -940,95 +859,37 @@ pub(crate) fn start_turn(cwd: &Path, dir: &Path) -> IdeResult<TurnStart> {
// As the turn's end is read, so the two compare.
let before = snapshot(cwd)?;
let mut saved = BTreeSet::new();
match previous {
Some(previous) => {
for rel in &previous.saved {
let unchanged =
before.get(rel).is_some_and(|now| now.is_some() && previous.before.get(rel) == Some(now));
if unchanged {
saved.insert(rel.clone());
} else {
let _ = std::fs::remove_file(dir.join(saved_name(rel)));
}
}
}
None => {
let _ = std::fs::remove_dir_all(dir);
}
}
for (rel, stamp) in &before {
let path = at.base.join(rel);
if stamp.is_none() || !std::fs::metadata(&path).is_ok_and(|m| m.is_file() && m.len() <= SAVED_MAX) {
continue;
}
let copy = dir.join(turn_copy_name(rel, stamp));
if copy.is_file() {
saved.insert(rel.clone());
if stamp.is_none()
|| saved.contains(rel)
|| !std::fs::metadata(&path).is_ok_and(|m| m.is_file() && m.len() <= SAVED_MAX)
{
continue;
}
std::fs::create_dir_all(dir)?;
// One that can't be copied is listed but can't be rolled back, as a large one.
if std::fs::copy(&path, &copy).is_ok() {
if std::fs::copy(&path, dir.join(saved_name(rel))).is_ok() {
saved.insert(rel.clone());
}
}
Ok(TurnStart { head, heads, before, saved, changed: None, stamped: true })
}
/// Removes the copies in `dir` that none of `turns` uses any more.
pub(crate) fn prune_turn_copies<'a>(dir: &Path, turns: impl IntoIterator<Item = &'a TurnStart>) {
let used: BTreeSet<String> =
turns.into_iter().flat_map(|t| t.saved.iter().filter_map(move |rel| t.copy_name(rel))).collect();
let Ok(read) = std::fs::read_dir(dir) else { return };
for entry in read.flatten() {
if !used.contains(&*entry.file_name().to_string_lossy()) {
let _ = std::fs::remove_file(entry.path());
}
}
}
/// A file to put back as it was.
pub(crate) struct PutBack {
/// Relative to the checkout, as the task names it.
pub rel: String,
pub path: PathBuf,
/// `None`: there was no file.
pub content: Option<Vec<u8>>,
}
/// The files among `rels` that differ from how they were as the turn `start` began, with what
/// to put back. Fails, changing nothing, when one can't be put back.
pub(crate) fn rewind(cwd: &Path, start: &TurnStart, dir: &Path, rels: &BTreeSet<String>) -> IdeResult<Vec<PutBack>> {
let Some(at) = TurnRepos::of(cwd)? else { return Ok(Vec::new()) };
let mut lower_counts: BTreeMap<String, usize> = BTreeMap::new();
for rel in rels {
*lower_counts.entry(rel.to_lowercase()).or_default() += 1;
}
let mut out = Vec::new();
for rel in rels {
let path = at.base.join(rel);
// A folder (a submodule, say) has nothing to put back.
if path.is_dir() {
continue;
}
let then = at_turn_start(&at, rel, start, dir)?;
// On a case-insensitive disk, `existing(&path)` can read a case-only rename's new name;
// keep the write so `put_back` deletes the new name and recreates the old one.
let case_collision = lower_counts.get(&rel.to_lowercase()).is_some_and(|&n| n > 1);
if !case_collision && existing(&path).is_some_and(|now| now == then) {
continue;
}
out.push(PutBack { rel: rel.clone(), path, content: then });
}
Ok(out)
}
/// Writes what `rewind` or `plan_restore` planned, returning the files back to their saved
/// pre-task copy so `before` can be restamped.
pub(crate) fn put_back(
mut planned: Vec<PutBack>,
before: &BTreeMap<String, Stamp>,
saved: Option<&Path>,
) -> IdeResult<Vec<(String, Stamp)>> {
// Removals first so a case-only rename on a case-insensitive disk ends at its old name.
planned.sort_by_key(|f| f.content.is_some());
let mut restamped = Vec::new();
for file in planned {
let should_restamp = matches!(before.get(&file.rel), Some(Some(_)))
&& file
.content
.as_deref()
.is_some_and(|bytes| saved.and_then(|d| saved_copy(d, &file.rel)).as_deref() == Some(bytes));
put(&file.path, file.content)?;
if should_restamp {
restamped.push((file.rel, stamp(&file.path)));
}
}
Ok(restamped)
Ok(TurnStart { head, heads, before, saved, changed: None })
}
/// The files that changed in `cwd` since the turn `start` began: in the working tree (as
@@ -1058,12 +919,7 @@ pub(crate) fn changed_in_turn(cwd: &Path, start: &TurnStart) -> IdeResult<(Vec<S
fn at_turn_start(at: &TurnRepos, rel: &str, start: &TurnStart, dir: &Path) -> IdeResult<Option<Vec<u8>>> {
match start.before.get(rel) {
Some(None) => Ok(None),
Some(Some(_)) => match start
.saved
.contains(rel)
.then(|| start.copy_name(rel).and_then(|name| std::fs::read(dir.join(name)).ok()))
.flatten()
{
Some(Some(_)) => match start.saved.contains(rel).then(|| saved_copy(dir, rel)).flatten() {
Some(bytes) => Ok(Some(bytes)),
None => Err(IdeError::invalid(format!(
"{rel} had changes when the turn started that weren't saved; roll it back in Git instead"
@@ -1456,64 +1312,30 @@ mod tests {
git(&repo, &["commit", "-q", "-m", "init"]);
let dir = tmp.path().join("turn");
let set = |names: &[&str]| names.iter().map(|n| (*n).to_owned()).collect::<BTreeSet<_>>();
let copy = |turn: &TurnStart, rel: &str| std::fs::read(dir.join(turn.copy_name(rel).unwrap())).ok();
let at = |turn: &TurnStart, rel: &str| {
at_turn_start(&TurnRepos::of(&repo).unwrap().unwrap(), rel, turn, &dir).unwrap()
};
std::fs::write(repo.join("a.txt"), "turn 1\n").unwrap();
std::fs::write(repo.join("b.txt"), "b\n").unwrap();
let first = start_turn(&repo, &dir).unwrap();
let first = start_turn(&repo, &dir, None).unwrap();
assert_eq!(first.saved, set(&["a.txt", "b.txt"]));
// A copy made again would replace this mark.
std::fs::write(dir.join(first.copy_name("b.txt").unwrap()), "kept\n").unwrap();
std::fs::write(dir.join(saved_name("b.txt")), "kept\n").unwrap();
std::thread::sleep(std::time::Duration::from_millis(10));
std::fs::write(repo.join("a.txt"), "turn two\n").unwrap();
let second = start_turn(&repo, &dir).unwrap();
let second = start_turn(&repo, &dir, Some(&first)).unwrap();
assert_eq!(second.saved, set(&["a.txt", "b.txt"]));
assert_eq!(copy(&second, "a.txt").as_deref(), Some(&b"turn two\n"[..]));
assert_eq!(copy(&second, "b.txt").as_deref(), Some(&b"kept\n"[..]));
// The first turn keeps its own copy of the file changed since.
assert_eq!(at(&first, "a.txt").as_deref(), Some(&b"turn 1\n"[..]));
assert_eq!(saved_copy(&dir, "a.txt").as_deref(), Some(&b"turn two\n"[..]));
assert_eq!(saved_copy(&dir, "b.txt").as_deref(), Some(&b"kept\n"[..]));
// Back as committed: nothing to keep a copy of, and the committed text is the start.
// Back as committed: nothing to keep a copy of.
git(&repo, &["checkout", "--", "a.txt"]);
let third = start_turn(&repo, &dir).unwrap();
let third = start_turn(&repo, &dir, Some(&second)).unwrap();
assert_eq!(third.saved, set(&["b.txt"]));
assert_eq!(at(&third, "a.txt").as_deref(), Some(&b"base\n"[..]));
// Dropping the earlier turns drops the copies only they used.
prune_turn_copies(&dir, [&third]);
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1);
assert_eq!(copy(&third, "b.txt").as_deref(), Some(&b"kept\n"[..]));
}
#[test]
fn put_back_removes_new_name_before_writing_old_name_for_case_only_rename() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("repo");
std::fs::create_dir(&repo).unwrap();
git(&repo, &["init", "-q", "-b", "main"]);
std::fs::write(repo.join("A.txt"), "upper\n").unwrap();
git(&repo, &["add", "."]);
git(&repo, &["commit", "-q", "-m", "init"]);
let dir = tmp.path().join("turn");
let start = start_turn(&repo, &dir).unwrap();
git(&repo, &["mv", "A.txt", "a.txt"]);
let changed = changed_in_turn(&repo, &start).unwrap().1;
let planned = rewind(&repo, &start, &dir, &changed).unwrap();
put_back(planned, &BTreeMap::new(), None).unwrap();
assert_eq!(std::fs::read_to_string(repo.join("A.txt")).unwrap(), "upper\n");
let entries: Vec<String> = std::fs::read_dir(&repo)
.unwrap()
.filter_map(|e| e.ok())
.map(|e| e.file_name().to_string_lossy().into_owned())
.filter(|n| n != ".git")
.collect();
assert_eq!(entries, ["A.txt"]);
assert_eq!(saved_copy(&dir, "a.txt"), None);
// Without a record of the last turn (a task from before), every copy is made afresh.
let fresh = start_turn(&repo, &dir, None).unwrap();
assert_eq!(fresh.saved, set(&["b.txt"]));
assert_eq!(saved_copy(&dir, "b.txt").as_deref(), Some(&b"b\n"[..]));
}
#[cfg(unix)]
@@ -1528,7 +1350,7 @@ mod tests {
git(&repo, &["commit", "-q", "-m", "init"]);
std::fs::write(repo.join("a.txt"), "turn 1\n").unwrap();
let dir = tmp.path().join("turn");
let start = start_turn(&repo, &dir).unwrap();
let start = start_turn(&repo, &dir, None).unwrap();
std::fs::write(repo.join("a.txt"), "turn 2\n").unwrap();
std::fs::write(repo.join("new.txt"), "new\n").unwrap();
let link = tmp.path().join("link");
-3
View File
@@ -10,6 +10,3 @@ ide-core.workspace = true
serde.workspace = true
specta.workspace = true
which = "8"
[dev-dependencies]
tempfile.workspace = true
+2 -74
View File
@@ -12,12 +12,11 @@ mod process;
pub use model::*;
use ide_core::process::{own_group, prepare};
use ide_core::{CancellationToken, IdeError, IdeResult};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::process::Command;
use std::sync::OnceLock;
use std::time::{Duration, Instant};
use std::time::Duration;
/// `adb devices` is quick unless it starts the daemon, which can take a moment.
const DEVICES: Duration = Duration::from_secs(20);
@@ -29,8 +28,6 @@ const TAIL_LINES: u32 = 200;
/// while `IDLE` makes sure a quiet stream still shows its last line promptly.
const BATCH_IDLE: Duration = Duration::from_millis(60);
const BATCH_MAX: usize = 300;
/// How long a started emulator gets to fail: a locked or broken AVD exits within it.
const EMULATOR_STARTUP: Duration = Duration::from_secs(3);
fn exe(name: &str) -> String {
if cfg!(windows) { format!("{name}.exe") } else { name.to_owned() }
@@ -94,51 +91,6 @@ fn executable() -> IdeResult<PathBuf> {
})
}
/// The SDK's `emulator` executable, which starts AVDs.
pub fn emulator_executable() -> Option<PathBuf> {
let name = exe("emulator");
sdk_roots().into_iter().map(|root| root.join("emulator").join(&name)).find(|p| p.is_file())
}
/// Starts AVD `avd` in its own process group, so it
/// outlives whoever asked: a restarted `flutter daemon`, a closed project, the IDE. Fails when
/// the emulator exits within its first seconds, with what it printed.
pub fn launch_emulator(avd: &str) -> IdeResult<()> {
let emulator = emulator_executable().ok_or_else(|| {
IdeError::unavailable(
"the Android emulator was not found: install it with the Android SDK Manager, or set ANDROID_HOME",
)
})?;
start_emulator(&emulator, avd)
}
fn start_emulator(emulator: &Path, avd: &str) -> IdeResult<()> {
let name: String = avd.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }).collect();
let log_path = std::env::temp_dir().join(format!("openidea-emulator-{name}.log"));
let log = std::fs::File::create(&log_path)?;
let mut cmd = Command::new(emulator);
cmd.arg("-avd").arg(avd);
cmd.stdin(Stdio::null()).stdout(log.try_clone()?).stderr(log);
let mut child = prepare(own_group(&mut cmd)).spawn()?;
let deadline = Instant::now() + EMULATOR_STARTUP;
while Instant::now() < deadline {
if let Some(status) = child.try_wait()? {
let output = std::fs::read_to_string(&log_path).unwrap_or_default();
let tail: Vec<&str> = output.lines().filter(|l| !l.trim().is_empty()).collect();
let tail = tail[tail.len().saturating_sub(8)..].join("\n");
return Err(IdeError::unavailable(if tail.is_empty() {
format!("the emulator exited ({status})")
} else {
tail
}));
}
std::thread::sleep(Duration::from_millis(100));
}
// Reaps it whenever it ends.
std::thread::spawn(move || child.wait());
Ok(())
}
/// Connected devices, online ones first; starting the adb daemon when needed.
pub fn devices() -> IdeResult<Vec<AndroidDevice>> {
let adb = executable()?;
@@ -254,30 +206,6 @@ mod tests {
}
}
#[cfg(unix)]
#[test]
fn an_emulator_that_fails_at_once_says_why_and_one_that_runs_is_left_running() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let script = |name: &str, body: &str| {
let path = dir.path().join(name);
std::fs::write(&path, format!("#!/bin/sh\n{body}")).unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
path
};
let broken = script("broken", "echo \"PANIC: Missing emulator engine for $2\" >&2\nexit 1\n");
let e = start_emulator(&broken, "Pixel_9").unwrap_err();
assert_eq!(e.message, "PANIC: Missing emulator engine for Pixel_9");
let args = dir.path().join("args");
let running =
script("running", &format!("echo $$ > '{0}.pid'\necho \"$@\" > '{0}'\nexec sleep 30\n", args.display()));
start_emulator(&running, "Pixel_9").unwrap();
assert_eq!(std::fs::read_to_string(&args).unwrap().trim(), "-avd Pixel_9");
let pid = std::fs::read_to_string(dir.path().join("args.pid")).unwrap();
assert!(Command::new("kill").arg(pid.trim()).status().unwrap().success(), "still running");
}
#[test]
fn executable_is_absolute_when_found() {
if let Some(adb) = adb_executable() {
+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()),
]);
+10 -30
View File
@@ -965,7 +965,6 @@ pub struct LaunchBuild {
/// Compiles the module at `module` with its build system before a JVM launch and
/// returns the class directories it wrote, to put ahead of the jdtls classpath.
/// The build's console, messages and progress stream to `on_event` as it runs.
pub fn build_for_launch(
root: &Path,
model: &BuildModel,
@@ -973,9 +972,8 @@ pub fn build_for_launch(
test: bool,
kind: BuildKind,
cancel: &CancellationToken,
on_event: &(dyn Fn(BuildEvent) + Sync),
) -> IdeResult<LaunchBuild> {
let mut built = build_for_launches(root, model, &[module.to_path_buf()], test, kind, cancel, on_event)?;
let mut built = build_for_launches(root, model, &[module.to_path_buf()], test, kind, cancel)?;
Ok(built.pop().unwrap())
}
@@ -988,10 +986,9 @@ pub fn build_for_launches(
test: bool,
kind: BuildKind,
cancel: &CancellationToken,
on_event: &(dyn Fn(BuildEvent) + Sync),
) -> IdeResult<Vec<LaunchBuild>> {
let plan = merged_launch_plan(root, model, modules, test, kind, cancel)?;
let result = run(root, &plan, cancel, on_event)?;
let result = run(root, &plan, cancel, &|_| {})?;
let failure = if !result.success {
let errors: Vec<String> = result
.messages
@@ -1825,16 +1822,8 @@ mod tests {
std::fs::set_permissions(&wrapper, std::fs::Permissions::from_mode(0o755)).unwrap();
let mut model = reactor_model();
model.maven.as_mut().unwrap().projects[0].command = wrapper.to_string_lossy().into_owned();
let dirs = build_for_launch(
root,
&model,
&root.join("app"),
true,
BuildKind::Build,
&CancellationToken::new(),
&|_| {},
)
.unwrap();
let dirs = build_for_launch(root, &model, &root.join("app"), true, BuildKind::Build, &CancellationToken::new())
.unwrap();
assert_eq!(
dirs.class_dirs,
["app/target/test-classes", "app/target/classes", "middle/target/classes", "lib/target/classes"]
@@ -1845,25 +1834,16 @@ mod tests {
"mvnw",
"#!/bin/sh\necho '[ERROR] Kotlin compilation failed: unresolved reference broken' >&2\nexit 1\n",
);
let error = build_for_launch(
root,
&model,
&root.join("app"),
false,
BuildKind::Build,
&CancellationToken::new(),
&|_| {},
)
.unwrap()
.failure
.unwrap();
let error =
build_for_launch(root, &model, &root.join("app"), false, BuildKind::Build, &CancellationToken::new())
.unwrap()
.failure
.unwrap();
assert!(error.contains("Kotlin compilation failed"), "{error}");
let cancel = CancellationToken::new();
cancel.cancel();
assert_eq!(
build_for_launch(root, &model, &root.join("app"), false, BuildKind::Build, &cancel, &|_| {})
.unwrap_err()
.kind,
build_for_launch(root, &model, &root.join("app"), false, BuildKind::Build, &cancel).unwrap_err().kind,
ide_core::error::ErrorKind::Cancelled
);
}
+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| {
-1
View File
@@ -16,7 +16,6 @@ mod process;
#[cfg(test)]
mod process_numbers;
pub mod sbt;
pub mod surefire;
mod sync;
pub mod web;
mod xml;
-71
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)
@@ -2610,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();
-216
View File
@@ -1,216 +0,0 @@
//! A Maven module's Surefire configuration, for test runs OpenIDEA starts itself instead of
//! Surefire (IDEA's `MavenJUnitPatcher`): what the forked test JVM would get from the POM.
//!
//! Read from the effective POM the last sync cached (Maven merged parents, profiles and
//! `pluginManagement` there), else from the module's own `pom.xml` and its `<properties>`.
use crate::maven::{MavenModel, interpolate};
use crate::xml::{self, Element};
use std::collections::{BTreeMap, HashMap};
use std::path::Path;
const SUREFIRE: &str = "maven-surefire-plugin";
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct SurefireConfig {
/// `<argLine>`, split into JVM options.
pub arg_line: Vec<String>,
/// `<systemPropertyVariables>` and the older `<systemProperties>`.
pub system_properties: BTreeMap<String, String>,
/// `<environmentVariables>`.
pub environment: BTreeMap<String, String>,
pub working_directory: Option<String>,
/// `<additionalClasspathElements>`.
pub additional_classpath: Vec<String>,
/// `<classpathDependencyExcludes>`: `groupId:artifactId`.
pub classpath_excludes: Vec<String>,
}
/// The Surefire configuration of the Maven module at `module` (absolute), if it is one.
pub fn surefire_config(root: &Path, cache_dir: &Path, model: &MavenModel, module: &Path) -> Option<SurefireConfig> {
let same = |a: &Path, b: &Path| dunce::canonicalize(a).ok() == dunce::canonicalize(b).ok();
let project = model.projects.iter().find(|p| same(&root.join(&p.dir), module))?;
let pom = root.join(&project.pom);
let modified = |p: &Path| std::fs::metadata(p).and_then(|m| m.modified()).ok();
// A cache written before the POM last changed would apply an old configuration.
let effective = std::fs::read_dir(cache_dir).ok()?.flatten().map(|e| e.path()).find_map(|path| {
let name = path.file_name()?.to_str()?;
if !(name.starts_with("effective-pom-") && name.ends_with(".xml")) || modified(&path) < modified(&pom) {
return None;
}
let root = xml::parse(&xml::read_text(&path)?)?;
let projects: Vec<Element> = if root.name == "projects" {
root.children.into_iter().filter(|p| p.name == "project").collect()
} else {
vec![root]
};
projects.into_iter().find(|p| {
let group = p.text_of("groupId").or_else(|| p.at("parent/groupId").map(|g| g.text.trim().to_owned()));
group.as_deref() == Some(project.group_id.as_str())
&& p.text_of("artifactId").as_deref() == Some(&project.artifact_id)
})
});
let (element, own) = match effective {
Some(e) => (e, false),
// ponytail: without a sync, inherited configuration and parent properties are missing; Reload adds them.
None => (xml::parse(&xml::read_text(&pom)?)?, true),
};
let mut props: HashMap<String, String> = element
.child("properties")
.map(|p| p.children.iter().map(|c| (c.name.clone(), c.text.trim().to_owned())).collect())
.unwrap_or_default();
let dir = module.to_string_lossy().into_owned();
for (key, value) in [
("basedir", dir.clone()),
("project.basedir", dir.clone()),
("project.build.directory", format!("{dir}/target")),
("project.groupId", project.group_id.clone()),
("project.artifactId", project.artifact_id.clone()),
("project.version", project.version.clone()),
] {
props.entry(key.into()).or_insert(value);
}
Some(read(&element, &props, own))
}
/// `<build><plugins>` Surefire's configuration, then its `default-test` execution's.
fn read(project: &Element, props: &HashMap<String, String>, own: bool) -> SurefireConfig {
let is_surefire = |p: &&Element| p.text_of("artifactId").as_deref() == Some(SUREFIRE);
let mut plugins: Vec<&Element> = project.list("build/plugins", "plugin").into_iter().filter(is_surefire).collect();
if own && plugins.is_empty() {
plugins = project.list("build/pluginManagement/plugins", "plugin").into_iter().filter(is_surefire).collect();
}
let mut configurations: Vec<&Element> = Vec::new();
for plugin in plugins {
configurations.extend(plugin.child("configuration"));
let default_test = plugin
.list("executions", "execution")
.into_iter()
.find(|e| e.text_of("id").as_deref() == Some("default-test"));
configurations.extend(default_test.and_then(|e| e.child("configuration")));
}
let value = |text: &str| resolve(text.trim(), props);
let mut config = SurefireConfig::default();
for c in configurations {
if let Some(arg_line) = c.child("argLine") {
config.arg_line = split_arg_line(&value(&arg_line.text));
}
for p in c.child("systemPropertyVariables").map_or(&[][..], |p| &p.children) {
config.system_properties.insert(p.name.clone(), value(&p.text));
}
// `<systemProperties>`: `<property><name/><value/></property>` (deprecated, still honoured).
for p in c.list("systemProperties", "property") {
if let Some(name) = p.text_of("name") {
config.system_properties.insert(name, value(&p.text_of("value").unwrap_or_default()));
}
}
for e in c.child("environmentVariables").map_or(&[][..], |e| &e.children) {
config.environment.insert(e.name.clone(), value(&e.text));
}
if let Some(dir) = c.text_of("workingDirectory").map(|d| value(&d)).filter(|d| !d.is_empty()) {
config.working_directory = Some(dir);
}
let texts = |list: &str, item: &str| -> Vec<String> {
c.list(list, item).into_iter().map(|e| value(&e.text)).filter(|t| !t.is_empty()).collect()
};
config.additional_classpath.extend(texts("additionalClasspathElements", "additionalClasspathElement"));
config.classpath_excludes.extend(texts("classpathDependencyExcludes", "classpathDependencyExclude"));
}
config
}
/// `${…}` from the POM's properties, then Surefire's late replacement `@{…}` (a property a plugin
/// sets during the build, such as JaCoCo's `argLine`, is unknown here and left out, as in IDEA).
fn resolve(text: &str, props: &HashMap<String, String>) -> String {
let mut out = interpolate(text, props);
for open in ["@{", "${"] {
while let Some(start) = out.find(open) {
let Some(len) = out[start..].find('}') else { break };
let key = &out[start + 2..start + len];
let replacement = if open == "@{" { props.get(key).cloned().unwrap_or_default() } else { String::new() };
out.replace_range(start..=start + len, &replacement);
}
}
out.trim().to_owned()
}
/// Splits `argLine` as Surefire does (plexus `CommandLineUtils`): whitespace, `"…"` and `'…'`, no escapes.
fn split_arg_line(line: &str) -> Vec<String> {
let mut out = Vec::new();
let mut current: Option<String> = None;
let mut quote: Option<char> = None;
for c in line.chars() {
match quote {
Some(q) if c == q => quote = None,
Some(_) => current.get_or_insert_default().push(c),
None if c == '"' || c == '\'' => {
quote = Some(c);
current.get_or_insert_default();
}
None if c.is_whitespace() => out.extend(current.take()),
None => current.get_or_insert_default().push(c),
}
}
out.extend(current);
out
}
#[cfg(test)]
mod tests {
use super::*;
const POM: &str = r#"<project>
<groupId>com.example</groupId><artifactId>orders</artifactId><version>1</version>
<properties><openideaFail>true</openideaFail><mockito>/m2/mockito.jar</mockito></properties>
<build><plugins><plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>@{argLine} @{jacoco} -javaagent:${mockito} --add-opens "java.base/java.lang=ALL-UNNAMED" -Dx=${undefined}</argLine>
<systemPropertyVariables><openidea.fail>${openideaFail}</openidea.fail><dir>${project.build.directory}</dir></systemPropertyVariables>
<systemProperties><property><name>old</name><value>style</value></property></systemProperties>
<environmentVariables><TZ>UTC</TZ></environmentVariables>
<additionalClasspathElements><additionalClasspathElement>${basedir}/extra</additionalClasspathElement></additionalClasspathElements>
<classpathDependencyExcludes><classpathDependencyExclude>org.slf4j:slf4j-simple</classpathDependencyExclude></classpathDependencyExcludes>
</configuration>
<executions><execution><id>default-test</id><configuration><workingDirectory>${basedir}/work</workingDirectory></configuration></execution></executions>
</plugin></plugins></build>
</project>"#;
fn model(dir: &Path) -> MavenModel {
crate::maven::load(dir)
}
#[test]
fn reads_the_module_pom_and_the_effective_pom_the_sync_cached() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
std::fs::write(root.join("pom.xml"), POM).unwrap();
let cache = root.join("cache");
std::fs::create_dir_all(&cache).unwrap();
let config = surefire_config(root, &cache, &model(root), root).unwrap();
let d = root.to_string_lossy();
assert_eq!(
config.arg_line,
["-javaagent:/m2/mockito.jar", "--add-opens", "java.base/java.lang=ALL-UNNAMED", "-Dx="]
);
assert_eq!(config.system_properties["openidea.fail"], "true");
assert_eq!(config.system_properties["dir"], format!("{d}/target"));
assert_eq!(config.system_properties["old"], "style");
assert_eq!(config.environment["TZ"], "UTC");
assert_eq!(config.working_directory, Some(format!("{d}/work")));
assert_eq!(config.additional_classpath, [format!("{d}/extra")]);
assert_eq!(config.classpath_excludes, ["org.slf4j:slf4j-simple"]);
// A sync's effective POM wins: it has what the module inherits.
let effective = POM.replace("<argLine>", "<argLine>-Xmx1g ").replace("<TZ>UTC</TZ>", "<TZ>Asia/Tokyo</TZ>");
std::fs::write(cache.join("effective-pom-0.xml"), format!("<projects>{effective}</projects>")).unwrap();
let config = surefire_config(root, &cache, &model(root), root).unwrap();
assert_eq!(config.arg_line[0], "-Xmx1g");
assert_eq!(config.environment["TZ"], "Asia/Tokyo");
}
#[test]
fn splits_arg_line_like_surefire() {
assert_eq!(split_arg_line(r#" -a "b c" 'd "e"' C:\x\y "" "#), ["-a", "b c", r#"d "e""#, r"C:\x\y", ""]);
}
}
+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
-85
View File
@@ -1,85 +0,0 @@
use std::io::{Cursor, Error, ErrorKind, Result};
/// A top-down BITMAPV5HEADER and BGRA pixels. The alpha mask lets native paste targets
/// retain transparency; the PNG flavor is also written for browsers and image editors.
pub(crate) fn png_to_dib(png: &[u8]) -> Result<Vec<u8>> {
let invalid = |error| Error::new(ErrorKind::InvalidData, error);
let mut decoder = png::Decoder::new(Cursor::new(png));
decoder.set_transformations(png::Transformations::normalize_to_color8());
let mut reader = decoder.read_info().map_err(invalid)?;
let rgba_size = (reader.info().width as usize)
.checked_mul(reader.info().height as usize)
.and_then(|pixels| pixels.checked_mul(4))
.filter(|size| *size <= 64 * 1024 * 1024)
.ok_or_else(|| Error::new(ErrorKind::InvalidData, "Clipboard image is too large"))?;
let size = reader
.output_buffer_size()
.filter(|size| *size <= 64 * 1024 * 1024)
.ok_or_else(|| Error::new(ErrorKind::InvalidData, "Clipboard image is too large"))?;
let mut pixels = vec![0; size];
let info = reader.next_frame(&mut pixels).map_err(invalid)?;
let mut dib = vec![0; 124];
dib[0..4].copy_from_slice(&124u32.to_le_bytes());
dib[4..8].copy_from_slice(&info.width.to_le_bytes());
dib[8..12].copy_from_slice(&(-(info.height as i32)).to_le_bytes());
dib[12..14].copy_from_slice(&1u16.to_le_bytes());
dib[14..16].copy_from_slice(&32u16.to_le_bytes());
dib[16..20].copy_from_slice(&3u32.to_le_bytes()); // BI_BITFIELDS
dib[20..24].copy_from_slice(&(rgba_size as u32).to_le_bytes());
for (at, value) in [(40, 0x00ff0000u32), (44, 0x0000ff00), (48, 0x000000ff), (52, 0xff000000), (56, 0x73524742)] {
dib[at..at + 4].copy_from_slice(&value.to_le_bytes());
}
dib[108..112].copy_from_slice(&4u32.to_le_bytes()); // LCS_GM_IMAGES
for pixel in pixels[..info.buffer_size()].chunks_exact(info.color_type.samples()) {
let rgba = match info.color_type {
png::ColorType::Rgba => [pixel[0], pixel[1], pixel[2], pixel[3]],
png::ColorType::Rgb => [pixel[0], pixel[1], pixel[2], 255],
png::ColorType::Grayscale => [pixel[0], pixel[0], pixel[0], 255],
png::ColorType::GrayscaleAlpha => [pixel[0], pixel[0], pixel[0], pixel[1]],
png::ColorType::Indexed => unreachable!("palette expansion requested"),
};
dib.extend_from_slice(&[rgba[2], rgba[1], rgba[0], rgba[3]]);
}
Ok(dib)
}
#[cfg(test)]
mod tests {
use super::*;
fn encode(color: png::ColorType, pixels: &[u8]) -> Vec<u8> {
let mut png = Vec::new();
{
let mut encoder = png::Encoder::new(&mut png, 1, 2);
encoder.set_color(color);
encoder.set_depth(png::BitDepth::Eight);
encoder.write_header().unwrap().write_image_data(pixels).unwrap();
}
png
}
#[test]
fn keeps_rgba_colors_alpha_and_top_down_row_order() {
let png = encode(png::ColorType::Rgba, &[255, 0, 0, 128, 0, 255, 0, 255]);
let dib = png_to_dib(&png).unwrap();
assert_eq!(i32::from_le_bytes(dib[8..12].try_into().unwrap()), -2);
assert_eq!(&dib[124..], &[0, 0, 255, 128, 0, 255, 0, 255]);
let round_trip = crate::dib_to_png(&dib).unwrap();
let mut reader = png::Decoder::new(Cursor::new(round_trip)).read_info().unwrap();
let mut pixels = vec![0; reader.output_buffer_size().unwrap()];
reader.next_frame(&mut pixels).unwrap();
assert_eq!(pixels, [255, 0, 0, 128, 0, 255, 0, 255]);
}
#[test]
fn supports_rgb_and_grayscale_without_assuming_an_alpha_channel() {
for (color, pixels, expected) in [
(png::ColorType::Rgb, vec![255, 0, 0, 0, 255, 0], vec![0, 0, 255, 255, 0, 255, 0, 255]),
(png::ColorType::Grayscale, vec![20, 200], vec![20, 20, 20, 255, 200, 200, 200, 255]),
(png::ColorType::GrayscaleAlpha, vec![20, 10, 200, 250], vec![20, 20, 20, 10, 200, 200, 200, 250]),
] {
assert_eq!(&png_to_dib(&encode(color, &pixels)).unwrap()[124..], expected);
}
assert!(png_to_dib(b"not a PNG").is_err());
}
}
+5 -259
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
@@ -29,29 +25,6 @@
use std::path::PathBuf;
#[cfg(any(windows, test))]
mod image;
/// Writes a PNG as a native image, independently of WebView clipboard permissions.
/// Call on the main thread on macOS and Linux; `owner` is a window handle on Windows.
pub fn set_png(png: &[u8], owner: usize) -> std::io::Result<()> {
if png.get(..8) != Some(b"\x89PNG\r\n\x1a\n") || png.get(12..16) != Some(b"IHDR") || png.len() < 24 {
return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "Invalid clipboard image"));
}
let width = u32::from_be_bytes(png[16..20].try_into().unwrap()) as usize;
let height = u32::from_be_bytes(png[20..24].try_into().unwrap()) as usize;
if width == 0
|| height == 0
|| !width
.checked_mul(height)
.and_then(|pixels| pixels.checked_mul(4))
.is_some_and(|size| size <= 64 * 1024 * 1024)
{
return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "Clipboard image is too large"));
}
imp::set_png(png, owner)
}
/// Replaces every clipboard flavor with plain text. `owner` is the calling window
/// handle on Windows, ignored elsewhere. Call on the main thread on macOS and Linux.
pub fn set_text(text: &str, owner: usize) -> std::io::Result<()> {
@@ -83,7 +56,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 +78,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 +89,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> {
@@ -344,7 +240,6 @@ mod imp {
/// `CF_DIB`: Windows synthesizes it from `CF_BITMAP` and `CF_DIBV5`, so every
/// bitmap on the clipboard reads as one.
const CF_DIB: u32 = 8;
const CF_DIBV5: u32 = 17;
/// The `PNG` format browsers and the Snipping Tool add beside the bitmap; it
/// keeps transparency, so it is read first.
@@ -527,48 +422,6 @@ mod imp {
}
}
pub fn set_png(png: &[u8], owner: usize) -> std::io::Result<()> {
let dib = super::image::png_to_dib(png)?;
let format = png_format();
if format == 0 {
return Err(std::io::Error::last_os_error());
}
let formats = [(format, png), (CF_DIBV5, dib.as_slice())];
// SAFETY: allocations remain ours until SetClipboardData accepts them. Prepare both
// before replacing the clipboard; free only allocations the OS did not take.
unsafe {
let mut blocks: Vec<_> = formats.iter().map(|(_, bytes)| global_bytes(bytes)).collect();
if blocks.iter().any(|memory| memory.is_null()) || !open_for(owner as Handle) {
let error = std::io::Error::last_os_error();
for memory in blocks {
if !memory.is_null() {
GlobalFree(memory);
}
}
return Err(error);
}
let mut result = Ok(());
if EmptyClipboard() == 0 {
result = Err(std::io::Error::last_os_error());
} else {
for ((format, _), memory) in formats.iter().zip(&mut blocks) {
if SetClipboardData(*format, *memory).is_null() {
result = Err(std::io::Error::last_os_error());
break;
}
*memory = ptr::null_mut();
}
}
CloseClipboard();
for memory in blocks {
if !memory.is_null() {
GlobalFree(memory);
}
}
result
}
}
pub fn set_files(paths: &[PathBuf]) -> bool {
let bytes = encode(paths);
if bytes.len() <= HEADER {
@@ -636,7 +489,7 @@ mod imp {
NSBitmapImageFileType, NSBitmapImageRep, NSPasteboard, NSPasteboardReadingOptionKey, NSPasteboardTypePNG,
NSPasteboardTypeString, NSPasteboardTypeTIFF, NSPasteboardURLReadingFileURLsOnlyKey, NSPasteboardWriting,
};
use objc2_foundation::{NSArray, NSData, NSDictionary, NSNumber, NSString, NSURL};
use objc2_foundation::{NSArray, NSDictionary, NSNumber, NSString, NSURL};
use std::path::PathBuf;
use super::names_text;
@@ -734,23 +587,6 @@ mod imp {
})
}
pub fn set_png(png: &[u8], _owner: usize) -> std::io::Result<()> {
debug_assert!(MainThreadMarker::new().is_some(), "NSPasteboard access requires the main thread");
autoreleasepool(|_| {
let data = NSData::with_bytes(png);
if NSBitmapImageRep::imageRepWithData(&data).is_none() {
return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "Invalid clipboard image"));
}
let board = NSPasteboard::generalPasteboard();
board.clearContents();
if board.setData_forType(Some(&data), unsafe { NSPasteboardTypePNG }) {
Ok(())
} else {
Err(std::io::Error::other("Cannot write clipboard image"))
}
})
}
pub fn set_files(paths: &[PathBuf]) -> bool {
debug_assert!(MainThreadMarker::new().is_some(), "NSPasteboard access requires the main thread");
autoreleasepool(|_| {
@@ -781,21 +617,6 @@ mod imp {
mod imp {
use std::path::PathBuf;
pub fn set_png(png: &[u8], _owner: usize) -> std::io::Result<()> {
#[cfg(target_os = "linux")]
{
let image = gtk::gdk_pixbuf::Pixbuf::from_read(std::io::Cursor::new(png.to_vec()))
.map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error.to_string()))?;
gtk::Clipboard::get(&gtk::gdk::SELECTION_CLIPBOARD).set_image(&image);
Ok(())
}
#[cfg(not(target_os = "linux"))]
{
let _ = png;
Err(std::io::Error::other("Clipboard images are unavailable on this platform"))
}
}
pub fn set_text(text: &str, _owner: usize) -> std::io::Result<()> {
#[cfg(target_os = "linux")]
{
@@ -809,25 +630,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 +649,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
}
@@ -881,41 +658,10 @@ mod imp {
mod tests {
use super::*;
#[test]
fn invalid_or_oversized_images_are_rejected_before_accessing_the_clipboard() {
assert!(set_png(b"not a PNG", 0).is_err());
let mut header = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR".to_vec();
header.extend_from_slice(&100_000u32.to_be_bytes());
header.extend_from_slice(&100_000u32.to_be_bytes());
assert!(set_png(&header, 0).is_err());
}
fn paths(list: &[&str]) -> Vec<PathBuf> {
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.
-5
View File
@@ -201,7 +201,6 @@ pub struct FoldingSettings {
pub file_header: bool,
pub imports: bool,
pub doc_comments: bool,
pub go_short_blocks: bool,
}
impl Default for FoldingSettings {
@@ -212,7 +211,6 @@ impl Default for FoldingSettings {
file_header: true,
imports: true,
doc_comments: false,
go_short_blocks: true,
}
}
}
@@ -364,8 +362,6 @@ pub struct InlayHintsSettings {
pub parameters: bool,
/// Hints of other kinds (chaining, closing labels…).
pub other: bool,
/// The Dart server's closing labels (`// Column` after a widget's closing bracket).
pub closing_labels: bool,
pub disabled_languages: Vec<String>,
/// Code vision as a whole (usages, author and language-server lenses); the switches below apply while it is on.
pub code_vision: bool,
@@ -398,7 +394,6 @@ impl Default for InlayHintsSettings {
types: true,
parameters: true,
other: true,
closing_labels: true,
disabled_languages: Vec::new(),
code_vision: true,
code_vision_usages: true,
-18
View File
@@ -264,20 +264,6 @@ pub struct FlutterDevice {
pub emulator: bool,
/// The adb state keeping it from being used (`unauthorized`, `offline`, …).
pub unavailable: Option<String>,
/// The [`FlutterEmulator`] it runs on: an AVD name, or `apple_ios_simulator`.
#[serde(default)]
#[specta(optional)]
pub emulator_id: Option<String>,
}
/// An Android emulator (AVD) or the iOS Simulator that `flutter emulators --launch` can start.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct FlutterEmulator {
pub id: String,
pub name: String,
/// `android` or `ios`.
pub platform_type: Option<String>,
}
/// See [`FlutterDeviceList`].
@@ -303,10 +289,6 @@ pub enum FlutterDaemonStatus {
pub struct FlutterDeviceList {
pub status: FlutterDaemonStatus,
pub devices: Vec<FlutterDevice>,
/// The emulators that no listed device runs on.
#[serde(default)]
#[specta(optional)]
pub emulators: Vec<FlutterEmulator>,
}
/// See [`IdeEvent::Direnv`].
-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}");
}
}
}
+1 -29
View File
@@ -145,7 +145,7 @@ impl Default for AgentSettings {
show_work_time: true,
show_usage_limits: true,
show_cost: false,
fold_turns: false,
fold_turns: true,
smooth_text: true,
fit_window_width: false,
thinking: ThinkingDisplay::Auto,
@@ -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 {
@@ -1668,20 +1657,6 @@ pub struct MavenSettings {
/// Always update snapshots (`-U`): Maven checks remote repositories for newer SNAPSHOT
/// dependencies on every sync, build and run, and jdtls on import (`java.maven.updateSnapshots`).
pub update_snapshots: bool,
/// Who runs the JUnit 5 tests of the gutter's Run / Debug.
pub run_tests_using: MavenRunTestsUsing,
}
/// Build Tools › Maven › Run tests using. IDEA runs a Maven project's tests itself unless its build
/// and run actions are delegated to Maven.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum MavenRunTestsUsing {
/// OpenIDEA's JUnit Platform runner on the language server's test classpath (`java/junit-runner`).
#[default]
Ide,
/// Surefire (`mvn test -Dtest=…`).
Maven,
}
impl MavenSettings {
@@ -2124,10 +2099,8 @@ mod tests {
assert!(old.agents.show_cost);
assert!(old.agents.show_context_usage && old.agents.show_work_time && old.agents.show_usage_limits);
assert!(!old.agents.fit_window_width);
assert!(!old.agents.fold_turns);
assert!(!Settings::default().agents.show_cost);
assert!(!Settings::default().agents.fit_window_width);
assert!(!Settings::default().agents.fold_turns);
let mut settings = Settings::default();
settings.agents.show_usage_limits = false;
settings.agents.fit_window_width = true;
@@ -2345,7 +2318,6 @@ mod maven_linkage_tests {
let old: MavenSettings = serde_json::from_str(r#"{"home":"/opt/maven"}"#).unwrap();
assert!(old.runner_jre.is_empty());
assert!(!old.delegate_build);
assert_eq!(old.run_tests_using, MavenRunTestsUsing::Ide);
assert!(MavenSettings::default().runner_jre.is_empty());
let settings = MavenSettings { runner_jre: "/opt/jdk-21".into(), delegate_build: true, ..old };
let encoded = serde_json::to_string(&settings).unwrap();
+1 -1
View File
@@ -30,7 +30,7 @@ pub(crate) use inspect::{fields, instances, referrers, set_inspector, vm_target,
pub(crate) use scan::watch_for_attached_jvm;
pub(crate) use scan::{JvmFinder, attach_target, find_attached_jvm, find_local_jvm, local_jdwp_port};
use snapshot::{AttachProbe, JdkProbe, take_snapshot};
pub use threads::{JvmThreadDump, JvmThreadsResult, JvmThreadsUnavailable, VirtualThreadsNote, run_jvm_thread_dump};
pub use threads::{JvmThreadDump, JvmThreadsResult, JvmThreadsUnavailable, run_jvm_thread_dump};
pub(crate) use threads::{debugged_run_thread_dump, session_thread_dump};
pub const JVM_MEMORY_ADAPTERS: &[&str] = &["java-debug", crate::kotlin::ADAPTER, crate::kotlin_lsp::ADAPTER];
@@ -33,7 +33,6 @@ pub(crate) trait AttachProbe: Send + Sync {
fn ensure_listener(&self, pid: u32) -> Result<(), AttachError>;
/// Confirmed HotSpot and not one of Gradle's own JVMs; asks the JVM nothing.
fn is_application_jvm(&self, pid: u32) -> bool;
fn thread_dump_json(&self, pid: u32, dir: &Path) -> Result<String, AttachError>;
}
pub(super) struct JdkProbe {
@@ -92,10 +91,6 @@ impl AttachProbe for JdkProbe {
fn is_application_jvm(&self, pid: u32) -> bool {
ide_jvm_attach::is_application_jvm(pid)
}
fn thread_dump_json(&self, pid: u32, dir: &Path) -> Result<String, AttachError> {
ide_jvm_attach::thread_dump_json(pid, dir, ide_jvm_attach::THREAD_DUMP_TIMEOUT)
}
}
fn alive(pid: u32) -> bool {
+29 -189
View File
@@ -47,8 +47,6 @@ struct FakeProbe {
application_jvms: Vec<u32>,
/// Pids `ensure_listener` was asked for.
ensured: parking_lot::Mutex<Vec<u32>>,
json_dumps: parking_lot::Mutex<VecDeque<Result<String, AttachError>>>,
json_dirs: parking_lot::Mutex<Vec<PathBuf>>,
}
type StopHook = Box<dyn Fn() + Send + Sync>;
@@ -111,8 +109,6 @@ impl FakeProbe {
listener_starts: parking_lot::Mutex::new(VecDeque::new()),
application_jvms: Vec::new(),
ensured: parking_lot::Mutex::new(Vec::new()),
json_dumps: parking_lot::Mutex::new(VecDeque::new()),
json_dirs: parking_lot::Mutex::new(Vec::new()),
}
}
@@ -197,12 +193,6 @@ impl AttachProbe for FakeProbe {
fn is_application_jvm(&self, pid: u32) -> bool {
self.application_jvms.contains(&pid)
}
fn thread_dump_json(&self, _pid: u32, dir: &Path) -> Result<String, AttachError> {
self.enter("thread_dump_json");
self.json_dirs.lock().push(dir.to_owned());
self.leave();
self.json_dumps.lock().pop_front().expect("unexpected JSON thread dump request")
}
}
const FLAGS: &str = "-XX:+UseCompressedOops -XX:+StartAttachListener";
@@ -1215,95 +1205,10 @@ fn threads_jvm(reason: JvmMemoryUnavailable) -> JvmThreadsUnavailable {
JvmThreadsUnavailable::Jvm { reason }
}
/// The text dump alone: without a directory no JSON dump is asked for.
fn dump_text(fake: &FakeProbe, pid: u32, suspended: bool) -> JvmThreadsResult {
dump_threads(fake, pid, suspended, None, &|| suspended)
}
fn ready_dump(r: JvmThreadsResult) -> JvmThreadDump {
match r {
JvmThreadsResult::Ready { dump } => dump,
other => panic!("{other:?}"),
}
}
const VIRTUAL_JSON: &str = r#"{"threadDump":{"threadContainers":[]}}"#;
fn json_dir() -> &'static Path {
Path::new("/data/cache/heap-snapshots/x")
}
#[test]
fn threads_below_21_ask_for_no_json() {
let mut fake = dumping_threads(99, vec![Ok(THREADS.into())]);
fake.version = Some(JavaVersion { major: 17, text: "17.0.13".into() });
let dump = ready_dump(dump_threads(&fake, 12, false, Some(json_dir()), &|| false));
assert_eq!((dump.virtual_json, dump.virtual_note), (None, None));
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print"]);
}
#[test]
fn threads_on_21_add_the_json_after_the_text() {
let fake = dumping_threads(99, vec![Ok(THREADS.into())]);
*fake.json_dumps.lock() = vec![Ok(VIRTUAL_JSON.into())].into();
let dump = ready_dump(dump_threads(&fake, 12, false, Some(json_dir()), &|| false));
assert_eq!(dump.text, THREADS);
assert_eq!((dump.virtual_json.as_deref(), dump.virtual_note), (Some(VIRTUAL_JSON), None));
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print", "thread_dump_json"]);
assert_eq!(*fake.json_dirs.lock(), [json_dir()]);
}
#[test]
fn a_failed_json_dump_keeps_the_text_dump() {
let cases = [
(AttachError::TooLarge, VirtualThreadsNote::TooLarge),
(AttachError::Timeout, VirtualThreadsNote::Failed),
(AttachError::Protocol("no thread dump file".into()), VirtualThreadsNote::Failed),
];
for (error, note) in cases {
let fake = dumping_threads(99, vec![Ok(THREADS.into())]);
*fake.json_dumps.lock() = vec![Err(error)].into();
let dump = ready_dump(dump_threads(&fake, 12, false, Some(json_dir()), &|| false));
assert_eq!((dump.text.as_str(), dump.virtual_json, dump.virtual_note), (THREADS, None, Some(note)));
}
// No directory to write the file into.
let fake = dumping_threads(99, vec![Ok(THREADS.into())]);
let dump = ready_dump(dump_text(&fake, 12, false));
assert_eq!((dump.virtual_json, dump.virtual_note), (None, Some(VirtualThreadsNote::Failed)));
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print"]);
}
#[test]
fn a_failed_text_dump_asks_for_no_json() {
let fake = dumping_threads(99, vec![Err(AttachError::Timeout)]);
let r = dump_threads(&fake, 12, false, Some(json_dir()), &|| false);
assert_eq!(threads_unavailable(r), threads_jvm(JvmMemoryUnavailable::TimedOut));
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print"]);
}
#[test]
fn threads_while_suspended_on_21_skip_the_json() {
let fake = dumping_threads(12, vec![Ok(THREADS.into())]);
let dump = ready_dump(dump_threads(&fake, 12, true, Some(json_dir()), &|| true));
assert_eq!((dump.virtual_json, dump.virtual_note), (None, Some(VirtualThreadsNote::WhileSuspended)));
assert_eq!(*fake.commands.lock(), ["thread_print"]);
// The program hits a breakpoint while the text dump is taken.
let stopped = Arc::new(AtomicBool::new(false));
let mut fake = dumping_threads(99, vec![Ok(THREADS.into())]);
let stop = stopped.clone();
fake.stops_on = Some(("thread_print", Box::new(move || stop.store(true, Ordering::SeqCst))));
let dump = ready_dump(dump_threads(&fake, 12, false, Some(json_dir()), &|| stopped.load(Ordering::SeqCst)));
assert!(!dump.taken_while_suspended);
assert_eq!((dump.virtual_json, dump.virtual_note), (None, Some(VirtualThreadsNote::WhileSuspended)));
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print"]);
}
#[test]
fn threads_while_running_start_the_listener() {
let fake = dumping_threads(99, vec![Ok(THREADS.into())]);
let r = dump_text(&fake, 12, false);
let r = dump_threads(&fake, 12, false);
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert_eq!((dump.text.as_str(), dump.pid, dump.java_version.as_str()), (THREADS, 12, "21.0.5"));
assert!(!dump.taken_while_suspended);
@@ -1313,7 +1218,10 @@ fn threads_while_running_start_the_listener() {
#[test]
fn threads_while_suspended_without_listener_do_not_attach() {
let fake = dumping_threads(99, Vec::new());
assert_eq!(threads_unavailable(dump_text(&fake, 12, true)), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning));
assert_eq!(
threads_unavailable(dump_threads(&fake, 12, true)),
threads_jvm(JvmMemoryUnavailable::ListenerNotRunning)
);
assert!(fake.commands.lock().is_empty());
}
@@ -1322,12 +1230,12 @@ fn threads_while_suspended_on_11_are_refused() {
let mut fake = dumping_threads(12, Vec::new());
fake.version = Some(JavaVersion { major: 11, text: "11.0.25".into() });
assert_eq!(
threads_unavailable(dump_text(&fake, 12, true)),
threads_unavailable(dump_threads(&fake, 12, true)),
threads_jvm(JvmMemoryUnavailable::UnsafeWhileSuspended { java_major: 11 })
);
fake.version = None;
assert_eq!(
threads_unavailable(dump_text(&fake, 12, true)),
threads_unavailable(dump_threads(&fake, 12, true)),
threads_jvm(JvmMemoryUnavailable::UnsafeWhileSuspended { java_major: 0 })
);
assert!(fake.commands.lock().is_empty());
@@ -1337,7 +1245,7 @@ fn threads_while_suspended_on_11_are_refused() {
fn threads_while_suspended_on_17_use_the_running_listener() {
let mut fake = dumping_threads(12, vec![Ok(THREADS.into())]);
fake.version = Some(JavaVersion { major: 17, text: "17.0.13".into() });
let r = dump_text(&fake, 12, true);
let r = dump_threads(&fake, 12, true);
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert!(dump.taken_while_suspended);
assert_eq!(dump.java_version, "17.0.13");
@@ -1349,7 +1257,7 @@ fn threads_of_a_tree_without_a_listener_go_to_its_first_application_jvm() {
// A shell (10) started a Gradle client (11) that started the program's JVM (12).
let mut fake = dumping_threads(99, vec![Ok(THREADS.into())]);
fake.application_jvms = vec![12];
let r = dump_tree(&fake, &[10, 11, 12], false, None, &|| false);
let r = dump_tree(&fake, &[10, 11, 12], false);
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert_eq!(dump.pid, 12);
assert_eq!(*fake.ensured.lock(), [12]);
@@ -1358,7 +1266,7 @@ fn threads_of_a_tree_without_a_listener_go_to_its_first_application_jvm() {
let fake = dumping_threads(99, Vec::new());
*fake.listener_starts.lock() = vec![Err(AttachError::NotAJvm)].into();
assert_eq!(
threads_unavailable(dump_tree(&fake, &[10, 11], false, None, &|| false)),
threads_unavailable(dump_tree(&fake, &[10, 11], false)),
threads_jvm(JvmMemoryUnavailable::NoJvmProcess)
);
assert_eq!(*fake.ensured.lock(), [10]);
@@ -1382,7 +1290,7 @@ async fn launched_thread_dump_without_a_listener_finds_the_jvm_below_the_reporte
let fake = Arc::new(fake);
let probe: Arc<dyn AttachProbe> = fake.clone();
let target = JvmTarget::Launched(std::process::id() as i32);
let r = thread_dump(&state, || false, |_| probe, target, None).await.unwrap();
let r = thread_dump(&state, || false, |_| probe, target).await.unwrap();
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert_eq!(dump.pid, jvm);
assert_eq!(*fake.ensured.lock(), [jvm]);
@@ -1432,7 +1340,7 @@ async fn run_dump_through_a_linked_session_whose_jvm_is_not_located() {
let bare = stopped_attach(0);
let fake = Arc::new(dumping_threads(99, Vec::new()));
let probe: Arc<dyn AttachProbe> = fake.clone();
let r = known_pid_dump(&bare.session, |_| probe, 555, None).await.unwrap();
let r = known_pid_dump(&bare.session, |_| probe, 555).await.unwrap();
assert_eq!(threads_unavailable(r), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning));
assert!(fake.commands.lock().is_empty());
@@ -1440,7 +1348,7 @@ async fn run_dump_through_a_linked_session_whose_jvm_is_not_located() {
let bare = bare_session("attach");
let fake = Arc::new(dumping_threads(99, vec![Ok(THREADS.into())]));
let probe: Arc<dyn AttachProbe> = fake.clone();
let r = known_pid_dump(&bare.session, |_| probe, 555, None).await.unwrap();
let r = known_pid_dump(&bare.session, |_| probe, 555).await.unwrap();
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert_eq!((dump.pid, dump.taken_while_suspended), (555, false));
assert_eq!(*fake.ensured.lock(), [555]);
@@ -1461,71 +1369,26 @@ async fn run_dump_of_a_suspended_debugged_jvm_takes_the_suspended_path() {
fake.version = Some(JavaVersion { major: 11, text: "11.0.25".into() });
let fake = Arc::new(fake);
let probe: Arc<dyn AttachProbe> = fake.clone();
let r = known_pid_dump(&bare.session, |_| probe, 4242, None).await.unwrap();
let r = known_pid_dump(&bare.session, |_| probe, 4242).await.unwrap();
assert_eq!(threads_unavailable(r), threads_jvm(JvmMemoryUnavailable::UnsafeWhileSuspended { java_major: 11 }));
assert!(fake.commands.lock().is_empty());
// No listener: none is started, the JVM's Signal Dispatcher being stopped.
let fake = Arc::new(dumping_threads(99, Vec::new()));
let probe: Arc<dyn AttachProbe> = fake.clone();
let r = known_pid_dump(&bare.session, |_| probe, 4242, None).await.unwrap();
let r = known_pid_dump(&bare.session, |_| probe, 4242).await.unwrap();
assert_eq!(threads_unavailable(r), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning));
assert!(fake.commands.lock().is_empty());
let mut fake = dumping_threads(4242, vec![Ok(THREADS.into())]);
fake.version = Some(JavaVersion { major: 17, text: "17.0.13".into() });
let probe: Arc<dyn AttachProbe> = Arc::new(fake);
let r = known_pid_dump(&bare.session, |_| probe, 4242, None).await.unwrap();
let r = known_pid_dump(&bare.session, |_| probe, 4242).await.unwrap();
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert!(dump.taken_while_suspended);
assert_eq!(dump.pid, 4242);
}
#[tokio::test]
async fn run_dump_of_a_debugged_jvm_asks_for_no_json_while_the_session_holds_it() {
let bare = stopped_attach(4242);
let fake = Arc::new(dumping_threads(4242, vec![Ok(THREADS.into())]));
let probe: Arc<dyn AttachProbe> = fake.clone();
let dump = ready_dump(known_pid_dump(&bare.session, |_| probe, 4242, Some(json_dir().into())).await.unwrap());
assert!(dump.taken_while_suspended);
assert_eq!((dump.virtual_json, dump.virtual_note), (None, Some(VirtualThreadsNote::WhileSuspended)));
assert_eq!(*fake.commands.lock(), ["thread_print"]);
// Running at first, the program hits a breakpoint while the text dump is taken.
let bare = bare_session("attach");
bare.session.jvm_pid.store(4242, Ordering::Release);
let mut fake = dumping_threads(4242, vec![Ok(THREADS.into())]);
let session = bare.session.clone();
fake.stops_on = Some(("thread_print", Box::new(move || session.suspended.stopped(None, true))));
let fake = Arc::new(fake);
let probe: Arc<dyn AttachProbe> = fake.clone();
let dump = ready_dump(known_pid_dump(&bare.session, |_| probe, 4242, Some(json_dir().into())).await.unwrap());
assert!(!dump.taken_while_suspended);
assert_eq!((dump.virtual_json, dump.virtual_note), (None, Some(VirtualThreadsNote::WhileSuspended)));
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print"]);
}
#[tokio::test]
async fn run_dump_through_a_linked_session_whose_jvm_is_not_located_asks_for_no_json_while_stopped() {
// Gradle bootRun Debug after an earlier run dump opened the listener: the session's pid is still 0.
let bare = stopped_attach(0);
let fake = Arc::new(dumping_threads(555, vec![Ok(THREADS.into())]));
let probe: Arc<dyn AttachProbe> = fake.clone();
let dump = ready_dump(known_pid_dump(&bare.session, |_| probe, 555, Some(json_dir().into())).await.unwrap());
assert_eq!((dump.pid, dump.taken_while_suspended), (555, true));
assert_eq!((dump.virtual_json, dump.virtual_note), (None, Some(VirtualThreadsNote::WhileSuspended)));
assert_eq!(*fake.commands.lock(), ["thread_print"]);
// Running, the same session gets the JSON dump too.
let bare = bare_session("attach");
let fake = Arc::new(dumping_threads(555, vec![Ok(THREADS.into())]));
*fake.json_dumps.lock() = vec![Ok(VIRTUAL_JSON.into())].into();
let probe: Arc<dyn AttachProbe> = fake.clone();
let dump = ready_dump(known_pid_dump(&bare.session, |_| probe, 555, Some(json_dir().into())).await.unwrap());
assert_eq!((dump.virtual_json.as_deref(), dump.virtual_note), (Some(VIRTUAL_JSON), None));
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print", "thread_dump_json"]);
}
#[tokio::test]
async fn run_dump_of_a_debugged_jvm_waits_for_the_session_turn() {
let bare = bare_session("attach");
@@ -1534,7 +1397,7 @@ async fn run_dump_of_a_debugged_jvm_waits_for_the_session_turn() {
let probe: Arc<dyn AttachProbe> = fake.clone();
let histogram = bare.session.jvm_memory.lock().await;
let mut queued = Box::pin(known_pid_dump(&bare.session, |_| probe, 4242, None));
let mut queued = Box::pin(known_pid_dump(&bare.session, |_| probe, 4242));
assert!(tokio::time::timeout(Duration::from_millis(50), &mut queued).await.is_err());
// The program hits a breakpoint while the dump waits behind the session's histogram.
bare.session.suspended.stopped(None, true);
@@ -1548,28 +1411,28 @@ fn threads_of_an_exited_program() {
let mut fake = dumping_threads(99, Vec::new());
fake.alive = false;
*fake.listener_starts.lock() = vec![Err(AttachError::NoListener)].into();
assert_eq!(threads_unavailable(dump_text(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
assert_eq!(threads_unavailable(dump_text(&fake, 12, true)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
assert_eq!(threads_unavailable(dump_threads(&fake, 12, true)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
}
#[test]
fn thread_dump_errors_map_to_reasons() {
let fake = dumping_threads(12, vec![Err(AttachError::Timeout)]);
assert_eq!(threads_unavailable(dump_text(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::TimedOut));
assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::TimedOut));
let fake = dumping_threads(99, Vec::new());
*fake.listener_starts.lock() = vec![Err(AttachError::ListenerDidNotStart)].into();
assert_eq!(threads_unavailable(dump_text(&fake, 12, false)), JvmThreadsUnavailable::ListenerDidNotStart);
assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), JvmThreadsUnavailable::ListenerDidNotStart);
assert_eq!(*fake.commands.lock(), ["ensure_listener"]);
let mut fake = dumping_threads(99, Vec::new());
*fake.listener_starts.lock() = vec![Err(AttachError::NotAJvm), Err(AttachError::NotAJvm)].into();
assert_eq!(threads_unavailable(dump_text(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::NoJvmProcess));
assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::NoJvmProcess));
fake.alive = false;
assert_eq!(threads_unavailable(dump_text(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
let fake = dumping_threads(12, vec![Err(AttachError::Command { code: 1, message: "no".into() })]);
let JvmThreadsUnavailable::Failed { message } = threads_unavailable(dump_text(&fake, 12, false)) else {
let JvmThreadsUnavailable::Failed { message } = threads_unavailable(dump_threads(&fake, 12, false)) else {
panic!("not a failure")
};
assert!(message.contains("no"), "{message}");
@@ -1593,20 +1456,14 @@ fn thread_results_serialize_with_camel_case_tags() {
java_version: String::new(),
taken_while_suspended: true,
elapsed_ms: 3,
virtual_json: None,
virtual_note: Some(VirtualThreadsNote::WhileSuspended),
};
assert_eq!(
serde_json::to_value(JvmThreadsResult::Ready { dump }).unwrap(),
serde_json::json!({
"status": "ready",
"dump": {
"text": "t", "pid": 7, "javaVersion": "", "takenWhileSuspended": true, "elapsedMs": 3,
"virtualJson": null, "virtualNote": "whileSuspended"
}
"dump": {"text": "t", "pid": 7, "javaVersion": "", "takenWhileSuspended": true, "elapsedMs": 3}
})
);
assert_eq!(serde_json::to_value(VirtualThreadsNote::TooLarge).unwrap(), serde_json::json!("tooLarge"));
}
#[cfg(unix)]
@@ -1622,7 +1479,7 @@ async fn threads_take_the_memory_lock() {
let running = Suspension::default();
let (classes, threads) = tokio::join!(
snapshot(&state, &running, |_| probe.clone(), JvmTarget::Launched(pid as i32), None),
thread_dump(&state, || false, |_| probe.clone(), JvmTarget::Launched(pid as i32), None)
thread_dump(&state, || false, |_| probe.clone(), JvmTarget::Launched(pid as i32))
);
assert!(matches!(classes.unwrap(), JvmMemoryResult::Ready { .. }));
let threads = threads.unwrap();
@@ -1636,14 +1493,12 @@ async fn threads_take_the_memory_lock() {
async fn queued_thread_dump_reads_suspension_under_the_lock() {
let pid = std::process::id();
let state = tokio::sync::Mutex::new(JvmMemoryState::default());
let suspended = Arc::new(Suspension::default());
let suspended = Suspension::default();
let fake = Arc::new(dumping_threads(0, Vec::new()));
let probe: Arc<dyn AttachProbe> = fake.clone();
let running = state.lock().await;
let stopped = suspended.clone();
let target = JvmTarget::Launched(pid as i32);
let mut queued = Box::pin(thread_dump(&state, move || stopped.get(), |_| probe, target, Some(json_dir().into())));
let mut queued = Box::pin(thread_dump(&state, || suspended.get(), |_| probe, JvmTarget::Launched(pid as i32)));
assert!(tokio::time::timeout(Duration::from_millis(50), &mut queued).await.is_err());
// The program hits a breakpoint while the dump waits behind a class-table request.
suspended.stopped(None, true);
@@ -1660,27 +1515,12 @@ async fn attached_thread_dump_keeps_the_scanned_jvm() {
fake.jdwp = Some((5005, 4242));
let probe: Arc<dyn AttachProbe> = Arc::new(fake);
let target = JvmTarget::Attached { pid: &jvm_pid, jdwp_port: Some(5005) };
let r = thread_dump(&state, || false, |_| probe, target, None).await.unwrap();
let r = thread_dump(&state, || false, |_| probe, target).await.unwrap();
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert_eq!(dump.pid, 4242);
assert_eq!(jvm_pid.load(Ordering::SeqCst), 4242);
}
#[cfg(unix)]
#[tokio::test]
async fn session_thread_dump_writes_the_json_into_the_given_directory() {
let pid = std::process::id();
let state = tokio::sync::Mutex::new(JvmMemoryState::default());
let fake = dumping_threads(pid, vec![Ok(THREADS.into())]);
*fake.json_dumps.lock() = vec![Ok(VIRTUAL_JSON.into())].into();
let fake = Arc::new(fake);
let probe: Arc<dyn AttachProbe> = fake.clone();
let target = JvmTarget::Launched(pid as i32);
let r = thread_dump(&state, || false, |_| probe, target, Some(json_dir().into())).await.unwrap();
assert_eq!(ready_dump(r).virtual_json.as_deref(), Some(VIRTUAL_JSON));
assert_eq!(*fake.json_dirs.lock(), [json_dir()]);
}
#[tokio::test]
async fn capability_matches_memory() {
for adapter in JVM_MEMORY_ADAPTERS.iter().copied().chain(["debugpy"]) {
+17 -96
View File
@@ -8,15 +8,11 @@ use super::{
};
use crate::session::Session;
use ide_core::{IdeError, IdeResult};
use ide_jvm_attach::{AttachError, JavaVersion};
use ide_jvm_attach::AttachError;
use serde::{Deserialize, Serialize};
use specta::Type;
use std::path::{Path, PathBuf};
use std::sync::Arc;
/// The first release whose virtual threads are final and that writes the JSON dump.
const VIRTUAL_THREADS_MAJOR: u32 = 21;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct JvmThreadDump {
@@ -27,20 +23,6 @@ pub struct JvmThreadDump {
pub taken_while_suspended: bool,
/// Wall time of the `Thread.print` request.
pub elapsed_ms: u32,
/// `Thread.dump_to_file -format=json`, which also lists virtual threads; JDK 21+ only.
pub virtual_json: Option<String>,
/// Why `virtual_json` is missing from a JDK 21+ dump; none below 21.
pub virtual_note: Option<VirtualThreadsNote>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum VirtualThreadsNote {
/// A debugger holds the VM, which would hang the JSON request until it resumes.
WhileSuspended,
/// Over the attach reply limit (64 MiB).
TooLarge,
Failed,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
@@ -66,17 +48,13 @@ pub enum JvmThreadsResult {
Unavailable { reason: JvmThreadsUnavailable },
}
/// A thread dump of `pid`, a JVM no debugger holds; `json_dir` is an absolute, owner-only
/// directory the JVM may write the JSON dump into. Blocking for up to the listener start and
/// A thread dump of `pid`, a JVM no debugger holds. Blocking for up to the listener start and
/// dump timeouts, so callers run it in `spawn_blocking`.
pub fn run_jvm_thread_dump(pid: u32, json_dir: Option<&Path>) -> JvmThreadsResult {
dump_threads(&JdkProbe { suspended: false }, pid, false, json_dir, &|| false)
pub fn run_jvm_thread_dump(pid: u32) -> JvmThreadsResult {
dump_threads(&JdkProbe { suspended: false }, pid, false)
}
pub(crate) async fn session_thread_dump(
session: Arc<Session>,
json_dir: Option<PathBuf>,
) -> IdeResult<JvmThreadsResult> {
pub(crate) async fn session_thread_dump(session: Arc<Session>) -> IdeResult<JvmThreadsResult> {
until_located(&session).await;
let launched = histogram_pid(&session);
// Detached, so a caller that gives up cannot release the lock while the JVM is still
@@ -84,9 +62,7 @@ pub(crate) async fn session_thread_dump(
tokio::spawn(async move {
let target = session_target(&session, launched);
let probe = |suspended| -> Arc<dyn AttachProbe> { Arc::new(JdkProbe { suspended }) };
let stopped = session.clone();
let suspended = move || capture_suspended(&stopped);
thread_dump(&session.jvm_memory, suspended, probe, target, json_dir).await
thread_dump(&session.jvm_memory, || capture_suspended(&session), probe, target).await
})
.await
.map_err(|e| IdeError::internal(format!("JVM thread dump failed: {e}")))?
@@ -94,53 +70,43 @@ pub(crate) async fn session_thread_dump(
/// A thread dump of `pid`, a run's JVM that `session` debugs, taken as the session's own dump
/// is: a JVM the debugger holds suspended is never asked to open a listener.
pub(crate) async fn debugged_run_thread_dump(
session: Arc<Session>,
pid: u32,
json_dir: Option<PathBuf>,
) -> IdeResult<JvmThreadsResult> {
pub(crate) async fn debugged_run_thread_dump(session: Arc<Session>, pid: u32) -> IdeResult<JvmThreadsResult> {
// Detached for the same reason as `session_thread_dump`.
tokio::spawn(async move {
let probe = |suspended| -> Arc<dyn AttachProbe> { Arc::new(JdkProbe { suspended }) };
known_pid_dump(&session, probe, pid, json_dir).await
known_pid_dump(&session, probe, pid).await
})
.await
.map_err(|e| IdeError::internal(format!("JVM thread dump failed: {e}")))?
}
/// The session's suspension decides the JSON dump too: it is read again before that request.
pub(super) async fn known_pid_dump(
session: &Arc<Session>,
session: &Session,
probe: impl FnOnce(bool) -> Arc<dyn AttachProbe>,
pid: u32,
json_dir: Option<PathBuf>,
) -> IdeResult<JvmThreadsResult> {
let target =
i32::try_from(pid).map_or(JvmTarget::Unavailable(JvmMemoryUnavailable::NoJvmProcess), JvmTarget::Known);
let stopped = session.clone();
let suspended = move || capture_suspended(&stopped);
thread_dump(&session.jvm_memory, suspended, probe, target, json_dir).await
thread_dump(&session.jvm_memory, || capture_suspended(session), probe, target).await
}
/// Takes the class-table lock, so a dump never runs beside a histogram or heap dump of the same
/// session; `suspended_now` and then `probe` are read once it is held, and `suspended_now` again
/// before the JSON dump.
/// session; `suspended` and then `probe` are read once it is held.
pub(super) async fn thread_dump(
state: &tokio::sync::Mutex<JvmMemoryState>,
suspended_now: impl Fn() -> bool + Send + Sync + 'static,
suspended: impl FnOnce() -> bool,
probe: impl FnOnce(bool) -> Arc<dyn AttachProbe>,
target: JvmTarget<'_>,
json_dir: Option<PathBuf>,
) -> IdeResult<JvmThreadsResult> {
let _turn = state.lock().await;
let suspended = suspended_now();
let suspended = suspended();
let lookup = match lookup(target) {
Ok(lookup) => lookup,
Err(reason) => return Ok(jvm(reason)),
};
let probe = probe(suspended);
let (found, outcome) = tokio::task::spawn_blocking(move || match resolve_jvm(lookup, &*probe, suspended) {
Ok((tree, found)) => (found, dump_tree(&*probe, &tree, suspended, json_dir.as_deref(), &suspended_now)),
Ok((tree, found)) => (found, dump_tree(&*probe, &tree, suspended)),
Err(reason) => (None, jvm(reason)),
})
.await
@@ -152,32 +118,19 @@ pub(super) async fn thread_dump(
/// `tree` starts with the session's reported pid, followed by its descendants: the JVM is the
/// first with a listener, else the first application JVM (the reported pid may be a shell or a
/// Gradle client), else the reported pid.
pub(super) fn dump_tree(
probe: &dyn AttachProbe,
tree: &[i32],
suspended: bool,
json_dir: Option<&Path>,
suspended_now: &dyn Fn() -> bool,
) -> JvmThreadsResult {
pub(super) fn dump_tree(probe: &dyn AttachProbe, tree: &[i32], suspended: bool) -> JvmThreadsResult {
let jvm_pid = pick_jvm_pid(tree, |p| probe.has_listener(p))
.or_else(|| pick_jvm_pid(tree, |p| probe.is_application_jvm(p)))
.or_else(|| tree.first().and_then(|&p| u32::try_from(p).ok()).filter(|&p| p > 0));
match jvm_pid {
Some(pid) => dump_threads(probe, pid, suspended, json_dir, suspended_now),
Some(pid) => dump_threads(probe, pid, suspended),
None => jvm(JvmMemoryUnavailable::NoJvmProcess),
}
}
/// Blocking. A JVM a debugger holds suspended cannot open a listener (its Signal Dispatcher is
/// stopped), and one below 17 hangs even with one, so it is asked only when both are ruled out.
/// The JSON dump follows a text dump that succeeded; its failure only sets the note.
pub(crate) fn dump_threads(
probe: &dyn AttachProbe,
pid: u32,
suspended: bool,
json_dir: Option<&Path>,
suspended_now: &dyn Fn() -> bool,
) -> JvmThreadsResult {
pub(crate) fn dump_threads(probe: &dyn AttachProbe, pid: u32, suspended: bool) -> JvmThreadsResult {
if suspended {
if !probe.has_listener(pid) {
return jvm(gone(probe, pid));
@@ -196,8 +149,6 @@ pub(crate) fn dump_threads(
Err(e) => return failure(probe, pid, e),
};
let elapsed_ms = u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX);
let (virtual_json, virtual_note) =
virtual_threads(probe, pid, version.as_ref(), suspended, json_dir, suspended_now);
JvmThreadsResult::Ready {
dump: JvmThreadDump {
text,
@@ -205,40 +156,10 @@ pub(crate) fn dump_threads(
java_version: version.map(|v| v.text).unwrap_or_default(),
taken_while_suspended: suspended,
elapsed_ms,
virtual_json,
virtual_note,
},
}
}
/// The program may have stopped during the text dump, so the suspension is read again.
fn virtual_threads(
probe: &dyn AttachProbe,
pid: u32,
version: Option<&JavaVersion>,
suspended: bool,
json_dir: Option<&Path>,
suspended_now: &dyn Fn() -> bool,
) -> (Option<String>, Option<VirtualThreadsNote>) {
if version.is_none_or(|v| v.major < VIRTUAL_THREADS_MAJOR) {
return (None, None);
}
if suspended || suspended_now() {
return (None, Some(VirtualThreadsNote::WhileSuspended));
}
let Some(dir) = json_dir else {
return (None, Some(VirtualThreadsNote::Failed));
};
match probe.thread_dump_json(pid, dir) {
Ok(json) => (Some(json), None),
Err(AttachError::TooLarge) => (None, Some(VirtualThreadsNote::TooLarge)),
Err(e) => {
tracing::warn!("JSON thread dump of JVM {pid}: {e}");
(None, Some(VirtualThreadsNote::Failed))
}
}
}
fn failure(probe: &dyn AttachProbe, pid: u32, error: AttachError) -> JvmThreadsResult {
let reason = match error {
AttachError::ListenerDidNotStart => JvmThreadsUnavailable::ListenerDidNotStart,
+22 -30
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 {
@@ -1978,27 +1977,20 @@ impl DebugManager {
jvm_memory::session_heap_dump(session, dir, cancel).await
}
/// `Thread.print -l` of the session's JVM, taking the session's class-table turn, and on JDK
/// 21+ the JSON dump written into `json_dir`. A JVM the debugger holds suspended is asked
/// only when it is 17 or later and its listener already runs: otherwise the request would hang
/// until the program resumes.
pub async fn jvm_thread_dump(&self, s: DebugSessionId, json_dir: Option<PathBuf>) -> IdeResult<JvmThreadsResult> {
/// `Thread.print -l` of the session's JVM, taking the session's class-table turn. A JVM the
/// debugger holds suspended is asked only when it is 17 or later and its listener already
/// runs: otherwise the request would hang until the program resumes.
pub async fn jvm_thread_dump(&self, s: DebugSessionId) -> IdeResult<JvmThreadsResult> {
let session = self.session(s)?;
jvm_memory::session_thread_dump(session, json_dir).await
jvm_memory::session_thread_dump(session).await
}
/// `Thread.print -l` of `pid`, the JVM of `run`, when a live session debugs it (a build
/// tool's run started for Debug, Attach to Process): taken as [`Self::jvm_thread_dump`] takes
/// it, under that session's turn and suspension, so a suspended JVM is not asked for the JSON
/// dump either. `None` when no session debugs `pid`.
pub async fn debugged_jvm_thread_dump(
&self,
run: RunId,
pid: u32,
json_dir: Option<PathBuf>,
) -> Option<IdeResult<JvmThreadsResult>> {
/// it, under that session's turn and suspension. `None` when no session debugs `pid`.
pub async fn debugged_jvm_thread_dump(&self, run: RunId, pid: u32) -> Option<IdeResult<JvmThreadsResult>> {
let session = self.jvm_session_of(run, pid)?;
Some(jvm_memory::debugged_run_thread_dump(session, pid, json_dir).await)
Some(jvm_memory::debugged_run_thread_dump(session, pid).await)
}
/// A session attached to `run` first: one whose JVM is not located yet (its attach-time scan
+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)
+2 -2
View File
@@ -3096,7 +3096,7 @@ async fn a_run_dump_goes_through_the_session_attached_to_the_run() {
let pid = jvm.id();
assert_eq!(h.manager.jvm_session_of(RunId(7), pid).map(|s| s.id), Some(id));
assert!(h.manager.jvm_session_of(RunId(8), pid).is_none());
let dump = h.manager.debugged_jvm_thread_dump(RunId(7), pid, None).await.unwrap().unwrap();
let dump = h.manager.debugged_jvm_thread_dump(RunId(7), pid).await.unwrap().unwrap();
let alive = jvm.try_wait().unwrap().is_none();
let _ = jvm.kill();
let _ = jvm.wait();
@@ -3120,7 +3120,7 @@ async fn a_run_jvm_is_found_by_the_session_attached_to_it() {
let id = h.start(cfg).await.unwrap();
assert_eq!(h.manager.jvm_session_of(RunId(1), 4242).map(|s| s.id), Some(id));
assert!(h.manager.jvm_session_of(RunId(1), 4243).is_none());
assert!(h.manager.debugged_jvm_thread_dump(RunId(1), 4243, None).await.is_none());
assert!(h.manager.debugged_jvm_thread_dump(RunId(1), 4243).await.is_none());
}
#[cfg(unix)]
+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?
})
+40 -93
View File
@@ -67,7 +67,7 @@ pub fn schemas(driver: DbDriver, system: bool) -> &'static str {
AND has_schema_privilege(nspname, 'USAGE') ORDER BY 1"
}
DbDriver::Mysql if system => "SELECT schema_name FROM information_schema.schemata ORDER BY 1",
DbDriver::SqlServer if system => "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA ORDER BY 1",
DbDriver::SqlServer if system => "SELECT schema_name FROM information_schema.schemata ORDER BY 1",
DbDriver::Snowflake if system => "SELECT schema_name FROM information_schema.schemata ORDER BY 1",
DbDriver::Snowflake => {
"SELECT schema_name FROM information_schema.schemata WHERE schema_name <> 'INFORMATION_SCHEMA' ORDER BY 1"
@@ -89,8 +89,8 @@ pub fn schemas(driver: DbDriver, system: bool) -> &'static str {
WHERE schema_name NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys') ORDER BY 1"
}
DbDriver::SqlServer => {
"SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA \
WHERE SCHEMA_NAME NOT IN ('sys', 'INFORMATION_SCHEMA', 'guest') ORDER BY 1"
"SELECT schema_name FROM information_schema.schemata \
WHERE schema_name NOT IN ('sys', 'information_schema', 'guest') ORDER BY 1"
}
}
}
@@ -133,8 +133,8 @@ pub fn tables(driver: DbDriver, schema: &str) -> String {
quote_literal(driver, schema)
),
DbDriver::SqlServer => format!(
"SELECT TABLE_NAME, CASE WHEN TABLE_TYPE LIKE '%VIEW%' THEN 'view' ELSE 'table' END \
FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = {} ORDER BY 1",
"SELECT table_name, CASE WHEN table_type LIKE '%VIEW%' THEN 'view' ELSE 'table' END \
FROM information_schema.tables WHERE table_schema = {} ORDER BY 1",
quote_literal(driver, schema)
),
}
@@ -177,14 +177,14 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
ORDER BY ordinal_position"
),
DbDriver::SqlServer => format!(
"SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT, \
CASE WHEN EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc \
JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE k ON k.CONSTRAINT_NAME = tc.CONSTRAINT_NAME \
AND k.TABLE_SCHEMA = tc.TABLE_SCHEMA AND k.TABLE_NAME = tc.TABLE_NAME \
WHERE tc.CONSTRAINT_TYPE = 'PRIMARY KEY' AND tc.TABLE_SCHEMA = {s} \
AND tc.TABLE_NAME = {t} AND k.COLUMN_NAME = c.COLUMN_NAME) THEN 1 ELSE 0 END \
FROM INFORMATION_SCHEMA.COLUMNS c WHERE c.TABLE_SCHEMA = {s} AND c.TABLE_NAME = {t} \
ORDER BY c.ORDINAL_POSITION"
"SELECT column_name, data_type, is_nullable, column_default, \
CASE WHEN EXISTS (SELECT 1 FROM information_schema.table_constraints tc \
JOIN information_schema.key_column_usage k ON k.constraint_name = tc.constraint_name \
AND k.table_schema = tc.table_schema AND k.table_name = tc.table_name \
WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_schema = {s} \
AND tc.table_name = {t} AND k.column_name = c.column_name) THEN 1 ELSE 0 END \
FROM information_schema.columns c WHERE c.table_schema = {s} AND c.table_name = {t} \
ORDER BY c.ordinal_position"
),
DbDriver::Snowflake => format!(
"SELECT column_name, {SNOWFLAKE_TYPE}, is_nullable, column_default, 0 \
@@ -300,18 +300,18 @@ pub fn completion_columns(driver: DbDriver) -> &'static str {
ORDER BY c.table_schema, c.table_name, c.ordinal_position LIMIT 50000"
}
DbDriver::SqlServer => {
"SELECT c.TABLE_SCHEMA, c.TABLE_NAME, CASE WHEN t.TABLE_TYPE LIKE '%VIEW%' THEN 'view' ELSE 'table' END, \
c.COLUMN_NAME, c.DATA_TYPE, c.IS_NULLABLE, \
CASE WHEN EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc \
JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE k ON k.CONSTRAINT_NAME = tc.CONSTRAINT_NAME \
AND k.TABLE_SCHEMA = tc.TABLE_SCHEMA AND k.TABLE_NAME = tc.TABLE_NAME \
WHERE tc.CONSTRAINT_TYPE = 'PRIMARY KEY' AND tc.TABLE_SCHEMA = c.TABLE_SCHEMA \
AND tc.TABLE_NAME = c.TABLE_NAME AND k.COLUMN_NAME = c.COLUMN_NAME) THEN 1 ELSE 0 END, \
CASE WHEN c.COLUMN_DEFAULT IS NOT NULL THEN 1 ELSE 0 END \
FROM INFORMATION_SCHEMA.COLUMNS c JOIN INFORMATION_SCHEMA.TABLES t \
ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME \
WHERE c.TABLE_SCHEMA NOT IN ('sys', 'INFORMATION_SCHEMA') \
ORDER BY c.TABLE_SCHEMA, c.TABLE_NAME, c.ORDINAL_POSITION"
"SELECT c.table_schema, c.table_name, CASE WHEN t.table_type LIKE '%VIEW%' THEN 'view' ELSE 'table' END, \
c.column_name, c.data_type, c.is_nullable, \
CASE WHEN EXISTS (SELECT 1 FROM information_schema.table_constraints tc \
JOIN information_schema.key_column_usage k ON k.constraint_name = tc.constraint_name \
AND k.table_schema = tc.table_schema AND k.table_name = tc.table_name \
WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_schema = c.table_schema \
AND tc.table_name = c.table_name AND k.column_name = c.column_name) THEN 1 ELSE 0 END, \
CASE WHEN c.column_default IS NOT NULL THEN 1 ELSE 0 END \
FROM information_schema.columns c JOIN information_schema.tables t \
ON t.table_schema = c.table_schema AND t.table_name = c.table_name \
WHERE c.table_schema NOT IN ('sys', 'information_schema') \
ORDER BY c.table_schema, c.table_name, c.ordinal_position"
}
DbDriver::Snowflake => {
"SELECT c.table_schema, c.table_name, CASE t.table_type WHEN 'VIEW' THEN 'view' \
@@ -372,12 +372,11 @@ pub fn foreign_keys(driver: DbDriver) -> &'static str {
ORDER BY table_schema, table_name, constraint_name, ordinal_position LIMIT 20000"
}
DbDriver::SqlServer => {
"SELECT OBJECT_SCHEMA_NAME(fk.parent_object_id), OBJECT_NAME(fk.parent_object_id), fk.name, pc.name, \
OBJECT_SCHEMA_NAME(fk.referenced_object_id), OBJECT_NAME(fk.referenced_object_id), rc.name \
FROM sys.foreign_keys fk JOIN sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id \
JOIN sys.columns pc ON pc.object_id = fkc.parent_object_id AND pc.column_id = fkc.parent_column_id \
JOIN sys.columns rc ON rc.object_id = fkc.referenced_object_id AND rc.column_id = fkc.referenced_column_id \
WHERE fk.is_ms_shipped = 0 ORDER BY 1, 2, 3, fkc.constraint_column_id"
"SELECT table_schema, table_name, constraint_name, column_name, \
referenced_table_schema, referenced_table_name, referenced_column_name \
FROM information_schema.key_column_usage WHERE referenced_table_name IS NOT NULL \
AND table_schema NOT IN ('sys', 'information_schema') \
ORDER BY table_schema, table_name, constraint_name, ordinal_position"
}
DbDriver::Oracle => {
"SELECT con.owner, con.table_name, con.constraint_name, col.column_name, \
@@ -411,13 +410,7 @@ pub fn table_foreign_keys(driver: DbDriver, schema: &str, table: &str) -> String
"SELECT table_schema, table_name, constraint_name, column_name, referenced_table_schema, referenced_table_name, referenced_column_name FROM information_schema.key_column_usage WHERE referenced_table_name IS NOT NULL AND table_schema = {s} AND table_name = {t} ORDER BY constraint_name, ordinal_position"
),
DbDriver::SqlServer => format!(
"SELECT OBJECT_SCHEMA_NAME(fk.parent_object_id), OBJECT_NAME(fk.parent_object_id), fk.name, pc.name, \
OBJECT_SCHEMA_NAME(fk.referenced_object_id), OBJECT_NAME(fk.referenced_object_id), rc.name \
FROM sys.foreign_keys fk JOIN sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id \
JOIN sys.columns pc ON pc.object_id = fkc.parent_object_id AND pc.column_id = fkc.parent_column_id \
JOIN sys.columns rc ON rc.object_id = fkc.referenced_object_id AND rc.column_id = fkc.referenced_column_id \
WHERE fk.parent_object_id = OBJECT_ID(N{}) ORDER BY 3, fkc.constraint_column_id",
quote_literal(driver, &qualified(driver, schema, table))
"SELECT table_schema, table_name, constraint_name, column_name, referenced_table_schema, referenced_table_name, referenced_column_name FROM information_schema.key_column_usage WHERE referenced_table_name IS NOT NULL AND table_schema = {s} AND table_name = {t} ORDER BY constraint_name, ordinal_position"
),
DbDriver::Oracle => format!(
"SELECT con.owner, con.table_name, con.constraint_name, col.column_name, rcon.owner, rcon.table_name, rcol.column_name FROM all_constraints con JOIN all_cons_columns col ON col.owner = con.owner AND col.table_name = con.table_name AND col.constraint_name = con.constraint_name JOIN all_constraints rcon ON rcon.owner = con.r_owner AND rcon.constraint_name = con.r_constraint_name JOIN all_cons_columns rcol ON rcol.owner = rcon.owner AND rcol.table_name = rcon.table_name AND rcol.constraint_name = rcon.constraint_name WHERE con.constraint_type = 'R' AND con.owner = {s} AND con.table_name = {t} ORDER BY con.constraint_name, col.position"
@@ -719,8 +712,8 @@ pub fn routines(driver: DbDriver, schema: &str) -> Option<String> {
FROM information_schema.routines r WHERE r.routine_schema = {s} ORDER BY 1"
)),
DbDriver::SqlServer => Some(format!(
"SELECT r.ROUTINE_NAME, lower(r.ROUTINE_TYPE), '', r.DATA_TYPE \
FROM INFORMATION_SCHEMA.ROUTINES r WHERE r.ROUTINE_SCHEMA = {s} ORDER BY 1"
"SELECT r.routine_name, lower(r.routine_type), '', r.data_type \
FROM information_schema.routines r WHERE r.routine_schema = {s} ORDER BY 1"
)),
DbDriver::Snowflake => Some(format!(
"SELECT function_name, 'function', argument_signature, data_type FROM information_schema.functions \
@@ -1026,65 +1019,19 @@ mod tests {
assert_eq!(crate::conn::begin_statement(DbDriver::SqlServer), "BEGIN TRAN");
assert_eq!(
schemas(DbDriver::SqlServer, true),
"SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA ORDER BY 1"
"SELECT schema_name FROM information_schema.schemata ORDER BY 1"
);
assert!(schemas(DbDriver::SqlServer, false).contains("NOT IN ('sys', 'INFORMATION_SCHEMA', 'guest')"));
assert!(schemas(DbDriver::SqlServer, false).contains("NOT IN ('sys', 'information_schema', 'guest')"));
}
#[test]
fn sqlserver_introspection_queries() {
assert!(tables(DbDriver::SqlServer, "dbo").contains("INFORMATION_SCHEMA.TABLES"));
assert!(columns(DbDriver::SqlServer, "dbo", "t").contains("INFORMATION_SCHEMA.COLUMNS"));
assert!(tables(DbDriver::SqlServer, "dbo").contains("information_schema.tables"));
assert!(columns(DbDriver::SqlServer, "dbo", "t").contains("information_schema.columns"));
assert!(indexes(DbDriver::SqlServer, "dbo", "t").contains("sys.indexes"));
assert!(foreign_keys(DbDriver::SqlServer).contains("sys.foreign_key_columns"));
assert!(table_foreign_keys(DbDriver::SqlServer, "dbo", "t").contains("OBJECT_ID(N'[dbo].[t]')"));
assert!(completion_columns(DbDriver::SqlServer).contains("INFORMATION_SCHEMA.COLUMNS"));
}
/// Under a case-sensitive or binary collation, catalog names only resolve as declared:
/// `INFORMATION_SCHEMA` views and their columns in upper case, `sys` views in lower case.
#[test]
fn sqlserver_catalog_names_keep_their_declared_case() {
let d = DbDriver::SqlServer;
let queries = [
schemas(d, true).to_owned(),
schemas(d, false).to_owned(),
tables(d, "dbo"),
columns(d, "dbo", "t"),
indexes(d, "dbo", "t"),
completion_columns(d).to_owned(),
foreign_keys(d).to_owned(),
table_foreign_keys(d, "dbo", "t"),
routines(d, "dbo").unwrap(),
];
const COLUMNS: [&str; 15] = [
"information_schema",
"schema_name",
"table_name",
"table_schema",
"table_type",
"column_name",
"data_type",
"is_nullable",
"column_default",
"constraint_name",
"constraint_type",
"ordinal_position",
"routine_name",
"routine_type",
"routine_schema",
];
for q in queries {
let words: Vec<&str> = q.split(|c: char| !c.is_alphanumeric() && c != '_').collect();
for (i, word) in words.iter().enumerate() {
let catalog = COLUMNS.contains(&word.to_lowercase().as_str())
|| i > 0 && words[i - 1] == "INFORMATION_SCHEMA" && !word.is_empty();
if catalog {
assert_eq!(*word, word.to_uppercase(), "{word} in {q}");
}
}
assert!(!q.contains("referenced_table_name"), "SQL Server has no referenced_* columns: {q}");
}
assert!(foreign_keys(DbDriver::SqlServer).contains("referenced_table_name IS NOT NULL"));
assert!(table_foreign_keys(DbDriver::SqlServer, "dbo", "t").contains("table_schema = 'dbo'"));
assert!(completion_columns(DbDriver::SqlServer).contains("information_schema.columns"));
}
#[test]
-59
View File
@@ -136,62 +136,3 @@ async fn sqlserver_creates_from_a_held_model_and_force_drops_a_held_database() {
assert!(!db.databases("s").await.unwrap().names.contains(&name));
drop(held);
}
/// #5772: a case-sensitive collation resolves catalog names only in their declared case.
#[tokio::test]
async fn sqlserver_introspection_works_under_a_case_sensitive_collation() {
use ide_db::sql;
let Ok(server) = std::env::var("OPENIDEA_TEST_SQLSERVER") else { return };
let parts = server.splitn(4, ':');
let source = |database: &str| DataSource {
driver: DbDriver::SqlServer,
host: parts.clone().next().unwrap().into(),
port: Some(parts.clone().nth(1).unwrap().parse().unwrap()),
user: parts.clone().nth(2).unwrap().into(),
database: database.into(),
ssl: DbSslMode::Disable,
..Default::default()
};
let password = parts.clone().nth(3);
let name = format!("oi_cs_catalog_{}", std::process::id());
let master = Pool::connect(&source("master"), password, None).await.unwrap();
master.rows(&format!("CREATE DATABASE {name} COLLATE Latin1_General_CS_AS"), 1).await.unwrap();
let pool = Pool::connect(&source(&name), password, None).await.unwrap();
pool.rows("CREATE TABLE dbo.Parent (Id int PRIMARY KEY)", 1).await.unwrap();
pool.rows("CREATE TABLE dbo.Child (Id int PRIMARY KEY, ParentId int CONSTRAINT FK_Child_Parent REFERENCES dbo.Parent (Id))", 1)
.await
.unwrap();
pool.rows("CREATE VIEW dbo.Kids AS SELECT Id FROM dbo.Child", 1).await.unwrap();
pool.rows("CREATE PROCEDURE dbo.Touch AS SELECT 1", 1).await.unwrap();
let d = DbDriver::SqlServer;
let cells = |rows: Vec<Vec<Option<String>>>| -> Vec<Vec<String>> {
rows.into_iter().map(|r| r.into_iter().map(Option::unwrap_or_default).collect()).collect()
};
let schemas = cells(pool.rows(sql::schemas(d, false), 100).await.unwrap());
assert!(schemas.contains(&vec!["dbo".to_owned()]));
assert!(!schemas.iter().any(|s| s[0] == "INFORMATION_SCHEMA" || s[0] == "sys"));
assert!(
cells(pool.rows(sql::schemas(d, true), 100).await.unwrap()).contains(&vec!["INFORMATION_SCHEMA".to_owned()])
);
assert_eq!(
cells(pool.rows(&sql::tables(d, "dbo"), 100).await.unwrap()),
[["Child", "table"], ["Kids", "view"], ["Parent", "table"]]
);
assert_eq!(
cells(pool.rows(&sql::columns(d, "dbo", "Child"), 100).await.unwrap())
.iter()
.map(|c| (c[0].as_str(), c[4].as_str()))
.collect::<Vec<_>>(),
[("Id", "1"), ("ParentId", "0")]
);
let fk = ["dbo", "Child", "FK_Child_Parent", "ParentId", "dbo", "Parent", "Id"];
assert_eq!(cells(pool.rows(&sql::table_foreign_keys(d, "dbo", "Child"), 100).await.unwrap()), [fk]);
assert_eq!(cells(pool.rows(sql::foreign_keys(d), 100).await.unwrap()), [fk]);
assert_eq!(cells(pool.rows(sql::completion_columns(d), 100).await.unwrap()).len(), 4);
assert_eq!(cells(pool.rows(&sql::routines(d, "dbo").unwrap(), 100).await.unwrap())[0][..2], ["Touch", "procedure"]);
drop(pool);
master
.rows(&format!("ALTER DATABASE {name} SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE {name}"), 1)
.await
.unwrap();
}
+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");
}
}
}
+21 -201
View File
@@ -3,38 +3,31 @@
//! The daemon speaks JSON-RPC over stdio, one bracketed message per line. After
//! `daemon.connected` it is asked for `device.enable`, which makes it report `device.added` /
//! `device.removed`, and once for `device.getDevices`, whose answer ends the "discovering" state.
//! `emulator.getEmulators` lists what can be started, then and whenever the chooser opens.
//!
//! The daemon keeps running after its stdin closes, so closing the pipe does not end it: on Unix
//! a watcher in its process group ends the group once the IDE is gone, even after a crash. A
//! 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};
use ide_core::event::{FlutterDaemonStatus, FlutterDevice, FlutterDeviceList};
use ide_core::process::{kill_tree, own_group, prepare, terminate_tree};
use ide_core::tool_path::{find_command, search_path_in};
use ide_core::{IdeEvent, SharedSink};
use parking_lot::Mutex;
use serde_json::{Value, json};
use std::collections::{BTreeMap, HashMap, VecDeque};
use std::collections::{BTreeMap, VecDeque};
use std::io::{BufRead, BufReader, Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::Arc;
use std::sync::mpsc;
use std::time::Duration;
const ENABLE: u64 = 1;
const GET_DEVICES: u64 = 2;
const GET_EMULATORS: u64 = 3;
/// `emulator.launch` waits for `xcrun simctl` or similar; past this the daemon is stuck.
const LAUNCH_TIMEOUT: Duration = Duration::from_secs(60);
/// How long the daemon gets to exit on `SIGTERM`.
const KILL_GRACE: Duration = Duration::from_millis(200);
/// Lines of unrecognised output kept to explain a failure.
@@ -46,9 +39,6 @@ enum Message {
Added(FlutterDevice),
Removed(String),
Devices(Vec<FlutterDevice>),
Emulators(Vec<FlutterEmulator>),
/// The answer to a request of ours other than the ones above.
Response(u64, Result<(), String>),
Other,
}
@@ -61,15 +51,9 @@ fn device(value: &Value) -> Option<FlutterDevice> {
category: text("category"),
emulator: value.get("emulator").and_then(Value::as_bool).unwrap_or(false),
unavailable: None,
emulator_id: text("emulatorId"),
})
}
fn emulator(value: &Value) -> Option<FlutterEmulator> {
let text = |key| value.get(key).and_then(Value::as_str).map(str::to_owned);
Some(FlutterEmulator { id: text("id")?, name: text("name")?, platform_type: text("platformType") })
}
/// The messages of one stdout line; `None` for anything outside the protocol (the tool's own
/// chatter, such as waiting for the startup lock).
fn parse_line(line: &str) -> Option<Vec<Message>> {
@@ -90,23 +74,11 @@ fn parse_message(message: &Value) -> Message {
params.get("id").and_then(Value::as_str).map_or(Message::Other, |id| Message::Removed(id.to_owned()))
}
Some(_) => Message::Other,
None => {
let result = message.get("result").and_then(Value::as_array).into_iter().flatten();
match message.get("id").and_then(Value::as_u64) {
Some(ENABLE) | None => Message::Other,
Some(GET_DEVICES) => Message::Devices(result.filter_map(device).collect()),
// A failure (no Android SDK, no Xcode) lists none.
Some(GET_EMULATORS) => Message::Emulators(result.filter_map(emulator).collect()),
Some(id) => Message::Response(
id,
match message.get("error") {
None | Some(Value::Null) => Ok(()),
Some(Value::String(error)) => Err(error.clone()),
Some(error) => Err(error.to_string()),
},
),
}
None if message.get("id").and_then(Value::as_u64) == Some(GET_DEVICES) => {
let result = message.get("result").and_then(Value::as_array);
Message::Devices(result.into_iter().flatten().filter_map(device).collect())
}
None => Message::Other,
}
}
@@ -114,12 +86,6 @@ fn request(id: u64, method: &str) -> String {
format!("{}\n", json!([{ "id": id, "method": method }]))
}
/// The emulators no device runs on.
fn idle_emulators(emulators: &[FlutterEmulator], devices: &BTreeMap<String, FlutterDevice>) -> Vec<FlutterEmulator> {
let running = |e: &FlutterEmulator| devices.values().any(|d| d.emulator_id.as_ref() == Some(&e.id));
emulators.iter().filter(|e| !running(e)).cloned().collect()
}
/// The daemon's devices, plus the Android devices adb sees that Flutter leaves out until they
/// are usable. A daemon Android device's id is its adb serial.
fn merged(daemon: &BTreeMap<String, FlutterDevice>, adb: &[AndroidDevice]) -> Vec<FlutterDevice> {
@@ -131,7 +97,6 @@ fn merged(daemon: &BTreeMap<String, FlutterDevice>, adb: &[AndroidDevice]) -> Ve
category: Some("mobile".into()),
emulator: d.serial.starts_with("emulator-"),
unavailable: Some(d.state.clone()),
emulator_id: None,
}));
let rank = |d: &FlutterDevice| match d.category.as_deref() {
Some("mobile") => 0,
@@ -156,30 +121,15 @@ struct State {
status: FlutterDaemonStatus,
devices: BTreeMap<String, FlutterDevice>,
adb: Vec<AndroidDevice>,
emulators: Vec<FlutterEmulator>,
/// Requests awaiting their answer; dropped with the daemon, which fails them.
pending: HashMap<u64, mpsc::Sender<Result<(), String>>>,
next_id: u64,
}
impl State {
fn list(&self) -> FlutterDeviceList {
FlutterDeviceList {
status: self.status.clone(),
devices: merged(&self.devices, &self.adb),
emulators: idle_emulators(&self.emulators, &self.devices),
}
}
/// Writes `requests` to the daemon; false without one.
fn send(&mut self, requests: &str) -> bool {
let Some(stdin) = self.running.as_mut().and_then(|r| r.stdin.as_mut()) else { return false };
stdin.write_all(requests.as_bytes()).and_then(|()| stdin.flush()).is_ok()
FlutterDeviceList { status: self.status.clone(), devices: merged(&self.devices, &self.adb) }
}
fn shut_down(&mut self) {
self.generation += 1;
self.pending.clear();
if let Some(Running { mut child, stdin }) = self.running.take() {
drop(stdin);
// Off the caller's thread: closing a window must not wait for the grace period.
@@ -191,7 +141,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 +152,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.
@@ -235,57 +181,12 @@ impl FlutterDaemon {
state.list()
}
/// Reads adb again (a device awaiting authorization changes no daemon event) and asks the
/// daemon for its emulators again (one may have been created since).
/// Reads adb again: a device awaiting authorization changes no daemon event.
pub fn refresh(&self) {
let mut state = self.0.state.lock();
if state.status == FlutterDaemonStatus::Ready {
state.send(&request(GET_EMULATORS, "emulator.getEmulators"));
}
let generation = state.generation;
drop(state);
let generation = self.0.state.lock().generation;
refresh_adb(&self.0, generation);
}
/// Starts an emulator the list offers; it shows up as a device once booted. Blocks until the
/// launch is under way. An AVD is started by `ide-android` rather than the daemon, which
/// would make it a child of its process group and end it with the daemon.
pub fn launch_emulator(&self, id: &str) -> Result<(), String> {
let mut state = self.0.state.lock();
let android = state.emulators.iter().any(|e| e.id == id && e.platform_type.as_deref() == Some("android"));
if android {
drop(state);
return ide_android::launch_emulator(id).map_err(|e| e.message);
}
state.next_id = state.next_id.max(GET_EMULATORS) + 1;
let request_id = state.next_id;
let (tx, rx) = mpsc::channel();
state.pending.insert(request_id, tx);
let params = json!({ "emulatorId": id });
let line = format!("{}\n", json!([{ "id": request_id, "method": "emulator.launch", "params": params }]));
if !state.send(&line) {
state.pending.remove(&request_id);
return Err("the Flutter daemon is not running".into());
}
drop(state);
let answer = rx.recv_timeout(LAUNCH_TIMEOUT);
self.0.state.lock().pending.remove(&request_id);
match answer {
Ok(result) => result,
Err(mpsc::RecvTimeoutError::Timeout) => Err("the Flutter daemon did not answer".into()),
Err(mpsc::RecvTimeoutError::Disconnected) => Err("the Flutter daemon exited".into()),
}
}
/// 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();
@@ -293,7 +194,6 @@ impl FlutterDaemon {
state.status = FlutterDaemonStatus::Stopped;
state.devices.clear();
state.adb.clear();
state.emulators.clear();
}
/// Ends the daemon before returning, for a process about to exit.
@@ -311,7 +211,6 @@ fn start(shared: &Arc<Shared>, state: &mut State) {
state.status = FlutterDaemonStatus::Starting;
state.devices.clear();
state.adb.clear();
state.emulators.clear();
let (shared, generation) = (shared.clone(), state.generation);
std::thread::spawn(move || run(&shared, generation));
}
@@ -366,7 +265,6 @@ fn finish(shared: &Shared, generation: u64, status: FlutterDaemonStatus) {
return;
}
let running = state.running.take();
state.pending.clear();
state.status = status;
let list = state.list();
drop(state);
@@ -400,14 +298,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);
};
@@ -464,25 +358,12 @@ fn handle(shared: &Arc<Shared>, generation: u64, message: Message) -> bool {
match message {
Message::Other => return true,
Message::Connected => {
state.send(
&(request(ENABLE, "device.enable")
+ &request(GET_DEVICES, "device.getDevices")
+ &request(GET_EMULATORS, "emulator.getEmulators")),
);
return true;
}
Message::Response(id, result) => {
if let Some(tx) = state.pending.remove(&id) {
let _ = tx.send(result);
if let Some(stdin) = state.running.as_mut().and_then(|r| r.stdin.as_mut()) {
let requests = request(ENABLE, "device.enable") + &request(GET_DEVICES, "device.getDevices");
let _ = stdin.write_all(requests.as_bytes()).and_then(|()| stdin.flush());
}
return true;
}
Message::Emulators(emulators) => {
if state.emulators == emulators {
return true;
}
state.emulators = emulators;
}
Message::Added(device) => {
state.devices.insert(device.id.clone(), device);
}
@@ -514,7 +395,6 @@ mod tests {
category: Some(category.into()),
emulator,
unavailable: None,
emulator_id: None,
}
}
@@ -553,33 +433,6 @@ mod tests {
let Some([Message::Devices(devices)]) = answer.as_deref() else { panic!("{answer:?}") };
assert_eq!((devices[0].id.as_str(), devices[0].category.as_deref()), ("chrome", None));
assert_eq!(parse_line(r#"[{"id":1,"result":null}]"#), Some(vec![Message::Other]));
let emulators = parse_line(
r#"[{"id":3,"result":[{"id":"apple_ios_simulator","name":"iOS Simulator","category":"mobile","platformType":"ios"}]}]"#,
);
let Some([Message::Emulators(emulators)]) = emulators.as_deref() else { panic!("{emulators:?}") };
assert_eq!(
(emulators[0].id.as_str(), emulators[0].platform_type.as_deref()),
("apple_ios_simulator", Some("ios"))
);
assert_eq!(
parse_line(r#"[{"id":3,"error":"Unable to find Android SDK","trace":""}]"#),
Some(vec![Message::Emulators(vec![])])
);
assert_eq!(parse_line(r#"[{"id":7,"result":null}]"#), Some(vec![Message::Response(7, Ok(()))]));
assert_eq!(
parse_line(r#"[{"id":7,"error":"emulator 'x' not found","trace":"..."}]"#),
Some(vec![Message::Response(7, Err("emulator 'x' not found".into()))])
);
}
#[test]
fn offers_only_the_emulators_no_device_runs_on() {
let emulator = |id: &str| FlutterEmulator { id: id.into(), name: id.into(), platform_type: None };
let mut pixel = dev("emulator-5554", "Pixel", "mobile", true);
pixel.emulator_id = Some("Pixel_9".into());
let devices: BTreeMap<_, _> = [(pixel.id.clone(), pixel)].into_iter().collect();
let idle = idle_emulators(&[emulator("Pixel_9"), emulator("apple_ios_simulator")], &devices);
assert_eq!(idle, [emulator("apple_ios_simulator")]);
}
#[test]
@@ -645,9 +498,8 @@ mod tests {
echo $$ > pid
echo 'Waiting for another flutter command to release the startup lock...'
echo '[{"event":"daemon.connected","params":{"version":"0.6.1","pid":1}}]'
read enable; read get; read emulators; echo "$enable$get$emulators" > requests
read enable; read get; echo "$enable$get" > requests
echo '[{"id":1,"result":null}]'
echo '[{"id":3,"result":[{"id":"apple_ios_simulator","name":"iOS Simulator","category":"mobile","platformType":"ios"}]}]'
echo '[{"id":2,"result":[{"id":"macos","name":"macOS","category":"desktop","emulator":false}]}]'
echo '[{"event":"device.added","params":{"id":"chrome","name":"Chrome","category":"web","emulator":false}}]'
echo '[{"event":"device.removed","params":{"id":"macos","name":"macOS"}}]'
@@ -666,8 +518,6 @@ cat > /dev/null
});
let requests = std::fs::read_to_string(dir.path().join("requests")).unwrap();
assert!(requests.contains("device.enable") && requests.contains("device.getDevices"), "{requests}");
assert!(requests.contains("emulator.getEmulators"), "{requests}");
assert_eq!(daemon.devices().emulators[0].name, "iOS Simulator");
assert!(lists.0.lock().iter().any(|l| l.devices.iter().any(|d| d.id == "macos")));
let pid = std::fs::read_to_string(dir.path().join("pid")).unwrap();
@@ -679,36 +529,6 @@ cat > /dev/null
assert_eq!(daemon.0.state.lock().status, FlutterDaemonStatus::Stopped);
}
#[test]
fn launches_an_emulator_through_the_daemon_and_reports_its_error() {
let dir = tempfile::tempdir().unwrap();
let script = r#"
echo '[{"event":"daemon.connected","params":{"version":"0.6.1","pid":1}}]'
read enable; read get; read emulators
echo '[{"id":2,"result":[]}]'
echo '[{"id":3,"result":[{"id":"apple_ios_simulator","name":"iOS Simulator","platformType":"ios"}]}]'
read launch; echo "$launch" > launch
echo '[{"id":4,"result":null}]'
read launch
echo '[{"id":5,"error":"Unable to run Simulator: xcrun not found","trace":""}]'
cat > /dev/null
"#;
let (daemon, _lists) = daemon(dir.path(), script);
daemon.devices();
wait_for("the emulators", || !daemon.devices().emulators.is_empty());
assert_eq!(daemon.launch_emulator("apple_ios_simulator"), Ok(()));
let launch = std::fs::read_to_string(dir.path().join("launch")).unwrap();
let launch: Value = serde_json::from_str(&launch).unwrap();
assert_eq!(launch[0]["method"], "emulator.launch");
assert_eq!(launch[0]["params"], json!({ "emulatorId": "apple_ios_simulator" }));
assert_eq!(
daemon.launch_emulator("apple_ios_simulator"),
Err("Unable to run Simulator: xcrun not found".into())
);
daemon.stop();
assert_eq!(daemon.launch_emulator("apple_ios_simulator"), Err("the Flutter daemon is not running".into()));
}
#[test]
fn the_daemon_does_not_outlive_the_ide() {
let dir = tempfile::tempdir().unwrap();
-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"));
-5
View File
@@ -190,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(),
@@ -401,7 +399,6 @@ impl Host {
project.agents.shutdown();
project.flutter.stop();
project.devtools.stop();
project.widget_preview.stop();
project.notebooks.stop_admission();
// 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
@@ -531,7 +528,6 @@ impl Host {
for project in self.projects() {
project.flutter.kill();
project.devtools.kill();
project.widget_preview.kill();
}
}
@@ -574,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
@@ -515,7 +515,6 @@ async fn resolve_jvm_application(
test == Some(true),
policy,
&cancel,
None,
)
.await?;
use ide_lsp::jdtls::JavaBuildStatus;
+2 -9
View File
@@ -360,17 +360,10 @@ pub async fn agent_fork(host: &Host, window: &str, task: String, turns: Option<u
}
/// Drops the task's turns after its first `turns`; returns the message of the first dropped one.
/// With `files`, the files those turns changed go back as they were before them.
#[command(trust = trusted)]
pub async fn agent_rollback(
host: &Host,
window: &str,
task: String,
turns: u32,
files: bool,
) -> IdeResult<Option<AgentPrompt>> {
pub async fn agent_rollback(host: &Host, window: &str, task: String, turns: u32) -> IdeResult<Option<AgentPrompt>> {
host.require_trust(window)?;
host.project(window)?.agents.rollback(&task, turns, files).await
host.project(window)?.agents.rollback(&task, turns).await
}
/// Checks the selected installation without modifying it.
+2 -86
View File
@@ -114,12 +114,6 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
extra["__adapterJavaHome"] = serde_json::json!(runtime.home);
config.extra_json = Some(extra.to_string());
}
if finds_java_sources(&config)
&& let Ok(project) = host.project(window)
{
let roots = host.blocking(move || Ok(java_source_roots(&project))).await?;
config = add_java_source_paths(config, &roots);
}
let root = config.cwd.clone().map(PathBuf::from).unwrap_or_default();
let mut ruby_tools = Vec::new();
if config.adapter == "rdbg" && config.request == "launch" {
@@ -314,46 +308,6 @@ fn start_java_attach_listener(mut config: LaunchConfig, windows: bool) -> Launch
config
}
/// The project's source and test roots, as the IDE detects them (no Maven / Gradle import needed).
fn java_source_roots(project: &crate::project::Project) -> Vec<PathBuf> {
use ide_workspace::roots::RootKind;
project
.roots()
.roots
.iter()
.filter(|r| matches!(r.kind, RootKind::Source | RootKind::Test))
.map(|r| project.root.join(&r.path))
.filter(|p| p.is_dir())
.collect()
}
/// Debuggers that look a frame's source up in `sourcePaths` when their own model has no file:
/// java-debug after jdtls (which has not imported a project whose Maven sync failed), and
/// java-analyzer after the module it debugs (whose sibling modules it does not load).
fn finds_java_sources(config: &LaunchConfig) -> bool {
matches!(config.adapter.as_str(), "java-debug" | ide_dap::adapter::JAVA_ANALYZER)
}
/// Without a file for the stopped frame the editor cannot follow the execution point, so Java
/// sessions get every source root of the project. The user's own list wins.
fn add_java_source_paths(mut config: LaunchConfig, roots: &[PathBuf]) -> LaunchConfig {
if !finds_java_sources(&config) || roots.is_empty() {
return config;
}
let mut extra = match config.extra_json.as_deref().map(serde_json::from_str) {
None => serde_json::Map::new(),
Some(Ok(serde_json::Value::Object(extra))) => extra,
Some(_) => return config,
};
if extra.get("sourcePaths").is_some_and(|v| !v.is_null()) {
return config;
}
let paths: Vec<String> = roots.iter().map(|r| r.to_string_lossy().into_owned()).collect();
extra.insert("sourcePaths".into(), paths.into());
config.extra_json = Some(serde_json::Value::Object(extra).to_string());
config
}
/// A JVM launched by java-debug writes what java-debug decodes its output as
/// (see [`ide_core::output_encoding::java_debug_vm_args`]).
fn match_java_debug_encoding(mut config: LaunchConfig, windows: bool) -> LaunchConfig {
@@ -717,21 +671,11 @@ pub async fn debug_jvm_memory_classes(
host.debugger.jvm_memory_classes(session).await
}
/// A `Thread.print -l` of the debuggee JVM (with the JSON dump on JDK 21+), or why it cannot be
/// taken.
/// A `Thread.print -l` of the debuggee JVM, or why it cannot be taken.
#[command(trust = trusted)]
pub async fn debug_jvm_thread_dump(host: &Host, window: &str, session: DebugSessionId) -> IdeResult<JvmThreadsResult> {
host.require_trust(window)?;
let heap_root = host.heap.root().to_path_buf();
let dir = host.blocking(move || Ok(super::thread_dump::json_dir(&heap_root))).await?;
let result = host.debugger.jvm_thread_dump(session, dir.clone()).await;
let _ = host
.blocking(move || {
super::thread_dump::discard_json_dir(dir);
Ok(())
})
.await;
result
host.debugger.jvm_thread_dump(session).await
}
/// Up to `limit` live instances of the class in the stopped JVM.
@@ -793,34 +737,6 @@ mod tests {
serde_json::from_str::<serde_json::Value>(config.extra_json.as_deref().unwrap()).unwrap()["vmArgs"].clone()
}
#[test]
fn java_debug_sessions_look_up_sources_in_project_roots() {
let roots = [PathBuf::from("/p/src/main/java"), PathBuf::from("/p/src/test/java")];
let source_paths = |config: &LaunchConfig| {
serde_json::from_str::<serde_json::Value>(config.extra_json.as_deref().unwrap()).unwrap()["sourcePaths"]
.clone()
};
for adapter in ["java-debug", ide_dap::adapter::JAVA_ANALYZER] {
for request in ["launch", "attach"] {
let config = add_java_source_paths(launch(adapter, request, serde_json::json!({"port": 5005})), &roots);
assert_eq!(source_paths(&config), serde_json::json!(["/p/src/main/java", "/p/src/test/java"]));
}
}
let mut bare = launch("java-debug", "attach", serde_json::json!({}));
bare.extra_json = None;
assert_eq!(
source_paths(&add_java_source_paths(bare, &roots)),
serde_json::json!(["/p/src/main/java", "/p/src/test/java"])
);
let own = launch("java-debug", "launch", serde_json::json!({"sourcePaths": ["/elsewhere"]}));
assert_eq!(source_paths(&add_java_source_paths(own, &roots)), serde_json::json!(["/elsewhere"]));
let other = launch("debugpy", "launch", serde_json::json!({}));
assert_eq!(add_java_source_paths(other.clone(), &roots).extra_json, other.extra_json);
let none = launch("java-debug", "launch", serde_json::json!({}));
assert_eq!(add_java_source_paths(none.clone(), &[]).extra_json, none.extra_json);
}
#[test]
fn java_debug_launches_on_windows_write_utf8() {
let extra =
+2 -29
View File
@@ -25,42 +25,15 @@ pub fn flutter_daemon_restart(host: &Host, window: &str) -> IdeResult<FlutterDev
Ok(host.project(window)?.flutter.restart())
}
/// Starts an emulator from [`FlutterDeviceList::emulators`]. Returns once the launch is under way: the device follows as `IdeEvent::FlutterDevices`.
#[command(trust = trusted)]
pub async fn flutter_emulator_launch(host: &Host, window: &str, id: String) -> IdeResult<()> {
let project = host.project(window)?;
tokio::task::spawn_blocking(move || project.flutter.launch_emulator(&id))
.await
.map_err(|e| IdeError::internal(e.to_string()))?
.map_err(IdeError::unavailable)
}
/// The address of the project's DevTools server, started on first use. A server that failed or
/// exited is only started again by the next request.
#[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);
ide_command::domain!(flutter: flutter_devices, flutter_devices_refresh, flutter_daemon_restart, flutter_devtools_url);
+9 -196
View File
@@ -4,11 +4,9 @@ pub(crate) mod cache;
use crate::Host;
use ide_command::command;
use super::Channel;
use super::build::{load, with_profiles, workspace};
use cache::LaunchEvents;
use ide_build::BuildModel;
use ide_build::compile::{self, BuildEvent};
use ide_build::compile;
use ide_core::error::ErrorKind;
use ide_core::settings::Settings;
use ide_core::{CancellationToken, IdeError, IdeResult, RequestId};
@@ -20,8 +18,6 @@ use std::path::{Path, PathBuf};
/// Builds according to `policy`, then resolves the runtime (or test)
/// classpath and the JDK of the module at `module` (absolute, or relative to the project root).
/// 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.
#[command(trust = trusted)]
pub async fn java_resolve_launch(
host: &Host,
@@ -30,16 +26,12 @@ pub async fn java_resolve_launch(
test: bool,
policy: BuildPolicy,
request: RequestId,
on_event: Channel<BuildEvent>,
) -> IdeResult<JavaLaunchInfo> {
// Resources a Gradle build filters or renames are processed by Gradle, replacing the language
// server's plain copies.
host.require_trust(window)?;
let cancel = host.begin_project_request(window, request);
let events: LaunchEvents = std::sync::Arc::new(move |event| {
let _ = on_event.send(event);
});
let result = resolve_launch(host, window, module, test, policy, &cancel, Some(events)).await;
let result = resolve_launch(host, window, module, test, policy, &cancel).await;
host.end_request(request);
result
}
@@ -51,15 +43,8 @@ pub(crate) async fn resolve_launch(
test: bool,
policy: BuildPolicy,
cancel: &CancellationToken,
events: Option<LaunchEvents>,
) -> IdeResult<JavaLaunchInfo> {
let started = std::time::Instant::now();
let progress = |message: &str| {
if let Some(events) = &events {
events(BuildEvent::Progress { message: message.to_owned(), fraction: None });
}
};
progress("Resolving the module");
let project = host.project(window)?;
let module = ide_core::project_roots::resolve(&project.root, &module);
let scope = {
@@ -69,11 +54,11 @@ pub(crate) async fn resolve_launch(
.map_err(|e| IdeError::internal(e.to_string()))??
};
if !project.lsp.java_served_by_jdtls(&module) {
return resolve_launch_without_jdtls(host, &project, module, scope, test, policy, cancel, events).await;
return resolve_launch_without_jdtls(host, &project, module, scope, test, policy, cancel).await;
}
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 waiting = launches.waiting.add(module.clone(), test, policy);
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;
@@ -105,9 +90,6 @@ pub(crate) async fn resolve_launch(
};
let mut external_build =
if delegated { Some(project.lsp.java_external_build(&module, cancel).await?) } else { None };
if build && !delegated {
progress("Compiling with the Java language server");
}
let mut info = project.lsp.java_launch(&module, test, build && !delegated, full, delegated, cancel).await?;
if info.errors.iter().any(|e| processor_recreated_a_file(&e.message)) {
if build && !delegated && is_maven {
@@ -136,11 +118,6 @@ pub(crate) async fn resolve_launch(
tokio::task::spawn_blocking(move || {
let _external_build = external_build;
let (root, cache, settings) = (&scope.root, &scope.cache, &scope.settings);
let on_event = |event: BuildEvent| {
if let Some(events) = &events {
events(event);
}
};
let local_repo = ide_sdk::apply::maven_local_repository(root, settings);
// Module outputs the launch runs from a snapshot of: the originals must not come back.
let mut snapshotted = Vec::new();
@@ -153,7 +130,7 @@ pub(crate) async fn resolve_launch(
root,
&model,
&module,
cache::BuildOptions { test, policy, rebuild_on_jdt_errors, members, events: events.clone() },
cache::BuildOptions { test, policy, rebuild_on_jdt_errors, members },
local_repo.clone(),
&cancel,
)?;
@@ -163,7 +140,7 @@ pub(crate) async fn resolve_launch(
snapshotted = outputs.originals;
copies
} else if external {
let built = compile::build_for_launch(root, &model, &module, test, build_kind, &cancel, &on_event)?;
let built = compile::build_for_launch(root, &model, &module, test, build_kind, &cancel)?;
if let Some(failure) = built.failure {
if policy != BuildPolicy::MakeAndContinueOnErrors {
return Err(IdeError::internal(failure));
@@ -177,7 +154,6 @@ pub(crate) async fn resolve_launch(
};
let mut class_paths: Vec<String> = built.iter().map(|p| p.to_string_lossy().into_owned()).collect();
if delegated {
on_event(BuildEvent::Progress { message: "Resolving the classpath".into(), fraction: None });
// m2e runs inside jdtls on the server JDK and can resolve a different
// Maven profile/classifier than the module build. Ask the same Maven
// process that built the module for its runtime/test dependencies.
@@ -227,7 +203,6 @@ fn is_maven_module(root: &Path, model: &BuildModel, module: &Path) -> bool {
/// 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)]
async fn resolve_launch_without_jdtls(
host: &Host,
project: &std::sync::Arc<crate::Project>,
@@ -236,24 +211,18 @@ async fn resolve_launch_without_jdtls(
test: bool,
policy: BuildPolicy,
cancel: &CancellationToken,
events: Option<LaunchEvents>,
) -> IdeResult<JavaLaunchInfo> {
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) = {
let (scope, module, cancel, events) = (scope.clone(), module.clone(), cancel.clone(), events.clone());
let (scope, module, cancel) = (scope.clone(), module.clone(), cancel.clone());
tokio::task::spawn_blocking(move || {
let model = load_launch_model(&scope);
let on_event = |event: BuildEvent| {
if let Some(events) = &events {
events(event);
}
};
let built = if policy == BuildPolicy::NoBuild {
None
} else {
Some(compile::build_for_launch(&scope.root, &model, &module, test, kind, &cancel, &on_event))
Some(compile::build_for_launch(&scope.root, &model, &module, test, kind, &cancel))
};
(model, built)
})
@@ -285,9 +254,6 @@ async fn resolve_launch_without_jdtls(
}
}
let build_ms = started.elapsed().as_millis();
if let Some(events) = &events {
events(BuildEvent::Progress { message: "Resolving the classpath".into(), fraction: None });
}
let from_server = project.lsp.java_server_classpath(&module, test, cancel).await?;
let data_dir = host.local_data_dir.clone();
let cancel = cancel.clone();
@@ -508,7 +474,6 @@ async fn build_members(
members.push(cache::Member {
module: launch.module.clone(),
rebuild_on_jdt_errors: rebuild_on_jdt_errors(launch.policy, prefer_maven, errors),
events: launch.events.clone(),
});
}
Ok(members)
@@ -681,129 +646,6 @@ pub async fn java_build_workspace(
result
}
/// The JVM of OpenIDEA's JUnit runner for the module at `module`, given its resolved test classpath:
/// the classpath with the runner and `junit-platform-launcher` of the engine's version (unless the
/// classpath has one; from the engine's repository, else downloaded once from Maven Central), and,
/// for a Maven module, what its Surefire configuration gives the forked test JVM.
#[command(trust = trusted)]
pub async fn java_junit_runner(
host: &Host,
window: &str,
module: PathBuf,
class_paths: Vec<String>,
) -> IdeResult<JunitLaunch> {
host.require_trust(window)?;
let project = host.project(window)?;
let module = ide_core::project_roots::resolve(&project.root, &module);
let data_dir = host.local_data_dir.clone();
tokio::task::spawn_blocking(move || {
let scope = workspace::scope_for(&project, &module)?;
let model = load_launch_model(&scope);
let surefire = model
.maven
.as_ref()
.and_then(|maven| ide_build::surefire::surefire_config(&scope.root, &scope.cache, maven, &module))
.unwrap_or_default();
let runner = ide_sdk::java::junit_runner_jar(&data_dir)
.ok_or_else(|| IdeError::internal("Cannot install the JUnit runner"))?;
let launcher = match ide_sdk::java::junit_launcher(&class_paths) {
ide_sdk::java::JunitLauncher::OnClasspath => None,
ide_sdk::java::JunitLauncher::Found(path) => Some(path),
ide_sdk::java::JunitLauncher::Missing(version) => Some(download_junit_launcher(&data_dir, &version)?),
ide_sdk::java::JunitLauncher::NoPlatform => {
return Err(IdeError::unavailable(
"No JUnit Platform (junit-platform-engine) on the test classpath. To run these tests through \
Maven, set Settings › Build Tools › Maven › Run tests using to Maven.",
));
}
};
Ok(junit_launch(&module, class_paths, surefire, [Some(runner), launcher].into_iter().flatten()))
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
}
/// The test JVM of OpenIDEA's JUnit runner.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize, specta::Type)]
#[serde(rename_all = "camelCase")]
pub struct JunitLaunch {
pub class_paths: Vec<String>,
/// Surefire's `argLine`, then its system properties as `-Dkey=value`.
pub vm_args: Vec<String>,
pub env: std::collections::BTreeMap<String, String>,
pub working_directory: Option<String>,
/// The Surefire settings that were applied (`argLine`, `systemPropertyVariables`…), for the console.
pub surefire: Vec<String>,
}
fn junit_launch(
module: &Path,
class_paths: Vec<String>,
surefire: ide_build::surefire::SurefireConfig,
runner: impl Iterator<Item = PathBuf>,
) -> JunitLaunch {
let mut applied = Vec::new();
let mut note = |used: bool, name: &str| {
if used {
applied.push(name.to_owned());
}
};
note(!surefire.arg_line.is_empty(), "argLine");
note(!surefire.system_properties.is_empty(), "systemPropertyVariables");
note(!surefire.environment.is_empty(), "environmentVariables");
note(surefire.working_directory.is_some(), "workingDirectory");
note(!surefire.additional_classpath.is_empty(), "additionalClasspathElements");
note(!surefire.classpath_excludes.is_empty(), "classpathDependencyExcludes");
// `group:artifact` in a Maven repository (`g/r/p/artifact/…`) or the Gradle cache (`g.r.p/artifact/…`).
let excluded = |path: &str| {
let path = path.replace('\\', "/");
surefire.classpath_excludes.iter().any(|e| {
e.split_once(':').is_some_and(|(group, artifact)| {
path.contains(&format!("/{}/{artifact}/", group.replace('.', "/")))
|| path.contains(&format!("/{group}/{artifact}/"))
})
})
};
let mut class_paths: Vec<String> = class_paths.into_iter().filter(|p| !excluded(p)).collect();
class_paths.extend(surefire.additional_classpath);
class_paths.extend(runner.map(|p| p.to_string_lossy().into_owned()));
let mut vm_args = surefire.arg_line;
vm_args.extend(surefire.system_properties.into_iter().map(|(k, v)| format!("-D{k}={v}")));
JunitLaunch {
class_paths,
vm_args,
env: surefire.environment,
working_directory: surefire.working_directory.map(|d| module.join(d).to_string_lossy().into_owned()),
surefire: applied,
}
}
fn download_junit_launcher(data_dir: &Path, version: &str) -> IdeResult<PathBuf> {
if version.is_empty() || !version.chars().all(|c| c.is_ascii_alphanumeric() || "._-".contains(c)) {
return Err(IdeError::invalid(format!("Unexpected JUnit Platform version '{version}'")));
}
let name = format!("junit-platform-launcher-{version}.jar");
let dest = data_dir.join("junit").join(&name);
if dest.is_file() {
return Ok(dest);
}
std::fs::create_dir_all(dest.parent().expect("has a parent"))?;
let url = format!("https://repo1.maven.org/maven2/org/junit/platform/junit-platform-launcher/{version}/{name}");
let partial = dest.with_extension("jar.part");
// ponytail: unverified like the Lombok download (Central publishes SHA-1 only); HTTPS from Central.
let fetched = ide_tools::Http::new(&ide_core::tool_path::search_path())
.map(ide_tools::Http::https_only)
.and_then(|http| http.download(&url, &partial, None, &CancellationToken::new(), &|_| {}))
.and_then(|()| Ok(std::fs::rename(&partial, &dest)?));
fetched.map(|()| dest).map_err(|e| {
IdeError::unavailable(format!(
"Cannot download {name} from Maven Central ({}). Add org.junit.platform:junit-platform-launcher to the \
test dependencies, or set Settings › Build Tools › Maven › Run tests using to Maven.",
e.message
))
})
}
/// An annotation processor's error for writing a file this build already wrote (JDT's
/// `IdeFilerImpl`: "Source file already created", javac's Filer: "Attempt to recreate a file").
fn processor_recreated_a_file(message: &str) -> bool {
@@ -821,35 +663,6 @@ fn drop_processor_recreate_errors(info: &mut JavaLaunchInfo) {
mod tests {
use super::*;
#[test]
fn junit_launch_applies_the_surefire_configuration() {
let surefire = ide_build::surefire::SurefireConfig {
arg_line: vec!["-Xmx1g".into()],
system_properties: [("openidea.fail".to_owned(), "true".to_owned())].into(),
environment: [("TZ".to_owned(), "UTC".to_owned())].into(),
working_directory: Some("work".into()),
additional_classpath: vec!["/extra".into()],
classpath_excludes: vec!["org.slf4j:slf4j-simple".into(), "com.acme:gone".into()],
};
let classpath = vec![
"/m/target/test-classes".into(),
"/m2/org/slf4j/slf4j-simple/2.0/slf4j-simple-2.0.jar".into(),
"/gradle/files-2.1/com.acme/gone/1/abc/gone-1.jar".into(),
"/m2/org/slf4j/slf4j-api/2.0/slf4j-api-2.0.jar".into(),
];
let launch = junit_launch(Path::new("/m"), classpath, surefire, [PathBuf::from("/runner.jar")].into_iter());
assert_eq!(
launch.class_paths,
["/m/target/test-classes", "/m2/org/slf4j/slf4j-api/2.0/slf4j-api-2.0.jar", "/extra", "/runner.jar"]
);
assert_eq!(launch.vm_args, ["-Xmx1g", "-Dopenidea.fail=true"]);
assert_eq!(launch.env["TZ"], "UTC");
assert_eq!(launch.working_directory.as_deref(), Path::new("/m").join("work").to_str());
assert_eq!(launch.surefire.len(), 6);
let plain = junit_launch(Path::new("/m"), vec![], Default::default(), std::iter::empty());
assert!(plain.surefire.is_empty() && plain.vm_args.is_empty() && plain.working_directory.is_none());
}
fn fake_jdk(dir: &Path, version: Option<&str>) -> PathBuf {
let bin = dir.join("bin");
std::fs::create_dir_all(&bin).unwrap();
@@ -1133,4 +946,4 @@ mod tests {
}
}
ide_command::domain!(java: java_build_workspace, java_debug_adapter, java_debug_server, java_junit_runner, java_resolve_launch);
ide_command::domain!(java: java_build_workspace, java_debug_adapter, java_debug_server, java_resolve_launch);
+19 -61
View File
@@ -1,5 +1,5 @@
//! Immutable Maven outputs retained in the project cache, including across close/reopen.
use ide_build::compile::{self, BuildEvent, LaunchFingerprint};
use ide_build::compile::{self, LaunchFingerprint};
use ide_core::{CancellationToken, IdeError, IdeResult};
use ide_run::BuildPolicy;
use parking_lot::Mutex;
@@ -131,10 +131,6 @@ pub(super) fn has_record(root: &Path, cache: &Path, module: &Path) -> bool {
[false, true].into_iter().any(|test| record_path(root, cache, module, test).is_some_and(|record| record.is_file()))
}
/// Where the build of a launch streams its console, messages and progress: the run
/// console, the status bar and the Build tool window of the launch's request.
pub(in crate::ops) type LaunchEvents = Arc<dyn Fn(BuildEvent) + Send + Sync>;
#[derive(Default)]
pub(super) struct BuildOptions {
pub test: bool,
@@ -146,15 +142,13 @@ pub(super) struct BuildOptions {
/// together, #3971): their modules join this Maven run, and their launches then reuse
/// the snapshots recorded here instead of running Maven again.
pub members: Vec<Member>,
/// The launch's own events; members that join the build get them too.
pub events: Option<LaunchEvents>,
}
/// A launch module joining another launch's build; see [`BuildOptions::members`].
#[derive(Debug)]
pub(super) struct Member {
pub module: PathBuf,
pub rebuild_on_jdt_errors: bool,
pub events: Option<LaunchEvents>,
}
/// Launches share a build only within the same workspace project's cache.
@@ -186,12 +180,11 @@ impl Sessions {
#[derive(Default)]
pub(crate) struct Waiting(Arc<Mutex<Vec<Arc<WaitingLaunch>>>>);
#[derive(Debug)]
pub(super) struct WaitingLaunch {
pub module: PathBuf,
pub test: bool,
pub policy: BuildPolicy,
/// The launch's build events, for a build it joins.
pub events: Option<LaunchEvents>,
}
/// Leaves [`Waiting`] when dropped.
@@ -201,14 +194,8 @@ pub(super) struct WaitingGuard {
}
impl Waiting {
pub(super) fn add(
&self,
module: PathBuf,
test: bool,
policy: BuildPolicy,
events: Option<LaunchEvents>,
) -> WaitingGuard {
let launch = Arc::new(WaitingLaunch { module, test, policy, events });
pub(super) fn add(&self, module: PathBuf, test: bool, policy: BuildPolicy) -> WaitingGuard {
let launch = Arc::new(WaitingLaunch { module, test, policy });
self.0.lock().push(launch.clone());
WaitingGuard { all: self.0.clone(), launch }
}
@@ -279,7 +266,7 @@ impl Session {
cancel: &CancellationToken,
) -> IdeResult<Outputs> {
self.initialize();
let BuildOptions { test, policy, rebuild_on_jdt_errors, members, events } = options;
let BuildOptions { test, policy, rebuild_on_jdt_errors, members } = options;
let mut lead = match self.prepare(root, model, module, test, policy, &local_repo, cancel)? {
Ok(outputs) => return Ok(outputs),
Err(pending) => pending,
@@ -297,13 +284,11 @@ impl Session {
let policy = if rebuild_on_jdt_errors { BuildPolicy::Rebuild } else { policy };
let mut joined = Vec::new();
let mut rebuild = policy == BuildPolicy::Rebuild;
let mut sinks: Vec<LaunchEvents> = events.into_iter().collect();
for member in members {
if let Err(pending) =
self.prepare(root, model, &member.module, test, BuildPolicy::Make, &local_repo, cancel)?
{
rebuild |= member.rebuild_on_jdt_errors;
sinks.extend(member.events);
joined.push(pending);
}
}
@@ -313,13 +298,7 @@ impl Session {
tracing::info!(?modules, "Building the launch modules in one Maven run");
}
let kind = if rebuild { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
// Every launch waiting for this build follows it.
let on_event = |event: BuildEvent| {
for sink in &sinks {
sink(event.clone());
}
};
let mut built = compile::build_for_launches(root, model, &modules, test, kind, cancel, &on_event)?.into_iter();
let mut built = compile::build_for_launches(root, model, &modules, test, kind, cancel)?.into_iter();
let lead_built = built.next().unwrap();
for (pending, built) in joined.into_iter().zip(built) {
match built.failure {
@@ -669,31 +648,10 @@ mod tests {
let mut session = Session::new(root.join("cache"));
let (a, b) = (root.join("a"), root.join("b"));
let with = |rebuild_on_jdt_errors: bool| BuildOptions {
members: vec![Member { module: b.clone(), rebuild_on_jdt_errors, events: None }],
members: vec![Member { module: b.clone(), rebuild_on_jdt_errors }],
..Default::default()
};
// The lead's and the member's launches both follow the shared build.
let seen = Arc::new(Mutex::new(Vec::new()));
let sink = |name: &'static str| -> LaunchEvents {
let seen = seen.clone();
Arc::new(move |event| {
if let BuildEvent::Step { command, .. } = event {
seen.lock().push(format!("{name}: {command}"));
}
})
};
let options = BuildOptions {
members: vec![Member { module: b.clone(), rebuild_on_jdt_errors: false, events: Some(sink("b")) }],
events: Some(sink("a")),
..Default::default()
};
let lead = session.build(root, &model, &a, options, None, &cancel).unwrap();
let seen = seen.lock().clone();
assert_eq!(seen.len(), 2, "{seen:?}");
assert!(
seen[0].starts_with("a: ") && seen[1].starts_with("b: ") && seen[0].contains("-pl a,b -am"),
"{seen:?}"
);
let lead = session.build(root, &model, &a, with(false), None, &cancel).unwrap();
assert_eq!(fs::read_to_string(lead.snapshot.join("0/Main.class")).unwrap(), "a");
assert_eq!(fs::read_to_string(lead.snapshot.join("1/Main.class")).unwrap(), "lib");
// b's own launch runs from the snapshot the shared build recorded for it.
@@ -732,17 +690,17 @@ mod tests {
let root = dir.path();
let model = reactor_fixture(root);
let waiting = Waiting::default();
let lead = waiting.add(root.join("a"), false, BuildPolicy::Automatic, None);
let lead = waiting.add(root.join("a"), false, BuildPolicy::Automatic);
let _guards = [
waiting.add(root.join("b"), false, BuildPolicy::Make, None),
waiting.add(root.join("lib"), false, BuildPolicy::Automatic, None),
waiting.add(root.join("b"), false, BuildPolicy::Automatic, None),
waiting.add(root.join("a"), false, BuildPolicy::Automatic, None),
waiting.add(root.join("lib"), true, BuildPolicy::Automatic, None),
waiting.add(root.join("lib"), false, BuildPolicy::Rebuild, None),
waiting.add(root.join("lib"), false, BuildPolicy::MakeAndContinueOnErrors, None),
waiting.add(root.join("lib"), false, BuildPolicy::NoBuild, None),
waiting.add(root.join("other"), false, BuildPolicy::Automatic, None),
waiting.add(root.join("b"), false, BuildPolicy::Make),
waiting.add(root.join("lib"), false, BuildPolicy::Automatic),
waiting.add(root.join("b"), false, BuildPolicy::Automatic),
waiting.add(root.join("a"), false, BuildPolicy::Automatic),
waiting.add(root.join("lib"), true, BuildPolicy::Automatic),
waiting.add(root.join("lib"), false, BuildPolicy::Rebuild),
waiting.add(root.join("lib"), false, BuildPolicy::MakeAndContinueOnErrors),
waiting.add(root.join("lib"), false, BuildPolicy::NoBuild),
waiting.add(root.join("other"), false, BuildPolicy::Automatic),
];
let join = |prefer_maven| {
super::super::joining_launches(
-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,
+4 -59
View File
@@ -3,7 +3,6 @@ use ide_command::command;
use ide_core::{IdeResult, RunId};
use ide_dap::{JvmMemoryUnavailable, JvmThreadsResult, JvmThreadsUnavailable};
use ide_jvm_attach::{ProcEntry, is_hotspot, process_table, select_run_jvm};
use std::path::{Path, PathBuf};
use std::sync::Arc;
/// A `Thread.print -l` of the JVM a run started: the deepest HotSpot JVM of the run's process
@@ -23,43 +22,13 @@ pub async fn run_jvm_thread_dump(
Ok(pid) => pid,
Err(refused) => return Ok(refused),
};
let heap_root = host.heap.root().to_path_buf();
let dir = host.blocking(move || Ok(json_dir(&heap_root))).await?;
// A debugger attached to this run or JVM (Debug of a build tool's run, Attach to Process)
// may hold it suspended, which only its session knows.
let result = match host.debugger.debugged_jvm_thread_dump(id, pid, dir.clone()).await {
Some(dump) => dump,
None => {
let json = dir.clone();
// The attach handshake blocks for seconds.
host.blocking(move || Ok(ide_dap::run_jvm_thread_dump(pid, json.as_deref()))).await
}
};
let _ = host
.blocking(move || {
discard_json_dir(dir);
Ok(())
})
.await;
result
}
/// A fresh owner-only directory for the JVM's JSON dump under the heap snapshot root, whose
/// stale-directory sweep also removes a file a JVM writes after its request timed out. `None`
/// when it cannot be created: the dump then goes without virtual threads.
pub(crate) fn json_dir(heap_root: &Path) -> Option<PathBuf> {
ide_heap::create_snapshot_dir(heap_root)
.inspect_err(|e| tracing::warn!("no directory for the JSON thread dump under {}: {e}", heap_root.display()))
.ok()
}
pub(crate) fn discard_json_dir(dir: Option<PathBuf>) {
if let Some(dir) = dir
&& let Err(e) = std::fs::remove_dir_all(&dir)
&& e.kind() != std::io::ErrorKind::NotFound
{
tracing::warn!("could not delete thread dump directory {}: {e}", dir.display());
if let Some(dump) = host.debugger.debugged_jvm_thread_dump(id, pid).await {
return dump;
}
// The attach handshake blocks for seconds.
host.blocking(move || Ok(ide_dap::run_jvm_thread_dump(pid))).await
}
fn unavailable(reason: JvmThreadsUnavailable) -> JvmThreadsResult {
@@ -131,30 +100,6 @@ mod tests {
assert_eq!(run_jvm(false, Some(10), None, table, |pid| pid == 11), Ok(11));
}
#[cfg(unix)]
#[test]
fn json_dir_is_private_and_removed_afterwards() {
use std::os::unix::fs::PermissionsExt;
let root = tempfile::tempdir().unwrap();
let heap_root = root.path().join("heap-snapshots");
let dir = json_dir(&heap_root).expect("a directory");
assert_eq!(dir.parent(), Some(heap_root.as_path()));
assert_eq!(std::fs::metadata(&dir).unwrap().permissions().mode() & 0o777, 0o700);
// A file the JVM wrote after its request timed out goes with the directory.
std::fs::write(dir.join("threads-1-2.json"), "{}").unwrap();
discard_json_dir(Some(dir.clone()));
assert!(!dir.exists());
discard_json_dir(None);
}
#[test]
fn json_dir_is_none_when_it_cannot_be_created() {
let root = tempfile::tempdir().unwrap();
let blocked = root.path().join("file");
std::fs::write(&blocked, "").unwrap();
assert_eq!(json_dir(&blocked), None);
}
#[cfg(not(unix))]
#[test]
fn unsupported_without_reading_the_process_table() {
+2 -49
View File
@@ -136,10 +136,6 @@ pub trait PluginWorkspace: Send + Sync {
fn apply_edits(&self, path: &Path, version: u64, edits: &[TextEdit], background: bool) -> Result<u64, HostError>;
/// Code from the project may run (git hooks and config on fetch).
fn trusted(&self, root: &Path) -> bool;
/// Git roots with the same directory mappings as the VCS tool window.
fn repositories(&self, _root: &Path) -> Result<ide_vcs::Repos, HostError> {
Err(HostError::NotFound("no open project repositories".into()))
}
/// The git executable of the project at `root` (see [`crate::Project::git_executable`]).
fn git_executable(&self, _root: &Path) -> Option<PathBuf> {
None
@@ -2398,40 +2394,8 @@ impl HostApi for PluginApi {
fn vcs_remotes(&self, root: &Path) -> Result<Vec<(String, String)>, HostError> {
let Some(repo) = ide_vcs::Repo::discover(root).map_err(failed)? else { return Ok(Vec::new()) };
plugin_remotes(&repo)
}
fn vcs_roots(&self, root: &Path) -> Result<Vec<String>, HostError> {
let workspace = self.shared.workspace().ok_or(HostError::Cancelled)?;
Ok(workspace
.repositories(root)?
.roots()
.iter()
.filter(|r| r.starts_with(root) || root.starts_with(r))
.map(|r| to_ipc(r))
.collect())
}
fn vcs_repository_at(&self, root: &Path, path: &str) -> Result<Option<ide_plugin::RepositoryInfo>, HostError> {
let workspace = self.shared.workspace().ok_or(HostError::Cancelled)?;
if !workspace.trusted(root) {
return Err(HostError::Failed("the project is in Restricted Mode: git does not run there".into()));
}
let path = ide_plugin::resolve_in_root(root, path).map_err(HostError::Invalid)?;
let repos = workspace.repositories(root)?;
// A link to a nested worktree directory denotes that worktree, not its entry in the parent.
let Some(repo) = repos.at_root(&path).or_else(|| repos.for_path(&path)) else { return Ok(None) };
let relative = path.strip_prefix(repo.root()).map_err(failed)?;
let info = repo.branch_info().map_err(failed)?;
Ok(Some(ide_plugin::RepositoryInfo {
root: to_ipc(repo.root()),
relative_path: to_ipc(relative),
branch: info.head,
commit: info.head_commit,
upstream: info.upstream,
ahead: info.ahead,
remotes: plugin_remotes(repo)?,
}))
let remotes = repo.remotes().map_err(failed)?;
Ok(remotes.into_iter().map(|r| (r.name, without_credentials(&r.url))).collect())
}
fn vcs_fetch(&self, root: &Path, cancel: &CancellationToken) -> Result<(), HostError> {
@@ -3766,13 +3730,6 @@ impl PluginWorkspace for HostWorkspace {
HostWorkspace::project_covering(self, root).is_some_and(|p| p.is_trusted())
}
fn repositories(&self, root: &Path) -> Result<ide_vcs::Repos, HostError> {
Ok(self
.project_covering(root)
.ok_or_else(|| HostError::NotFound("the project is no longer open".into()))?
.repos())
}
fn git_executable(&self, root: &Path) -> Option<PathBuf> {
HostWorkspace::project_covering(self, root)?.git_executable()
}
@@ -4737,10 +4694,6 @@ fn from_window<'a>(client: Option<&'a str>, what: &str) -> Result<&'a str, HostE
client.ok_or_else(|| HostError::Invalid(format!("can only {what} from a command the user invoked")))
}
fn plugin_remotes(repo: &ide_vcs::Repo) -> Result<Vec<(String, String)>, HostError> {
Ok(repo.remotes().map_err(failed)?.into_iter().map(|r| (r.name, without_credentials(&r.url))).collect())
}
/// `url` without the `user:password@` a remote may carry (`https://user:token@host/…`):
/// `vcs.read` must not hand out credentials. scp-style `git@host:path` has no password.
fn without_credentials(url: &str) -> String {
+6 -67
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>,
@@ -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,
@@ -905,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,
@@ -1042,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(
@@ -2385,11 +2361,8 @@ fn git_metadata_watch(root: &Path, sink: &SharedSink) -> Option<Arc<ide_vcs::Met
.ok()
}
/// Whether a VCS metadata path changed for a reason other than our own status run
/// refreshing an index: the main repository's `.git/index` or a linked worktree's
/// `.git/worktrees/<id>/index`.
fn vcs_path_changed(path: &Path) -> bool {
path.file_name().is_none_or(|n| n != "index") || !ide_vcs::is_own_index_write(path)
!path.ends_with(".git/index") || !ide_vcs::is_own_index_write(path)
}
#[cfg(test)]
@@ -2473,40 +2446,6 @@ mod index_event_tests {
std::fs::remove_file(&index).unwrap();
assert!(vcs_path_changed(&index));
}
#[test]
fn status_write_in_a_linked_worktree_is_suppressed() {
let tmp = tempfile::tempdir().unwrap();
let main = tmp.path().join("main");
std::fs::create_dir(&main).unwrap();
let git = |dir: &std::path::Path, args: &[&str]| {
let output = std::process::Command::new("git")
.current_dir(dir)
.args(["-c", "user.name=t", "-c", "user.email=t@t"])
.args(args)
.output()
.unwrap();
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
};
git(&main, &["init", "-q"]);
std::fs::write(main.join("file.txt"), "original\n").unwrap();
git(&main, &["add", "file.txt"]);
git(&main, &["commit", "-qm", "init"]);
let linked = tmp.path().join("linked");
git(&main, &["worktree", "add", "-q", linked.to_str().unwrap()]);
std::fs::File::options()
.write(true)
.open(linked.join("file.txt"))
.unwrap()
.set_modified(std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1))
.unwrap();
let index = main.join(".git/worktrees/linked/index");
let before = std::fs::read(&index).unwrap();
ide_vcs::Repo::discover(&linked).unwrap().unwrap().status().unwrap();
assert_ne!(before, std::fs::read(&index).unwrap(), "status must actually write the index");
assert!(!vcs_path_changed(&index));
assert!(vcs_path_changed(&main.join(".git/worktrees/linked/HEAD")));
}
}
#[cfg(all(test, unix))]
-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();
-34
View File
@@ -81,10 +81,6 @@ impl TestWorkspace {
}
impl PluginWorkspace for TestWorkspace {
fn repositories(&self, root: &Path) -> Result<ide_vcs::Repos, HostError> {
ide_vcs::Repos::discover(root, &|_| false).map_err(|e| HostError::Failed(e.message))
}
fn run_configuration(&self, _client: &str, plugin: &str, id: &str) -> Result<ide_run::RunConfig, HostError> {
if !(plugin == "execution" && matches!(id, "detected" | "dynamic") || plugin == "api14" && id == "tests") {
return Err(HostError::NotFound(id.into()));
@@ -3613,36 +3609,6 @@ fn commands_see_the_paths_they_were_run_on() {
assert_eq!(f.run("jobs", "selection", None).unwrap().as_deref(), Some(""));
}
#[test]
fn plugin_reads_the_repository_owning_the_path() {
let f = fixture(Limits::default());
f.install(&sample("jobs"));
let lookup = |path: Option<&str>| f.run("jobs", "repository-at", path);
for name in ["alpha", "beta", "alpha/nested"] {
let dir = f.project.join(name);
std::fs::create_dir_all(&dir).unwrap();
git(&dir, &["init", "-b", "work"]);
git(&dir, &["remote", "add", "origin", &format!("https://user:[email protected]/{name}.git")]);
std::fs::write(dir.join("file.txt"), name).unwrap();
}
assert_eq!(lookup(None).unwrap().unwrap().lines().count(), 3);
for (path, repo, relative) in [
("alpha/file.txt", "alpha", "file.txt"),
("beta/file.txt", "beta", "file.txt"),
("alpha/nested/file.txt", "alpha/nested", "file.txt"),
("alpha/nested", "alpha/nested", ""),
] {
let root = to_ipc(&f.project.join(repo));
let expected = format!("{root}|{relative}|work|[(\"origin\", \"https://example.org/{repo}.git\")]");
assert_eq!(lookup(Some(path)).unwrap().as_deref(), Some(expected.as_str()));
}
assert_eq!(lookup(Some(".")).unwrap(), None);
assert!(lookup(Some("..")).unwrap_err().contains("outside"));
f.host.set_capability("jobs", "vcs.read", false).unwrap();
assert!(lookup(None).unwrap_err().contains("vcs.read"));
assert!(lookup(Some("alpha/file.txt")).unwrap_err().contains("vcs.read"));
}
#[test]
fn vcs_remotes_clipboard_and_open_url() {
let f = fixture(Limits::default());
+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();
+4 -21
View File
@@ -85,26 +85,9 @@ done
for (index, root) in roots.into_iter().enumerate() {
let module = if root == &sibling { root.join("app") } else { root.strip_prefix(&primary).unwrap().join("app") };
let test = index != 0;
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, 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();
assert!(
events.iter().any(|e| matches!(e, BuildEvent::Step { command, .. } if command.contains("-pl app -am"))),
"{events:?}"
);
assert!(
events
.iter()
.any(|e| matches!(e, BuildEvent::Progress { message, .. } if message == "Resolving the classpath")),
"{events:?}"
);
let info = ops::java::java_resolve_launch(&host, "main", module, test, BuildPolicy::Make, RequestId::next())
.await
.unwrap();
let out = root.join("app/target").join(if test { "test-classes" } else { "classes" });
let jar = root.join("app").join(if test { "test.jar" } else { "runtime.jar" });
assert!(info.class_paths.iter().any(|p| std::path::Path::new(p) == out));
@@ -112,7 +95,7 @@ done
let calls = fs::read_to_string(root.join("calls")).unwrap();
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));
}
}
+3 -8
View File
@@ -18,16 +18,11 @@ const DUMP_BASE_TIMEOUT: Duration = Duration::from_secs(30);
/// Only `-all` and a quoted path: any argument the DCmd rejects while the VM is suspended
/// hangs the attach listener (17/21/25) until resume, and so does an unquoted path with a space.
pub fn heap_dump_command(path: &Path) -> Result<String, AttachError> {
Ok(format!("GC.heap_dump -all {}", quoted_path(path, "heap dump")?))
}
/// `path` in double quotes, as a DCmd argument; `what` names the file in errors.
pub(crate) fn quoted_path(path: &Path, what: &str) -> Result<String, AttachError> {
let text = path.to_str().ok_or_else(|| AttachError::Protocol(format!("{what} path {path:?} is not UTF-8")))?;
let text = path.to_str().ok_or_else(|| AttachError::Protocol(format!("heap dump path {path:?} is not UTF-8")))?;
if text.contains(['"', '\0', '\n', '\r']) {
return Err(AttachError::Protocol(format!("{what} path {text:?} cannot be quoted for the JVM")));
return Err(AttachError::Protocol(format!("heap dump path {text:?} cannot be quoted for the JVM")));
}
Ok(format!("\"{text}\""))
Ok(format!("GC.heap_dump -all \"{text}\""))
}
/// The JVM answers result code 0 for IO failures too, so success is told apart by its text.
+1 -2
View File
@@ -20,6 +20,5 @@ pub use listener::{LISTENER_START_TIMEOUT, ensure_listener, is_hotspot};
pub use properties::{jdwp_port, parse_properties};
pub use socket::{AttachError, MAX_OUTPUT, agent_properties, has_listener, jcmd, temp_dir};
pub use threads::{
ProcEntry, RUN_TOKEN_PROPERTY, THREAD_DUMP_TIMEOUT, is_application_jvm, process_table, select_run_jvm,
thread_dump_json, thread_print,
ProcEntry, RUN_TOKEN_PROPERTY, THREAD_DUMP_TIMEOUT, is_application_jvm, process_table, select_run_jvm, thread_print,
};
+2 -126
View File
@@ -1,12 +1,9 @@
use std::collections::{HashMap, HashSet, VecDeque};
use std::io::Read;
use std::path::Path;
use std::process::Command;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use std::time::Duration;
use crate::heap_dump::quoted_path;
use crate::listener::is_hotspot;
use crate::socket::{AttachError, MAX_OUTPUT, jcmd};
use crate::socket::{AttachError, jcmd};
/// Default budget for `thread_print`; a dump of a healthy JVM takes milliseconds, so this only
/// bounds a JVM stuck at a safepoint.
@@ -33,55 +30,6 @@ pub fn thread_print(pid: u32, timeout: Duration) -> Result<String, AttachError>
jcmd(pid, "Thread.print -l", timeout)
}
/// `Thread.dump_to_file -format=json`, the only dump that lists virtual threads (JDK 21+). The
/// JVM writes it into `dir`, an absolute directory; the file is read up to [`MAX_OUTPUT`] and
/// deleted whatever the outcome. Never send it to a VM a debugger holds suspended: 21 and 25 hang
/// the request, and every later attach request behind it, until the VM resumes.
pub fn thread_dump_json(pid: u32, dir: &Path, timeout: Duration) -> Result<String, AttachError> {
dump_json_with(pid, dir, MAX_OUTPUT, |command| jcmd(pid, command, timeout))
}
fn dump_json_with(
pid: u32,
dir: &Path,
max: usize,
send: impl FnOnce(&str) -> Result<String, AttachError>,
) -> Result<String, AttachError> {
// The JVM resolves a relative path against its own working directory.
if !dir.is_absolute() {
return Err(AttachError::Protocol(format!("thread dump directory {dir:?} is not absolute")));
}
// JDK 21 has no `-overwrite` and writes nothing when the file exists.
let nanos = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |since| since.as_nanos());
let path = dir.join(format!("threads-{pid}-{nanos}.json"));
let command = format!("Thread.dump_to_file -format=json {}", quoted_path(&path, "thread dump")?);
let _delete = DeleteOnDrop(&path);
let reply = send(&command)?;
read_capped(&path, max).map_err(|e| match e {
AttachError::Io(e) if e.kind() == std::io::ErrorKind::NotFound => {
AttachError::Protocol(format!("the JVM wrote no thread dump: {}", reply.trim()))
}
e => e,
})
}
fn read_capped(path: &Path, max: usize) -> Result<String, AttachError> {
let mut bytes = Vec::new();
std::fs::File::open(path)?.take(max as u64 + 1).read_to_end(&mut bytes)?;
if bytes.len() > max {
return Err(AttachError::TooLarge);
}
String::from_utf8(bytes).map_err(|_| AttachError::Protocol("the thread dump is not UTF-8".into()))
}
struct DeleteOnDrop<'a>(&'a Path);
impl Drop for DeleteOnDrop<'_> {
fn drop(&mut self) {
let _ = std::fs::remove_file(self.0);
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ProcEntry {
pub pid: u32,
@@ -171,7 +119,6 @@ fn deepest_jvm_in_tree(table: &[ProcEntry], root: u32, is_hotspot: &dyn Fn(u32)
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
fn entry(pid: u32, ppid: u32, command: &str) -> ProcEntry {
ProcEntry { pid, ppid, command: command.to_string() }
@@ -292,77 +239,6 @@ mod tests {
assert_eq!(select_run_jvm(&table, 10, None, not_the_shell), Some(11));
}
/// The path the fake JVM is asked to write, from `Thread.dump_to_file … "<path>"`.
fn requested_path(command: &str) -> PathBuf {
PathBuf::from(command.split('"').nth(1).expect("quoted path"))
}
fn is_empty(dir: &Path) -> bool {
std::fs::read_dir(dir).unwrap().next().is_none()
}
/// `<tmp>/a b`: the space is what an unquoted path would break on.
fn dir_with_space() -> (tempfile::TempDir, PathBuf) {
let root = tempfile::tempdir().unwrap();
let dir = root.path().join("a b");
std::fs::create_dir(&dir).unwrap();
(root, dir)
}
#[test]
fn json_dump_reads_the_file_and_deletes_it() {
let (_root, dir) = dir_with_space();
let mut sent = String::new();
let json = dump_json_with(42, &dir, 1024, |command| {
sent = command.to_owned();
std::fs::write(requested_path(command), "{\"threadDump\":{}}").unwrap();
Ok(format!("Created {}\n", requested_path(command).display()))
})
.unwrap();
assert_eq!(json, "{\"threadDump\":{}}");
let prefix = format!("Thread.dump_to_file -format=json \"{}", dir.join("threads-42-").display());
assert!(sent.starts_with(&prefix) && sent.ends_with(".json\""), "{sent}");
assert!(is_empty(&dir));
}
#[test]
fn json_dump_file_is_deleted_when_it_is_too_large() {
let (_root, dir) = dir_with_space();
let result = dump_json_with(42, &dir, 1024, |command| {
std::fs::write(requested_path(command), vec![b' '; 1025]).unwrap();
Ok(String::new())
});
assert!(matches!(result, Err(AttachError::TooLarge)), "{result:?}");
assert!(is_empty(&dir));
}
#[test]
fn json_dump_file_is_deleted_when_the_request_fails() {
let (_root, dir) = dir_with_space();
let result = dump_json_with(42, &dir, 1024, |command| {
// The JVM wrote the file but the reply came too late.
std::fs::write(requested_path(command), "{}").unwrap();
Err(AttachError::Timeout)
});
assert!(matches!(result, Err(AttachError::Timeout)), "{result:?}");
assert!(is_empty(&dir));
}
#[test]
fn json_dump_without_a_file_reports_the_reply() {
let (_root, dir) = dir_with_space();
// JDK 21 answers result code 0 when it writes nothing.
let result = dump_json_with(42, &dir, 1024, |_| Ok("/x.json exists, use -overwrite to overwrite\n".into()));
let Err(AttachError::Protocol(message)) = result else { panic!("{result:?}") };
assert!(message.contains("exists"), "{message}");
}
#[test]
fn json_dump_refuses_a_relative_directory() {
let result = dump_json_with(42, Path::new("dumps"), 1024, |_| panic!("sent a relative path"));
assert!(matches!(result, Err(AttachError::Protocol(_))), "{result:?}");
}
#[test]
fn select_skips_gradle_workers_and_the_kotlin_daemon() {
// `--no-daemon`: the build's helper JVMs sit beside the application in the run's tree.
+1 -50
View File
@@ -11,7 +11,7 @@ use ide_jvm_attach::{
AttachError, HeapDumpReply, LISTENER_START_TIMEOUT, THREAD_DUMP_TIMEOUT, agent_properties, ensure_listener,
find_jvm_by_jdwp_port, has_listener, heap_dump, heap_dump_command, histogram_safe_while_suspended, is_hotspot,
java_version_of, jcmd, jdwp_port, parse_class_histogram, parse_heap_dump_reply, parse_release, process_table,
select_run_jvm, temp_dir, thread_dump_json, thread_print, vm_flags,
select_run_jvm, temp_dir, thread_print, vm_flags,
};
/// Two threads that each hold one monitor and wait for the other's after 200 ms.
@@ -33,25 +33,6 @@ public class Deadlock {
}
"#;
/// Two virtual threads in a monitor deadlock, which `Thread.print` does not list.
const VIRTUAL_DEADLOCK_JAVA: &str = r#"
public class VirtualDeadlock {
static final Object A = new Object(), B = new Object();
static void sleep(long ms) {
try { Thread.sleep(ms); } catch (InterruptedException e) { throw new RuntimeException(e); }
}
public static void main(String[] args) {
Thread.ofVirtual().name("v-sync-1").start(() -> { synchronized (A) { sleep(200); synchronized (B) { } } });
Thread.ofVirtual().name("v-sync-2").start(() -> { synchronized (B) { sleep(200); synchronized (A) { } } });
System.out.println("READY");
System.out.flush();
sleep(60_000);
}
}
"#;
const MAIN_JAVA: &str = r#"
import java.util.ArrayList;
import java.util.List;
@@ -405,33 +386,3 @@ fn thread_print_reports_a_deadlock() {
assert!(table.iter().any(|entry| entry.pid == pid && entry.command.contains("Deadlock")));
assert_eq!(select_run_jvm(&table, pid, None, is_hotspot), Some(pid));
}
#[test]
#[ignore = "needs a real JDK >= 21: set OPENIDEA_TEST_JAVA to its bin/java"]
fn thread_dump_json_lists_virtual_threads() {
let Some(java) = std::env::var_os("OPENIDEA_TEST_JAVA").map(PathBuf::from) else {
eprintln!("OPENIDEA_TEST_JAVA is not set; skipping");
return;
};
let major = reported_major(&java);
if major < 21 {
eprintln!("JDK {major} has no virtual threads; skipping");
return;
}
let dir = tempfile::tempdir().unwrap();
let mut guard =
launch_class(&java, dir.path(), "VirtualDeadlock", VIRTUAL_DEADLOCK_JAVA, &["-XX:+StartAttachListener"]);
let pid = guard.0.id();
wait_for_ready(&output_lines(&mut guard.0));
wait_for_listener(pid);
std::thread::sleep(Duration::from_secs(1));
let dumps = dir.path().join("a b");
std::fs::create_dir(&dumps).unwrap();
let started = Instant::now();
let json = thread_dump_json(pid, &dumps, THREAD_DUMP_TIMEOUT).unwrap();
eprintln!("JDK {major} JSON thread dump: {} bytes in {:?}", json.len(), started.elapsed());
assert!(json.contains("\"threadContainers\""), "{json}");
assert!(json.contains("\"v-sync-1\"") && json.contains("\"v-sync-2\""), "{json}");
assert!(std::fs::read_dir(&dumps).unwrap().next().is_none(), "dump file left in {dumps:?}");
}
-1
View File
@@ -358,7 +358,6 @@ pub enum FoldKind {
Region,
Comment,
Imports,
Compact,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
+1 -70
View File
@@ -144,11 +144,7 @@ pub(super) fn folding(
if !node.is_named() {
return true;
}
if spec.name == "go"
&& let Some(end) = go_compact_end(&node, text)
{
push(&mut out, start, end, FoldKind::Compact);
} else if let Some(close_row) = kinds.bracket_close_row(&node) {
if let Some(close_row) = kinds.bracket_close_row(&node) {
push(&mut out, start, close_row, FoldKind::Region);
} else if kinds.has(&node, FOLD_NODE) {
push(&mut out, start, last_content_row(&node, text), FoldKind::Region);
@@ -161,71 +157,6 @@ pub(super) fn folding(
out
}
// Only join a single statement on the next line. Comments, blank lines and
// nested multi-line statements must keep their own lines.
fn go_compact_end(node: &Node, text: &str) -> Option<usize> {
let start = node.start_position().row;
let braced = match node.kind() {
"block" => {
let parent = node.parent()?;
if parent.kind() != "if_statement"
|| parent.child_by_field_name("consequence") != Some(*node)
|| !go_error_guard(parent.child_by_field_name("condition")?, text)
{
return None;
}
true
}
"expression_case" | "type_case" | "communication_case" | "default_case" => false,
_ => return None,
};
let body = node.named_child(node.named_child_count().checked_sub(1)?)?;
if body.kind() != "statement_list" || body.named_child_count() != 1 {
return None;
}
let header_end = body.prev_sibling()?;
if header_end.kind() != if braced { "{" } else { ":" } || header_end.end_position().row != start {
return None;
}
let statement = body.named_child(0)?;
let position = statement.start_position();
if statement.has_error()
|| statement.is_extra()
|| position.row != start + 1
|| statement.end_position().row != position.row
|| !own_line(text, statement.start_byte(), position.column)
|| !text.get(header_end.end_byte()..statement.start_byte())?.trim().is_empty()
{
return None;
}
let tail = text.get(statement.end_byte()..)?.split('\n').next()?.trim();
if !matches!(tail, "" | ";") {
return None;
}
let end = start + if braced { 2 } else { 1 };
(!braced || node.end_position().row == end).then_some(end)
}
// Folding runs without Go type information. Recognize conventional error
// guards and leave other nil checks alone.
fn go_error_guard(condition: Node, text: &str) -> bool {
if condition.kind() != "binary_expression"
|| !condition.child_by_field_name("operator").is_some_and(|op| op.kind() == "!=")
{
return false;
}
let (Some(left), Some(right)) = (condition.child_by_field_name("left"), condition.child_by_field_name("right"))
else {
return false;
};
let name = match (left.kind(), right.kind()) {
("identifier", "nil") => left,
("nil", "identifier") => right,
_ => return false,
};
name.utf8_text(text.as_bytes()).is_ok_and(|name| name == "err" || name.ends_with("Err"))
}
fn push(out: &mut Vec<FoldRange>, start: usize, end: usize, kind: FoldKind) {
if end > start {
out.push(FoldRange { start_line: start as u32, end_line: end as u32, kind });
-50
View File
@@ -1206,56 +1206,6 @@ fn folding_go_imports_and_ruby_ends() {
);
}
#[test]
fn go_compact_folds_keep_only_single_line_statements_inline() {
let src = r#"package main
func f() {
if err != nil {
return err
}
if err != nil {
return err // keep the comment on its own line
}
switch mode {
case "compact":
run()
case "multi":
run()
stop()
default:
return err
}
if err != nil {
return fmt.Errorf(
"keep both lines")
}
}
"#;
let found = folds("go", src);
let compact: Vec<_> = found.iter().copied().filter(|r| r.2 == FoldKind::Compact).collect();
assert_eq!(compact, [(3, 5, FoldKind::Compact), (10, 11, FoldKind::Compact), (15, 16, FoldKind::Compact)]);
assert!(found.contains(&(6, 8, FoldKind::Region)));
assert!(found.contains(&(18, 21, FoldKind::Region)));
}
#[test]
fn go_compact_if_folds_are_limited_to_conventional_error_guards() {
for (guard, kind) in [
("err != nil", FoldKind::Compact),
("nil != err", FoldKind::Compact),
("parseErr := parse(); parseErr != nil", FoldKind::Compact),
("cfg != nil", FoldKind::Region),
("err == nil", FoldKind::Region),
("invalid", FoldKind::Region),
] {
let source = format!(
"package main\nfunc f() error {{\n if {guard} {{\n return err\n }}\n return nil\n}}\n"
);
assert!(folds("go", &source).contains(&(2, 4, kind)), "unexpected fold for {guard}");
}
}
#[test]
fn folding_swift_control_flow_and_haskell_binds() {
assert_eq!(
-105
View File
@@ -1,105 +0,0 @@
//! The Dart analysis server's closing labels (`dart/textDocument/publishClosingLabels`): the
//! widget or call a closing `)` / `]` ends, shown after it at the end of the line (`// Column`).
use crate::convert::Conv;
use crate::text::{DocText, Encoding, col_to_byte, units};
use crate::types::{InlayHint, InlayKind};
use ide_core::Pos;
use lsp_types as lsp;
use serde::Deserialize;
use std::collections::BTreeMap;
use std::path::Path;
#[cfg(test)]
use std::sync::Arc;
#[derive(Deserialize)]
pub(crate) struct Params {
pub uri: String,
pub labels: Vec<Label>,
}
#[derive(Clone, Deserialize)]
pub(crate) struct Label {
range: lsp::Range,
label: String,
}
/// One end-of-line hint per line, as the Flutter plugin shows them: `// Padding // Center` when
/// several constructs close on one line. A label whose range no longer ends in `)` or `]` (the
/// text changed since the analysis) is left out.
pub(crate) fn hints(conv: &Conv, path: &Path, text: &DocText, labels: Vec<Label>) -> Vec<InlayHint> {
let mut lines: BTreeMap<u32, Vec<String>> = BTreeMap::new();
for l in labels {
let end = conv.pos(path, l.range.end);
let line = text.line(end.line as usize);
let before = &line[..col_to_byte(line, end.col as usize, Encoding::Utf16)];
if before.ends_with([')', ']']) {
lines.entry(end.line).or_default().push(l.label);
}
}
lines
.into_iter()
.map(|(line, labels)| InlayHint {
position: Pos::new(line, units(text.line(line as usize), Encoding::Utf16) as u32),
label: format!("// {}", labels.join(" // ")),
kind: InlayKind::ClosingLabel,
padding_left: true,
padding_right: false,
tooltip: None,
parts: Vec::new(),
text_edits: Vec::new(),
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn labels(v: serde_json::Value) -> Vec<Label> {
serde_json::from_value(v).unwrap()
}
fn label(line: u32, from: u32, to: u32, label: &str) -> serde_json::Value {
json!({ "label": label, "range": { "start": { "line": line, "character": from }, "end": { "line": line, "character": to } } })
}
#[test]
fn labels_go_to_the_end_of_the_line_and_share_it() {
let text = DocText::new("return Center(\n child: Padding(\n child: Text('a'))), // x\n");
let conv = Conv::new(Encoding::Utf16, |_: &Path| None::<Arc<DocText>>);
let hints = hints(
&conv,
Path::new("/a.dart"),
&text,
labels(json!([label(2, 4, 21, "Padding"), label(2, 4, 22, "Center"), label(2, 11, 20, "Text")])),
);
assert_eq!(hints.len(), 1);
assert_eq!(hints[0].label, "// Padding // Center // Text");
assert_eq!(hints[0].position, Pos::new(2, 28));
assert_eq!(hints[0].kind, InlayKind::ClosingLabel);
}
#[test]
fn a_label_that_no_longer_ends_at_a_bracket_is_dropped() {
let text = DocText::new("Column(children: [])\nRow(\n");
let conv = Conv::new(Encoding::Utf16, |_: &Path| None::<Arc<DocText>>);
let hints = hints(
&conv,
Path::new("/a.dart"),
&text,
labels(json!([label(0, 0, 19, "<Widget>[]"), label(1, 0, 3, "Row")])),
);
assert_eq!(hints.iter().map(|h| h.label.as_str()).collect::<Vec<_>>(), ["// <Widget>[]"]);
}
#[test]
fn utf8_servers_and_wide_characters_give_utf16_columns() {
let text = Arc::new(DocText::new("Text('🙂')\n"));
let doc = text.clone();
let conv = Conv::new(Encoding::Utf8, move |_: &Path| Some(doc.clone()));
let hints = hints(&conv, Path::new("/a.dart"), &text, labels(json!([label(0, 0, 12, "Text")])));
assert_eq!(hints[0].position, Pos::new(0, 10));
}
}
-18
View File
@@ -414,23 +414,6 @@ impl ClientHandler {
}
}
fn publish_closing_labels(&self, mgr: &LspManager, params: Value) {
let params: crate::closing_labels::Params = match serde_json::from_value(params) {
Ok(p) => p,
Err(e) => {
tracing::debug!("{}: bad publishClosingLabels: {e}", self.server.name);
return;
}
};
let Some(path) = uri_to_path(&params.uri) else { return };
if !self.server.is_live(self.generation) {
return;
}
if mgr.set_closing_labels(&path, &self.server, self.generation, self.encoding(), params.labels) {
mgr.sink().emit(IdeEvent::LspRefresh { server: self.server.id, kind: LspRefreshKind::InlayHints });
}
}
/// Once per unresolved plugin, whether m2e marked a `pom.xml` or only logged it.
fn build_plan_failure(&self, mgr: &LspManager, (plugin, body): (String, String)) {
if mgr.first_message(&self.server.name, &format!("build plan: {plugin}")) {
@@ -639,7 +622,6 @@ impl Handler for ClientHandler {
}
"textDocument/publishDiagnostics" => self.publish_diagnostics(&mgr, params),
"dart/textDocument/publishFlutterOutline" => self.publish_flutter_outline(&mgr, params),
"dart/textDocument/publishClosingLabels" => self.publish_closing_labels(&mgr, params),
"window/showMessage" => self.show_message(&mgr, &params),
"window/logMessage" => {
let text = params.get("message").and_then(Value::as_str).unwrap_or_default();
-72
View File
@@ -10,7 +10,6 @@ mod angular;
mod arduino;
mod caps;
mod clang_tidy;
mod closing_labels;
mod compose;
mod convert;
mod external_project;
@@ -87,7 +86,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);
@@ -152,14 +150,6 @@ struct DocState {
/// When the servers last got new text (open or change): diagnostics published before are stale.
changed: std::time::Instant,
flutter_outline: Option<FlutterOutline>,
/// The Dart server's closing labels for the current text; dropped on the next change.
closing_labels: Option<ClosingLabels>,
}
struct ClosingLabels {
server: ide_core::ServerId,
generation: u64,
hints: Vec<InlayHint>,
}
/// The widget tree last published for a document, valid while that server instance runs.
@@ -1313,7 +1303,6 @@ impl LspManager {
notebook: None,
changed: std::time::Instant::now(),
flutter_outline: None,
closing_labels: None,
};
let compose_added = {
let mut docs = self.docs.lock();
@@ -1362,7 +1351,6 @@ impl LspManager {
let Some(d) = docs.get_mut(&doc) else { return };
d.version = version as i32;
d.changed = std::time::Instant::now();
d.closing_labels = None;
// Servers that have this document open on their current instance.
let targets: Vec<(Arc<Server>, Running, SyncKind, Encoding)> = d
@@ -2449,34 +2437,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,
@@ -2493,37 +2453,6 @@ impl LspManager {
changed
}
/// Records published closing labels; whether what the open documents of `path` show changed.
fn set_closing_labels(
&self,
path: &Path,
server: &Server,
generation: u64,
enc: Encoding,
labels: Vec<closing_labels::Label>,
) -> bool {
let mut changed = false;
for d in self.docs.lock().values_mut().filter(|d| d.path == path && d.notebook.is_none()) {
// Not `self.conv`: it would lock `docs` again for a UTF-8 server's text.
let text = d.text.clone();
let conv = Conv::new(enc, move |_: &Path| Some(text.clone()));
let hints = closing_labels::hints(&conv, path, &d.text, labels.clone());
changed |= !hints.is_empty() || d.closing_labels.as_ref().is_some_and(|c| !c.hints.is_empty());
d.closing_labels = Some(ClosingLabels { server: server.id, generation, hints });
}
changed
}
fn closing_label_hints(&self, doc: DocId, range: Range) -> Vec<InlayHint> {
let docs = self.docs.lock();
let Some(d) = docs.get(&doc) else { return Vec::new() };
let Some(c) = d.closing_labels.as_ref() else { return Vec::new() };
if !d.servers.iter().any(|a| a.server.id == c.server && a.server.is_live(c.generation)) {
return Vec::new();
}
c.hints.iter().filter(|h| range.start <= h.position && h.position <= range.end).cloned().collect()
}
pub async fn workspace_symbols(&self, query: &str, cancel: CancellationToken) -> IdeResult<Vec<WorkspaceSymbol>> {
let servers: Vec<Arc<Server>> = self.servers.lock().clone();
let targets = self.ready_targets(&servers, |c| c.has("workspaceSymbolProvider")).await;
@@ -3386,7 +3315,6 @@ impl LspManager {
}
}
let mut v = out.finish(Vec::new())?;
v.extend(self.closing_label_hints(doc, range));
v.sort_by_key(|h| h.position);
Ok(v)
}
-1
View File
@@ -237,7 +237,6 @@ impl LspManager {
notebook: Some(path.to_owned()),
changed: std::time::Instant::now(),
flutter_outline: None,
closing_labels: None,
},
);
state.cells.push((cell.id.clone(), doc));
-56
View File
@@ -247,8 +247,6 @@ pub enum InlayKind {
Type,
Parameter,
Other,
/// What a closing bracket ends, at the end of its line (the Dart server's closing labels).
ClosingLabel,
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
@@ -654,57 +652,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),
}
-113
View File
@@ -1549,119 +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())]);
let (doc, path) = h.open("a.mk", "Center(\n child: Text('x'))\n");
h.wait_status("mock", ServerStatus::Ready).await;
let s = h.launcher.state("mock");
s.respond("textDocument/inlayHint", json!([]));
let refreshes = || {
h.events
.lock()
.iter()
.filter(|e| matches!(e, IdeEvent::LspRefresh { kind: LspRefreshKind::InlayHints, .. }))
.count()
};
let at = |l0: u32, c0: u32, c1: u32| json!({"start":{"line":l0,"character":c0},"end":{"line":1,"character":c1}});
let labels = json!({ "uri": uri_of(&path), "labels": [
{ "range": at(1, 9, 18), "label": "Text" },
{ "range": at(0, 0, 19), "label": "Center" },
]});
s.peer().notify("dart/textDocument/publishClosingLabels", labels).unwrap();
eventually(|| refreshes() == 1).await;
let whole = Range::new(Pos::new(0, 0), Pos::new(2, 0));
let hints = h.mgr.inlay_hints(doc, whole).await.unwrap();
assert_eq!(hints.len(), 1);
assert_eq!(hints[0].label, "// Text // Center");
assert_eq!(hints[0].position, Pos::new(1, 19));
assert_eq!(hints[0].kind, InlayKind::ClosingLabel);
assert!(h.mgr.inlay_hints(doc, Range::new(Pos::new(0, 0), Pos::new(0, 7))).await.unwrap().is_empty());
// Edited text: the labels wait for the next analysis.
h.mgr.did_change(doc, 2, &[change(rng(0, 0, 0, 0), " ")], &|| unreachable!());
assert!(h.mgr.inlay_hints(doc, whole).await.unwrap().is_empty());
}
#[tokio::test(flavor = "multi_thread")]
async fn diagnostics_become_events_and_feed_code_actions() {
let h = harness(&[("mock", incremental_caps())]);
+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;
-2
View File
@@ -317,8 +317,6 @@ pub trait HostApi: Send + Sync {
fn storage_keys(&self, prefix: &str) -> Result<Vec<String>, HostError>;
fn vcs_status(&self, root: &Path) -> Result<Option<RepositoryStatus>, HostError>;
fn vcs_remotes(&self, root: &Path) -> Result<Vec<(String, String)>, HostError>;
fn vcs_roots(&self, root: &Path) -> Result<Vec<String>, HostError>;
fn vcs_repository_at(&self, root: &Path, path: &str) -> Result<Option<crate::RepositoryInfo>, HostError>;
fn vcs_fetch(&self, root: &Path, cancel: &CancellationToken) -> Result<(), HostError>;
/// The commit being prepared in `client`'s window (`None`: no repository),
/// waiting for the window until `cancel` fires.
Loaded 100 of 628 files, more files were not shown because too many files have changed in this diff. Show more