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

..
Автор SHA1 Повідомлення Дата
l0ng-ai cfc916bfdb fix(vcs): Skip the Git Log diff preview when it cannot open 2026-10-29 09:13:21 +08:00
l0ng-ai f1ff2731f0 feat(vcs): Preview the selected file's diff in the Git Log
Selecting a single changed file in the Git Log's changes pane shows its diff
in the editor's preview tab without taking focus, so arrow keys walk through
the files. View Options › Show Diff Preview turns it off; double-click and
Show Diff still open a regular diff tab.
2026-10-29 08:48:23 +08:00
116 змінених файлів з 428 додано та 5140 видалено

No files matched your search

Створено
-1
Переглянути файл
@@ -4479,7 +4479,6 @@ dependencies = [
"hex",
"ide-core",
"ide-language",
"libc",
"parking_lot",
"serde",
"serde_json",
+1 -1
Переглянути файл
@@ -87,7 +87,7 @@ tree-sitter = "0.25"
lsp-types = "0.97"
gix = { version = "0.89", default-features = false }
portable-pty = "0.9"
reqwest = { version = "0.13", default-features = false, features = ["rustls-no-provider", "http2", "charset", "socks", "gzip", "deflate", "brotli"] }
reqwest = { version = "0.13", default-features = false, features = ["rustls-no-provider", "http2", "charset", "gzip", "deflate", "brotli"] }
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12", "logging"] }
rustls-platform-verifier = "0.7"
sqlx = { version = "0.9", default-features = false, features = ["runtime-tokio", "tls-rustls-ring-webpki", "sqlite", "postgres", "mysql"] }
-37
Переглянути файл
@@ -46,8 +46,6 @@ const STDERR_LINES: usize = 20;
/// Updates of a session's state rather than its conversation.
const SESSION_STATE: [&str; 5] =
["session_info_update", "config_option_update", "current_mode_update", "available_commands_update", "usage_update"];
/// A native agent's own update: it is about to retry a failed API request (see [`AgentRetry`]).
pub(crate) const RETRY_UPDATE: &str = "openidea_retry";
/// Referenced files up to this size are embedded in the prompt (when the agent takes it).
const MAX_EMBED: u64 = 256 * 1024;
/// How long a probe waits for the agent to answer `initialize`.
@@ -266,7 +264,6 @@ impl AgentManager {
if matches!(f.task.status, AgentStatus::Running | AgentStatus::NeedsInput | AgentStatus::Starting) {
f.task.status = AgentStatus::Ready;
}
f.task.retry = None;
let task = Task::restore(f, shared.clone());
task.state.lock().conversation.settle(now_ms());
tasks.insert(task.id.clone(), task);
@@ -392,7 +389,6 @@ impl AgentManager {
queue: Vec::new(),
capabilities: self.shared.probes.lock().get(&spec.id).map(|p| p.capabilities).unwrap_or_default(),
resets_ms: None,
retry: None,
};
let file = TaskFile {
task: task.clone(),
@@ -581,7 +577,6 @@ impl AgentManager {
usage: None,
queue: Vec::new(),
resets_ms: None,
retry: None,
..s.task.clone()
};
TaskFile {
@@ -835,22 +830,9 @@ impl Task {
self.shared.emit(AgentEvent::Task { task });
}
/// Shows (or clears) the agent's pending retry; emitted only when it changes.
fn set_retry(&self, retry: Option<AgentRetry>) {
{
let mut s = self.state.lock();
if s.task.retry == retry {
return;
}
s.task.retry = retry;
}
self.emit_task();
}
fn set_status(&self, status: AgentStatus, error: Option<String>) {
{
let mut s = self.state.lock();
s.task.retry = None;
s.task.status = status;
s.task.error = error;
s.task.updated_ms = now_ms();
@@ -1282,12 +1264,6 @@ impl Task {
}
return;
}
if kind == RETRY_UPDATE {
if !self.replaying.load(Ordering::Acquire) {
self.set_retry(retry_of(update, now_ms()));
}
return;
}
if kind == "session_info_update" {
// The agent's own title for the session replaces the first line of the prompt.
let title = update.get("title").and_then(Value::as_str).map(str::trim).filter(|t| !t.is_empty());
@@ -1356,8 +1332,6 @@ impl Task {
}
fn apply(self: &Arc<Self>, session: Option<&str>, kind: &str, update: &Value) {
// Output again: the retried request went through.
self.set_retry(None);
let applied = self.state.lock().conversation.apply(session, update, now_ms());
self.mark_dirty(applied);
// A subagent can start or finish after the turn that started it: saved right away.
@@ -1582,17 +1556,6 @@ fn is_zero(n: &u32) -> bool {
*n == 0
}
/// The retry a [`RETRY_UPDATE`] announces, timed from `now`.
fn retry_of(update: &Value, now: f64) -> Option<AgentRetry> {
let n = |k: &str| update.get(k).and_then(Value::as_u64);
Some(AgentRetry {
attempt: u32::try_from(n("attempt")?).unwrap_or(u32::MAX),
max_retries: n("maxRetries").and_then(|m| u32::try_from(m).ok()),
retry_at_ms: now + n("retryDelayMs").unwrap_or(0) as f64,
error: update.get("error").and_then(Value::as_str).filter(|e| !e.is_empty()).map(str::to_owned),
})
}
fn model_of(config: &[AgentConfigOption]) -> Option<String> {
config.iter().find(|o| o.category.as_deref() == Some("model")).and_then(|o| o.current.clone())
}
-15
Переглянути файл
@@ -81,21 +81,6 @@ pub struct AgentTask {
/// When a [`AgentStatus::Limited`] task's limit resets (ms since the epoch), if the agent said.
#[serde(default)]
pub resets_ms: Option<f64>,
/// The agent is retrying a failed API request (connection lost, overloaded…); cleared
/// by its next output or any status change.
#[serde(default)]
pub retry: Option<AgentRetry>,
}
/// An API request the agent is about to retry.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentRetry {
pub attempt: u32,
pub max_retries: Option<u32>,
/// When the next attempt starts (ms since the epoch).
pub retry_at_ms: f64,
pub error: Option<String>,
}
/// One value of a select-type session setting.
-14
Переглянути файл
@@ -917,20 +917,6 @@ fn pending_starts_round_trip() {
}
}
#[test]
fn api_retries_are_announced() {
let mut t = Translator::new("s", PathBuf::from("/w"), true);
let out = t.on_message(&json!({"type": "system", "subtype": "api_retry", "attempt": 3, "max_retries": 10,
"retry_delay_ms": 4000, "error_status": null, "error": "Connection error."}));
assert_eq!(out.len(), 1);
assert_eq!(out[0].session, "s");
assert_eq!(
out[0].update,
json!({"sessionUpdate": crate::RETRY_UPDATE, "attempt": 3, "maxRetries": 10, "retryDelayMs": 4000,
"error": "Connection error."})
);
}
#[test]
fn streamed_text_is_not_sent_twice() {
let mut t = Translator::new("s", PathBuf::from("/w"), true);
-18
Переглянути файл
@@ -5,7 +5,6 @@
//! Agent tool use that launched them: their messages carry it as `parent_tool_use_id`.
use super::tools;
use crate::RETRY_UPDATE;
use serde_json::{Value, json};
use std::collections::{HashMap, VecDeque};
use std::path::PathBuf;
@@ -428,23 +427,6 @@ impl Translator {
}
Vec::new()
}
// Claude Code retries a failed API request on its own; without this the turn looks stuck.
Some("api_retry") => {
let n = |k: &str| msg.get(k).and_then(Value::as_u64);
let error = msg.get("error").and_then(|e| {
e.as_str().map(str::to_owned).or_else(|| e.get("message")?.as_str().map(str::to_owned))
});
vec![Update {
session: self.root.clone(),
update: json!({
"sessionUpdate": RETRY_UPDATE,
"attempt": n("attempt").unwrap_or(1),
"maxRetries": n("max_retries"),
"retryDelayMs": n("retry_delay_ms").unwrap_or(0),
"error": error,
}),
}]
}
Some("task_notification") if self.children.get(&tool_use).is_some_and(|c| c.background != Some(false)) => {
let stop = match msg.get("status").and_then(Value::as_str) {
Some("failed") => "error",
+1 -1
Переглянути файл
@@ -504,7 +504,7 @@ fn install_binary(b: &Binary, dir: &Path, cancel: &CancellationToken, emit: Emit
ArchiveKind::Raw | ArchiveKind::Gz => parents.iter().fold(dir.to_path_buf(), |p, s| p.join(s)),
_ => dir.to_path_buf(),
};
archive::extract(&file, kind, &dest, exe_name, cancel)?;
archive::extract(&file, kind, &dest, exe_name)?;
let _ = fs::remove_dir_all(&downloads);
let exe = segments.iter().fold(dir.to_path_buf(), |p, s| p.join(s));
if !exe.is_file() {
-11
Переглянути файл
@@ -709,14 +709,3 @@ async fn usage_limits_and_late_settings() {
let config = mgr.task(&task.id).unwrap().state.lock().task.config.clone();
assert_eq!(config.iter().find(|o| o.id == "effort").unwrap().current.as_deref(), Some("high"));
}
#[test]
fn retry_updates_become_a_countdown() {
let update =
json!({"sessionUpdate": RETRY_UPDATE, "attempt": 2, "maxRetries": 10, "retryDelayMs": 1500, "error": ""});
assert_eq!(
retry_of(&update, 1000.0),
Some(AgentRetry { attempt: 2, max_retries: Some(10), retry_at_ms: 2500.0, error: None })
);
assert_eq!(retry_of(&json!({"sessionUpdate": RETRY_UPDATE}), 0.0), None, "no attempt");
}
-2
Переглянути файл
@@ -50,8 +50,6 @@ pub enum IdeEvent {
message: Option<String>,
fraction: Option<f32>,
done: bool,
/// The UI may stop it with `cancel_task(id)` (see [`crate::task`]).
cancellable: bool,
},
/// Project indexing state changed (dumb mode on/off).
IndexState {
-90
Переглянути файл
@@ -1,90 +0,0 @@
//! JSON with comments (`devcontainer.json`, `deno.jsonc`, `tsconfig.json`): turned
//! into plain JSON for `serde_json`.
/// Strips `//` and `/* */` comments and trailing commas so JSONC parses as JSON.
pub fn strip(src: &str) -> String {
let mut out = String::with_capacity(src.len());
let mut chars = src.chars().peekable();
let mut in_str = false;
while let Some(c) = chars.next() {
if in_str {
out.push(c);
if c == '\\' {
if let Some(n) = chars.next() {
out.push(n);
}
} else if c == '"' {
in_str = false;
}
continue;
}
match c {
'"' => {
in_str = true;
out.push(c);
}
'/' if chars.peek() == Some(&'/') => {
for n in chars.by_ref() {
if n == '\n' {
out.push('\n');
break;
}
}
}
'/' if chars.peek() == Some(&'*') => {
chars.next();
let mut prev = '\0';
for n in chars.by_ref() {
if prev == '*' && n == '/' {
break;
}
prev = n;
}
}
_ => out.push(c),
}
}
// Remove trailing commas before `}` / `]` (outside strings).
let mut cleaned = String::with_capacity(out.len());
let bytes: Vec<char> = out.chars().collect();
let mut in_str = false;
let mut i = 0;
while i < bytes.len() {
let c = bytes[i];
if in_str {
cleaned.push(c);
if c == '\\' && i + 1 < bytes.len() {
cleaned.push(bytes[i + 1]);
i += 1;
} else if c == '"' {
in_str = false;
}
} else if c == '"' {
in_str = true;
cleaned.push(c);
} else if c == ',' {
let next = bytes[i + 1..].iter().find(|ch| !ch.is_whitespace());
if !matches!(next, Some('}') | Some(']')) {
cleaned.push(c);
}
} else {
cleaned.push(c);
}
i += 1;
}
cleaned
}
#[cfg(test)]
mod tests {
use super::strip;
#[test]
fn drops_comments_and_trailing_commas_outside_strings() {
let src = "{\n // line\n \"a\": [1, 2,], /* block */\n \"url\": \"https://x.dev//y /* no */\",\n \"q\": \"say \\\"hi\\\",\",\n}\n";
let v: serde_json::Value = serde_json::from_str(&strip(src)).unwrap();
assert_eq!(v["a"], serde_json::json!([1, 2]));
assert_eq!(v["url"], "https://x.dev//y /* no */");
assert_eq!(v["q"], "say \"hi\",");
}
}
-3
Переглянути файл
@@ -11,13 +11,10 @@ pub mod ids;
pub mod ignored;
pub mod inspection_settings;
pub mod ipc_path;
pub mod jsonc;
pub mod process;
pub mod project_dir;
pub mod proxy_settings;
pub mod remote_settings;
pub mod settings;
pub mod task;
pub mod text;
pub mod workflow_settings;
+25 -135
Переглянути файл
@@ -2,7 +2,7 @@
use std::ffi::{OsStr, OsString};
use std::process::Command;
use std::sync::{Arc, RwLock};
use std::sync::OnceLock;
/// Windows `CREATE_NO_WINDOW` creation flag, for call sites that combine it
/// with other flags (and then call [`host_env`] themselves). Prefer [`prepare`] otherwise.
@@ -13,7 +13,7 @@ pub const CREATE_NO_WINDOW: u32 = 0x0800_0000;
///
/// - Windows: release builds use the GUI subsystem, so without `CREATE_NO_WINDOW` every
/// console child flashes a `cmd` window.
/// - Linux AppImage, reloaded and project variables: see [`host_env`].
/// - Linux AppImage: see [`host_env`].
///
/// Variables the call site has already set are kept; call it before `env_clear`.
pub fn prepare(cmd: &mut Command) -> &mut Command {
@@ -30,12 +30,10 @@ pub fn prepare(cmd: &mut Command) -> &mut Command {
/// `GST_PLUGIN_*`, ... into the mounted image for the IDE itself; a host program that
/// inherits them loads the image's (older) libraries and plugins next to its own, e.g.
/// `curl: symbol lookup error ... nghttp2_...`. The IDE process keeps its environment
/// (WebKit and GTK still need it). Then applies the [`set_env_overlay`] variables and
/// those of a manual HTTP proxy ([`crate::proxy_settings::ProxySettings::child_env`]).
/// Variables the call site has already set are kept. A no-op outside an AppImage
/// without an overlay.
/// (WebKit and GTK still need it). Variables the call site has already set are kept.
/// A no-op outside an AppImage.
pub fn host_env(cmd: &mut Command) -> &mut Command {
let fixes = child_env_changes();
let fixes = appimage_fixes();
if fixes.is_empty() {
return cmd;
}
@@ -51,58 +49,30 @@ pub fn host_env(cmd: &mut Command) -> &mut Command {
/// The [`host_env`] changes as `(name, value)` pairs, `None` meaning "remove", for spawners
/// that are not a `std::process::Command` (a PTY `CommandBuilder`). Apply before the call
/// site's own variables. Empty outside an AppImage without an overlay.
/// site's own variables. Empty outside an AppImage.
pub fn host_env_fixes() -> Vec<(OsString, Option<OsString>)> {
child_env_changes()
appimage_fixes()
}
/// This process's environment as a child should inherit it (see [`host_env`]), for call
/// sites that build a child's environment from the IDE's own instead of inheriting it.
pub fn host_vars() -> impl Iterator<Item = (OsString, OsString)> {
apply_changes(std::env::vars_os().collect(), &child_env_changes()).into_iter()
let fixes = appimage_fixes();
std::env::vars_os().filter_map(move |(k, v)| match fixes.iter().find(|(f, _)| *f == k) {
Some((_, fixed)) => fixed.clone().map(|v| (k, v)),
None => Some((k, v)),
})
}
/// [`std::env::var_os`] as a child should see it (see [`host_env`]).
pub fn host_var_os(key: impl AsRef<OsStr>) -> Option<OsString> {
let key = key.as_ref();
match child_env_changes().into_iter().find(|(k, _)| k == key) {
match appimage_fixes().into_iter().find(|(k, _)| k == key) {
Some((_, fixed)) => fixed,
None => std::env::var_os(key),
}
}
/// `vars` with `changes` applied (`None` removes), new names appended.
fn apply_changes(
mut vars: Vec<(OsString, OsString)>,
changes: &[(OsString, Option<OsString>)],
) -> Vec<(OsString, OsString)> {
for (key, value) in changes {
let at = vars.iter().position(|(k, _)| k == key);
match (at, value) {
(Some(i), Some(v)) => vars[i].1 = v.clone(),
(Some(i), None) => {
vars.remove(i);
}
(None, Some(v)) => vars.push((key.clone(), v.clone())),
(None, None) => {}
}
}
vars
}
/// The AppImage fixes, the overlay, then the manual proxy's (a later one wins); one entry per name.
fn child_env_changes() -> Vec<(OsString, Option<OsString>)> {
let mut changes = appimage_fixes();
let overlay = env_overlay();
changes.retain(|(k, _)| !overlay.iter().any(|(o, _)| o == k));
changes.extend(overlay.iter().cloned());
// A manual HTTP proxy reaches tools that read `HTTP_PROXY` (language servers, git, curl).
let proxy = crate::proxy_settings::proxy().child_env();
changes.retain(|(k, _)| !proxy.iter().any(|(p, _)| p == k));
changes.extend(proxy);
changes
}
/// Read on every call, not cached: startup rewrites `PATH` (login shell, managed tools).
fn appimage_fixes() -> Vec<(OsString, Option<OsString>)> {
if !cfg!(target_os = "linux") || std::env::var_os("APPDIR").is_none() {
@@ -150,72 +120,23 @@ fn appimage_env_fixes(vars: &[(OsString, OsString)]) -> Vec<(OsString, Option<Os
fixes
}
type Vars = Arc<Vec<(OsString, OsString)>>;
type Changes = Arc<Vec<(OsString, Option<OsString>)>>;
static SHELL_ENV: OnceLock<Vec<(OsString, OsString)>> = OnceLock::new();
static SHELL_ENV: RwLock<Option<Vars>> = RwLock::new(None);
static OVERLAY: RwLock<Option<Changes>> = RwLock::new(None);
/// Records the login shell's environment: read at startup off the main thread, and again
/// by Reload Environment.
/// Records the login shell's environment, read once at startup off the main thread.
pub fn set_shell_env(vars: Vec<(OsString, OsString)>) {
*SHELL_ENV.write().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(vars));
}
/// The login shell's environment as last read, all of it (`None` until it has been read).
pub fn login_env() -> Option<Vars> {
SHELL_ENV.read().unwrap_or_else(|e| e.into_inner()).clone()
let _ = SHELL_ENV.set(vars);
}
/// The login shell's variables this process lacks: an app started from Finder/Dock gets only
/// PATH from the shell, not what rc files export (API keys and provider switches, SDK homes...).
/// Apply before a call site's own variables so those win. Empty until the shell has been read.
/// Names the overlay sets are left out: [`host_env`] gives them their value.
pub fn shell_env() -> impl Iterator<Item = (OsString, OsString)> {
let overlay = env_overlay();
let vars = login_env().unwrap_or_default();
let lacking: Vec<_> = vars
.iter()
.filter(|(k, _)| std::env::var_os(k).is_none() && !overlay.iter().any(|(o, _)| o == k))
.cloned()
.collect();
lacking.into_iter()
}
/// Variables every child process gets on top of this process's environment (`None`: removed)
/// unless its call site sets them: an environment re-read after startup (this process's own
/// can't change safely once threads run) and the project's (`remoteEnv`). Replaces the
/// previous overlay; children already running keep what they started with.
pub fn set_env_overlay(changes: Vec<(OsString, Option<OsString>)>) {
*OVERLAY.write().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(changes));
}
/// The current [`set_env_overlay`] variables.
pub fn env_overlay() -> Changes {
OVERLAY.read().unwrap_or_else(|e| e.into_inner()).clone().unwrap_or_default()
}
const DEFAULT_PATHEXT: &str = ".COM;.EXE;.BAT;.CMD";
/// File names an executable `name` may have on disk. Unix: the name itself. Windows: the
/// name when it already ends in a `PATHEXT` extension, else the name with each
/// extension (an extensionless file is not executable there).
pub fn executable_names(name: &str, windows: bool, pathext: Option<&str>) -> Vec<String> {
if !windows {
return vec![name.to_owned()];
}
let exts: Vec<&str> = pathext
.filter(|p| !p.trim().is_empty())
.unwrap_or(DEFAULT_PATHEXT)
.split(';')
.map(str::trim)
.filter(|e| e.starts_with('.') && e.len() > 1)
.collect();
let lower = name.to_ascii_lowercase();
if exts.iter().any(|e| lower.ends_with(&e.to_ascii_lowercase())) {
return vec![name.to_owned()];
}
exts.iter().map(|e| format!("{name}{}", e.to_ascii_lowercase())).collect()
pub fn shell_env() -> impl Iterator<Item = (&'static OsStr, &'static OsStr)> {
SHELL_ENV
.get()
.into_iter()
.flatten()
.filter(|(k, _)| std::env::var_os(k).is_none())
.map(|(k, v)| (k.as_os_str(), v.as_os_str()))
}
#[cfg(test)]
@@ -223,41 +144,10 @@ mod tests {
use super::*;
#[test]
fn shell_env_adds_only_what_the_process_lacks_and_the_overlay_wins() {
fn shell_env_adds_only_what_the_process_lacks() {
set_shell_env(vec![("OPENIDEA_SHELL_ONLY_VAR".into(), "1".into()), ("PATH".into(), "/from/shell".into())]);
let vars: Vec<_> = shell_env().collect();
assert_eq!(vars, [(OsString::from("OPENIDEA_SHELL_ONLY_VAR"), OsString::from("1"))]);
// The overlay (process-wide too, hence the same test).
set_shell_env(vec![("OPENIDEA_OVERLAY_A".into(), "shell".into()), ("OPENIDEA_OVERLAY_B".into(), "b".into())]);
set_env_overlay(vec![
("OPENIDEA_OVERLAY_A".into(), Some("project".into())),
("PATH".into(), Some("/reloaded".into())),
("HOME".into(), None),
]);
let mut cmd = Command::new("true");
cmd.env("PATH", "/custom");
host_env(&mut cmd);
let get = |k: &str| cmd.get_envs().find(|(n, _)| *n == k).map(|(_, v)| v.map(OsStr::to_owned));
assert_eq!(get("OPENIDEA_OVERLAY_A"), Some(Some("project".into())));
assert_eq!(get("PATH"), Some(Some("/custom".into())), "the call site's value wins");
assert_eq!(get("HOME"), Some(None));
let shell: Vec<_> = shell_env().map(|(k, _)| k).collect();
assert_eq!(shell, [OsString::from("OPENIDEA_OVERLAY_B")]);
assert_eq!(host_var_os("PATH"), Some("/reloaded".into()));
assert!(host_vars().all(|(k, _)| k != "HOME"));
assert!(host_vars().any(|(k, v)| k == "OPENIDEA_OVERLAY_A" && v == "project"));
assert_eq!(host_env_fixes().len(), env_overlay().len());
set_env_overlay(Vec::new());
}
#[test]
fn changes_apply_in_order() {
let vars = apply_changes(
env(&[("A", "1"), ("B", "2")]),
&[("A".into(), Some("3".into())), ("B".into(), None), ("C".into(), Some("4".into())), ("D".into(), None)],
);
assert_eq!(vars, env(&[("A", "3"), ("C", "4")]));
assert_eq!(vars, [(OsStr::new("OPENIDEA_SHELL_ONLY_VAR"), OsStr::new("1"))]);
}
fn env(pairs: &[(&str, &str)]) -> Vec<(OsString, OsString)> {
-365
Переглянути файл
@@ -1,365 +0,0 @@
//! Appearance & Behavior › System Settings › HTTP Proxy, and the proxy the IDE's own
//! connections use: [`set_proxy`] makes a configuration current, every outgoing
//! request asks [`proxy`] (the HTTP client, `curl` downloads, the updater), and with a
//! manual proxy child processes get `HTTP_PROXY` / `HTTPS_PROXY` / `NO_PROXY`.
use serde::{Deserialize, Serialize};
use specta::Type;
use std::ffi::OsString;
use std::sync::{Arc, RwLock};
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum ProxyMode {
/// Every connection goes direct.
None,
/// The system's proxy: `HTTP_PROXY` / `HTTPS_PROXY` / `NO_PROXY` of the environment.
#[default]
Auto,
/// The proxy configured here.
Manual,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum ProxyKind {
#[default]
Http,
Socks,
}
impl ProxyKind {
pub fn default_port(self) -> u16 {
match self {
ProxyKind::Http => 80,
ProxyKind::Socks => 1080,
}
}
fn scheme(self) -> &'static str {
match self {
ProxyKind::Http => "http",
// Host names resolve on the proxy.
ProxyKind::Socks => "socks5h",
}
}
}
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct ProxySettings {
pub mode: ProxyMode,
pub kind: ProxyKind,
pub host: String,
pub port: u16,
/// Hosts reached directly, comma-separated; `*` matches any characters (`*.example.com`, `192.168.*`).
pub no_proxy: String,
/// Send `login` / `password` to the proxy.
pub authenticate: bool,
pub login: String,
/// Kept in the saved passwords rather than `settings.toml`; filled in when settings are read.
pub password: String,
}
impl Default for ProxySettings {
fn default() -> Self {
Self {
mode: ProxyMode::Auto,
kind: ProxyKind::Http,
host: String::new(),
port: ProxyKind::Http.default_port(),
no_proxy: String::new(),
authenticate: false,
login: String::new(),
password: String::new(),
}
}
}
impl std::fmt::Debug for ProxySettings {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ProxySettings")
.field("mode", &self.mode)
.field("kind", &self.kind)
.field("host", &self.host)
.field("port", &self.port)
.field("no_proxy", &self.no_proxy)
.field("authenticate", &self.authenticate)
.field("login", &self.login)
.field("password", &if self.password.is_empty() { "" } else { "***" })
.finish()
}
}
/// How a connection to some host is made.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProxyRoute {
Direct,
/// Whatever the environment says (the HTTP library's / `curl`'s own proxy lookup).
System,
/// Through this proxy URL, credentials included (`http://user:pass@proxy:3128`).
Via(String),
}
/// Loopback hosts never go through the manual proxy.
const LOOPBACK: [&str; 3] = ["localhost", "127.0.0.1", "::1"];
impl ProxySettings {
/// A manual proxy with a host: what [`Self::route`] sends connections through.
pub fn manual(&self) -> bool {
self.mode == ProxyMode::Manual && !self.host.trim().is_empty()
}
/// What is wrong with the manual configuration, if anything.
pub fn problem(&self) -> Option<String> {
if self.mode != ProxyMode::Manual {
return None;
}
let host = self.host.trim();
if host.is_empty() {
return Some("Proxy host is empty".into());
}
if host.contains(['/', '@', ' ']) {
return Some(format!("Invalid proxy host: {host}"));
}
if self.port == 0 {
return Some("Proxy port must be between 1 and 65535".into());
}
if self.authenticate && self.login.trim().is_empty() {
return Some("Proxy login is empty".into());
}
None
}
/// Whether `host` is reached directly: loopback, or a "No proxy for" entry.
pub fn bypasses(&self, host: &str) -> bool {
let host = host.trim().trim_start_matches('[').trim_end_matches(']').to_ascii_lowercase();
if LOOPBACK.contains(&host.as_str()) {
return true;
}
self.no_proxy_entries().any(|pattern| glob_match(&pattern, &host))
}
fn no_proxy_entries(&self) -> impl Iterator<Item = String> + '_ {
self.no_proxy.split([',', ';', '\n']).map(|e| e.trim().to_ascii_lowercase()).filter(|e| !e.is_empty())
}
/// The manual proxy as a URL, with the credentials when it authenticates.
pub fn proxy_url(&self) -> Option<String> {
if !self.manual() {
return None;
}
let host = self.host.trim();
let host = if host.contains(':') && !host.starts_with('[') { format!("[{host}]") } else { host.to_owned() };
let auth = if self.authenticate && !self.login.is_empty() {
format!("{}:{}@", encode_userinfo(&self.login), encode_userinfo(&self.password))
} else {
String::new()
};
Some(format!("{}://{auth}{host}:{}", self.kind.scheme(), self.port))
}
/// How to connect to `host` (`None`: not known yet, e.g. the request has no URL).
pub fn route(&self, host: Option<&str>) -> ProxyRoute {
match self.mode {
ProxyMode::None => ProxyRoute::Direct,
ProxyMode::Auto => ProxyRoute::System,
ProxyMode::Manual => match self.proxy_url() {
Some(_) if host.is_some_and(|h| self.bypasses(h)) => ProxyRoute::Direct,
Some(url) => ProxyRoute::Via(url),
None => ProxyRoute::Direct,
},
}
}
/// [`Self::route`] for the host of `url` (`https://user@host:443/path`).
pub fn route_for_url(&self, url: &str) -> ProxyRoute {
self.route(url_host(url).as_deref())
}
/// Arguments that make a `curl` download of `url` follow this configuration. The
/// manual proxy itself comes from the environment (see [`Self::child_env`]), which
/// keeps the credentials out of the command line.
pub fn curl_args(&self, url: &str) -> Vec<&'static str> {
match self.route_for_url(url) {
ProxyRoute::Direct => vec!["--noproxy", "*"],
ProxyRoute::System => Vec::new(),
// Only this configuration decides what bypasses the proxy.
ProxyRoute::Via(_) => vec!["--noproxy", ""],
}
}
/// Variables child processes get with a manual proxy (`HTTP_PROXY`, `HTTPS_PROXY`,
/// `ALL_PROXY`, `NO_PROXY` and their lowercase forms); none otherwise.
pub fn child_env(&self) -> Vec<(OsString, Option<OsString>)> {
let Some(url) = self.proxy_url() else { return Vec::new() };
let mut no_proxy: Vec<String> = LOOPBACK.iter().map(|h| (*h).to_owned()).collect();
// `*.example.com` is `.example.com` to curl, Go, Python and Node.
no_proxy.extend(self.no_proxy_entries().map(|e| e.strip_prefix('*').map(str::to_owned).unwrap_or(e)));
no_proxy.dedup();
let no_proxy = no_proxy.join(",");
let mut env = Vec::new();
for name in ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"] {
env.push((OsString::from(name), Some(OsString::from(&url))));
env.push((OsString::from(name.to_ascii_lowercase()), Some(OsString::from(&url))));
}
env.push((OsString::from("NO_PROXY"), Some(OsString::from(&no_proxy))));
env.push((OsString::from("no_proxy"), Some(OsString::from(no_proxy))));
env
}
}
/// Case-insensitive host glob (`pattern` is lowercase): `*` matches any run of characters.
fn glob_match(pattern: &str, host: &str) -> bool {
let (p, h) = (pattern.as_bytes(), host.as_bytes());
let (mut pi, mut hi) = (0, 0);
let mut star: Option<(usize, usize)> = None;
while hi < h.len() {
if pi < p.len() && p[pi] == b'*' {
star = Some((pi, hi));
pi += 1;
} else if pi < p.len() && p[pi] == h[hi] {
pi += 1;
hi += 1;
} else if let Some((sp, sh)) = star {
pi = sp + 1;
hi = sh + 1;
star = Some((sp, sh + 1));
} else {
return false;
}
}
p[pi..].iter().all(|&c| c == b'*')
}
fn encode_userinfo(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for b in s.bytes() {
if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
out.push(b as char);
} else {
out.push_str(&format!("%{b:02X}"));
}
}
out
}
/// The host of `url`, without brackets, userinfo or port.
fn url_host(url: &str) -> Option<String> {
let rest = url.split_once("://").map_or(url, |(_, r)| r);
let authority = rest.split(['/', '?', '#']).next()?;
let authority = authority.rsplit_once('@').map_or(authority, |(_, a)| a);
let host =
if let Some(v6) = authority.strip_prefix('[') { v6.split(']').next()? } else { authority.split(':').next()? };
(!host.is_empty()).then(|| host.to_ascii_lowercase())
}
static CURRENT: RwLock<Option<Arc<ProxySettings>>> = RwLock::new(None);
/// Makes `settings` (password filled in) the proxy of every later connection and child process.
pub fn set_proxy(settings: ProxySettings) {
*CURRENT.write().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(settings));
}
/// The current proxy configuration (the default, auto-detect, until [`set_proxy`]).
pub fn proxy() -> Arc<ProxySettings> {
CURRENT.read().unwrap_or_else(|e| e.into_inner()).clone().unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::*;
fn manual(host: &str, port: u16) -> ProxySettings {
ProxySettings { mode: ProxyMode::Manual, host: host.into(), port, ..Default::default() }
}
#[test]
fn auto_is_the_default_and_defers_to_the_system() {
let p = ProxySettings::default();
assert_eq!(p.mode, ProxyMode::Auto);
assert_eq!(p.route_for_url("https://example.com/"), ProxyRoute::System);
assert!(p.curl_args("https://example.com/").is_empty());
assert!(p.child_env().is_empty());
assert_eq!(p.problem(), None);
}
#[test]
fn no_proxy_goes_direct() {
let p = ProxySettings { mode: ProxyMode::None, ..manual("proxy", 3128) };
assert_eq!(p.route_for_url("https://example.com/"), ProxyRoute::Direct);
assert_eq!(p.curl_args("https://example.com/"), ["--noproxy", "*"]);
assert!(p.child_env().is_empty());
}
#[test]
fn manual_http_and_socks_urls() {
let p = manual("proxy.corp", 3128);
assert_eq!(p.route_for_url("https://example.com/x"), ProxyRoute::Via("http://proxy.corp:3128".into()));
assert_eq!(p.curl_args("https://example.com/x"), ["--noproxy", ""]);
let socks = ProxySettings { kind: ProxyKind::Socks, ..manual("10.0.0.1", 1080) };
assert_eq!(socks.proxy_url().as_deref(), Some("socks5h://10.0.0.1:1080"));
assert_eq!(manual("::1", 8080).proxy_url().as_deref(), Some("http://[::1]:8080"));
// Manual without a host connects directly.
assert_eq!(manual(" ", 80).route(Some("example.com")), ProxyRoute::Direct);
assert!(manual(" ", 80).problem().is_some());
assert!(manual("proxy", 0).problem().is_some());
assert!(manual("http://proxy", 80).problem().is_some());
}
#[test]
fn credentials_are_percent_encoded() {
let p = ProxySettings {
authenticate: true,
login: "dom\\me".into(),
password: "p@ss:w/rd".into(),
..manual("proxy", 3128)
};
assert_eq!(p.proxy_url().as_deref(), Some("http://dom%5Cme:p%40ss%3Aw%2Frd@proxy:3128"));
// Not sent without "Proxy authentication".
let off = ProxySettings { authenticate: false, ..p.clone() };
assert_eq!(off.proxy_url().as_deref(), Some("http://proxy:3128"));
assert!(ProxySettings { login: " ".into(), ..p.clone() }.problem().is_some());
assert!(!format!("{p:?}").contains("p@ss"));
}
#[test]
fn no_proxy_for_list_matches_globs_and_loopback() {
let p = ProxySettings { no_proxy: "*.example.com, 192.168.*,Intranet".into(), ..manual("proxy", 3128) };
assert!(p.bypasses("api.example.com"));
assert!(p.bypasses("a.b.EXAMPLE.com"));
assert!(!p.bypasses("example.com"));
assert!(!p.bypasses("example.com.evil.org"));
assert!(p.bypasses("192.168.1.20"));
assert!(p.bypasses("intranet"));
assert!(!p.bypasses("intranet2"));
assert!(p.bypasses("localhost") && p.bypasses("127.0.0.1") && p.bypasses("[::1]"));
assert_eq!(p.route_for_url("https://[email protected]:8443/v1"), ProxyRoute::Direct);
assert_eq!(p.curl_args("http://192.168.0.5/"), ["--noproxy", "*"]);
assert!(matches!(p.route_for_url("https://github.com"), ProxyRoute::Via(_)));
}
#[test]
fn child_processes_get_the_manual_proxy() {
let p = ProxySettings {
no_proxy: "*.corp, 10.*".into(),
authenticate: true,
login: "me".into(),
password: "pw".into(),
..manual("proxy", 3128)
};
let env = p.child_env();
let get = |k: &str| env.iter().find(|(n, _)| n == k).and_then(|(_, v)| v.clone()).unwrap();
assert_eq!(get("HTTPS_PROXY"), "http://me:pw@proxy:3128");
assert_eq!(get("http_proxy"), "http://me:pw@proxy:3128");
assert_eq!(get("NO_PROXY"), "localhost,127.0.0.1,::1,.corp,10.*");
}
#[test]
fn url_hosts() {
assert_eq!(url_host("https://Example.com:443/a?b").as_deref(), Some("example.com"));
assert_eq!(url_host("http://u:p@[::1]:80/").as_deref(), Some("::1"));
assert_eq!(url_host("example.com/x").as_deref(), Some("example.com"));
assert_eq!(url_host("file:///tmp/x"), None);
}
}
-4
Переглянути файл
@@ -7,7 +7,6 @@ use std::collections::BTreeMap;
pub use crate::editor_settings::*;
pub use crate::inspection_settings::*;
pub use crate::proxy_settings::{ProxyKind, ProxyMode, ProxySettings};
pub use crate::remote_settings::*;
pub use crate::workflow_settings::*;
@@ -26,8 +25,6 @@ pub struct Settings {
/// keymap's own overrides. `keymap` may name one of these ids.
pub custom_keymaps: BTreeMap<String, CustomKeymap>,
pub notifications: NotificationSettings,
/// System Settings › HTTP Proxy (global only).
pub proxy: ProxySettings,
/// Interpreters / toolchains per language (Python, Node.js, Rust, Go, TypeScript).
pub languages: LanguagesSettings,
/// Project Structure: source / test / resource / excluded folders (project-relative).
@@ -137,7 +134,6 @@ impl Default for Settings {
keymap_overrides: BTreeMap::new(),
custom_keymaps: BTreeMap::new(),
notifications: NotificationSettings::default(),
proxy: ProxySettings::default(),
languages: LanguagesSettings::default(),
project_structure: ProjectStructureSettings::default(),
vcs: VcsSettings::default(),
-74
Переглянути файл
@@ -1,74 +0,0 @@
//! Cancelling background tasks the backend reports itself ([`IdeEvent::Task`](crate::IdeEvent)
//! with `cancellable`), such as a language server's work-done progress. Requests the UI
//! starts are cancelled through their `RequestId` instead.
use crate::TaskId;
use std::collections::HashMap;
use std::sync::{Mutex, MutexGuard};
type Cancel = Box<dyn FnOnce() + Send>;
static CANCELS: Mutex<Option<HashMap<TaskId, Cancel>>> = Mutex::new(None);
fn cancels() -> MutexGuard<'static, Option<HashMap<TaskId, Cancel>>> {
CANCELS.lock().unwrap_or_else(|e| e.into_inner())
}
/// Keeps task `id` cancellable with [`cancel`] until dropped (when the task ends).
#[must_use = "the task stops being cancellable when this is dropped"]
pub struct CancelHandle(TaskId);
impl Drop for CancelHandle {
fn drop(&mut self) {
if let Some(map) = cancels().as_mut() {
map.remove(&self.0);
}
}
}
/// Makes task `id` cancellable: [`cancel`] runs `f` once, while the handle lives.
pub fn on_cancel(id: TaskId, f: impl FnOnce() + Send + 'static) -> CancelHandle {
cancels().get_or_insert_with(HashMap::new).insert(id, Box::new(f));
CancelHandle(id)
}
/// Cancels task `id`; false when it is not cancellable (or already ended / cancelled).
pub fn cancel(id: TaskId) -> bool {
let f = cancels().as_mut().and_then(|map| map.remove(&id));
match f {
Some(f) => {
f();
true
}
None => false,
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
#[test]
fn cancel_runs_the_callback_once_while_the_handle_lives() {
let hits = Arc::new(AtomicUsize::new(0));
let id = TaskId::next();
let h = hits.clone();
let handle = on_cancel(id, move || {
h.fetch_add(1, Ordering::SeqCst);
});
assert!(cancel(id));
assert!(!cancel(id));
assert_eq!(hits.load(Ordering::SeqCst), 1);
drop(handle);
let other = TaskId::next();
let h = hits.clone();
drop(on_cancel(other, move || {
h.fetch_add(1, Ordering::SeqCst);
}));
assert!(!cancel(other), "an ended task is not cancelled");
assert_eq!(hits.load(Ordering::SeqCst), 1);
}
}
-3
Переглянути файл
@@ -221,8 +221,6 @@ pub struct DebuggerSettings {
/// Data Views: list variables by name instead of the adapter's order.
pub sort_values: bool,
pub value_tooltip: bool,
/// While suspended, selecting an expression shows its value.
pub value_tooltip_on_selection: bool,
pub value_tooltip_delay: u32,
/// Stepping: do not step into library code (debugpy `justMyCode`, js-debug `skipFiles`).
pub skip_library_code: bool,
@@ -240,7 +238,6 @@ impl Default for DebuggerSettings {
inline_values: true,
sort_values: false,
value_tooltip: true,
value_tooltip_on_selection: true,
value_tooltip_delay: 700,
skip_library_code: true,
python: PythonDebuggerSettings::default(),
+13 -108
Переглянути файл
@@ -6,7 +6,6 @@
//! Adapters that run inside another process (java-debug inside jdtls) are
//! reached through a `debugServer` port in the launch arguments instead.
use ide_core::process::executable_names;
use ide_core::{IdeError, IdeResult};
use ide_language::{DebuggerConfig, LanguageRegistry};
use std::future::Future;
@@ -196,43 +195,30 @@ fn search_dirs() -> Vec<PathBuf> {
dirs
}
fn is_executable(path: &Path, windows: bool) -> bool {
fn is_executable(path: &Path) -> bool {
#[cfg(unix)]
if !windows {
{
use std::os::unix::fs::PermissionsExt;
return path.metadata().map(|m| m.is_file() && m.permissions().mode() & 0o111 != 0).unwrap_or(false);
path.metadata().map(|m| m.is_file() && m.permissions().mode() & 0o111 != 0).unwrap_or(false)
}
#[cfg(not(unix))]
let _ = windows;
path.is_file()
{
path.is_file()
}
}
/// Resolves `command` to an executable: paths are taken as-is (relative to `cwd`), bare names are looked up on PATH.
/// On Windows only `PATHEXT` files count (`foo` → `foo.exe` / `foo.cmd`), so a `.jar` or an
/// extensionless script next to a shim is never started as a program.
pub fn find_binary(command: &str, cwd: &Path) -> Option<PathBuf> {
let pathext = std::env::var("PATHEXT").ok();
find_binary_in(command, cwd, &search_dirs(), cfg!(windows), pathext.as_deref())
}
fn find_binary_in(
command: &str,
cwd: &Path,
dirs: &[PathBuf],
windows: bool,
pathext: Option<&str>,
) -> Option<PathBuf> {
let p = Path::new(command);
if p.components().count() > 1 || p.is_absolute() {
let full = if p.is_absolute() { p.to_path_buf() } else { cwd.join(p) };
let (dir, name) = (full.parent()?, full.file_name()?.to_str()?);
return executable_names(name, windows, pathext)
.into_iter()
.map(|n| dir.join(n))
.find(|c| is_executable(c, windows));
return is_executable(&full).then_some(full);
}
let names = executable_names(command, windows, pathext);
dirs.iter().flat_map(|d| names.iter().map(move |n| d.join(n))).find(|c| is_executable(c, windows))
let exts: &[&str] = if cfg!(windows) { &["", ".exe", ".cmd", ".bat"] } else { &[""] };
search_dirs()
.into_iter()
.flat_map(|d| exts.iter().map(move |e| d.join(format!("{command}{e}"))))
.find(|c| is_executable(c))
}
/// [`find_binary`], plus Xcode's toolchain on macOS (`xcrun -f lldb-dap`): Xcode ships
@@ -248,7 +234,7 @@ fn xcrun_tool(command: &str) -> Option<PathBuf> {
}
let out = std::process::Command::new("/usr/bin/xcrun").args(["-f", command]).stderr(Stdio::null()).output().ok()?;
let path = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
(out.status.success() && is_executable(&path, false)).then_some(path)
(out.status.success() && is_executable(&path)).then_some(path)
}
#[cfg(not(target_os = "macos"))]
@@ -302,22 +288,6 @@ pub async fn prepare_debugpy(spec: &mut AdapterSpec) -> IdeResult<()> {
)))
}
/// An adapter that is a plugin of another program (java-debug, a jdtls bundle) rather
/// than a program: it has no process of its own and is reached through `debugServer`.
pub fn is_plugin_bundle(command: &str) -> bool {
Path::new(command).extension().is_some_and(|e| e.eq_ignore_ascii_case("jar"))
}
/// A launch of a plugin adapter without the `debugServer` of its host program.
pub fn not_standalone(spec: &AdapterSpec) -> IdeError {
IdeError::unavailable(format!(
"debug adapter `{}` runs inside the Java language server and can't be started on its own. \
Debug an Application, Spring Boot, JUnit, Maven or Gradle configuration, or start the JVM \
with a JDWP agent and attach with a Remote JVM Debug configuration",
spec.adapter
))
}
pub fn missing(spec: &AdapterSpec) -> IdeError {
let mut msg = format!(
"debug adapter `{}` not found (`{}` is neither installed by OpenIDEA nor on PATH)",
@@ -406,9 +376,6 @@ impl AdapterLauncher for ProcessLauncher {
if spec.adapter == DEBUGPY_TOOL {
prepare_debugpy(&mut spec).await?;
}
if is_plugin_bundle(&spec.command) {
return Err(not_standalone(&spec));
}
let (command, cwd) = (spec.command.clone(), spec.cwd.clone());
let binary = tokio::task::spawn_blocking(move || resolve_binary(&command, &cwd))
.await
@@ -617,66 +584,4 @@ mod tests {
let err = ProcessLauncher.launch(spec, None).await.err().unwrap();
assert_eq!(err.kind, ide_core::error::ErrorKind::Unavailable);
}
/// The managed tools layout (`<tools>/<tool>/bin`) as Windows sees it: only `PATHEXT`
/// files run, so the java-debug bundle jar and POSIX shims are never adapter programs.
#[test]
fn windows_resolution_only_takes_pathext_files() {
let dir = std::env::temp_dir().join(format!("openidea-dap-win-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let java_debug = dir.join("java-debug").join("bin");
let js_debug = dir.join("js-debug").join("bin");
let codelldb = dir.join("codelldb").join("bin");
for d in [&java_debug, &js_debug, &codelldb] {
std::fs::create_dir_all(d).unwrap();
}
let jar = "com.microsoft.java.debug.plugin.jar";
std::fs::write(java_debug.join(jar), "PK").unwrap();
std::fs::write(js_debug.join("js-debug-adapter"), "#!/bin/sh\n").unwrap();
std::fs::write(js_debug.join("js-debug-adapter.cmd"), "@echo off\r\n").unwrap();
std::fs::write(codelldb.join("codelldb.exe"), "MZ").unwrap();
let dirs = [java_debug.clone(), js_debug.clone(), codelldb.clone()];
let cwd = dir.clone();
let win = |cmd: &str| find_binary_in(cmd, &cwd, &dirs, true, Some(".COM;.EXE;.BAT;.CMD"));
assert_eq!(win(jar), None);
assert_eq!(win(&java_debug.join(jar).to_string_lossy()), None);
assert_eq!(win("js-debug-adapter"), Some(js_debug.join("js-debug-adapter.cmd")));
assert_eq!(win("codelldb"), Some(codelldb.join("codelldb.exe")));
assert_eq!(win(&codelldb.join("codelldb").to_string_lossy()), Some(codelldb.join("codelldb.exe")));
assert_eq!(win(&codelldb.join("codelldb.exe").to_string_lossy()), Some(codelldb.join("codelldb.exe")));
assert_eq!(win("netcoredbg"), None);
let _ = std::fs::remove_dir_all(&dir);
}
/// Unix needs the executable bit: a plain file (the bundle jar) is not a program.
#[cfg(unix)]
#[test]
fn unix_resolution_needs_the_executable_bit() {
use std::os::unix::fs::PermissionsExt;
let dir = std::env::temp_dir().join(format!("openidea-dap-unix-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("plugin.jar"), "PK").unwrap();
std::fs::write(dir.join("adapter"), "#!/bin/sh\n").unwrap();
std::fs::set_permissions(dir.join("adapter"), std::fs::Permissions::from_mode(0o755)).unwrap();
let dirs = [dir.clone()];
assert_eq!(find_binary_in("plugin.jar", &dir, &dirs, false, None), None);
assert_eq!(find_binary_in("adapter", &dir, &dirs, false, None), Some(dir.join("adapter")));
let _ = std::fs::remove_dir_all(&dir);
}
/// java-debug (from `languages/java.toml` or the built-in) is only reachable through
/// jdtls: a launch without `debugServer` is refused instead of starting the jar.
#[tokio::test]
async fn plugin_adapters_are_never_started_as_processes() {
assert!(is_plugin_bundle("com.microsoft.java.debug.plugin.jar"));
assert!(is_plugin_bundle("C:\\tools\\java-debug\\bin\\Plugin.JAR"));
for cmd in ["codelldb", "python3", "js-debug-adapter", "dlv", "netcoredbg.exe", "lldb-dap"] {
assert!(!is_plugin_bundle(cmd), "{cmd}");
}
let spec = resolve(&builtin("java-debug").unwrap(), std::env::temp_dir());
let err = ProcessLauncher.launch(spec, None).await.err().unwrap();
assert_eq!(err.kind, ide_core::error::ErrorKind::Unavailable);
assert!(err.message.contains("runs inside the Java language server"), "{}", err.message);
}
}
-1
Переглянути файл
@@ -378,7 +378,6 @@ async fn on_event(mgr: &Arc<DebugManager>, s: &Arc<Session>, event: &str, body:
message: str_("message"),
fraction: body.get("percentage").and_then(Value::as_f64).map(|p| (p / 100.0) as f32),
done,
cancellable: false,
});
}
"hotcodereplace" => s.emit(DebugEvent::HotCodeReplace {
+6 -4
Переглянути файл
@@ -24,13 +24,16 @@ fn main() {
.init();
let home = dirs::home_dir().unwrap_or_default();
let base = std::env::var_os("OPENIDEA_SERVER_HOME").map(PathBuf::from).unwrap_or_else(|| home.join(".openidea"));
// An SSH exec channel gets a minimal environment: take the login shell's, read
// afresh on every start, plus the IDE-managed tools. Before any other thread starts.
ide_host::shell_env::inherit_login_shell_env("openidea-server");
// An SSH exec channel gets a minimal PATH: take the login shell's, as the
// desktop app does, plus the IDE-managed tools. Before any other thread starts.
let refresh_shell_path = ide_host::shell_env::inherit_login_shell_path("openidea-server");
let data_dir = base.join("data");
ide_tools::extend_process_path(&data_dir);
ide_dap::adapter::set_tools_root(ide_tools::tools_dir(&data_dir));
ide_sdk::java::add_jdk_root(&ide_tools::jdk::jdks_dir(&data_dir));
if let Some(refresh) = refresh_shell_path {
refresh();
}
let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build().expect("tokio runtime");
let code = runtime.block_on(run(base));
std::process::exit(code);
@@ -61,7 +64,6 @@ async fn run(base: PathBuf) -> i32 {
sink_for: Box::new(move |window| rpc::event_sink(sink_peer.clone(), Some(window.to_owned()))),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: true,
}));
tracing::info!("openidea-server {} ready", env!("CARGO_PKG_VERSION"));
rpc::serve(host.clone(), Dispatcher::standard(), peer, tokio::io::stdin(), tokio::io::stdout()).await;
-488
Переглянути файл
@@ -1,488 +0,0 @@
//! The environment child processes get beyond this process's own: the login shell's as
//! re-read by Reload Environment, and (remote server) the project's
//! `devcontainer.json` `remoteEnv`, plus its `postStartCommand` once per server start.
//!
//! Both reach every child through `ide_core::process::set_env_overlay`: terminals, runs,
//! language servers, debug adapters, build tools and git all spawn through
//! `ide_core::process::prepare` / `host_env`.
use ide_core::event::NotifyLevel;
use ide_core::{CancellationToken, IdeError, IdeEvent, IdeResult, SharedSink, TaskId};
use ide_workspace::devcontainer::{self, LifecycleCommand};
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::{BTreeSet, HashSet};
use std::ffi::{OsStr, OsString};
use std::io::{BufRead, BufReader, Read};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::Arc;
use std::time::Duration;
type Changes = Vec<(OsString, Option<OsString>)>;
/// What Reload Environment changed.
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct EnvReloaded {
/// Names of the variables new child processes now get differently (added, changed or removed).
pub changed: Vec<String>,
/// The `devcontainer.json` whose `remoteEnv` applies, if any.
pub devcontainer: Option<String>,
/// Whether the login shell was read (it isn't on Windows).
pub shell_read: bool,
}
#[derive(Default)]
struct State {
/// The login shell's environment when this process started (before the first reload).
baseline: Option<Vec<(OsString, OsString)>>,
/// The login shell's changes since this process started (Reload Environment).
login: Changes,
/// The open project's `remoteEnv`.
project: Changes,
/// Project roots whose `postStartCommand` ran in this process.
post_started: HashSet<PathBuf>,
}
pub struct Environment {
/// Whether the open project's `devcontainer.json` applies (the remote server: one project per process).
project_env: bool,
data_dir: PathBuf,
state: Mutex<State>,
/// Stops running `postStartCommand`s when the host shuts down.
cancel: CancellationToken,
}
impl Environment {
pub(crate) fn new(project_env: bool, data_dir: PathBuf) -> Self {
Self { project_env, data_dir, state: Mutex::default(), cancel: CancellationToken::new() }
}
pub(crate) fn shutdown(&self) {
self.cancel.cancel();
}
/// A project opened at `root`: applies its `remoteEnv` and returns its `postStartCommand`
/// when it hasn't run in this process yet. Problems with the file are notified, not errors.
pub(crate) fn project_opened(&self, root: &Path, sink: &SharedSink) -> Option<LifecycleCommand> {
if !self.project_env {
return None;
}
let config = self.load_project(root, sink);
let post_start = config.and_then(|c| c.post_start);
let first = self.state.lock().post_started.insert(root.to_path_buf());
post_start.filter(|_| first)
}
pub(crate) fn project_closed(&self) {
if self.project_env {
self.state.lock().project.clear();
self.publish();
}
}
/// Reads `root`'s `devcontainer.json` and applies its `remoteEnv` (none: clears it).
fn load_project(&self, root: &Path, sink: &SharedSink) -> Option<devcontainer::DevContainer> {
let config = match devcontainer::load(root) {
Ok(c) => c,
Err(e) => {
sink.emit(IdeEvent::Notify {
level: NotifyLevel::Warning,
title: "devcontainer.json was not applied".into(),
body: Some(e),
});
None
}
};
let login = self.state.lock().login.clone();
let project = config.as_ref().map(|c| project_changes(c, root, &login)).unwrap_or_default();
self.state.lock().project = project;
self.publish();
config
}
fn publish(&self) {
let state = self.state.lock();
ide_core::process::set_env_overlay(merge(&state.login, &state.project));
}
/// Reload Environment: reads the login shell again and re-applies the project's
/// `remoteEnv` (`root`). Blocking (it runs the shell); children already running keep
/// their environment.
pub fn reload(&self, root: Option<&Path>, sink: &SharedSink) -> IdeResult<EnvReloaded> {
let before: Vec<_> = ide_core::process::host_vars().collect();
let fresh = crate::shell_env::read_login_env_now().map_err(IdeError::unavailable)?;
let shell_read = fresh.is_some();
if let Some(fresh) = fresh {
let old = {
let mut state = self.state.lock();
let baseline = state
.baseline
.get_or_insert_with(|| ide_core::process::login_env().map(|v| v.to_vec()).unwrap_or_default());
baseline.clone()
};
let login = login_changes(&|k| std::env::var_os(k), &old, &fresh, &|path| {
ide_tools::path_with_tools(&self.data_dir, path)
});
ide_core::process::set_shell_env(fresh);
self.state.lock().login = login;
}
let devcontainer = match root.filter(|_| self.project_env) {
Some(root) => self.load_project(root, sink).map(|c| c.path.to_string_lossy().into_owned()),
None => {
self.publish();
None
}
};
let after: Vec<_> = ide_core::process::host_vars().collect();
Ok(EnvReloaded { changed: changed_names(&before, &after), devcontainer, shell_read })
}
/// Runs `cmd` (a `postStartCommand`) in `root` on its own thread, as a background task;
/// a failure is a notification.
pub(crate) fn spawn_post_start(&self, cmd: LifecycleCommand, root: PathBuf, sink: SharedSink) {
let cancel = self.cancel.child_token();
let spawned = std::thread::Builder::new().name("openidea-post-start".into()).spawn(move || {
run_post_start(&cmd, &root, &sink, &cancel);
});
if let Err(e) = spawned {
tracing::warn!("postStartCommand: {e}");
}
}
}
/// `project` after `login`; one entry per name, the later one winning.
fn merge(login: &Changes, project: &Changes) -> Changes {
let mut out: Changes = login.iter().filter(|(k, _)| !project.iter().any(|(p, _)| p == k)).cloned().collect();
out.extend(project.iter().cloned());
out
}
/// What children need on top of this process's environment (`process`) to see the login
/// shell's `fresh` one: changed and new variables, and those `old` (the shell at startup)
/// had that it no longer sets, when this process took them from it. `PATH` gets the
/// managed tool folders (`with_tools`) as at startup.
fn login_changes(
process: &dyn Fn(&OsStr) -> Option<OsString>,
old: &[(OsString, OsString)],
fresh: &[(OsString, OsString)],
with_tools: &dyn Fn(&OsStr) -> OsString,
) -> Changes {
let effective = |k: &OsStr, v: &OsStr| if k == "PATH" { with_tools(v) } else { v.to_owned() };
let mut out = Changes::new();
for (k, v) in fresh {
let v = effective(k, v);
if process(k).as_ref() != Some(&v) {
out.push((k.clone(), Some(v)));
}
}
for (k, v) in old {
if !fresh.iter().any(|(f, _)| f == k) && process(k) == Some(effective(k, v)) {
out.push((k.clone(), None));
}
}
out
}
/// `remoteEnv` resolved against the environment before it (this process's plus `login`).
fn project_changes(config: &devcontainer::DevContainer, root: &Path, login: &Changes) -> Changes {
let lookup = |name: &str| -> Option<String> {
match login.iter().find(|(k, _)| k == name) {
Some((_, v)) => v.as_ref().map(|v| v.to_string_lossy().into_owned()),
None => std::env::var_os(name).map(|v| v.to_string_lossy().into_owned()),
}
};
devcontainer::resolve_env(config, root, &lookup).into_iter().map(|(k, v)| (k.into(), v.map(Into::into))).collect()
}
fn changed_names(before: &[(OsString, OsString)], after: &[(OsString, OsString)]) -> Vec<String> {
let get = |vars: &[(OsString, OsString)], k: &OsString| vars.iter().find(|(n, _)| n == k).map(|(_, v)| v.clone());
let names: BTreeSet<&OsString> = before.iter().chain(after).map(|(k, _)| k).collect();
names.into_iter().filter(|k| get(before, k) != get(after, k)).map(|k| k.to_string_lossy().into_owned()).collect()
}
/// Output lines kept for the failure notification.
const TAIL_LINES: usize = 20;
const TITLE: &str = "postStartCommand";
/// Runs a `postStartCommand` to the end (each of an object's commands in parallel),
/// reporting progress as a background task and a failure as an error notification.
fn run_post_start(cmd: &LifecycleCommand, root: &Path, sink: &SharedSink, cancel: &CancellationToken) {
let task = TaskId::next();
let _cancel_handle = ide_core::task::on_cancel(task, {
let cancel = cancel.clone();
move || cancel.cancel()
});
let progress = |message: Option<String>, done: bool| {
sink.emit(IdeEvent::Task { id: task, title: TITLE.into(), message, fraction: None, done, cancellable: !done });
};
progress(Some("Starting…".into()), false);
let tail = Arc::new(Mutex::new(Vec::<String>::new()));
let on_line = |name: Option<&str>, line: String| {
tracing::info!(target: "post_start", "{}{line}", name.map(|n| format!("[{n}] ")).unwrap_or_default());
progress(Some(line.clone()), false);
let mut tail = tail.lock();
tail.push(match name {
Some(n) => format!("[{n}] {line}"),
None => line,
});
let excess = tail.len().saturating_sub(TAIL_LINES);
tail.drain(..excess);
};
let failures: Vec<String> = std::thread::scope(|scope| {
let runs: Vec<_> = cmd
.commands()
.into_iter()
.map(|(name, c)| {
let on_line = &on_line;
scope.spawn(move || {
let argv = c.argv().unwrap_or_default();
run_one(&argv, root, cancel, &|line| on_line(name, line))
.err()
.map(|e| name.map_or_else(|| e.clone(), |n| format!("{n}: {e}")))
})
})
.collect();
runs.into_iter().filter_map(|r| r.join().unwrap_or_else(|_| Some("panicked".into()))).collect()
});
progress(None, true);
if failures.is_empty() || cancel.is_cancelled() {
return;
}
let tail = tail.lock().join("\n");
let body = if tail.is_empty() { failures.join("\n") } else { format!("{}\n\n{tail}", failures.join("\n")) };
sink.emit(IdeEvent::Notify {
level: NotifyLevel::Error,
title: "postStartCommand failed".into(),
body: Some(body),
});
}
/// Runs `argv` in `root` with the children's environment, its stdout and stderr line by line
/// to `on_line`; `Err` says how it failed.
fn run_one(argv: &[String], root: &Path, cancel: &CancellationToken, on_line: &dyn Fn(String)) -> Result<(), String> {
let (program, args) = argv.split_first().ok_or("empty command")?;
let mut child = ide_core::process::prepare(&mut Command::new(program))
.args(args)
.current_dir(root)
.envs(ide_core::process::shell_env())
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.map_err(|e| format!("cannot start {program}: {e}"))?;
let (tx, rx) = std::sync::mpsc::channel::<String>();
let pipes: [Option<Box<dyn Read + Send>>; 2] = [
child.stdout.take().map(|p| Box::new(p) as Box<dyn Read + Send>),
child.stderr.take().map(|p| Box::new(p) as Box<dyn Read + Send>),
];
for pipe in pipes.into_iter().flatten() {
let tx = tx.clone();
std::thread::spawn(move || {
for line in BufReader::new(pipe).lines().map_while(Result::ok) {
if tx.send(line).is_err() {
break;
}
}
});
}
drop(tx);
let status = loop {
match rx.recv_timeout(Duration::from_millis(50)) {
Ok(line) => on_line(line),
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {}
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break child.wait(),
}
if cancel.is_cancelled() {
let _ = child.kill();
let _ = child.wait();
return Err("cancelled".into());
}
// A process it started in the background may keep the pipes open: the command is done.
if let Ok(Some(status)) = child.try_wait() {
let deadline = std::time::Instant::now() + Duration::from_secs(1);
while let Ok(line) = rx.recv_timeout(Duration::from_millis(100)) {
on_line(line);
if std::time::Instant::now() > deadline {
break;
}
}
break Ok(status);
}
}
.map_err(|e| e.to_string())?;
match status.code() {
Some(0) => Ok(()),
Some(code) => Err(format!("exited with code {code}")),
None => Err("terminated by a signal".into()),
}
}
#[cfg(test)]
mod tests {
use super::*;
use ide_core::EventSink;
fn vars(pairs: &[(&str, &str)]) -> Vec<(OsString, OsString)> {
pairs.iter().map(|(k, v)| (OsString::from(k), OsString::from(v))).collect()
}
fn change(k: &str, v: Option<&str>) -> (OsString, Option<OsString>) {
(k.into(), v.map(Into::into))
}
#[test]
fn reload_changes_are_relative_to_this_process() {
// This process took the login shell's environment at startup (the server), PATH with tools.
let process = vars(&[("PATH", "/tools:/a"), ("KEEP", "1"), ("EDITED", "old"), ("DROPPED", "x"), ("SSH", "s")]);
let old = vars(&[("PATH", "/a"), ("KEEP", "1"), ("EDITED", "old"), ("DROPPED", "x")]);
let fresh = vars(&[("PATH", "/b:/a"), ("KEEP", "1"), ("EDITED", "new"), ("ADDED", "y")]);
let lookup = |k: &OsStr| process.iter().find(|(n, _)| n == k).map(|(_, v)| v.clone());
let with_tools = |p: &OsStr| {
let mut s = OsString::from("/tools:");
s.push(p);
s
};
let got = login_changes(&lookup, &old, &fresh, &with_tools);
assert_eq!(
got,
[
change("PATH", Some("/tools:/b:/a")),
change("EDITED", Some("new")),
change("ADDED", Some("y")),
change("DROPPED", None),
]
);
// Nothing changed: nothing to apply.
assert!(login_changes(&lookup, &old, &old, &with_tools).is_empty());
}
#[test]
fn variables_the_process_had_before_the_shell_stay() {
// The desktop app: the shell had `FROM_LAUNCHD` with another value than the process.
let process = vars(&[("FROM_LAUNCHD", "process")]);
let lookup = |k: &OsStr| process.iter().find(|(n, _)| n == k).map(|(_, v)| v.clone());
let got = login_changes(&lookup, &vars(&[("FROM_LAUNCHD", "shell")]), &[], &|p| p.to_owned());
assert!(got.is_empty(), "{got:?}");
}
#[test]
fn project_variables_win_and_see_the_reloaded_login_values() {
let login = vec![change("OPENIDEA_TEST_TOOLS", Some("/reloaded")), change("A", Some("login"))];
let config = devcontainer::parse(
r#"{ "remoteEnv": { "A": "project", "B": "${containerEnv:OPENIDEA_TEST_TOOLS}/bin" } }"#,
)
.unwrap();
let project = project_changes(&config, Path::new("/p"), &login);
assert_eq!(project, [change("A", Some("project")), change("B", Some("/reloaded/bin"))]);
let merged = merge(&login, &project);
assert_eq!(
merged,
[
change("OPENIDEA_TEST_TOOLS", Some("/reloaded")),
change("A", Some("project")),
change("B", Some("/reloaded/bin"))
]
);
}
#[test]
fn changed_names_cover_added_edited_and_removed() {
let before = vars(&[("A", "1"), ("B", "2"), ("C", "3")]);
let after = vars(&[("A", "1"), ("B", "two"), ("D", "4")]);
assert_eq!(changed_names(&before, &after), ["B", "C", "D"]);
}
// Used by the Unix-only post-start tests.
#[cfg_attr(not(unix), allow(dead_code))]
#[derive(Default)]
struct Events(Mutex<Vec<IdeEvent>>);
impl EventSink for Events {
fn emit(&self, e: IdeEvent) {
self.0.lock().push(e);
}
}
#[cfg_attr(not(unix), allow(dead_code))]
fn run(cmd: LifecycleCommand, root: &Path) -> Vec<IdeEvent> {
let events = Arc::new(Events::default());
let sink: SharedSink = events.clone();
run_post_start(&cmd, root, &sink, &CancellationToken::new());
events.0.lock().clone()
}
#[cfg_attr(not(unix), allow(dead_code))]
fn failure(events: &[IdeEvent]) -> Option<String> {
events.iter().find_map(|e| match e {
IdeEvent::Notify { level: NotifyLevel::Error, body, .. } => body.clone(),
_ => None,
})
}
#[cfg(unix)]
#[test]
fn post_start_forms_run_in_the_project_root() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let events = run(LifecycleCommand::Shell("pwd > shell.txt; echo done".into()), root);
assert!(failure(&events).is_none(), "{events:?}");
let pwd = std::fs::read_to_string(root.join("shell.txt")).unwrap();
assert_eq!(dunce::canonicalize(pwd.trim()).unwrap(), dunce::canonicalize(root).unwrap());
let messages: Vec<_> = events
.iter()
.filter_map(|e| match e {
IdeEvent::Task { message, done, .. } => Some((message.clone(), *done)),
_ => None,
})
.collect();
assert!(messages.contains(&(Some("done".into()), false)), "{messages:?}");
assert_eq!(messages.last(), Some(&(None, true)));
let exec = LifecycleCommand::Exec(vec!["touch".into(), "exec file.txt".into()]);
assert!(failure(&run(exec, root)).is_none());
assert!(root.join("exec file.txt").is_file(), "array form: no shell splitting");
let parallel = LifecycleCommand::Parallel(vec![
("a".into(), LifecycleCommand::Shell("touch a.txt".into())),
("b".into(), LifecycleCommand::Exec(vec!["touch".into(), "b.txt".into()])),
]);
assert!(failure(&run(parallel, root)).is_none());
assert!(root.join("a.txt").is_file() && root.join("b.txt").is_file());
}
#[cfg(unix)]
#[test]
fn a_failing_post_start_is_notified_with_its_output() {
let tmp = tempfile::tempdir().unwrap();
let events = run(LifecycleCommand::Shell("echo starting; echo broken >&2; exit 3".into()), tmp.path());
let body = failure(&events).expect("a failure notification");
assert!(body.contains("exited with code 3"), "{body}");
assert!(body.contains("starting") && body.contains("broken"), "{body}");
assert!(matches!(events.last(), Some(IdeEvent::Notify { .. })));
let parallel = LifecycleCommand::Parallel(vec![
("ok".into(), LifecycleCommand::Shell("true".into())),
("missing".into(), LifecycleCommand::Exec(vec!["openidea-no-such-program".into()])),
]);
let body = failure(&run(parallel, tmp.path())).unwrap();
assert!(body.starts_with("missing: cannot start openidea-no-such-program"), "{body}");
}
#[cfg(unix)]
#[test]
fn cancelling_stops_a_running_post_start() {
let tmp = tempfile::tempdir().unwrap();
let cancel = CancellationToken::new();
let started = std::time::Instant::now();
let c = cancel.clone();
std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(200));
c.cancel();
});
let result = run_one(&["sleep".into(), "30".into()], tmp.path(), &cancel, &|_| {});
assert_eq!(result, Err("cancelled".into()));
assert!(started.elapsed() < Duration::from_secs(10));
}
}
+15 -29
Переглянути файл
@@ -3,11 +3,8 @@
//! wraps one [`Host`] and adds windows, menus and plugins; `openidea-server`
//! runs one on a remote machine and serves it over JSON-RPC ([`rpc`]).
pub mod environment;
pub mod ops;
mod project;
mod proxy;
mod requests;
pub mod rpc;
pub mod shell_env;
@@ -18,7 +15,7 @@ use ide_language::{LanguageRegistry, Syntax};
use ide_run::ProcessManager;
use ide_terminal::TerminalManager;
use ide_workspace::SettingsStore;
use parking_lot::RwLock;
use parking_lot::{Mutex, RwLock};
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Arc, OnceLock};
@@ -36,9 +33,6 @@ pub struct HostConfig {
/// The window that owns what `window` starts (e.g. a settings window's parent).
pub owner: fn(&str) -> &str,
pub runtime: tokio::runtime::Handle,
/// Apply the open project's `devcontainer.json` (`remoteEnv`, `postStartCommand`) to
/// this process's children: the remote server, which has one project.
pub project_environment: bool,
}
pub struct Host {
@@ -55,30 +49,23 @@ pub struct Host {
pub ssh: Arc<ide_ssh::SshManager>,
/// SFTP deployment, remote file editing and runs on run targets.
pub remote: Arc<ide_remote::RemoteService>,
/// What child processes get beyond this process's environment (Reload Environment, `remoteEnv`).
pub environment: environment::Environment,
/// The HTTP proxy's saved password (see `proxy.rs`).
proxy_password: ide_ssh::secrets::SecretFile,
pub(crate) sink_for: SinkFactory,
owner: fn(&str) -> &str,
pub runtime: tokio::runtime::Handle,
/// One project per window, keyed by window label.
projects: RwLock<HashMap<String, Arc<Project>>>,
requests: requests::Requests,
requests: Mutex<HashMap<RequestId, CancellationToken>>,
}
impl Host {
pub fn new(config: HostConfig) -> Self {
let HostConfig { config_dir, data_dir, languages, syntax, sink_for, owner, runtime, project_environment } =
config;
let HostConfig { config_dir, data_dir, languages, syntax, sink_for, owner, runtime } = config;
let global_settings = SettingsStore::load(&config_dir, None);
let ssh = Arc::new(ide_ssh::SshManager::new(data_dir.join("ssh-passwords.json")));
ssh.set_configs(global_settings.effective().ssh.configs);
let host = Self {
proxy_password: ide_ssh::secrets::SecretFile::new(data_dir.join("proxy-password.json")),
Self {
remote: Arc::new(ide_remote::RemoteService::new(ssh.clone(), data_dir.join("remote"))),
ssh,
environment: environment::Environment::new(project_environment, data_dir.clone()),
global_settings,
// Sessions, runs and terminals report to the window that started them (`window_sink`).
terminals: TerminalManager::new(),
@@ -92,10 +79,8 @@ impl Host {
owner,
runtime,
projects: RwLock::default(),
requests: Default::default(),
};
host.apply_proxy();
host
requests: Mutex::default(),
}
}
/// The tree-sitter grammars (blocks only if start-up warm-up is still running).
@@ -133,9 +118,6 @@ impl Host {
pub fn close_project(&self, window: &str) {
if let Some(project) = self.projects.write().remove(window) {
if !project.light {
self.environment.project_closed();
}
project.agents.shutdown();
let lsp = project.lsp.clone();
self.runtime.spawn(async move { lsp.shutdown_all().await });
@@ -145,7 +127,6 @@ impl Host {
/// Stops what this host started: language servers, agents, runs and terminals.
/// For a process that exits without dropping the host (the remote server).
pub async fn shutdown(&self) {
self.environment.shutdown();
self.processes.kill_all();
self.terminals.kill_all();
let projects: Vec<_> = self.projects.write().drain().map(|(_, p)| p).collect();
@@ -158,16 +139,21 @@ impl Host {
// ---- cancellable requests: the UI allocates ids, `cancel_request` cancels ----
pub fn begin_request(&self, id: RequestId) -> CancellationToken {
self.requests.begin(id)
let token = CancellationToken::new();
if let Some(old) = self.requests.lock().insert(id, token.clone()) {
old.cancel();
}
token
}
pub fn end_request(&self, id: RequestId) {
self.requests.end(id);
self.requests.lock().remove(&id);
}
/// Cancels request `id`, also when it has not begun yet (it then starts out cancelled).
pub fn cancel_request(&self, id: RequestId) {
self.requests.cancel(id);
if let Some(token) = self.requests.lock().remove(&id) {
token.cancel();
}
}
pub(crate) fn insert_project(&self, window: &str, project: Arc<Project>) {
-20
Переглянути файл
@@ -1,20 +0,0 @@
//! Reload Environment: new child processes get the login shell's current environment
//! (and, on the remote server, the project's `remoteEnv`) without a restart.
use crate::Host;
use crate::environment::EnvReloaded;
use crate::rpc::Dispatcher;
use ide_core::IdeResult;
use std::sync::Arc;
/// Re-reads the login shell (and the window's project `remoteEnv` where it applies);
/// running terminals and processes keep their environment.
pub async fn reload(host: &Arc<Host>, window: &str) -> IdeResult<EnvReloaded> {
let root = host.project(window).ok().filter(|p| !p.light).map(|p| p.root.clone());
let sink = host.window_sink(window);
let h = host.clone();
host.blocking(move || h.environment.reload(root.as_deref(), &sink)).await
}
pub(crate) fn register(d: &mut Dispatcher) {
d.add("env_reload", |c| async move { reload(&c.host, &c.window).await });
}
-2
Переглянути файл
@@ -9,7 +9,6 @@ pub mod bytes;
pub mod coverage;
pub mod debug;
pub mod doc;
pub mod env;
pub mod fs;
pub mod history;
pub mod java;
@@ -76,7 +75,6 @@ pub fn register_all(d: &mut crate::rpc::Dispatcher) {
doc::register(d);
search::register(d);
run::register(d);
env::register(d);
}
impl Host {
+4 -13
Переглянути файл
@@ -43,10 +43,10 @@ pub fn current(host: &Host, window: &str) -> Option<ProjectInfo> {
/// Effective settings for the window's project, or global settings without one.
pub fn settings(host: &Host, window: &str) -> Settings {
host.with_proxy_password(match host.project(window) {
match host.project(window) {
Ok(p) => p.settings.effective(),
Err(_) => host.global_settings.effective(),
})
}
}
pub fn roots(host: &Host, window: &str) -> IdeResult<ide_workspace::ProjectRoots> {
@@ -64,8 +64,7 @@ pub struct SettingsApplied {
/// Sets `key` to `value` (JSON text, e.g. `14` or `"dark"`) for the window's
/// project or globally, and applies it to the open projects: file defaults,
/// file types, language servers, index scope, SSH configurations and the HTTP proxy
/// (whose password goes to the saved passwords, not the settings file).
/// file types, language servers, index scope and SSH configurations.
pub fn set_settings(
host: &Host,
window: &str,
@@ -78,11 +77,6 @@ pub fn set_settings(
let current = host.project(window).ok();
// A LightEdit window has no project layer: its values are global.
let project_scope = matches!(scope, SettingsScope::Project) && current.as_ref().is_some_and(|p| !p.light);
let is_proxy = key == "proxy" || key.starts_with("proxy.");
let Some(value) = host.take_proxy_password(key, value)? else {
host.apply_proxy();
return Ok(SettingsApplied { settings: settings(host, window), project_scope, roots_changed: None });
};
let settings = match &current {
Some(p) if project_scope => p.settings.set(scope, key, value)?,
Some(p) => {
@@ -119,9 +113,6 @@ pub fn set_settings(
if key == "ssh" || key.starts_with("ssh.") {
host.ssh.set_configs(host.global_settings.effective().ssh.configs);
}
if is_proxy {
host.apply_proxy();
}
// A new interpreter / toolchain / server executable restarts the language servers it affects.
if ["languages", "tools", "languageServers"].iter().any(|k| key == *k || key.starts_with(&format!("{k}."))) {
for project in affected() {
@@ -141,5 +132,5 @@ pub fn set_settings(
});
}
let roots_changed = current.as_ref().filter(|_| roots_changed && project_scope).map(|p| p.root.clone().into());
Ok(SettingsApplied { settings: host.with_proxy_password(settings), project_scope, roots_changed })
Ok(SettingsApplied { settings, project_scope, roots_changed })
}
-5
Переглянути файл
@@ -75,8 +75,6 @@ impl Host {
}
self.close_project(window);
let sink: SharedSink = (self.sink_for)(window);
// Before anything the project starts: its children get the project's environment.
let post_start = self.environment.project_opened(&root, &sink);
let settings = SettingsStore::load(&self.config_dir, Some(&root));
let detected_roots = Arc::new(RwLock::new(ide_workspace::roots::detect(&root)));
let excludes = exclude_globs(&settings.effective(), &detected_roots.read());
@@ -313,9 +311,6 @@ impl Host {
}));
}
self.insert_project(window, project.clone());
if let Some(cmd) = post_start {
self.environment.spawn_post_start(cmd, project.root.clone(), project.sink.clone());
}
Ok(project)
}
-50
Переглянути файл
@@ -1,50 +0,0 @@
//! System Settings › HTTP Proxy on the host: the global settings made current for
//! connections and child processes, the password kept in the saved passwords
//! (owner-only `proxy-password.json`) instead of `settings.toml`.
use crate::Host;
use ide_core::IdeResult;
use ide_core::settings::Settings;
const PASSWORD_KEY: &str = "httpProxy";
impl Host {
/// `settings` with the saved proxy password filled in, as the Settings dialog edits it.
pub fn with_proxy_password(&self, mut settings: Settings) -> Settings {
// A password typed into settings.toml by hand counts too, unless one was saved.
if let Some(password) = self.proxy_password.get(PASSWORD_KEY) {
settings.proxy.password = password;
}
settings
}
/// Makes the global proxy settings the proxy of every later connection and child process.
pub fn apply_proxy(&self) {
let settings = self.with_proxy_password(self.global_settings.effective());
if let Some(problem) = settings.proxy.problem() {
tracing::warn!("HTTP proxy: {problem}");
}
ide_core::proxy_settings::set_proxy(settings.proxy);
}
/// Takes the proxy password out of a settings write of `key` and saves it.
/// Returns the value left to write, `None` when nothing is.
pub(crate) fn take_proxy_password(
&self,
key: &str,
mut value: serde_json::Value,
) -> IdeResult<Option<serde_json::Value>> {
let password = match key {
"proxy.password" => Some(value.take()),
"proxy" => value.as_object_mut().and_then(|o| o.remove("password")),
_ => return Ok(Some(value)),
};
if let Some(password) = password {
match password.as_str().filter(|p| !p.is_empty()) {
Some(p) => self.proxy_password.set(PASSWORD_KEY, p)?,
None => self.proxy_password.delete(PASSWORD_KEY),
}
}
Ok((key != "proxy.password").then_some(value))
}
}
-116
Переглянути файл
@@ -1,116 +0,0 @@
//! Cancellable requests: the UI allocates ids, `cancel_request` cancels.
//!
//! A cancel can arrive before the command that owns the id has begun: the UI shows
//! a task (with Cancel) and then awaits other work first (saving documents, a
//! queue, a branch lookup), or the command waits for something before it gets to
//! `begin`. Such a cancel is remembered for a while so the request starts out
//! cancelled instead of running to the end.
use ide_core::{CancellationToken, RequestId};
use parking_lot::Mutex;
use std::collections::{HashMap, VecDeque};
use std::time::{Duration, Instant};
/// How long a cancel for a request that has not begun is remembered.
const EARLY_CANCEL_TTL: Duration = Duration::from_secs(120);
/// At most this many are remembered (ids of finished requests end up here too).
const EARLY_CANCEL_MAX: usize = 1024;
#[derive(Default)]
pub(crate) struct Requests {
inner: Mutex<Inner>,
}
#[derive(Default)]
struct Inner {
running: HashMap<RequestId, CancellationToken>,
/// Cancelled before they began, oldest first.
early: VecDeque<(RequestId, Instant)>,
}
impl Inner {
fn prune(&mut self, now: Instant) {
while self.early.front().is_some_and(|(_, at)| now.duration_since(*at) > EARLY_CANCEL_TTL)
|| self.early.len() > EARLY_CANCEL_MAX
{
self.early.pop_front();
}
}
}
impl Requests {
pub(crate) fn begin(&self, id: RequestId) -> CancellationToken {
let token = CancellationToken::new();
let mut inner = self.inner.lock();
inner.prune(Instant::now());
if let Some(i) = inner.early.iter().position(|(early, _)| *early == id) {
inner.early.remove(i);
token.cancel();
return token;
}
if let Some(old) = inner.running.insert(id, token.clone()) {
old.cancel();
}
token
}
pub(crate) fn end(&self, id: RequestId) {
self.inner.lock().running.remove(&id);
}
pub(crate) fn cancel(&self, id: RequestId) {
let mut inner = self.inner.lock();
match inner.running.remove(&id) {
Some(token) => token.cancel(),
None => {
let now = Instant::now();
inner.early.push_back((id, now));
inner.prune(now);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cancel_reaches_a_running_request() {
let r = Requests::default();
let token = r.begin(RequestId(1));
assert!(!token.is_cancelled());
r.cancel(RequestId(1));
assert!(token.is_cancelled());
}
#[test]
fn a_cancel_before_begin_cancels_the_request_when_it_begins() {
let r = Requests::default();
r.cancel(RequestId(7));
assert!(r.begin(RequestId(7)).is_cancelled());
// Only once: the id is not cancelled for good.
assert!(!r.begin(RequestId(7)).is_cancelled());
assert!(!r.begin(RequestId(8)).is_cancelled());
}
#[test]
fn early_cancels_are_bounded() {
let r = Requests::default();
for i in 0..(EARLY_CANCEL_MAX as u32 + 10) {
r.cancel(RequestId(i));
}
assert_eq!(r.inner.lock().early.len(), EARLY_CANCEL_MAX);
assert!(!r.begin(RequestId(0)).is_cancelled(), "the oldest were dropped");
assert!(r.begin(RequestId(EARLY_CANCEL_MAX as u32 + 9)).is_cancelled());
}
#[test]
fn a_finished_request_is_not_cancelled_again() {
let r = Requests::default();
let token = r.begin(RequestId(3));
r.end(RequestId(3));
r.cancel(RequestId(3));
assert!(!token.is_cancelled());
}
}
+1 -2
Переглянути файл
@@ -13,7 +13,7 @@
use crate::Host;
use crate::ops::{self, Emit};
use ide_core::{IdeError, IdeEvent, IdeResult, RequestId, TaskId};
use ide_core::{IdeError, IdeEvent, IdeResult, RequestId};
use ide_jsonrpc::{Handler, Peer, codes};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
@@ -165,7 +165,6 @@ impl Dispatcher {
c.host.cancel_request(c.arg::<RequestId>("id")?);
Ok(())
})
.add("cancel_task", |c| async move { Ok(ide_core::task::cancel(c.arg::<TaskId>("id")?)) })
.add("fs_read_dir", |c| async move { ops::fs::read_dir(&c.host, &c.window, c.arg("path")?) })
.add("fs_create_file", |c| async move { ops::fs::create_file(&c.host, &c.window, c.arg("path")?) })
.add("fs_create_dir", |c| async move { ide_vfs::create_dir(&c.arg::<PathBuf>("path")?) })
+9 -153
Переглянути файл
@@ -3,16 +3,12 @@
//! on macOS/Linux we take PATH from the login shell at startup.
//!
//! Spawning an interactive login shell costs ~1 s with typical rc files, so the
//! desktop app caches the value: a warm start uses the cached PATH immediately
//! and refreshes the cache in the background for the next launch.
//! value is cached: a warm start uses the cached PATH immediately and refreshes
//! the cache in the background for the next launch.
//!
//! The rest of the shell's environment (API keys, provider switches, SDK homes)
//! goes to child processes through `ide_core::process::shell_env`. It stays in
//! memory, never in the cache: it may hold secrets.
//!
//! The remote server reads the whole environment afresh on every start
//! ([`inherit_login_shell_env`]), and Reload Environment reads it again while
//! running ([`read_login_env_now`], applied by [`crate::environment`]).
#[cfg(unix)]
use std::ffi::{OsStr, OsString};
@@ -26,15 +22,14 @@ pub fn inherit_login_shell_path(identifier: &str) -> Option<impl FnOnce() + use<
if std::env::var_os("OPENIDEA_SKIP_SHELL_ENV").is_some() {
return None;
}
record_startup_env();
let cache = path_cache(identifier);
let cache = dirs::cache_dir().map(|d| d.join(identifier).join("login-path"));
let cached = cache.as_ref().and_then(|c| std::fs::read_to_string(c).ok()).filter(|p| !p.trim().is_empty());
let refresh = cached.is_some();
let path = match cached {
Some(path) => path,
None => {
// Slow shell rc files must not delay the first start indefinitely.
let env = read_login_env(&login_shell(), Duration::from_secs(3))?;
let env = read_login_env(Duration::from_secs(3))?;
let fresh = login_path(&env)?;
ide_core::process::set_shell_env(env);
if let Some(cache) = &cache {
@@ -48,7 +43,7 @@ pub fn inherit_login_shell_path(identifier: &str) -> Option<impl FnOnce() + use<
let cache = cache.filter(|_| refresh)?;
Some(move || {
std::thread::spawn(move || {
let Some(env) = read_login_env(&login_shell(), Duration::from_secs(10)) else { return };
let Some(env) = read_login_env(Duration::from_secs(10)) else { return };
if let Some(fresh) = login_path(&env) {
write_cache(&cache, &fresh);
}
@@ -57,82 +52,6 @@ pub fn inherit_login_shell_path(identifier: &str) -> Option<impl FnOnce() + use<
})
}
/// This process's environment before it took anything from the login shell: what a
/// shell read later starts from.
#[cfg(unix)]
static STARTUP_ENV: std::sync::OnceLock<Vec<(OsString, OsString)>> = std::sync::OnceLock::new();
#[cfg(unix)]
fn record_startup_env() {
let _ = STARTUP_ENV.set(std::env::vars_os().collect());
}
/// How long the server waits for the login shell before it falls back to the cached PATH.
#[cfg(unix)]
const SERVER_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
/// The remote server's start: this process takes the login shell's whole environment,
/// read now (an SSH exec channel gets a minimal one and no rc files), so every child
/// inherits it and a changed rc file applies on the next start. Falls back to the PATH
/// cached by the last start when the shell can't be read in time.
///
/// Call at startup before any other thread reads the environment.
#[cfg(unix)]
pub fn inherit_login_shell_env(identifier: &str) {
if std::env::var_os("OPENIDEA_SKIP_SHELL_ENV").is_some() {
return;
}
record_startup_env();
let cache = path_cache(identifier);
match read_login_env(&login_shell(), SERVER_READ_TIMEOUT) {
Some(env) => {
for (k, v) in &env {
// SAFETY: documented to run at startup before any other thread reads the environment.
unsafe { std::env::set_var(k, v) };
}
if let (Some(cache), Some(path)) = (&cache, login_path(&env)) {
write_cache(cache, &path);
}
ide_core::process::set_shell_env(env);
}
None => {
let cached = cache.and_then(|c| std::fs::read_to_string(c).ok()).filter(|p| !p.trim().is_empty());
if let Some(path) = cached {
// SAFETY: as above.
unsafe { std::env::set_var("PATH", path.trim()) };
}
}
}
}
/// The login shell's environment, read now (Reload Environment). `Ok(None)` where the
/// IDE doesn't read it (Windows, `OPENIDEA_SKIP_SHELL_ENV`).
#[cfg(unix)]
pub fn read_login_env_now() -> Result<Option<Vec<(OsString, OsString)>>, String> {
if std::env::var_os("OPENIDEA_SKIP_SHELL_ENV").is_some() {
return Ok(None);
}
let shell = login_shell();
read_login_env(&shell, SERVER_READ_TIMEOUT)
.map(Some)
.ok_or_else(|| format!("could not read the environment of the login shell ({shell})"))
}
#[cfg(not(unix))]
pub fn read_login_env_now() -> Result<Option<Vec<(std::ffi::OsString, std::ffi::OsString)>>, String> {
Ok(None)
}
#[cfg(unix)]
fn login_shell() -> String {
std::env::var("SHELL").unwrap_or_else(|_| "/bin/zsh".into())
}
#[cfg(unix)]
fn path_cache(identifier: &str) -> Option<std::path::PathBuf> {
dirs::cache_dir().map(|d| d.join(identifier).join("login-path"))
}
#[cfg(unix)]
fn write_cache(cache: &std::path::Path, path: &str) {
if let Some(dir) = cache.parent() {
@@ -150,35 +69,17 @@ fn login_path(env: &[(OsString, OsString)]) -> Option<String> {
#[cfg(unix)]
const SHELL_OWN: &[&str] = &["PWD", "OLDPWD", "SHLVL", "_"];
/// The environment of `shell` started as an interactive login shell; PATH included, the
/// shell's own bookkeeping left out.
/// The login shell's environment; PATH included, the shell's own bookkeeping left out.
#[cfg(unix)]
pub(crate) fn read_login_env(shell: &str, timeout: std::time::Duration) -> Option<Vec<(OsString, OsString)>> {
fn read_login_env(timeout: std::time::Duration) -> Option<Vec<(OsString, OsString)>> {
use std::io::Read;
use std::os::unix::ffi::OsStrExt;
use std::process::{Command, Stdio};
use std::time::Instant;
let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/zsh".into());
const MARK: &str = "__OPENIDEA_ENV__";
let mut cmd = Command::new(shell);
// As at startup: what this process took from the shell (and what a reload added) must
// not go in again, or rc files that append to PATH would append twice and a variable
// they no longer export would come back.
if let Some(startup) = STARTUP_ENV.get() {
let now: Vec<OsString> = std::env::vars_os().map(|(k, _)| k).collect();
let overlay = ide_core::process::env_overlay();
for k in now.iter().chain(overlay.iter().map(|(k, _)| k)) {
let before = startup.iter().find(|(n, _)| n == k).map(|(_, v)| v);
if overlay.iter().any(|(o, _)| o == k) || std::env::var_os(k).as_ref() != before {
match before {
Some(v) => cmd.env(k, v),
None => cmd.env_remove(k),
};
}
}
}
ide_core::process::prepare(&mut cmd);
let mut child = cmd
let mut child = ide_core::process::prepare(&mut Command::new(&shell))
.args(["-ilc", &format!("printf '{MARK}'; /usr/bin/env -0; printf '{MARK}'")])
.stdin(Stdio::null())
.stdout(Stdio::piped())
@@ -222,48 +123,3 @@ pub(crate) fn read_login_env(shell: &str, timeout: std::time::Duration) -> Optio
pub fn inherit_login_shell_path(_identifier: &str) -> Option<fn()> {
None
}
#[cfg(not(unix))]
pub fn inherit_login_shell_env(_identifier: &str) {}
#[cfg(all(test, unix))]
mod tests {
use super::*;
use std::os::unix::fs::PermissionsExt;
use std::time::Duration;
/// A stand-in login shell: runs the IDE's `-ilc` script after exporting what `rc` holds.
fn fake_shell(dir: &std::path::Path) -> (String, std::path::PathBuf) {
let rc = dir.join("rc");
let shell = dir.join("shell");
std::fs::write(&shell, format!("#!/bin/sh\n. {}\nshift\nexec /bin/sh -c \"$1\"\n", rc.display())).unwrap();
std::fs::set_permissions(&shell, std::fs::Permissions::from_mode(0o755)).unwrap();
(shell.to_string_lossy().into_owned(), rc)
}
#[test]
fn every_read_sees_the_current_rc_file() {
let tmp = tempfile::tempdir().unwrap();
let (shell, rc) = fake_shell(tmp.path());
let get = |env: &[(OsString, OsString)], k: &str| {
env.iter().find(|(n, _)| n == k).map(|(_, v)| v.to_string_lossy().into_owned())
};
std::fs::write(&rc, "export OPENIDEA_TEST_RC=one\nexport PATH=/one/bin:$PATH\n").unwrap();
let first = read_login_env(&shell, Duration::from_secs(10)).unwrap();
assert_eq!(get(&first, "OPENIDEA_TEST_RC").as_deref(), Some("one"));
assert!(get(&first, "PATH").unwrap().starts_with("/one/bin:"));
assert!(get(&first, "PWD").is_none() && get(&first, "SHLVL").is_none());
std::fs::write(&rc, "export OPENIDEA_TEST_RC='two words'\n").unwrap();
let second = read_login_env(&shell, Duration::from_secs(10)).unwrap();
assert_eq!(get(&second, "OPENIDEA_TEST_RC").as_deref(), Some("two words"));
}
#[test]
fn a_shell_that_hangs_times_out() {
let tmp = tempfile::tempdir().unwrap();
let (shell, rc) = fake_shell(tmp.path());
std::fs::write(&rc, "sleep 5\n").unwrap();
assert!(read_login_env(&shell, Duration::from_millis(200)).is_none());
}
}
-1
Переглянути файл
@@ -14,7 +14,6 @@ fn host(base: &std::path::Path) -> Arc<Host> {
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
}))
}
-74
Переглянути файл
@@ -1,74 +0,0 @@
//! System Settings › HTTP Proxy: applied on write, the password kept out of settings.toml.
use ide_core::NullSink;
use ide_core::proxy_settings::{ProxyMode, ProxyRoute, proxy};
use ide_host::{Host, HostConfig, ops};
use ide_workspace::SettingsScope;
use std::sync::Arc;
fn host(base: &std::path::Path) -> Arc<Host> {
Arc::new(Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
}))
}
fn set(host: &Host, key: &str, value: &str) -> ide_core::settings::Settings {
ops::project::set_settings(host, "main", SettingsScope::Global, key, value).unwrap().settings
}
fn settings_files(base: &std::path::Path) -> String {
let mut text = String::new();
for entry in walk(&base.join("config")) {
text.push_str(&std::fs::read_to_string(entry).unwrap_or_default());
}
text
}
fn walk(dir: &std::path::Path) -> Vec<std::path::PathBuf> {
let mut out = Vec::new();
for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() {
let path = entry.path();
if path.is_dir() { out.extend(walk(&path)) } else { out.push(path) }
}
out
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn manual_proxy_applies_and_the_password_is_saved_apart() {
let tmp = tempfile::tempdir().unwrap();
let host = host(tmp.path());
assert_eq!(proxy().mode, ProxyMode::Auto);
set(&host, "proxy.mode", "\"manual\"");
set(&host, "proxy.host", "\"proxy.corp\"");
set(&host, "proxy.port", "3128");
set(&host, "proxy.authenticate", "true");
set(&host, "proxy.login", "\"me\"");
let settings = set(&host, "proxy.password", "\"s3cret\"");
assert_eq!(settings.proxy.password, "s3cret", "the dialog sees the saved password");
assert_eq!(
proxy().route_for_url("https://example.com/"),
ProxyRoute::Via("http://me:[email protected]:3128".into())
);
assert!(!settings_files(tmp.path()).contains("s3cret"), "no password in settings.toml");
let saved = std::fs::read_to_string(tmp.path().join("data/proxy-password.json")).unwrap();
assert!(saved.contains("s3cret"));
assert_eq!(ops::project::settings(&host, "main").proxy.password, "s3cret");
// A whole-table write keeps the password out of the file too; an empty one forgets it.
let settings = set(&host, "proxy", r#"{"mode":"none","host":"proxy.corp","password":""}"#);
assert_eq!(settings.proxy.password, "");
assert!(!settings_files(tmp.path()).contains("password"));
assert_eq!(proxy().route_for_url("https://example.com/"), ProxyRoute::Direct);
set(&host, "proxy", r#"{"mode":"auto"}"#);
assert_eq!(proxy().mode, ProxyMode::Auto);
}
-178
Переглянути файл
@@ -1,178 +0,0 @@
//! The remote server's environment: the login shell read afresh on every start, the
//! project's `devcontainer.json` (`remoteEnv`, `postStartCommand`) and Reload Environment.
//! One test in its own binary: it changes this process's environment.
#![cfg(unix)]
use ide_core::event::NotifyLevel;
use ide_core::{EventSink, IdeEvent, SharedSink};
use ide_host::{Host, HostConfig};
use parking_lot::Mutex;
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
use std::process::Command;
use std::sync::Arc;
use std::time::{Duration, Instant};
#[derive(Default)]
struct Events(Mutex<Vec<IdeEvent>>);
impl EventSink for Events {
fn emit(&self, e: IdeEvent) {
self.0.lock().push(e);
}
}
/// What a child process started now sees for `name`.
fn child_var(name: &str) -> String {
let out = ide_core::process::prepare(&mut Command::new("/bin/sh"))
.args(["-c", &format!("printf %s \"${name}\"")])
.output()
.unwrap();
String::from_utf8(out.stdout).unwrap()
}
fn wait_for(what: &str, mut done: impl FnMut() -> bool) {
let deadline = Instant::now() + Duration::from_secs(20);
while !done() {
assert!(Instant::now() < deadline, "timed out waiting for {what}");
std::thread::sleep(Duration::from_millis(20));
}
}
fn write(path: &Path, text: &str) {
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, text).unwrap();
}
#[test]
fn server_environment_from_login_shell_and_devcontainer() {
let tmp = tempfile::tempdir().unwrap();
let tmp = dunce::canonicalize(tmp.path()).unwrap();
// A stand-in login shell that sources `rc`, as an rc file would be.
let rc = tmp.join("rc");
let shell = tmp.join("shell");
write(&shell, &format!("#!/bin/sh\n. {}\nshift\nexec /bin/sh -c \"$1\"\n", rc.display()));
std::fs::set_permissions(&shell, std::fs::Permissions::from_mode(0o755)).unwrap();
// SAFETY: no other thread runs yet.
unsafe {
std::env::set_var("SHELL", &shell);
// The PATH cache goes under the temporary home.
std::env::set_var("HOME", tmp.join("home"));
std::env::set_var("XDG_CACHE_HOME", tmp.join("home/.cache"));
std::env::remove_var("OPENIDEA_SKIP_SHELL_ENV");
}
// Two server starts: each reads the login shell again (not the cached PATH).
write(&rc, "export OPENIDEA_RC_VAR=one\nexport PATH=/start-one/bin:/usr/bin:/bin\n");
ide_host::shell_env::inherit_login_shell_env("openidea-server-test");
assert_eq!(std::env::var("OPENIDEA_RC_VAR").unwrap(), "one");
write(&rc, "export OPENIDEA_RC_VAR=two\nexport PATH=/start-two/bin:/usr/bin:/bin\n");
ide_host::shell_env::inherit_login_shell_env("openidea-server-test");
assert_eq!(std::env::var("OPENIDEA_RC_VAR").unwrap(), "two");
assert!(std::env::var("PATH").unwrap().starts_with("/start-two/bin:"), "{:?}", std::env::var("PATH"));
let base = tmp.join("server");
ide_tools::extend_process_path(&base.join("data"));
let runtime = tokio::runtime::Builder::new_multi_thread().worker_threads(2).enable_all().build().unwrap();
let events = Arc::new(Events::default());
let sink_events = events.clone();
let host = Arc::new(Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(move |_| sink_events.clone() as SharedSink),
owner: |w| w,
runtime: runtime.handle().clone(),
project_environment: true,
}));
assert!(ide_host::rpc::Dispatcher::standard().commands().contains(&"env_reload"));
let project = tmp.join("demo");
write(
&project.join(".devcontainer/devcontainer.json"),
r#"{
// remoteEnv sees the login shell's variables
"remoteEnv": {
"FROM_PROJECT": "${containerEnv:OPENIDEA_RC_VAR}-${localWorkspaceFolderBasename}",
"PATH": "/project/bin:${containerEnv:PATH}",
},
"postStartCommand": ["/bin/sh", "-c", "echo \"$FROM_PROJECT\" >> started.txt; echo post-start-output"],
}"#,
);
runtime.block_on(ide_host::ops::project::open(&host, "main", &project)).unwrap();
assert_eq!(child_var("FROM_PROJECT"), "two-demo");
assert!(child_var("PATH").starts_with("/project/bin:"), "{}", child_var("PATH"));
assert_eq!(child_var("OPENIDEA_RC_VAR"), "two");
// PTY spawners (terminals, runs in a terminal) take the same variables.
assert!(ide_core::process::host_env_fixes().iter().any(|(k, v)| k == "FROM_PROJECT" && v.is_some()));
let started = project.join("started.txt");
wait_for("postStartCommand", || std::fs::read_to_string(&started).is_ok_and(|s| s.ends_with('\n')));
assert_eq!(std::fs::read_to_string(&started).unwrap(), "two-demo\n");
wait_for("the task to end", || events.0.lock().iter().any(|e| matches!(e, IdeEvent::Task { done: true, .. })));
assert!(events.0.lock().iter().any(
|e| matches!(e, IdeEvent::Task { message: Some(m), title, .. } if m == "post-start-output" && title == "postStartCommand")
));
// Reload Environment: the edited rc file and the project file apply to new children.
write(&rc, "export OPENIDEA_RC_VAR=three\nexport OPENIDEA_RC_NEW=new\nexport PATH=/start-two/bin:/usr/bin:/bin\n");
let reloaded = runtime.block_on(ide_host::ops::env::reload(&host, "main")).unwrap();
assert!(reloaded.shell_read);
for name in ["FROM_PROJECT", "OPENIDEA_RC_NEW", "OPENIDEA_RC_VAR"] {
assert!(reloaded.changed.iter().any(|c| c == name), "{name} in {:?}", reloaded.changed);
}
assert!(!reloaded.changed.iter().any(|c| c == "PATH"), "{:?}", reloaded.changed);
assert!(reloaded.devcontainer.as_deref().is_some_and(|p| p.ends_with("devcontainer.json")));
assert_eq!(child_var("OPENIDEA_RC_VAR"), "three");
assert_eq!(child_var("OPENIDEA_RC_NEW"), "new");
assert_eq!(child_var("FROM_PROJECT"), "three-demo");
// This process keeps its own environment; only children change.
assert_eq!(std::env::var("OPENIDEA_RC_VAR").unwrap(), "two");
// A variable the rc file stops exporting goes away for new children, whether this
// process started with it or a reload added it.
write(&rc, "export PATH=/start-two/bin:/usr/bin:/bin\n");
let reloaded = runtime.block_on(ide_host::ops::env::reload(&host, "main")).unwrap();
for name in ["FROM_PROJECT", "OPENIDEA_RC_NEW", "OPENIDEA_RC_VAR"] {
assert!(reloaded.changed.iter().any(|c| c == name), "{name} in {:?}", reloaded.changed);
}
assert_eq!(child_var("OPENIDEA_RC_NEW"), "");
assert_eq!(child_var("OPENIDEA_RC_VAR"), "");
assert_eq!(child_var("FROM_PROJECT"), "-demo");
// The shell starts from the environment this process started with: an rc file that
// prepends to PATH does so once, however often it is reloaded.
write(&rc, "export PATH=/prepended/bin:$PATH\n");
let first = runtime.block_on(ide_host::ops::env::reload(&host, "main")).unwrap();
assert!(first.changed.iter().any(|c| c == "PATH"), "{:?}", first.changed);
let again = runtime.block_on(ide_host::ops::env::reload(&host, "main")).unwrap();
assert!(again.changed.is_empty(), "{:?}", again.changed);
assert_eq!(child_var("PATH").matches("/prepended/bin").count(), 1, "{}", child_var("PATH"));
// Reopening the project doesn't run postStartCommand again (once per server start).
host.close_project("main");
assert_eq!(child_var("FROM_PROJECT"), "", "remoteEnv leaves with the project");
runtime.block_on(ide_host::ops::project::open(&host, "main", &project)).unwrap();
std::thread::sleep(Duration::from_millis(500));
assert_eq!(std::fs::read_to_string(&started).unwrap(), "two-demo\n");
// A failing postStartCommand is a notification; the project opens regardless.
let failing = tmp.join("failing");
write(&failing.join(".devcontainer.json"), r#"{ "postStartCommand": "echo oops >&2; exit 7" }"#);
runtime.block_on(ide_host::ops::project::open(&host, "main", &failing)).unwrap();
wait_for("the failure notification", || {
events.0.lock().iter().any(|e| {
matches!(e, IdeEvent::Notify { level: NotifyLevel::Error, title, body: Some(b) }
if title == "postStartCommand failed" && b.contains("exited with code 7") && b.contains("oops"))
})
});
// A broken file is a warning, not an error.
let broken = tmp.join("broken");
write(&broken.join(".devcontainer.json"), "{ \"remoteEnv\": ");
runtime.block_on(ide_host::ops::project::open(&host, "main", &broken)).unwrap();
assert!(events.0.lock().iter().any(|e| matches!(e,
IdeEvent::Notify { level: NotifyLevel::Warning, title, .. } if title == "devcontainer.json was not applied")));
runtime.block_on(host.shutdown());
}
-1
Переглянути файл
@@ -61,7 +61,6 @@ async fn serves_projects_files_documents_search_and_runs() {
sink_for: Box::new(move |w| rpc::event_sink(sink_peer.clone(), Some(w.to_owned()))),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
}));
let (client_io, server_io) = tokio::io::duplex(1 << 20);
let (sr, sw) = tokio::io::split(server_io);
-187
Переглянути файл
@@ -1,187 +0,0 @@
//! The one place the backend builds an HTTP client: TLS with the platform's
//! certificates, timeouts, and the proxy of System Settings › HTTP Proxy.
use ide_core::proxy_settings::{ProxyMode, ProxyRoute, ProxySettings};
use ide_core::{CancellationToken, IdeError, IdeResult};
use parking_lot::Mutex;
use std::sync::Arc;
use std::time::Duration;
/// `builder` routed as `proxy` says: direct, the environment's proxy (reqwest's
/// default), or the manual proxy except for the "No proxy for" hosts.
pub fn with_proxy(builder: reqwest::ClientBuilder, proxy: &ProxySettings) -> reqwest::ClientBuilder {
match proxy.mode {
ProxyMode::Auto => builder,
ProxyMode::None => builder.no_proxy(),
ProxyMode::Manual => {
let proxy = proxy.clone();
// A custom proxy also turns off the environment's.
builder.proxy(reqwest::Proxy::custom(move |url| match proxy.route(url.host_str()) {
ProxyRoute::Via(via) => Some(via),
ProxyRoute::Direct | ProxyRoute::System => None,
}))
}
}
}
/// A client for `proxy`.
pub fn build(proxy: &ProxySettings) -> IdeResult<reqwest::Client> {
use rustls_platform_verifier::BuilderVerifierExt;
let fail = |e: String| IdeError::internal(format!("HTTP client: {e}"));
let provider = Arc::new(rustls::crypto::ring::default_provider());
let tls = rustls::ClientConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()
.map_err(|e| fail(e.to_string()))?
.with_platform_verifier()
.map_err(|e| fail(e.to_string()))?
.with_no_client_auth();
let builder = reqwest::Client::builder()
.tls_backend_preconfigured(tls)
.connect_timeout(Duration::from_secs(30))
.user_agent(concat!("OpenIDEA-HttpClient/", env!("CARGO_PKG_VERSION")));
with_proxy(builder, proxy).build().map_err(|e| fail(e.to_string()))
}
/// The client for the current proxy settings, rebuilt when they change.
pub fn shared() -> IdeResult<reqwest::Client> {
static CLIENT: Mutex<Option<(Arc<ProxySettings>, reqwest::Client)>> = Mutex::new(None);
let proxy = ide_core::proxy_settings::proxy();
let mut cached = CLIENT.lock();
if let Some((settings, client)) = cached.as_ref()
&& **settings == *proxy
{
return Ok(client.clone());
}
let client = build(&proxy)?;
*cached = Some((proxy, client.clone()));
Ok(client)
}
/// HTTP Proxy › Check connection: GETs `url` through `proxy` (the settings as
/// edited, not yet applied). Any response but `407` counts as connected.
pub async fn check_connection(proxy: &ProxySettings, url: &str, cancel: &CancellationToken) -> IdeResult<String> {
if let Some(problem) = proxy.problem() {
return Err(IdeError::invalid(problem));
}
let url = url.trim();
let url = if url.contains("://") { url.to_owned() } else { format!("http://{url}") };
let client = build(proxy)?;
let request = client.get(&url).timeout(Duration::from_secs(30));
let response = tokio::select! {
r = request.send() => r.map_err(|e| IdeError::new(ide_core::error::ErrorKind::Io, describe(&e)))?,
() = cancel.cancelled() => return Err(IdeError::cancelled()),
};
let status = response.status();
if status == reqwest::StatusCode::PROXY_AUTHENTICATION_REQUIRED {
return Err(IdeError::new(ide_core::error::ErrorKind::PermissionDenied, "Proxy authentication required (407)"));
}
Ok(format!("{} {}", status.as_u16(), status.canonical_reason().unwrap_or("")).trim_end().to_owned())
}
/// reqwest errors with their causes ("error sending request: … connection refused").
pub(crate) fn describe(e: &reqwest::Error) -> String {
use std::error::Error;
let mut msg = e.to_string();
let mut source = e.source();
while let Some(s) = source {
let s_msg = s.to_string();
if !msg.contains(&s_msg) {
msg.push_str(": ");
msg.push_str(&s_msg);
}
source = s.source();
}
msg
}
#[cfg(test)]
mod tests {
use super::*;
use ide_core::proxy_settings::ProxyKind;
use std::io::{BufRead, BufReader, Write};
use std::net::TcpListener;
/// A one-shot HTTP server on loopback: answers `200` and hands back the request head.
fn server() -> (u16, std::thread::JoinHandle<String>) {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
let handle = std::thread::spawn(move || {
let (stream, _) = listener.accept().unwrap();
let mut reader = BufReader::new(stream.try_clone().unwrap());
let mut head = String::new();
loop {
let mut line = String::new();
if reader.read_line(&mut line).unwrap() == 0 || line == "\r\n" {
break;
}
head.push_str(&line);
}
let mut stream = stream;
stream.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok").unwrap();
head
});
(port, handle)
}
fn manual(port: u16) -> ProxySettings {
ProxySettings { mode: ProxyMode::Manual, host: "127.0.0.1".into(), port, ..Default::default() }
}
async fn get(proxy: &ProxySettings, url: &str) -> IdeResult<String> {
check_connection(proxy, url, &CancellationToken::new()).await
}
#[tokio::test]
async fn builds_for_every_mode() {
for mode in [ProxyMode::None, ProxyMode::Auto, ProxyMode::Manual] {
for kind in [ProxyKind::Http, ProxyKind::Socks] {
let p = ProxySettings { mode, kind, host: "proxy".into(), port: 3128, ..Default::default() };
assert!(build(&p).is_ok(), "{mode:?} {kind:?}");
}
}
}
#[tokio::test]
async fn manual_proxy_receives_the_request_with_credentials() {
let (port, proxy_server) = server();
let proxy = ProxySettings { authenticate: true, login: "me".into(), password: "s3cret".into(), ..manual(port) };
assert_eq!(get(&proxy, "http://example.invalid/ping").await.unwrap(), "200 OK");
let head = proxy_server.join().unwrap();
assert!(head.starts_with("GET http://example.invalid/ping HTTP/1.1"), "{head}");
// base64("me:s3cret")
assert!(head.to_ascii_lowercase().contains("proxy-authorization: basic bwu6cznjcmv0"), "{head}");
}
#[tokio::test]
async fn manual_proxy_without_authentication_sends_no_credentials() {
let (port, proxy_server) = server();
let proxy = ProxySettings { login: "me".into(), password: "x".into(), ..manual(port) };
get(&proxy, "http://example.invalid/").await.unwrap();
assert!(!proxy_server.join().unwrap().to_ascii_lowercase().contains("proxy-authorization"));
}
#[tokio::test]
async fn no_proxy_hosts_and_no_proxy_mode_connect_directly() {
// Nothing listens on the proxy port: a request through it would fail.
let dead = TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
let (port, target) = server();
let listed = ProxySettings { no_proxy: "example.com, 127.0.*".into(), ..manual(dead) };
assert!(listed.bypasses("127.0.0.1"));
get(&listed, &format!("http://127.0.0.1:{port}/direct")).await.unwrap();
assert!(target.join().unwrap().starts_with("GET /direct HTTP/1.1"));
let (port, target) = server();
let none = ProxySettings { mode: ProxyMode::None, ..manual(dead) };
get(&none, &format!("http://127.0.0.1:{port}/none")).await.unwrap();
assert!(target.join().unwrap().starts_with("GET /none HTTP/1.1"));
}
#[tokio::test]
async fn check_reports_errors() {
let dead = TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
let e = get(&manual(dead), "http://example.invalid/").await.unwrap_err();
assert!(!e.message.is_empty());
let e = get(&manual(0), "http://example.invalid/").await.unwrap_err();
assert!(e.message.contains("port"), "{}", e.message);
}
}
+41 -2
Переглянути файл
@@ -1,6 +1,5 @@
//! Preparing (substitution, body includes) and executing requests.
use crate::client::describe;
use crate::env::{Environments, Resolver};
use crate::parse::{BodyPart, RawRequest};
use ide_core::{CancellationToken, IdeError, IdeResult};
@@ -8,6 +7,7 @@ use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::BTreeSet;
use std::path::Path;
use std::sync::{Arc, OnceLock};
use std::time::Instant;
/// Bodies above this are cut (the full size is still reported).
@@ -98,6 +98,29 @@ pub fn prepare(
})
}
fn client() -> IdeResult<reqwest::Client> {
static CLIENT: OnceLock<Result<reqwest::Client, String>> = OnceLock::new();
CLIENT
.get_or_init(|| {
use rustls_platform_verifier::BuilderVerifierExt;
let provider = Arc::new(rustls::crypto::ring::default_provider());
let tls = rustls::ClientConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()
.map_err(|e| e.to_string())?
.with_platform_verifier()
.map_err(|e| e.to_string())?
.with_no_client_auth();
reqwest::Client::builder()
.tls_backend_preconfigured(tls)
.connect_timeout(std::time::Duration::from_secs(30))
.user_agent(concat!("OpenIDEA-HttpClient/", env!("CARGO_PKG_VERSION")))
.build()
.map_err(|e| e.to_string())
})
.clone()
.map_err(|e| IdeError::internal(format!("HTTP client: {e}")))
}
fn looks_textual(content_type: Option<&str>, bytes: &[u8]) -> bool {
if let Some(ct) = content_type {
let ct = ct.to_ascii_lowercase();
@@ -125,7 +148,7 @@ fn looks_textual(content_type: Option<&str>, bytes: &[u8]) -> bool {
/// Sends `req`; cancelled when `cancel` fires.
pub async fn execute(req: &PreparedRequest, cancel: &CancellationToken) -> IdeResult<HttpResponse> {
let client = crate::client::shared()?;
let client = client()?;
let method = reqwest::Method::from_bytes(req.method.as_bytes())
.map_err(|_| IdeError::invalid(format!("invalid method {}", req.method)))?;
let mut builder = client.request(method, &req.url);
@@ -182,6 +205,22 @@ pub async fn execute(req: &PreparedRequest, cancel: &CancellationToken) -> IdeRe
})
}
/// reqwest errors with their causes ("error sending request: … connection refused").
fn describe(e: &reqwest::Error) -> String {
use std::error::Error;
let mut msg = e.to_string();
let mut source = e.source();
while let Some(s) = source {
let s_msg = s.to_string();
if !msg.contains(&s_msg) {
msg.push_str(": ");
msg.push_str(&s_msg);
}
source = s.source();
}
msg
}
#[cfg(test)]
mod tests {
use super::*;
+1 -3
Переглянути файл
@@ -2,10 +2,8 @@
//!
//! [`parse`] splits a file into requests, [`env`] resolves `{{variables}}` from
//! `http-client(.private).env.json`, [`exec`] sends a request (cancellable,
//! timed) and [`history`] keeps the responses. [`client`] builds every HTTP client
//! of the backend, with the proxy of System Settings › HTTP Proxy.
//! timed) and [`history`] keeps the responses.
pub mod client;
pub mod env;
pub mod exec;
pub mod history;
-4
Переглянути файл
@@ -199,7 +199,6 @@ impl Shared {
message: None,
fraction: None,
done: true,
cancellable: false,
});
self.emit_state();
}
@@ -215,7 +214,6 @@ impl Shared {
message: Some("Scanning files…".into()),
fraction: None,
done: false,
cancellable: false,
});
let filter = self.filter();
@@ -262,7 +260,6 @@ impl Shared {
message: Some(format!("{done} / {total} files")),
fraction: Some(done as f32 / total.max(1) as f32),
done: false,
cancellable: false,
});
}
}
@@ -274,7 +271,6 @@ impl Shared {
message: None,
fraction: Some(1.0),
done: true,
cancellable: false,
});
self.emit_state();
let d = self.data.read();
+2 -26
Переглянути файл
@@ -30,18 +30,6 @@ impl ClientHandler {
self.server.running_gen(self.generation).map(|r| r.caps.read().encoding).unwrap_or_default()
}
/// Cancelling task `task` asks this server instance to stop the work of progress `token`.
fn cancel_handle(&self, task: TaskId, token: &Value) -> ide_core::task::CancelHandle {
let (server, generation, token) = (self.server.clone(), self.generation, token.clone());
ide_core::task::on_cancel(task, move || {
if let Some(run) = server.running_gen(generation)
&& let Err(e) = run.peer.notify("window/workDoneProgress/cancel", json!({ "token": token }))
{
tracing::debug!("{}: cannot cancel progress: {e}", server.name);
}
})
}
fn progress(&self, mgr: &LspManager, params: Value) {
let token = match &params["token"] {
Value::String(s) => s.clone(),
@@ -50,7 +38,6 @@ impl ClientHandler {
let value = &params["value"];
let message = value.get("message").and_then(Value::as_str).map(str::to_owned);
let fraction = value.get("percentage").and_then(Value::as_f64).map(|p| (p / 100.0).clamp(0.0, 1.0) as f32);
let cancellable = value.get("cancellable").and_then(Value::as_bool);
let event = {
let mut progress = self.server.progress.lock();
match value.get("kind").and_then(Value::as_str) {
@@ -62,30 +49,20 @@ impl ClientHandler {
.map(str::to_owned)
.unwrap_or_else(|| self.server.name.clone());
let task = TaskId::next();
let cancel = (cancellable == Some(true)).then(|| self.cancel_handle(task, &params["token"]));
let cancellable = cancel.is_some();
progress.insert(token, Progress { task, title: title.clone(), message: message.clone(), cancel });
IdeEvent::Task { id: task, title, message, fraction, done: false, cancellable }
progress.insert(token, Progress { task, title: title.clone(), message: message.clone() });
IdeEvent::Task { id: task, title, message, fraction, done: false }
}
Some("report") => {
let Some(p) = progress.get_mut(&token) else { return };
if message.is_some() {
p.message = message;
}
match cancellable {
Some(true) if p.cancel.is_none() => {
p.cancel = Some(self.cancel_handle(p.task, &params["token"]))
}
Some(false) => p.cancel = None,
_ => {}
}
IdeEvent::Task {
id: p.task,
title: p.title.clone(),
message: p.message.clone(),
fraction,
done: false,
cancellable: p.cancel.is_some(),
}
}
Some("end") => {
@@ -96,7 +73,6 @@ impl ClientHandler {
message: message.or(p.message),
fraction: Some(1.0),
done: true,
cancellable: false,
}
}
_ => return,
+5 -21
Переглянути файл
@@ -218,17 +218,8 @@ fn user_did_open(server: &Server, run: &Running, path: &Path, uri: &lsp::Uri, pa
}
}
/// No target for `feature`: names the running servers that lack it, so the UI can
/// tell "the server can't do this" from "no server is running" (the UI's
/// `unavailableText` matches the "… doesn't support …" wording).
fn unsupported(servers: &[Arc<Server>], feature: &str) -> IdeError {
let running: Vec<&str> = servers.iter().filter(|s| s.running().is_some()).map(|s| s.name.as_str()).collect();
if running.is_empty() {
IdeError::unavailable(format!("no running language server supports {feature}"))
} else {
let servers = running.join(", ");
IdeError::unavailable(format!("{servers} doesn't support {feature}"))
}
fn unsupported(feature: &str) -> IdeError {
IdeError::unavailable(format!("no running language server supports {feature}"))
}
/// Folds per-server results: any success wins over errors; errors surface only
@@ -562,14 +553,7 @@ impl LspManager {
/// Ends progress tasks and withdraws diagnostics of a dead instance.
fn clear_server_state(&self, server: &Server) {
for (id, title) in server.take_progress() {
self.sink.emit(ide_core::IdeEvent::Task {
id,
title,
message: None,
fraction: None,
done: true,
cancellable: false,
});
self.sink.emit(ide_core::IdeEvent::Task { id, title, message: None, fraction: None, done: true });
}
server.progress_ended();
for path in server.take_diagnostic_paths() {
@@ -839,7 +823,7 @@ impl LspManager {
let snap = self.snapshot(doc)?;
let targets = self.ready_targets(&snap.servers, pred).await;
if targets.is_empty() {
return Err(unsupported(&snap.servers, feature));
return Err(unsupported(feature));
}
Ok((snap, targets))
}
@@ -1192,7 +1176,7 @@ impl LspManager {
let servers: Vec<Arc<Server>> = self.servers.lock().clone();
let targets = self.ready_targets(&servers, |c| c.has("workspaceSymbolProvider")).await;
if targets.is_empty() {
return Err(unsupported(&servers, "workspace symbols"));
return Err(unsupported("workspace symbols"));
}
let requests = targets.iter().map(|t| {
let cancel = &cancel;
-2
Переглянути файл
@@ -67,8 +67,6 @@ pub struct Progress {
pub task: TaskId,
pub title: String,
pub message: Option<String>,
/// Set while the server accepts `window/workDoneProgress/cancel` for it.
pub cancel: Option<ide_core::task::CancelHandle>,
}
pub struct Server {
-45
Переглянути файл
@@ -520,20 +520,6 @@ async fn inline_completion_only_from_servers_that_advertise_it() {
assert!(plain.requested("textDocument/inlineCompletion").is_empty());
}
#[tokio::test(flavor = "multi_thread")]
async fn unsupported_feature_names_the_running_servers_that_lack_it() {
let h = harness(&[("plain", incremental_caps()), ("other", json!({ "textDocumentSync": 2 }))]);
let (doc, _) = h.open("a.mk", "let x = fo");
for name in ["plain", "other"] {
h.wait_status(name, ServerStatus::Ready).await;
}
let e = h.mgr.inline_completion(doc, Pos::new(0, 10), false, Default::default()).await.unwrap_err();
assert_eq!(e.kind, ide_core::error::ErrorKind::Unavailable);
assert_eq!(e.message, "plain, other doesn't support inline completion");
let e = h.mgr.type_hierarchy(doc, Pos::new(0, 4), HierarchyDirection::Incoming).await.unwrap_err();
assert_eq!(e.message, "plain, other doesn't support type hierarchy");
}
#[tokio::test(flavor = "multi_thread")]
async fn diagnostics_become_events_and_feed_code_actions() {
let h = harness(&[("mock", incremental_caps())]);
@@ -742,37 +728,6 @@ async fn progress_tasks_and_busy_status() {
assert!(tasks[2].3);
}
#[tokio::test(flavor = "multi_thread")]
async fn cancelling_a_cancellable_progress_task_asks_the_server_to_stop() {
let h = harness(&[("mock", incremental_caps())]);
h.open("a.mk", "x");
h.wait_status("mock", ServerStatus::Ready).await;
let s = h.launcher.state("mock");
let peer = s.peer();
let begin = |token: Value, cancellable: bool| json!({ "token": token, "value": { "kind": "begin", "title": "Building", "cancellable": cancellable } });
peer.notify("$/progress", begin(json!(7), true)).unwrap();
peer.notify("$/progress", begin(json!("plain"), false)).unwrap();
let task_of = |want: bool| {
h.events.lock().iter().find_map(|e| match e {
IdeEvent::Task { id, cancellable, done: false, .. } if *cancellable == want => Some(*id),
_ => None,
})
};
eventually(|| task_of(true).is_some() && task_of(false).is_some()).await;
let (cancellable, plain) = (task_of(true).unwrap(), task_of(false).unwrap());
assert!(!ide_core::task::cancel(plain), "the server did not offer to cancel it");
assert!(ide_core::task::cancel(cancellable));
eventually(|| !s.notified("window/workDoneProgress/cancel").is_empty()).await;
assert_eq!(s.notified("window/workDoneProgress/cancel"), [json!({ "token": 7 })]);
// Once it ended there is nothing left to cancel.
peer.notify("$/progress", json!({ "token": 7, "value": { "kind": "end" } })).unwrap();
eventually(|| {
h.events.lock().iter().any(|e| matches!(e, IdeEvent::Task { id, done: true, .. } if *id == cancellable))
})
.await;
assert!(!ide_core::task::cancel(cancellable));
}
#[tokio::test(flavor = "multi_thread")]
async fn angular_project_loading_shows_as_progress() {
let h = harness(&[("mock", incremental_caps())]);
+75 -3
Переглянути файл
@@ -227,11 +227,83 @@ fn detect_node(root: &Path, out: &mut Vec<RunConfig>) {
// ---------------------------------------------------------------- deno
/// Strips `//` and `/* */` comments and trailing commas so JSONC parses as JSON.
pub(crate) fn strip_jsonc(src: &str) -> String {
let mut out = String::with_capacity(src.len());
let mut chars = src.chars().peekable();
let mut in_str = false;
while let Some(c) = chars.next() {
if in_str {
out.push(c);
if c == '\\' {
if let Some(n) = chars.next() {
out.push(n);
}
} else if c == '"' {
in_str = false;
}
continue;
}
match c {
'"' => {
in_str = true;
out.push(c);
}
'/' if chars.peek() == Some(&'/') => {
for n in chars.by_ref() {
if n == '\n' {
out.push('\n');
break;
}
}
}
'/' if chars.peek() == Some(&'*') => {
chars.next();
let mut prev = '\0';
for n in chars.by_ref() {
if prev == '*' && n == '/' {
break;
}
prev = n;
}
}
_ => out.push(c),
}
}
// Remove trailing commas before `}` / `]` (outside strings).
let mut cleaned = String::with_capacity(out.len());
let bytes: Vec<char> = out.chars().collect();
let mut in_str = false;
let mut i = 0;
while i < bytes.len() {
let c = bytes[i];
if in_str {
cleaned.push(c);
if c == '\\' && i + 1 < bytes.len() {
cleaned.push(bytes[i + 1]);
i += 1;
} else if c == '"' {
in_str = false;
}
} else if c == '"' {
in_str = true;
cleaned.push(c);
} else if c == ',' {
let next = bytes[i + 1..].iter().find(|ch| !ch.is_whitespace());
if !matches!(next, Some('}') | Some(']')) {
cleaned.push(c);
}
} else {
cleaned.push(c);
}
i += 1;
}
cleaned
}
fn detect_deno(root: &Path, out: &mut Vec<RunConfig>) {
let Some(path) = first_existing(root, &["deno.json", "deno.jsonc"]) else { return };
let Some(json) = read(&path).and_then(|s| serde_json::from_str::<Json>(&ide_core::jsonc::strip(&s)).ok()) else {
return;
};
let Some(json) = read(&path).and_then(|s| serde_json::from_str::<Json>(&strip_jsonc(&s)).ok()) else { return };
let Some(tasks) = json.get("tasks").and_then(Json::as_object) else { return };
let mut names: Vec<&String> = tasks.keys().collect();
names.sort();
+22 -1
Переглянути файл
@@ -5,7 +5,28 @@
use std::ffi::OsStr;
use std::path::PathBuf;
pub use ide_core::process::executable_names;
const DEFAULT_PATHEXT: &str = ".COM;.EXE;.BAT;.CMD";
/// File names `name` may have on disk. Unix: the name itself. Windows: the
/// name when it already ends in a `PATHEXT` extension, else the name with each
/// extension (an extensionless file is not executable there).
pub fn executable_names(name: &str, windows: bool, pathext: Option<&str>) -> Vec<String> {
if !windows {
return vec![name.to_owned()];
}
let exts: Vec<&str> = pathext
.filter(|p| !p.trim().is_empty())
.unwrap_or(DEFAULT_PATHEXT)
.split(';')
.map(str::trim)
.filter(|e| e.starts_with('.') && e.len() > 1)
.collect();
let lower = name.to_ascii_lowercase();
if exts.iter().any(|e| lower.ends_with(&e.to_ascii_lowercase())) {
return vec![name.to_owned()];
}
exts.iter().map(|e| format!("{name}{}", e.to_ascii_lowercase())).collect()
}
/// First `search` directory holding `name` (see [`executable_names`]).
pub fn find_executable_in(name: &str, search: &OsStr, windows: bool, pathext: Option<&str>) -> Option<PathBuf> {
+6 -6
Переглянути файл
@@ -1,6 +1,6 @@
//! Saved passwords (SSH passwords / key passphrases by configuration id, the HTTP
//! proxy's), in the app's data directory rather than the OS credential store (no
//! system prompts). One JSON object, key → secret; owner-only on Unix.
//! Saved SSH passwords / key passphrases of SSH configurations, in the app's
//! data directory rather than the OS credential store (no system prompts).
//! One JSON object, configuration id → secret; owner-only on Unix.
use ide_core::{IdeError, IdeResult};
use parking_lot::Mutex;
@@ -35,14 +35,14 @@ impl SecretFile {
if all.remove(key).is_some()
&& let Err(e) = self.write(&all)
{
tracing::warn!("{}", e.message);
tracing::warn!("saved SSH passwords: {}", e.message);
}
}
fn read(&self) -> BTreeMap<String, String> {
match std::fs::read(&self.path) {
Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or_else(|e| {
tracing::warn!("saved passwords: {}: {e}", self.path.display());
tracing::warn!("saved SSH passwords: {}: {e}", self.path.display());
BTreeMap::new()
}),
Err(_) => BTreeMap::new(),
@@ -50,7 +50,7 @@ impl SecretFile {
}
fn write(&self, all: &BTreeMap<String, String>) -> IdeResult<()> {
let err = |e: std::io::Error| IdeError::unavailable(format!("saved passwords: {}: {e}", self.path.display()));
let err = |e: std::io::Error| IdeError::unavailable(format!("saved SSH passwords: {e}"));
if let Some(dir) = self.path.parent() {
std::fs::create_dir_all(dir).map_err(err)?;
}
-3
Переглянути файл
@@ -20,8 +20,5 @@ zip = { version = "=2.4.2", default-features = false, features = ["deflate"] }
sha2 = "0.10"
hex = "0.4"
[target.'cfg(unix)'.dependencies]
libc = "0.2"
[dev-dependencies]
tempfile.workspace = true
+24 -48
Переглянути файл
@@ -1,7 +1,7 @@
//! Archive extraction (zip / vsix, tar.gz, tar.xz, single-file gzip) and
//! executable discovery inside extracted trees.
use ide_core::{CancellationToken, IdeError, IdeResult};
use ide_core::{IdeError, IdeResult};
use std::fs::{self, File};
use std::io::{self, BufReader};
use std::path::{Component, Path, PathBuf};
@@ -41,29 +41,18 @@ fn io_err(context: &str, e: impl std::fmt::Display) -> IdeError {
IdeError::new(ide_core::error::ErrorKind::Io, format!("{context}: {e}"))
}
fn check(cancel: &CancellationToken) -> IdeResult<()> {
if cancel.is_cancelled() { Err(IdeError::cancelled()) } else { Ok(()) }
}
/// Unpacks `archive` into `dest` (created if needed). `Gz` / `Raw` payloads
/// are written to `dest/<single_name>`. Stops between entries once `cancel` fires.
pub fn extract(
archive: &Path,
kind: ArchiveKind,
dest: &Path,
single_name: &str,
cancel: &CancellationToken,
) -> IdeResult<()> {
check(cancel)?;
/// are written to `dest/<single_name>`.
pub fn extract(archive: &Path, kind: ArchiveKind, dest: &Path, single_name: &str) -> IdeResult<()> {
fs::create_dir_all(dest)?;
match kind {
ArchiveKind::Zip => extract_zip(archive, dest, cancel),
ArchiveKind::Zip => extract_zip(archive, dest),
ArchiveKind::TarGz => {
let gz = flate2::read::GzDecoder::new(BufReader::new(File::open(archive)?));
extract_tar(tar::Archive::new(gz), dest, cancel)
extract_tar(tar::Archive::new(gz), dest)
}
ArchiveKind::TarXz => extract_with_tar(archive, dest, "-xJf", cancel),
ArchiveKind::TarBz2 => extract_with_tar(archive, dest, "-xjf", cancel),
ArchiveKind::TarXz => extract_with_tar(archive, dest, "-xJf"),
ArchiveKind::TarBz2 => extract_with_tar(archive, dest, "-xjf"),
ArchiveKind::Gz => {
let mut gz = flate2::read::GzDecoder::new(BufReader::new(File::open(archive)?));
let target = dest.join(single_name);
@@ -79,11 +68,10 @@ pub fn extract(
}
}
fn extract_tar<R: io::Read>(mut archive: tar::Archive<R>, dest: &Path, cancel: &CancellationToken) -> IdeResult<()> {
fn extract_tar<R: io::Read>(mut archive: tar::Archive<R>, dest: &Path) -> IdeResult<()> {
archive.set_preserve_permissions(true);
archive.set_overwrite(true);
for entry in archive.entries().map_err(|e| io_err("reading archive", e))? {
check(cancel)?;
let mut entry = entry.map_err(|e| io_err("reading archive", e))?;
// `unpack_in` refuses entries escaping `dest` (returns Ok(false)).
entry.unpack_in(dest).map_err(|e| io_err("extracting", e))?;
@@ -91,10 +79,9 @@ fn extract_tar<R: io::Read>(mut archive: tar::Archive<R>, dest: &Path, cancel: &
Ok(())
}
fn extract_zip(archive: &Path, dest: &Path, cancel: &CancellationToken) -> IdeResult<()> {
fn extract_zip(archive: &Path, dest: &Path) -> IdeResult<()> {
let mut zip = zip::ZipArchive::new(BufReader::new(File::open(archive)?)).map_err(|e| io_err("reading zip", e))?;
for i in 0..zip.len() {
check(cancel)?;
let mut file = zip.by_index(i).map_err(|e| io_err("reading zip", e))?;
let Some(rel) = file.enclosed_name() else { continue };
if !is_safe_relative(&rel) {
@@ -129,13 +116,17 @@ fn extract_zip(archive: &Path, dest: &Path, cancel: &CancellationToken) -> IdeRe
/// `.tar.xz` / `.tar.bz2` go through the system `tar` (bsdtar on macOS/Windows, GNU tar
/// + xz / bzip2 on Linux).
fn extract_with_tar(archive: &Path, dest: &Path, flags: &str, cancel: &CancellationToken) -> IdeResult<()> {
fn extract_with_tar(archive: &Path, dest: &Path, flags: &str) -> IdeResult<()> {
let tar = which::which("tar").map_err(|_| IdeError::unavailable("`tar` is required to unpack this archive"))?;
let mut cmd = std::process::Command::new(tar);
cmd.arg(flags).arg(archive).arg("-C").arg(dest);
let (ok, output, _) = crate::process::run_collect(cmd, cancel, &|_| {})?;
if !ok {
return Err(io_err("tar failed", output.trim()));
let out = ide_core::process::prepare(&mut std::process::Command::new(tar))
.arg(flags)
.arg(archive)
.arg("-C")
.arg(dest)
.output()
.map_err(|e| io_err("running tar", e))?;
if !out.status.success() {
return Err(io_err("tar failed", String::from_utf8_lossy(&out.stderr).trim()));
}
Ok(())
}
@@ -278,21 +269,6 @@ mod tests {
assert_eq!(ArchiveKind::from_name("marksman.exe"), ArchiveKind::Raw);
}
#[test]
fn extraction_stops_when_cancelled() {
let tmp = tempfile::tempdir().unwrap();
let archive = tmp.path().join("a.tar.gz");
tar_gz(&archive, &[("one", b"1", 0o644), ("two", b"2", 0o644)]);
let cancel = CancellationToken::new();
cancel.cancel();
let dest = tmp.path().join("out");
for kind in [ArchiveKind::TarGz, ArchiveKind::Zip, ArchiveKind::TarXz, ArchiveKind::Raw] {
let err = extract(&archive, kind, &dest, "x", &cancel).unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled, "{kind:?}");
}
assert!(!dest.join("one").exists());
}
#[test]
fn extracts_tar_gz_and_locates_binary() {
let tmp = tempfile::tempdir().unwrap();
@@ -306,7 +282,7 @@ mod tests {
],
);
let dest = tmp.path().join("out");
extract(&archive, ArchiveKind::TarGz, &dest, "x", &CancellationToken::new()).unwrap();
extract(&archive, ArchiveKind::TarGz, &dest, "x").unwrap();
assert_eq!(fs::read_to_string(dest.join("main.lua")).unwrap(), "-- entry");
let found = locate(&dest, &["lua-language-server".into()]).unwrap();
assert_eq!(found, dest.join("bin/lua-language-server"));
@@ -330,7 +306,7 @@ mod tests {
],
);
let dest = tmp.path().join("out");
extract(&archive, ArchiveKind::Zip, &dest, "x", &CancellationToken::new()).unwrap();
extract(&archive, ArchiveKind::Zip, &dest, "x").unwrap();
let found = locate(&dest, &["codelldb".into()]).unwrap();
assert_eq!(found, dest.join("extension/adapter/codelldb"));
#[cfg(unix)]
@@ -347,7 +323,7 @@ mod tests {
let archive = tmp.path().join("evil.zip");
zip_file(&archive, &[("../escape.txt", b"x", 0o644), ("ok.txt", b"y", 0o644)]);
let dest = tmp.path().join("out");
extract(&archive, ArchiveKind::Zip, &dest, "x", &CancellationToken::new()).unwrap();
extract(&archive, ArchiveKind::Zip, &dest, "x").unwrap();
assert!(!tmp.path().join("escape.txt").exists());
assert!(dest.join("ok.txt").exists());
}
@@ -360,12 +336,12 @@ mod tests {
gz.write_all(b"taplo-binary").unwrap();
gz.finish().unwrap();
let dest = tmp.path().join("bin");
extract(&gz_path, ArchiveKind::Gz, &dest, "taplo", &CancellationToken::new()).unwrap();
extract(&gz_path, ArchiveKind::Gz, &dest, "taplo").unwrap();
assert_eq!(fs::read(dest.join("taplo")).unwrap(), b"taplo-binary");
let raw = tmp.path().join("marksman-macos");
fs::write(&raw, b"mm").unwrap();
extract(&raw, ArchiveKind::Raw, &dest, "marksman", &CancellationToken::new()).unwrap();
extract(&raw, ArchiveKind::Raw, &dest, "marksman").unwrap();
assert_eq!(fs::read(dest.join("marksman")).unwrap(), b"mm");
#[cfg(unix)]
{
+1 -5
Переглянути файл
@@ -290,13 +290,9 @@ impl Tools {
let archive = fetch_verified(&http, &dl, &staging, cancel, emit)?;
emit(InstallEvent::Line { text: "Extracting…".into() });
let pkg = staging.join("pkg");
archive::extract(&archive, archive::ArchiveKind::from_name(&dl.name), &pkg, "java", cancel)?;
archive::extract(&archive, archive::ArchiveKind::from_name(&dl.name), &pkg, "java")?;
let home = find_jdk_home(&pkg, self.platform)
.ok_or_else(|| IdeError::new(ErrorKind::Io, format!("no JDK found in {}", dl.name)))?;
// Last point to stop: from here the JDK replaces what is at `target`.
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
if target.exists() {
std::fs::remove_dir_all(&target)?;
}
+9 -15
Переглянути файл
@@ -149,24 +149,18 @@ fn managed_bin_dir(root: &Path, spec: &ToolSpec, platform: Platform) -> Option<P
/// debug adapters and terminals find managed tools. Call once at startup,
/// before other threads start (it mutates the process environment).
pub fn extend_process_path(app_data: &Path) {
let current = std::env::var_os("PATH").unwrap_or_default();
let extended = path_with_tools(app_data, &current);
if extended != current {
// SAFETY: documented to run at startup before any other thread reads the environment.
unsafe { std::env::set_var("PATH", extended) };
}
}
/// `path` (a `PATH` value) with [`tools_bin_dirs`] in front, those it lacks.
pub fn path_with_tools(app_data: &Path, path: &std::ffi::OsStr) -> OsString {
let mut dirs = tools_bin_dirs(app_data);
let current: Vec<PathBuf> = if path.is_empty() { Vec::new() } else { std::env::split_paths(path).collect() };
let current: Vec<PathBuf> =
std::env::var_os("PATH").map(|p| std::env::split_paths(&p).collect()).unwrap_or_default();
dirs.retain(|d| !current.contains(d));
if dirs.is_empty() {
return path.to_owned();
return;
}
dirs.extend(current);
std::env::join_paths(dirs).unwrap_or_else(|_| path.to_owned())
if let Ok(joined) = std::env::join_paths(dirs) {
// SAFETY: documented to run at startup before any other thread reads the environment.
unsafe { std::env::set_var("PATH", joined) };
}
}
/// `PATH` plus the usual per-user tool locations (GUI apps on macOS start with a minimal `PATH`).
@@ -991,9 +985,9 @@ impl Tools {
let exe_name = self.platform.exe(main);
match kind {
archive::ArchiveKind::Gz | archive::ArchiveKind::Raw => {
archive::extract(&archive, kind, &pkg.join("bin"), &exe_name, cancel)?
archive::extract(&archive, kind, &pkg.join("bin"), &exe_name)?
}
_ => archive::extract(&archive, kind, &pkg, &exe_name, cancel)?,
_ => archive::extract(&archive, kind, &pkg, &exe_name)?,
}
let names: Vec<String> = locate
.iter()
+2 -62
Переглянути файл
@@ -12,35 +12,7 @@ use std::time::{Duration, Instant};
pub type Emit<'a> = &'a dyn Fn(InstallEvent);
/// Starts the child as the leader of its own process group, so [`kill`] reaches what it
/// starts in turn (`npm` → `node`, `go install` → the compiler, `pip` → build backends).
fn own_group(cmd: &mut Command) -> &mut Command {
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
cmd.process_group(0);
}
cmd
}
/// Kills the child and everything it started.
fn kill(child: &mut Child) {
#[cfg(unix)]
if let Ok(pid) = i32::try_from(child.id()) {
// SAFETY: plain syscall; the child leads its own process group (`own_group`) and is not reaped yet.
unsafe {
libc::kill(-pid, libc::SIGKILL);
}
}
#[cfg(windows)]
{
let mut taskkill = Command::new("taskkill");
ide_core::process::prepare(&mut taskkill)
.args(["/T", "/F", "/PID", &child.id().to_string()])
.stdout(Stdio::null())
.stderr(Stdio::null());
let _ = taskkill.status();
}
let _ = child.kill();
let _ = child.wait();
}
@@ -76,7 +48,7 @@ pub fn run_streamed(cmd: Command, cancel: &CancellationToken, emit: Emit) -> Ide
/// Like [`run_streamed`] but returns `(success, output, status text)` instead of failing on a non-zero exit.
pub fn run_collect(mut cmd: Command, cancel: &CancellationToken, emit: Emit) -> IdeResult<(bool, String, String)> {
emit(InstallEvent::Line { text: format!("$ {}", describe(&cmd)) });
own_group(ide_core::process::prepare(&mut cmd)).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
ide_core::process::prepare(&mut cmd).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
let mut child = cmd.spawn().map_err(|e| IdeError::unavailable(format!("cannot run {}: {e}", describe(&cmd))))?;
let (tx, rx) = mpsc::channel::<String>();
let pipes: [Option<Box<dyn Read + Send>>; 2] = [
@@ -196,10 +168,8 @@ impl Http {
fn base(&self, url: &str) -> Command {
let mut cmd = Command::new(&self.curl);
own_group(ide_core::process::prepare(&mut cmd));
ide_core::process::prepare(&mut cmd);
cmd.args(["-fsSL", "--retry", "2", "--connect-timeout", "20", "-A", "openidea"]);
// System Settings › HTTP Proxy (a manual proxy comes in through `prepare`'s environment).
cmd.args(ide_core::proxy_settings::proxy().curl_args(url));
if self.https_only {
cmd.args(["--proto", "=https", "--proto-redir", "=https"]);
}
@@ -376,36 +346,6 @@ mod tests {
assert!(started.elapsed() < Duration::from_secs(5));
}
/// `npm` / `go` / `pip` run the real work in children of their own: cancelling
/// kills those too, not only the process the installer started.
#[cfg(unix)]
#[test]
fn cancellation_kills_what_the_child_started() {
let dir = tempfile::tempdir().unwrap();
let pid_file = dir.path().join("pid");
let cancel = CancellationToken::new();
let c2 = cancel.clone();
let watch = pid_file.clone();
std::thread::spawn(move || {
while !watch.exists() {
std::thread::sleep(Duration::from_millis(10));
}
std::thread::sleep(Duration::from_millis(50));
c2.cancel();
});
let mut cmd = Command::new("sh");
cmd.arg("-c").arg(format!("sleep 30 & echo $! > '{}'; wait", pid_file.display()));
let err = run_streamed(cmd, &cancel, &|_| {}).unwrap_err();
assert_eq!(err.kind, ErrorKind::Cancelled);
let pid: i32 = std::fs::read_to_string(&pid_file).unwrap().trim().parse().unwrap();
let deadline = Instant::now() + Duration::from_secs(5);
// SAFETY: signal 0 only checks that the process exists.
while unsafe { libc::kill(pid, 0) } == 0 {
assert!(Instant::now() < deadline, "the grandchild {pid} survived the cancel");
std::thread::sleep(Duration::from_millis(20));
}
}
#[cfg(unix)]
#[test]
fn quiet_run_times_out() {
-264
Переглянути файл
@@ -1,264 +0,0 @@
//! The project's `.devcontainer/devcontainer.json` (or `.devcontainer.json`) as a
//! remote host reads it: `remoteEnv` for every child process of the IDE backend and
//! `postStartCommand` once per backend start. No container is built.
use serde_json::Value;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
/// Where the configuration may be, first match wins.
const LOCATIONS: [&str; 2] = [".devcontainer/devcontainer.json", ".devcontainer.json"];
#[derive(Debug, Default, Clone, PartialEq)]
pub struct DevContainer {
pub path: PathBuf,
/// Values as written (`None`: unset the variable), substitutions not applied.
pub remote_env: BTreeMap<String, Option<String>>,
pub post_start: Option<LifecycleCommand>,
}
/// A lifecycle command in its three forms.
#[derive(Debug, Clone, PartialEq)]
pub enum LifecycleCommand {
/// Run through `/bin/sh -c`.
Shell(String),
/// Run directly: program and arguments, no shell.
Exec(Vec<String>),
/// Named commands (each a `Shell` or an `Exec`) run in parallel; all must succeed.
Parallel(Vec<(String, LifecycleCommand)>),
}
impl LifecycleCommand {
fn parse(v: &Value) -> Result<Option<Self>, String> {
Ok(match v {
Value::Null => None,
Value::String(s) if s.trim().is_empty() => None,
Value::String(s) => Some(Self::Shell(s.clone())),
Value::Array(items) => {
let args: Vec<String> = items
.iter()
.map(|i| i.as_str().map(str::to_owned).ok_or("array items must be strings"))
.collect::<Result<_, _>>()?;
(!args.is_empty()).then_some(Self::Exec(args))
}
Value::Object(map) => {
let mut named = Vec::new();
for (name, v) in map {
match Self::parse(v)? {
Some(Self::Parallel(_)) => return Err(format!("{name}: expected a string or an array")),
Some(c) => named.push((name.clone(), c)),
None => {}
}
}
(!named.is_empty()).then_some(Self::Parallel(named))
}
_ => return Err("expected a string, an array or an object".into()),
})
}
/// The single commands to run (one, or each of a `Parallel`), with their names.
pub fn commands(&self) -> Vec<(Option<&str>, &LifecycleCommand)> {
match self {
Self::Parallel(named) => named.iter().map(|(n, c)| (Some(n.as_str()), c)).collect(),
c => vec![(None, c)],
}
}
/// Program and arguments of a `Shell` or `Exec` command (`Parallel`: `None`).
pub fn argv(&self) -> Option<Vec<String>> {
match self {
Self::Shell(s) => Some(vec!["/bin/sh".into(), "-c".into(), s.clone()]),
Self::Exec(args) => Some(args.clone()),
Self::Parallel(_) => None,
}
}
}
/// The configuration file of the project at `root`, if it has one.
pub fn find(root: &Path) -> Option<PathBuf> {
LOCATIONS.iter().map(|l| root.join(l)).find(|p| p.is_file())
}
/// Reads the project's configuration: `Ok(None)` without one, `Err` with a message when
/// it can't be read or parsed.
pub fn load(root: &Path) -> Result<Option<DevContainer>, String> {
let Some(path) = find(root) else { return Ok(None) };
let text = std::fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?;
parse(&text).map(|mut c| {
c.path = path;
Some(c)
})
}
/// Parses `devcontainer.json` text (JSON with comments and trailing commas).
pub fn parse(text: &str) -> Result<DevContainer, String> {
let json: Value = serde_json::from_str(&ide_core::jsonc::strip(text)).map_err(|e| e.to_string())?;
let Value::Object(top) = json else { return Err("expected an object".into()) };
let mut config = DevContainer::default();
if let Some(env) = top.get("remoteEnv") {
let Value::Object(env) = env else { return Err("remoteEnv: expected an object".into()) };
for (k, v) in env {
let value = match v {
Value::Null => None,
Value::String(s) => Some(s.clone()),
Value::Number(n) => Some(n.to_string()),
Value::Bool(b) => Some(b.to_string()),
_ => return Err(format!("remoteEnv.{k}: expected a string")),
};
config.remote_env.insert(k.clone(), value);
}
}
if let Some(cmd) = top.get("postStartCommand") {
config.post_start = LifecycleCommand::parse(cmd).map_err(|e| format!("postStartCommand: {e}"))?;
}
Ok(config)
}
/// Expands `${localEnv:NAME}`, `${containerEnv:NAME}` and `${env:NAME}` (all the remote
/// host's environment, through `env`; `${…:NAME:default}` when unset), and
/// `${localWorkspaceFolder}` / `${containerWorkspaceFolder}` (and their `…Basename`) to
/// the project root. Unknown references stay as written.
pub fn substitute(value: &str, root: &Path, env: &dyn Fn(&str) -> Option<String>) -> String {
let mut out = String::with_capacity(value.len());
let mut rest = value;
while let Some(start) = rest.find("${") {
out.push_str(&rest[..start]);
let after = &rest[start + 2..];
let Some(end) = after.find('}') else {
out.push_str(&rest[start..]);
return out;
};
let inner = &after[..end];
match resolve(inner, root, env) {
Some(v) => out.push_str(&v),
None => out.push_str(&rest[start..start + 2 + end + 1]),
}
rest = &after[end + 1..];
}
out.push_str(rest);
out
}
fn resolve(inner: &str, root: &Path, env: &dyn Fn(&str) -> Option<String>) -> Option<String> {
let basename = || root.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
match inner {
"localWorkspaceFolder" | "containerWorkspaceFolder" => return Some(root.to_string_lossy().into_owned()),
"localWorkspaceFolderBasename" | "containerWorkspaceFolderBasename" => return Some(basename()),
_ => {}
}
let (scope, spec) = inner.split_once(':')?;
if !matches!(scope, "localEnv" | "containerEnv" | "env") {
return None;
}
let (name, default) = match spec.split_once(':') {
Some((name, default)) => (name, Some(default)),
None => (spec, None),
};
Some(env(name).or_else(|| default.map(str::to_owned)).unwrap_or_default())
}
/// `remoteEnv` with substitutions applied against `env` (the environment before it), in
/// order: `None` unsets the variable.
pub fn resolve_env(
config: &DevContainer,
root: &Path,
env: &dyn Fn(&str) -> Option<String>,
) -> Vec<(String, Option<String>)> {
config.remote_env.iter().map(|(k, v)| (k.clone(), v.as_deref().map(|v| substitute(v, root, env)))).collect()
}
#[cfg(test)]
mod tests {
use super::*;
fn env(name: &str) -> Option<String> {
match name {
"PATH" => Some("/usr/bin:/bin".into()),
"HOME" => Some("/home/me".into()),
_ => None,
}
}
#[test]
fn parses_jsonc_with_remote_env_and_post_start() {
let c = parse(
r#"{
// A comment
"name": "demo",
"remoteEnv": {
"PATH": "${containerEnv:PATH}:/opt/tools/bin",
"EMPTY": null,
"PORT": 8080, /* numbers are text */
},
"postStartCommand": "make dev",
}"#,
)
.unwrap();
assert_eq!(c.remote_env.get("PATH").unwrap().as_deref(), Some("${containerEnv:PATH}:/opt/tools/bin"));
assert_eq!(c.remote_env.get("EMPTY"), Some(&None));
assert_eq!(c.remote_env.get("PORT").unwrap().as_deref(), Some("8080"));
assert_eq!(c.post_start, Some(LifecycleCommand::Shell("make dev".into())));
}
#[test]
fn post_start_command_forms() {
let parse_cmd = |json: &str| parse(&format!(r#"{{ "postStartCommand": {json} }}"#)).map(|c| c.post_start);
assert_eq!(parse_cmd(r#""echo hi""#).unwrap().unwrap().argv().unwrap(), ["/bin/sh", "-c", "echo hi"]);
let exec = parse_cmd(r#"["npm", "run", "watch"]"#).unwrap().unwrap();
assert_eq!(exec, LifecycleCommand::Exec(vec!["npm".into(), "run".into(), "watch".into()]));
assert_eq!(exec.argv().unwrap(), ["npm", "run", "watch"]);
let parallel =
parse_cmd(r#"{ "server": "npm start", "db": ["pg_ctl", "start"], "none": "" }"#).unwrap().unwrap();
let names: Vec<_> = parallel.commands().into_iter().map(|(n, _)| n.unwrap()).collect();
assert_eq!(names, ["db", "server"]);
assert!(parallel.argv().is_none());
assert_eq!(parse_cmd(r#""""#).unwrap(), None);
assert_eq!(parse_cmd("[]").unwrap(), None);
assert!(parse_cmd("42").unwrap_err().contains("postStartCommand"));
assert!(parse_cmd("[1]").is_err());
assert!(parse_cmd(r#"{ "nested": { "a": "b" } }"#).is_err());
}
#[test]
fn invalid_files_are_errors() {
assert!(parse("{ \"remoteEnv\": [] }").unwrap_err().contains("remoteEnv"));
assert!(parse("{ not json").is_err());
assert!(parse("[]").is_err());
}
#[test]
fn substitutes_remote_env_references() {
let root = Path::new("/work/demo");
let s = |v: &str| substitute(v, root, &env);
assert_eq!(s("${containerEnv:PATH}:/opt/bin"), "/usr/bin:/bin:/opt/bin");
assert_eq!(s("${localEnv:HOME}/.cache"), "/home/me/.cache");
assert_eq!(s("${env:HOME}"), "/home/me");
assert_eq!(s("${localEnv:MISSING}"), "");
assert_eq!(s("${localEnv:MISSING:fallback}"), "fallback");
assert_eq!(s("${containerWorkspaceFolder}/bin:${localWorkspaceFolderBasename}"), "/work/demo/bin:demo");
assert_eq!(s("${unknown} ${other:X} $HOME ${open"), "${unknown} ${other:X} $HOME ${open");
}
#[test]
fn resolves_against_the_environment_before_it() {
let c = parse(r#"{ "remoteEnv": { "PATH": "/opt/bin:${containerEnv:PATH}", "GONE": null } }"#).unwrap();
let resolved = resolve_env(&c, Path::new("/p"), &env);
assert_eq!(
resolved,
[("GONE".to_owned(), None), ("PATH".to_owned(), Some("/opt/bin:/usr/bin:/bin".to_owned()))]
);
}
#[test]
fn finds_either_location() {
let tmp = tempfile::tempdir().unwrap();
assert_eq!(load(tmp.path()).unwrap(), None);
std::fs::write(tmp.path().join(".devcontainer.json"), r#"{ "postStartCommand": "a" }"#).unwrap();
assert_eq!(load(tmp.path()).unwrap().unwrap().post_start, Some(LifecycleCommand::Shell("a".into())));
std::fs::create_dir(tmp.path().join(".devcontainer")).unwrap();
std::fs::write(tmp.path().join(".devcontainer/devcontainer.json"), r#"{ "postStartCommand": "b" }"#).unwrap();
let c = load(tmp.path()).unwrap().unwrap();
assert_eq!(c.post_start, Some(LifecycleCommand::Shell("b".into())));
assert!(c.path.ends_with(".devcontainer/devcontainer.json"));
}
}
-1
Переглянути файл
@@ -1,7 +1,6 @@
//! The project model that ties documents, settings and history together.
pub mod caches;
pub mod devcontainer;
pub mod documents;
pub mod editorconfig;
pub mod file_defaults;
+6 -12
Переглянути файл
@@ -1,6 +1,6 @@
use crate::state::AppState;
use ide_core::settings::Settings;
use ide_core::{EventSink, IdeError, IdeResult, RequestId, TaskId};
use ide_core::{EventSink, IdeError, IdeResult, RequestId};
use ide_language::LanguageInfo;
use ide_workspace::RecentProject;
use ide_workspace::settings::SettingsScope;
@@ -128,7 +128,7 @@ pub fn settings_get(window: Window, state: State<'_, AppState>) -> Settings {
#[tauri::command]
#[specta::specta]
pub fn settings_get_global(state: State<'_, AppState>) -> Settings {
state.host.with_proxy_password(state.global_settings.effective())
state.global_settings.effective()
}
/// `value` is JSON text, e.g. `14` or `"dark"`. Every window (for a project
@@ -196,9 +196,11 @@ pub async fn settings_import(window: Window, state: State<'_, AppState>, path: P
tauri::async_runtime::spawn(async move { lsp.reconfigure().await });
}
crate::commands::ssh::apply_ssh_settings(&state);
state.host.apply_proxy();
state.sink.emit(ide_core::IdeEvent::SettingsChanged { key: String::new() });
let settings = ide_host::ops::project::settings(&state.host, window.label());
let settings = match state.project(window.label()) {
Ok(p) => p.settings.effective(),
Err(_) => state.global_settings.effective(),
};
Ok(SettingsImport { settings, storage })
}
@@ -223,14 +225,6 @@ pub fn cancel_request(state: State<'_, AppState>, id: RequestId) {
state.cancel_request(id);
}
/// Stops a background task the backend reported with `cancellable` set; false when it
/// has ended or can't be cancelled.
#[tauri::command]
#[specta::specta]
pub fn cancel_task(id: TaskId) -> bool {
ide_core::task::cancel(id)
}
#[derive(Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum LogLevel {
+8 -18
Переглянути файл
@@ -1,30 +1,20 @@
use crate::state::AppState;
use ide_core::{CancellationToken, IdeEvent, IdeResult, IpcPath, RequestId, SharedSink, TaskId};
use ide_core::{IdeEvent, IdeResult, IpcPath, RequestId, SharedSink, TaskId};
use ide_remote::{DeployedPath, SyncEntry, SyncStep, TransferReport};
use ide_ssh::RemoteEntry;
use std::path::PathBuf;
use tauri::{State, Window};
/// Reports a transfer as a background task (status bar progress) whose Cancel fires `token`.
fn progress(
sink: SharedSink,
title: &str,
token: CancellationToken,
) -> (impl FnMut(&str, usize, usize) + Send, impl FnOnce()) {
/// Reports a transfer as a background task (status bar progress).
fn progress(sink: SharedSink, title: &str) -> (impl FnMut(&str, usize, usize) + Send, impl FnOnce()) {
let id = TaskId::next();
let cancel = token;
let handle = ide_core::task::on_cancel(id, move || cancel.cancel());
let title = title.to_owned();
let (s, t) = (sink.clone(), title.clone());
let report = move |path: &str, i: usize, n: usize| {
let fraction = if n == 0 { None } else { Some(i as f32 / n as f32) };
let message = Some(path.to_owned());
s.emit(IdeEvent::Task { id, title: t.clone(), message, fraction, done: false, cancellable: true });
};
let done = move || {
drop(handle);
sink.emit(IdeEvent::Task { id, title, message: None, fraction: Some(1.0), done: true, cancellable: false })
s.emit(IdeEvent::Task { id, title: t.clone(), message: Some(path.to_owned()), fraction, done: false });
};
let done = move || sink.emit(IdeEvent::Task { id, title, message: None, fraction: Some(1.0), done: true });
(report, done)
}
@@ -44,7 +34,7 @@ pub async fn deploy_upload(
) -> IdeResult<TransferReport> {
let project = state.project(window.label())?;
let token = state.begin_request(request);
let (mut report, done) = progress(project.sink.clone(), "Uploading", token.clone());
let (mut report, done) = progress(project.sink.clone(), "Uploading");
let r = state
.remote
.upload(&project.settings.effective(), &project.root, server.as_deref(), &local(paths), token, &mut report)
@@ -66,7 +56,7 @@ pub async fn deploy_download(
) -> IdeResult<TransferReport> {
let project = state.project(window.label())?;
let token = state.begin_request(request);
let (mut report, done) = progress(project.sink.clone(), "Downloading", token.clone());
let (mut report, done) = progress(project.sink.clone(), "Downloading");
let r = state
.remote
.download(&project.settings.effective(), &project.root, server.as_deref(), &local(paths), token, &mut report)
@@ -118,7 +108,7 @@ pub async fn deploy_sync(
) -> IdeResult<TransferReport> {
let project = state.project(window.label())?;
let token = state.begin_request(request);
let (mut report, done) = progress(project.sink.clone(), "Synchronizing", token.clone());
let (mut report, done) = progress(project.sink.clone(), "Synchronizing");
let r = state
.remote
.sync(&project.settings.effective(), &project.root, server.as_deref(), &steps, token, &mut report)
-14
Переглянути файл
@@ -1,14 +0,0 @@
//! IPC commands of `ide_host::ops::env` (the shared implementation).
use crate::state::AppState;
use ide_core::IdeResult;
use ide_host::environment::EnvReloaded;
use tauri::{State, Window};
/// Reload Environment: new child processes get the login shell's current environment
/// (and the project's `remoteEnv` on a remote host); running ones keep theirs.
#[tauri::command]
#[specta::specta]
pub async fn env_reload(window: Window, state: State<'_, AppState>) -> IdeResult<EnvReloaded> {
ide_host::ops::env::reload(&state.host, window.label()).await
}
-8
Переглянути файл
@@ -76,11 +76,3 @@ pub fn http_history_get(window: Window, state: State<'_, AppState>, id: String)
pub fn http_history_clear(window: Window, state: State<'_, AppState>) -> IdeResult<()> {
state.project(window.label())?.http_history.clear()
}
/// System Settings › HTTP Proxy › Check connection: GETs `url` through `proxy` as
/// edited (not yet applied); the response status, or why there was none.
#[tauri::command]
#[specta::specta]
pub async fn proxy_check_connection(proxy: ide_core::settings::ProxySettings, url: String) -> IdeResult<String> {
ide_http::client::check_connection(&proxy, &url, &ide_core::CancellationToken::new()).await
}
-4
Переглянути файл
@@ -19,7 +19,6 @@ pub mod debug;
pub mod deploy;
pub mod doc;
pub mod docker;
pub mod env;
pub mod fs;
pub mod github;
pub mod history;
@@ -72,7 +71,6 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
app::project_rename,
app::project_roots,
app::cancel_request,
app::cancel_task,
app::log_frontend,
agent::agent_subscribe,
agent::agent_providers,
@@ -394,7 +392,6 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
http::http_history,
http::http_history_get,
http::http_history_clear,
http::proxy_check_connection,
db::db_sources,
db::db_save_sources,
db::db_set_password,
@@ -425,7 +422,6 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
crate::remote_dev::remote_current,
crate::remote_dev::remote_disconnect,
crate::remote_dev::remote_invoke,
env::env_reload,
db::db_test,
db::db_connected,
db::db_connect,
+1 -2
Переглянути файл
@@ -295,8 +295,7 @@ fn updater(app: &AppHandle) -> IdeResult<Option<tauri_plugin_updater::Updater>>
return Ok(None);
}
let env = update_endpoint_env();
let proxy = ide_core::proxy_settings::proxy();
let mut builder = app.updater_builder().configure_client(move |b| ide_http::client::with_proxy(b, &proxy));
let mut builder = app.updater_builder();
if let Some(url) = env {
let url = url.parse().map_err(|e| IdeError::invalid(format!("OPENIDEA_UPDATE_ENDPOINT: {e}")))?;
builder = builder.endpoints(vec![url]).map_err(|e| IdeError::invalid(e.to_string()))?;
-1
Переглянути файл
@@ -219,7 +219,6 @@ pub fn spec(os: Os) -> Vec<Entry> {
SEP,
act("remote.connect", "Remote Development…"),
act("remote.disconnect", "Disconnect from Remote Host"),
act("remote.reloadEnvironment", "Reload Environment"),
SEP,
act("file.save", "Save All"),
act("file.reloadAllFromDisk", "Reload All from Disk"),
-1
Переглянути файл
@@ -84,7 +84,6 @@ impl AppState {
}),
owner: Self::owner_window,
runtime: tauri::async_runtime::handle().inner().clone(),
project_environment: false,
}));
Ok(Self {
recent: RecentProjects::load(&config_dir),
+1 -72
Переглянути файл
@@ -56,11 +56,6 @@ export const commands = {
*/
projectRoots: () => typedError<ProjectRoots, IdeError>(__TAURI_INVOKE("project_roots")),
cancelRequest: (id: RequestId) => __TAURI_INVOKE<void>("cancel_request", { id }),
/**
* Stops a background task the backend reported with `cancellable` set; false when it
* has ended or can't be cancelled.
*/
cancelTask: (id: TaskId) => __TAURI_INVOKE<boolean>("cancel_task", { id }),
/** Routes frontend logs into the backend `tracing` pipeline. */
logFrontend: (level: LogLevel, message: string) => __TAURI_INVOKE<void>("log_frontend", { level, message }),
/** Streams the project's agent events to this window; returns every task. */
@@ -850,11 +845,6 @@ export const commands = {
httpHistory: () => typedError<HttpHistoryEntry[], IdeError>(__TAURI_INVOKE("http_history")),
httpHistoryGet: (id: string) => typedError<HttpExchange, IdeError>(__TAURI_INVOKE("http_history_get", { id })),
httpHistoryClear: () => typedError<null, IdeError>(__TAURI_INVOKE("http_history_clear")),
/**
* System Settings › HTTP Proxy › Check connection: GETs `url` through `proxy` as
* edited (not yet applied); the response status, or why there was none.
*/
proxyCheckConnection: (proxy: ProxySettings, url: string) => typedError<string, IdeError>(__TAURI_INVOKE("proxy_check_connection", { proxy, url })),
dbSources: () => typedError<DataSource[], IdeError>(__TAURI_INVOKE("db_sources")),
dbSaveSources: (sources: DataSource[]) => typedError<null, IdeError>(__TAURI_INVOKE("db_save_sources", { sources })),
/**
@@ -933,11 +923,6 @@ export const commands = {
* `on_channel` tagged with the id.
*/
remoteInvoke: (cmd: string, args: string, onChannel: Channel<ChannelFrame>) => typedError<string, IdeError>(__TAURI_INVOKE("remote_invoke", { cmd, args, onChannel })),
/**
* Reload Environment: new child processes get the login shell's current environment
* (and the project's `remoteEnv` on a remote host); running ones keep theirs.
*/
envReload: () => typedError<EnvReloaded, IdeError>(__TAURI_INVOKE("env_reload")),
/** Test Connection: connects with unsaved settings and returns the server version. */
dbTest: (source: DataSource, password: string | null, sshSecret: string | null) => typedError<string, IdeError>(__TAURI_INVOKE("db_test", { source, password, sshSecret })),
dbConnected: () => typedError<string[], IdeError>(__TAURI_INVOKE("db_connected")),
@@ -1179,15 +1164,6 @@ export type AgentRegistry = {
warning: string | null,
};
/** An API request the agent is about to retry. */
export type AgentRetry = {
attempt: number,
maxRetries: number | null,
/** When the next attempt starts (ms since the epoch). */
retryAtMs: number | null,
error: string | null,
};
/** Where an agent comes from. */
export type AgentSource = { kind: "builtin" } |
/** Defined by the user in `<config>/agents/<id>.toml`. */
@@ -1247,11 +1223,6 @@ export type AgentTask = {
capabilities?: AgentCapabilities,
/** When a [`AgentStatus::Limited`] task's limit resets (ms since the epoch), if the agent said. */
resetsMs?: number | null,
/**
* The agent is retrying a failed API request (connection lost, overloaded…); cleared
* by its next output or any status change.
*/
retry?: AgentRetry | null,
};
export type AgentToolDiff = {
@@ -2268,8 +2239,6 @@ export type DebuggerSettings = {
/** Data Views: list variables by name instead of the adapter's order. */
sortValues?: boolean,
valueTooltip?: boolean,
/** While suspended, selecting an expression shows its value. */
valueTooltipOnSelection?: boolean,
valueTooltipDelay?: number,
/** Stepping: do not step into library code (debugpy `justMyCode`, js-debug `skipFiles`). */
skipLibraryCode?: boolean,
@@ -2763,16 +2732,6 @@ export type EncodingSettings = {
export type EntryKind = "file" | "dir" | "symlink";
/** What Reload Environment changed. */
export type EnvReloaded = {
/** Names of the variables new child processes now get differently (added, changed or removed). */
changed: string[],
/** The `devcontainer.json` whose `remoteEnv` applies, if any. */
devcontainer: string | null,
/** Whether the login shell was read (it isn't on Windows). */
shellRead: boolean,
};
export type ErrorKind = "notFound" | "alreadyExists" | "permissionDenied" | "invalidInput" |
/** Document version mismatch; the UI must resync the full text. */
"outOfSync" | "cancelled" |
@@ -3278,9 +3237,7 @@ export type IdeEvent =
/** Full replacement of diagnostics for one file from one producer. */
{ type: "diagnostics"; path: IpcPath; source: string; items: Diagnostic[] } |
/** Progress of a background task; `fraction` is `None` when indeterminate. */
{ type: "task"; id: TaskId; title: string; message: string | null; fraction: number | null; done: boolean;
/** The UI may stop it with `cancel_task(id)` (see [`crate::task`]). */
cancellable: boolean } |
{ type: "task"; id: TaskId; title: string; message: string | null; fraction: number | null; done: boolean } |
/** Project indexing state changed (dumb mode on/off). */
{ type: "indexState"; indexing: boolean; files: number; symbols: number } |
/** Git status / branch information should be refreshed. */
@@ -4530,30 +4487,6 @@ export type ProjectStructureSettings = {
excludeFiles?: string,
};
export type ProxyKind = "http" | "socks";
export type ProxyMode =
/** Every connection goes direct. */
"none" |
/** The system's proxy: `HTTP_PROXY` / `HTTPS_PROXY` / `NO_PROXY` of the environment. */
"auto" |
/** The proxy configured here. */
"manual";
export type ProxySettings = {
mode?: ProxyMode,
kind?: ProxyKind,
host?: string,
port?: number,
/** Hosts reached directly, comma-separated; `*` matches any characters (`*.example.com`, `192.168.*`). */
noProxy?: string,
/** Send `login` / `password` to the proxy. */
authenticate?: boolean,
login?: string,
/** Kept in the saved passwords rather than `settings.toml`; filled in when settings are read. */
password?: string,
};
export type PruneTarget = "containers" |
/** Dangling images only. */
"images" |
@@ -5182,8 +5115,6 @@ export type Settings_Deserialize = {
*/
customKeymaps?: { [key in string]: CustomKeymap },
notifications?: NotificationSettings,
/** System Settings › HTTP Proxy (global only). */
proxy?: ProxySettings,
/** Interpreters / toolchains per language (Python, Node.js, Rust, Go, TypeScript). */
languages?: LanguagesSettings,
/** Project Structure: source / test / resource / excluded folders (project-relative). */
@@ -5237,8 +5168,6 @@ export type Settings_Serialize = {
*/
customKeymaps: { [key in string]: CustomKeymap },
notifications: NotificationSettings,
/** System Settings › HTTP Proxy (global only). */
proxy: ProxySettings,
/** Interpreters / toolchains per language (Python, Node.js, Rust, Go, TypeScript). */
languages: LanguagesSettings,
/** Project Structure: source / test / resource / excluded folders (project-relative). */
-47
Переглянути файл
@@ -21,7 +21,6 @@ const {
ghostText,
inlineCompletionExtension,
nextWord,
registerInlineCompletionActions,
requestInline,
toSuggestions,
} = await import("./inlineCompletion");
@@ -137,49 +136,3 @@ describe("inline completion", () => {
expect(nextWord(" ")).toBe(" ");
});
});
describe("inline completion without a provider", () => {
const unavailable = (message: string) => ({
status: "error" as const,
error: { kind: "unavailable" as const, message },
});
const hintText = () => document.querySelector(".cm-lsp-hint")?.textContent ?? null;
async function invoke(view: EditorView) {
const { useEditorRegistry } = await import("@/editor/api");
const { getAction } = await import("@/platform/actions");
useEditorRegistry.setState({ active: { view, ctx: view.state.facet(lspDoc)! } as never });
const off = registerInlineCompletionActions();
void getAction("editor.inlineCompletion.trigger")!.run({ ctx: {} } as never);
off();
}
it.each([
[
"names the running server that lacks it",
"jdtls doesn't support inline completion",
"jdtls doesn't support inline completion",
],
[
"says no server runs when none does",
"no running language server supports inline completion",
"No language server available",
],
])("on explicit invocation %s", async (_, message, shown) => {
const view = editor("String s = ");
ipc.lspInlineCompletion.mockResolvedValueOnce(unavailable(message));
await invoke(view);
await vi.waitFor(() => expect(hintText()).toBe(shown));
});
it("stays silent while typing", async () => {
const view = editor("String s = ");
ipc.lspInlineCompletion.mockResolvedValue(unavailable("jdtls doesn't support inline completion"));
expect(await requestInline(view, true)).toBe(false);
view.dispatch({ changes: { from: 11, insert: "x" }, userEvent: "input.type" });
await new Promise((r) => setTimeout(r, 120));
expect(hintText()).toBeNull();
expect(ghostDom(view)).toBeNull();
ipc.lspInlineCompletion.mockReset();
});
});
+1 -2
Переглянути файл
@@ -21,7 +21,6 @@ import {
type Command,
type InlineCompletionItem,
type RequestId,
unavailableText,
} from "@/platform/ipc";
import { activeEditor } from "@/editor/api";
import { docOf, isUnavailable, lspRequest } from "./lsp";
@@ -313,7 +312,7 @@ export function registerInlineCompletionActions(): () => void {
try {
if (!(await requestInline(v, false))) showHint(v, "No inline suggestions");
} catch (e) {
showHint(v, isUnavailable(e) ? unavailableText(e) : String(e));
showHint(v, isUnavailable(e) ? "No language server provides inline completion" : String(e));
}
}),
},
+1 -26
Переглянути файл
@@ -8,8 +8,7 @@ vi.mock("@/platform/ipc", async (orig) => {
return { ...actual, isTauri: () => true };
});
const { lspRequest, reportLspError } = await import("./lsp");
const { IpcError } = await import("@/platform/ipc");
const { lspRequest } = await import("./lsp");
describe("lspRequest", () => {
it("waits until open editors' edits reached the backend", async () => {
@@ -28,27 +27,3 @@ describe("lspRequest", () => {
view.destroy();
});
});
describe("reportLspError", () => {
const unavailable = (message: string) => new IpcError({ kind: "unavailable", message });
const hintText = () => document.querySelector(".cm-lsp-hint")?.textContent ?? null;
it.each([
["jdtls doesn't support type hierarchy", "jdtls doesn't support type hierarchy"],
["pyright, ruff doesn't support code lens", "pyright, ruff doesn't support code lens"],
["no running language server supports rename", "No language server available"],
["jdtls is not running", "No language server available"],
])("explicit %s → %s", (message, shown) => {
const view = new EditorView({ state: EditorState.create({ doc: "x" }), parent: document.body });
reportLspError(view, unavailable(message), true);
expect(hintText()).toBe(shown);
view.destroy();
});
it("stays silent for background requests", () => {
const view = new EditorView({ state: EditorState.create({ doc: "x" }), parent: document.body });
reportLspError(view, unavailable("jdtls doesn't support inlay hints"), false);
expect(hintText()).toBeNull();
view.destroy();
});
});
+3 -4
Переглянути файл
@@ -2,7 +2,7 @@
import { Facet } from "@codemirror/state";
import type { EditorView } from "@codemirror/view";
import { whenAllSynced, type EditorDocContext } from "@/editor/api";
import { IpcError, call, isCancelled, isTauri, unavailableText } from "@/platform/ipc";
import { IpcError, call, isCancelled, isTauri } from "@/platform/ipc";
import type { IdeError } from "@/bindings";
import { showHint } from "./hint";
@@ -44,8 +44,7 @@ export const NO_SERVER = "No language server available";
/**
* Error policy: background requests fail silently; explicit actions show a
* small hint at the caret ("No language server available" for missing servers,
* "jdtls doesn't support X" when the running server lacks the feature).
* small hint at the caret ("No language server available" for missing servers).
*/
export function reportLspError(view: EditorView | null, e: unknown, explicit: boolean) {
if (isCancelled(e)) return;
@@ -53,7 +52,7 @@ export function reportLspError(view: EditorView | null, e: unknown, explicit: bo
if (!isUnavailable(e)) console.debug("[lsp]", e);
return;
}
showHint(view, isUnavailable(e) ? unavailableText(e, NO_SERVER) : e instanceof Error ? e.message : String(e));
showHint(view, isUnavailable(e) ? NO_SERVER : e instanceof Error ? e.message : String(e));
}
/** Runs `fn` once `ms` after the last call; `cancel()` drops a pending run. */
+2 -7
Переглянути файл
@@ -13,7 +13,7 @@
import type { EditorView } from "@codemirror/view";
import type { Text } from "@codemirror/state";
import type { LocalSymbol, Location, OutlineItem, Pos, Range, SyntaxNode } from "@/bindings";
import { call, commands, isCancelled, isTauri, nextRequestId, unavailableText } from "@/platform/ipc";
import { call, commands, isCancelled, isTauri, nextRequestId } from "@/platform/ipc";
import { executeAction } from "@/platform/actions";
import { basename } from "@/platform/project";
import { editorsFor, whenSynced, type EditorDocContext } from "@/editor/api";
@@ -482,12 +482,7 @@ export async function safeDelete(view: EditorView): Promise<void> {
applyDeletion(view, docBefore, target, comments);
} catch (e) {
if (isCancelled(e)) return;
showHint(
view,
isUnavailable(e)
? cannotPerform(unavailableText(e, "No language server is available"))
: cannotPerform(errorText(e)),
);
showHint(view, isUnavailable(e) ? cannotPerform("No language server is available") : cannotPerform(errorText(e)));
} finally {
running = null;
}
-4
Переглянути файл
@@ -437,10 +437,6 @@
color: var(--fg-muted);
}
.retrying {
color: var(--warning);
}
.composerArea {
flex: none;
display: flex;
+3 -21
Переглянути файл
@@ -2,7 +2,7 @@
import { Fragment, useEffect, useLayoutEffect, useMemo, useRef, useState, type RefObject } from "react";
import clsx from "clsx";
import { useShallow } from "zustand/react/shallow";
import type { AgentChange, AgentEntry, AgentRetry, AgentTask, AgentUsage } from "@/bindings";
import type { AgentChange, AgentEntry, AgentTask, AgentUsage } from "@/bindings";
import { executeAction } from "@/platform/actions";
import { call, commands, onIdeEvent } from "@/platform/ipc";
import { basename, relativeDir, useProject } from "@/platform/project";
@@ -25,7 +25,7 @@ import {
import { useTx, tx } from "@/platform/i18n";
import { TaskStatusIcon } from "./AgentsView";
import { Composer } from "./Composer";
import { canSend, emptyDraft, retryParts, usageLabel, workTime } from "./composerModel";
import { canSend, emptyDraft, usageLabel, workTime } from "./composerModel";
import { ConfigPickers } from "./ConfigPickers";
import { findRanges, formatDuration, formatSentAt } from "./conversation";
import { Markdown } from "./Markdown";
@@ -381,11 +381,7 @@ function Stream({ task, entries, subagent, onOpenSubagent, finding, findFocus, o
{!subagent && (task.status === "running" || task.status === "starting") && !waiting && (
<div className={styles.working}>
<Spinner size={12} />
{task.retry ? (
<Retrying retry={task.retry} />
) : (
<T>{task.status === "starting" ? "Starting the agent…" : "Working…"}</T>
)}
<T>{task.status === "starting" ? "Starting the agent…" : "Working…"}</T>
{lastUser?.sentMs != null && !lastUser.doneMs && <Elapsed since={lastUser.sentMs} />}
</div>
)}
@@ -397,20 +393,6 @@ function Stream({ task, entries, subagent, onOpenSubagent, finding, findFocus, o
type UserEntry = Extract<AgentEntry, { type: "user" }>;
/** Time since `since`, ticking every second. */
/** The agent lost its API connection (or was refused) and retries on its own. */
function Retrying({ retry }: { retry: AgentRetry }) {
const tx = useTx();
const now = useNow(1000);
const { attempt, wait } = retryParts(retry, now);
return (
<span className={styles.retrying} title={retry.error ?? undefined}>
{wait > 0
? tx`API request failed, retrying in ${wait}s (attempt ${attempt})`
: tx`API request failed, retrying (attempt ${attempt})`}
</span>
);
}
function Elapsed({ since }: { since: number }) {
const now = useNow(1000);
return <span className={styles.muted}>{formatDuration(now - since)}</span>;
-9
Переглянути файл
@@ -13,7 +13,6 @@ import {
nextValue,
recall,
toPrompt,
retryParts,
usageLabel,
workTime,
} from "./composerModel";
@@ -265,11 +264,3 @@ describe("turns", () => {
]);
});
});
describe("retryParts", () => {
it("counts down to the next attempt and shows the limit when known", () => {
const retry = { attempt: 3, maxRetries: 10, retryAtMs: 5_400, error: "Connection error." };
expect(retryParts(retry, 1_000)).toEqual({ attempt: "3/10", wait: 5 });
expect(retryParts({ ...retry, maxRetries: null }, 9_000)).toEqual({ attempt: "3", wait: 0 });
});
});
+1 -17
Переглянути файл
@@ -1,13 +1,5 @@
/** Pure composer helpers: `@` / `/` completion, attachments, history recall, settings. */
import type {
AgentCommand,
AgentConfigOption,
AgentEntry,
AgentImage,
AgentPrompt,
AgentRetry,
AgentUsage,
} from "@/bindings";
import type { AgentCommand, AgentConfigOption, AgentEntry, AgentImage, AgentPrompt, AgentUsage } from "@/bindings";
import { tx } from "@/platform/i18n";
export interface FileRef {
@@ -139,14 +131,6 @@ export function nextValue(option: AgentConfigOption, current = option.current):
}
/** "12%" of the context window and a tooltip with the numbers. */
/** A pending API retry: "3/10" (or "3" when the agent gives no limit) and the seconds left. */
export function retryParts(r: AgentRetry, now: number): { attempt: string; wait: number } {
return {
attempt: r.maxRetries != null ? `${r.attempt}/${r.maxRetries}` : String(r.attempt),
wait: r.retryAtMs == null ? 0 : Math.max(0, Math.ceil((r.retryAtMs - now) / 1000)),
};
}
export function usageLabel(u: AgentUsage): { short: string; detail: string } {
const pct = Math.min(100, Math.round((u.used / u.size) * 100));
return { short: `${pct}%`, detail: tx`${tokens(u.used)} / ${tokens(u.size)} tokens` };
+2 -8
Переглянути файл
@@ -39,13 +39,9 @@ export function checkForUpdates(): Promise<void> {
async function runCheck() {
const title = t("app.update.checking");
// The check only reads: cancelling drops its answer (the request finishes on its own).
let abandon = () => {};
const abandoned = new Promise<"cancelled">((resolve) => (abandon = () => resolve("cancelled")));
upsertTask({ id: CHECK_TASK_ID, title, message: null, fraction: null, done: false, cancel: () => abandon() });
upsertTask({ id: CHECK_TASK_ID, title, message: null, fraction: null, done: false });
try {
const r = await Promise.race([call(commands.appCheckUpdate()), abandoned]);
if (r === "cancelled") return;
const r = await call(commands.appCheckUpdate());
if (!r.enabled) {
notifications().notify({
level: "info",
@@ -126,8 +122,6 @@ async function runInstall(version: string) {
fraction,
done: false,
cancel: p.type === "installing" ? undefined : cancel,
// Replacing the app happens in one step that must not be cut short.
uncancellable: p.type === "installing" ? t("app.update.installUncancellable") : undefined,
});
};
// The notification's action is spent: progress lives in the status bar from here.
+2 -5
Переглянути файл
@@ -23,7 +23,7 @@ import {
import { downloadJdkActions } from "@/platform/jdk";
import { useProject } from "@/platform/project";
import { editorService, notifications } from "@/workbench/contributions";
import { cancelTask, removeTask, upsertTask, useTasks } from "@/workbench/tasks";
import { removeTask, upsertTask } from "@/workbench/tasks";
import { profilesList, type GradleRunOptions, type MavenRunOptions } from "./model";
export interface BuildSettings {
@@ -231,10 +231,7 @@ export async function syncTool(tool: BuildTool): Promise<void> {
export function cancelSync(tool: BuildTool) {
const s = useBuild.getState().syncing[tool];
if (!s) return;
const taskId = `build-sync:${tool}`;
if (useTasks.getState().tasks.some((t) => t.id === taskId && t.cancel)) cancelTask(taskId);
else void commands.cancelRequest(s.request);
if (s) void commands.cancelRequest(s.request);
}
export function resetBuild() {
+2 -5
Переглянути файл
@@ -25,7 +25,7 @@ import {
} from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { maybeEditorService, notifications, toolWindowService } from "@/workbench/contributions";
import { cancelTask, removeTask, upsertTask, useTasks } from "@/workbench/tasks";
import { removeTask, upsertTask } from "@/workbench/tasks";
import { appendOutput, finishSummary, firstError, messageFiles, type BuildStatus, type ConsoleLine } from "./model";
export const BUILD_TASK_ID = "build:compile";
@@ -248,10 +248,7 @@ function showFailure() {
export function stopBuild() {
const { request } = useBuildRun.getState();
if (request == null) return;
// Through the task, so its progress says "Cancelling…" until the build has stopped.
if (useTasks.getState().tasks.some((t) => t.id === BUILD_TASK_ID && t.cancel)) cancelTask(BUILD_TASK_ID);
else backend.cancel(request);
if (request != null) backend.cancel(request);
}
/** Runs the last build again (the tool window's rerun button). */
+2 -2
Переглянути файл
@@ -3,7 +3,7 @@ import type { EditorView } from "@codemirror/view";
import { activeEditor, editorsFor } from "@/editor/api";
import { isVirtualUri, virtualDocument } from "@/platform/virtualDocs";
import { executeAction } from "@/platform/actions";
import { IpcError, call, commands, isCancelled, isTauri, unavailableText } from "@/platform/ipc";
import { IpcError, call, commands, isCancelled, isTauri } from "@/platform/ipc";
import type { IdeError } from "@/bindings";
import { maybeEditorService, notifications } from "@/workbench/contributions";
@@ -36,7 +36,7 @@ export function hint(text: string, tone: "info" | "warning" | "error" = "info")
export function reportError(e: unknown) {
if (isCancelled(e)) return;
hint(
isUnavailable(e) ? unavailableText(e) : e instanceof Error ? e.message : String(e),
isUnavailable(e) ? "No language server available" : e instanceof Error ? e.message : String(e),
isUnavailable(e) ? "info" : "error",
);
}
-14
Переглянути файл
@@ -162,20 +162,6 @@ describe("run config → launch config", () => {
expect(launchConfigFor(script, "/p")).not.toBeNull();
});
it("never hands a Java command to java-debug as a program to start", () => {
const tomcat = rc({
name: "tomcat9",
command: "C:\\apache-tomcat-9.0.98\\bin\\catalina.bat",
args: ["run"],
debugAdapter: "java-debug",
});
const gradle = rc({ kind: "gradle", command: "./gradlew", args: ["build"], debugAdapter: "java-debug" });
for (const c of [tomcat, gradle]) {
expect(launchConfigFor(c, "/p")).toBeNull();
expect(debugUnsupportedReason(c)).toContain("Remote JVM Debug");
}
});
it("delve: debug mode for run, test mode for test", () => {
const run = launchConfigFor(rc({ kind: "go", command: "go", args: ["run", "."], debugAdapter: "delve" }), "/p")!;
expect(run.program).toBe("/p");
-21
Переглянути файл
@@ -1,6 +1,4 @@
import { describe, expect, it } from "vitest";
import { EditorSelection, EditorState } from "@codemirror/state";
import { selectionExpression } from "../editor/valueTooltip";
import { classifyValue, identifiersIn, inlineValue, sortVariables } from "../values";
import { inlineValuesFor } from "../editor/execution";
import { frameLabel, groupFrames, isLibraryFrame } from "../frames";
@@ -111,22 +109,3 @@ describe("sortVariables", () => {
expect(names(sortVariables(items))).toEqual(["[0]", "[1]", "[10]", "[2]"]);
});
});
describe("selectionExpression", () => {
const at = (doc: string, from: number, to: number) =>
selectionExpression(EditorState.create({ doc, selection: EditorSelection.single(from, to) }));
it("takes a one-line selection", () => {
expect(at("total += item.price", 9, 19)).toEqual({ from: 9, text: "item.price" });
});
it("ignores empty, blank, multi-line and multiple selections", () => {
expect(at("a + b", 2, 2)).toBeNull();
expect(at("a b", 1, 4)).toBeNull();
expect(at("a\nb", 0, 3)).toBeNull();
const multi = EditorState.create({
doc: "a + b",
selection: EditorSelection.create([EditorSelection.range(0, 1), EditorSelection.range(4, 5)]),
extensions: EditorState.allowMultipleSelections.of(true),
});
expect(selectionExpression(multi)).toBeNull();
});
});
+1 -6
Переглянути файл
@@ -1,5 +1,5 @@
/** Debugger actions (ids match `keymaps/intellij-macos.ts`). */
import { executeAction, getAction, registerActions, type Action } from "@/platform/actions";
import { registerActions, type Action } from "@/platform/actions";
import { call, commands, isCancelled, isTauri, nextRequestId, type RunConfig, type RunId } from "@/platform/ipc";
import { downloadJdkActions } from "@/platform/jdk";
import { useProject } from "@/platform/project";
@@ -242,11 +242,6 @@ async function startConfig(arg: unknown) {
return;
}
config = configs[0]!;
// Through Run's debug flow: Maven / Gradle / scripts start the JVM with a JDWP agent there.
if (getAction("run.debugConfig")) {
await executeAction("run.debugConfig", config);
return;
}
}
if (isRemoteConfig(config)) {
await startRemote(config, root);
+2 -59
Переглянути файл
@@ -3,10 +3,9 @@
* while suspended, hovering an expression (or the selection under the mouse)
* evaluates it in the selected frame.
*/
import type { EditorState, Extension } from "@codemirror/state";
import type { Extension } from "@codemirror/state";
import type { DebugSessionId, Variable } from "@/bindings";
import { hoverTooltip, ViewPlugin, type EditorView, type ViewUpdate } from "@codemirror/view";
import { showHint } from "@/editor/lsp/hint";
import { hoverTooltip, type EditorView } from "@codemirror/view";
import { workflowSettings } from "@/platform/workflowSettings";
import { navigationModifierHeld } from "@/platform/navigationModifier";
import { activeSession, evaluate } from "../state";
@@ -110,59 +109,3 @@ export function valueTooltip(): Extension {
{ hoverTime: BASE_HOVER },
);
}
const SELECTION_DELAY = 400;
const MAX_SELECTION = 200;
/** The selected text when it can be evaluated: one non-blank line, not too long. */
export function selectionExpression(state: EditorState): { from: number; text: string } | null {
const sel = state.selection;
if (sel.ranges.length !== 1 || sel.main.empty) return null;
const text = state.sliceDoc(sel.main.from, sel.main.to).trim();
if (!text || text.length > MAX_SELECTION || text.includes("\n")) return null;
return { from: sel.main.from, text };
}
/**
* Settings › Debugger › Data Views › "Show value tooltip on code selection": while
* suspended, selecting an expression shows its value once the selection settles.
*/
export function selectionValueTooltip(): Extension {
return ViewPlugin.fromClass(
class {
private timer: ReturnType<typeof setTimeout> | undefined;
private seq = 0;
constructor(readonly view: EditorView) {}
update(u: ViewUpdate) {
if (!u.selectionSet) return;
clearTimeout(this.timer);
this.seq++;
if (!u.transactions.some((tr) => tr.isUserEvent("select"))) return;
const seq = this.seq;
this.timer = setTimeout(() => void this.show(seq), SELECTION_DELAY);
}
private async show(seq: number) {
if (!workflowSettings().debugger.valueTooltipOnSelection) return;
const session = activeSession();
if (!session || session.status !== "paused") return;
const expr = selectionExpression(this.view.state);
if (!expr) return;
let value;
try {
value = await evaluate(expr.text, "hover", session);
} catch {
return;
}
// The selection moved on while evaluating.
if (seq !== this.seq) return;
showHint(this.view, () => valueHint(expr.text, value, session.id), { pos: expr.from, timeout: 60_000 });
}
destroy() {
clearTimeout(this.timer);
}
},
);
}
+1 -2
Переглянути файл
@@ -6,7 +6,7 @@
import { lazyComponent } from "@/ui";
import { onIdeEvent } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { selectionValueTooltip, valueTooltip } from "./editor/valueTooltip";
import { valueTooltip } from "./editor/valueTooltip";
import { registerEditorContribution } from "@/editor/api";
import {
registerMenuGroup,
@@ -65,7 +65,6 @@ export function activate(): () => void {
executionPoint(ctx),
runToCursorInlay(ctx),
valueTooltip(),
selectionValueTooltip(),
smartStepTargets(ctx),
],
}),
-4
Переглянути файл
@@ -124,12 +124,8 @@ function commandName(cmd: string) {
/**
* Why `rc` can't be debugged even though it names a debugger, or null when it can.
* Bun's inspector speaks the WebKit Inspector protocol, which js-debug can't attach to.
* Java configurations reach this only when the Run feature found no JVM to attach to.
*/
export function debugUnsupportedReason(rc: RunConfig): string | null {
// java-debug runs inside jdtls: it launches Application configurations or attaches to a JDWP agent.
if (rc.debugAdapter === "java-debug")
return "The Java debugger can't start this command itself. Debug an Application, Spring Boot, Maven or Gradle configuration, or start the JVM with a JDWP agent and attach with a Remote JVM Debug configuration.";
const name = commandName(rc.command);
if (rc.kind === "bun" || (name === "bun" && rc.kind !== "npm"))
return (
-66
Переглянути файл
@@ -1,66 +0,0 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { EnvReloaded, IdeError } from "@/bindings";
import type { NotificationService } from "@/workbench/contributions";
type Outcome = { status: "ok"; data: EnvReloaded } | { status: "error"; error: IdeError };
let outcome: Outcome;
const envReload = vi.fn(async () => outcome);
const lspServers = vi.fn(async () => ({ status: "ok" as const, data: [{ id: 1 }, { id: 2 }] }));
const lspRestart = vi.fn(async (_id: number) => ({ status: "ok" as const, data: null }));
vi.mock("@/platform/ipc", async (orig) => {
const actual = await orig<typeof import("@/platform/ipc")>();
return { ...actual, commands: { ...actual.commands, envReload, lspServers, lspRestart } };
});
const { reloadEnvironment, reloadSummary } = await import("./environment");
const { provideNotificationService } = await import("@/workbench/contributions");
type Note = Parameters<NotificationService["notify"]>[0];
let notes: Note[];
beforeEach(() => {
notes = [];
provideNotificationService({ notify: (n) => void notes.push(n) });
vi.clearAllMocks();
});
const reloaded = (changed: string[]): EnvReloaded => ({ changed, devcontainer: null, shellRead: true });
describe("Reload Environment", () => {
it("says what changed and that running processes keep their environment", () => {
expect(reloadSummary(reloaded([]))).toBe(
"No variables changed. Terminals and processes already running keep their old environment; new ones get the new one.",
);
expect(reloadSummary(reloaded(["JAVA_HOME", "PATH"]))).toMatch(/^Changed: JAVA_HOME, PATH\. Terminals/);
const many = Array.from({ length: 10 }, (_, i) => `V${i}`);
expect(reloadSummary(reloaded(many))).toMatch(/^Changed: V0, V1, V2, V3, V4, V5, V6, V7 and 2 more\./);
});
it("offers to restart the language servers when something changed", async () => {
outcome = { status: "ok", data: reloaded(["PATH"]) };
await reloadEnvironment();
expect(envReload).toHaveBeenCalledOnce();
expect(notes).toHaveLength(1);
expect(notes[0]).toMatchObject({ level: "info", title: "Environment reloaded" });
const restart = notes[0]!.actions!.find((a) => a.label === "Restart Language Servers")!;
restart.run();
await vi.waitFor(() => expect(lspRestart).toHaveBeenCalledTimes(2));
expect(lspRestart.mock.calls.map((c) => c[0])).toEqual([1, 2]);
});
it("has nothing to restart when nothing changed", async () => {
outcome = { status: "ok", data: reloaded([]) };
await reloadEnvironment();
expect(notes[0]!.actions).toEqual([]);
});
it("reports a failure as an error", async () => {
outcome = {
status: "error",
error: { kind: "unavailable", message: "could not read the environment of the login shell (/bin/zsh)" },
} as Outcome;
await reloadEnvironment();
expect(notes[0]).toMatchObject({ level: "error", title: "Could not reload the environment" });
expect(String(notes[0]!.body)).toContain("login shell");
});
});
-64
Переглянути файл
@@ -1,64 +0,0 @@
/**
* Reload Environment: new terminals, runs, language servers and tools get the login
* shell's current environment (and, on a remote host, the project's `devcontainer.json`
* `remoteEnv`) without restarting the backend. What is already running keeps its own.
*/
import { tx } from "@/platform/i18n";
import { call, commands, type EnvReloaded } from "@/platform/ipc";
import { notifications } from "@/workbench/contributions";
const KEY = "remote.reloadEnvironment";
/** Variable names listed in the notification before "and N more". */
const LISTED = 8;
/** The notification text for a reload result. */
export function reloadSummary(r: EnvReloaded): string {
const names = r.changed.slice(0, LISTED).join(", ");
const more = r.changed.length - LISTED;
const changed =
r.changed.length === 0
? tx("No variables changed.")
: more > 0
? tx`Changed: ${names} and ${more} more.`
: tx`Changed: ${names}.`;
const keep = tx("Terminals and processes already running keep their old environment; new ones get the new one.");
return [changed, keep].join(" ");
}
async function restartLanguageServers() {
try {
const servers = await call(commands.lspServers());
await Promise.all(servers.map((s) => call(commands.lspRestart(s.id))));
} catch (e) {
notifications().notify({
group: "lsp",
level: "error",
title: "Failed to restart language server",
body: e instanceof Error ? e.message : String(e),
});
}
}
export async function reloadEnvironment() {
let result: EnvReloaded;
try {
result = await call(commands.envReload());
} catch (e) {
notifications().notify({
key: KEY,
level: "error",
title: "Could not reload the environment",
body: e instanceof Error ? e.message : String(e),
});
return;
}
notifications().notify({
key: KEY,
level: "info",
title: "Environment reloaded",
body: reloadSummary(result),
actions: result.changed.length
? [{ label: "Restart Language Servers", run: () => void restartLanguageServers() }]
: [],
});
}
-11
Переглянути файл
@@ -7,7 +7,6 @@ import { registerActions } from "@/platform/actions";
import { disconnectRemote } from "@/platform/remote";
import { registerOverlay } from "@/workbench/contributions";
import { ConnectHost } from "./ConnectDialog";
import { reloadEnvironment } from "./environment";
import { closeConnectDialog, openConnectDialog } from "./model";
export function activate(): () => void {
@@ -31,16 +30,6 @@ export function activate(): () => void {
when: "projectOpen",
run: () => disconnectRemote(),
},
{
id: "remote.reloadEnvironment",
title: "Reload Environment",
description:
"Reads the login shell's environment (and devcontainer.json remoteEnv on a remote host) again for new terminals and processes.",
category: "File",
keywords: ["env", "environment", "variables", "path", "shell", "remoteEnv", "devcontainer", "reload"],
when: "projectOpen",
run: () => reloadEnvironment(),
},
]),
];
return () => {
-42
Переглянути файл
@@ -261,48 +261,6 @@ describe("debugging build tool configurations", () => {
expect(jdwpLaunch(cfg({ id: "p", kind: "maven", args: ["package"] }))).toBeNull();
expect(jdwpLaunch(cfg({ id: "n", kind: "npm", args: ["test"] }))).toBeNull();
});
const AGENT = /-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=127\.0\.0\.1:0$/;
it.each([
["tomcat7:run"],
["org.apache.tomcat.maven:tomcat7-maven-plugin:2.2:run"],
["jetty:run"],
["jetty:run-war"],
["exec:java"],
])("debugs Maven's own JVM for the in-process goal %s", (goal) => {
const out = jdwpLaunch(cfg({ id: "m", kind: "maven", args: ["clean", goal], env: { MAVEN_OPTS: "-Xmx1g" } }))!;
expect(out.args).toEqual(["clean", goal]);
expect(out.env.MAVEN_OPTS).toMatch(/^-Xmx1g -agentlib:jdwp=/);
expect(out.env.MAVEN_OPTS).toMatch(AGENT);
});
it("keeps plain Maven builds out of the debugger unless set to the Java debugger", () => {
expect(jdwpLaunch(cfg({ id: "p", kind: "maven", args: ["exec:exec"] }))).toBeNull();
const chosen = jdwpLaunch(cfg({ id: "p", kind: "maven", args: ["package"], debugAdapter: "java-debug" }))!;
expect(chosen.env.MAVEN_OPTS).toMatch(AGENT);
});
it.each([
["shell", "C:\\apache-tomcat-9.0.98\\bin\\catalina.bat", ["run"]],
["shell", "/opt/tomcat9/bin/catalina.sh", ["run"]],
["program", "java", ["-jar", "app.war"]],
])("starts a %s configuration set to the Java debugger with an agent in JAVA_TOOL_OPTIONS", (kind, command, args) => {
const rc = cfg({ id: "tomcat9", kind, command, args, debugAdapter: "java-debug" });
const out = jdwpLaunch(rc)!;
expect(out.command).toBe(command);
expect(out.args).toEqual(args);
expect(out.env.JAVA_TOOL_OPTIONS).toMatch(AGENT);
const merged = jdwpLaunch({ ...rc, env: { JAVA_TOOL_OPTIONS: "-Dfile.encoding=UTF-8" } })!;
expect(merged.env.JAVA_TOOL_OPTIONS).toMatch(/^-Dfile\.encoding=UTF-8 -agentlib:jdwp=/);
});
it("leaves Application configurations and other debuggers alone", () => {
for (const kind of ["application", "spring-boot"])
expect(jdwpLaunch(cfg({ id: "a", kind, command: "java", debugAdapter: "java-debug" }))).toBeNull();
expect(jdwpLaunch(cfg({ id: "s", kind: "shell", command: "./run.sh", debugAdapter: "debugpy" }))).toBeNull();
expect(jdwpLaunch(cfg({ id: "g", kind: "gradle", args: ["build"], debugAdapter: "java-debug" }))).toBeNull();
});
});
describe("JUnit XML reports", () => {
+1 -17
Переглянути файл
@@ -4,26 +4,15 @@
* (`spring-boot:run` → `-Dspring-boot.run.jvmArguments`, Surefire →
* `-Dmaven.surefire.debug`, Gradle → `--debug-jvm`); when the agent reports
* its port, the Java debugger attaches. Output and the test tree stay in the Run tab.
* Maven goals that run the application inside Maven's JVM (`tomcat7:run`, `jetty:run`,
* `exec:java`) get the agent through `MAVEN_OPTS`; any other configuration set to the Java
* debugger (a script such as `catalina.sh run`) through `JAVA_TOOL_OPTIONS`, which every JVM reads.
*/
import { executeAction } from "@/platform/actions";
import type { RunConfig } from "@/platform/ipc";
import { isJvmApplication, JDWP_AGENT, jdwpListeningPort } from "@/platform/javaLaunch";
import { JDWP_AGENT, jdwpListeningPort } from "@/platform/javaLaunch";
import { startRun, useRun } from "./store";
const isMavenTestGoal = (a: string) =>
/^(test|verify|integration-test|surefire:test|failsafe:integration-test)$/.test(a);
const isGradleJvmTask = (a: string) => /(^|:)(test|bootRun|run|integrationTest|check)$/.test(a);
/** A plugin goal that runs the application in Maven's own JVM (`tomcat7:run`, `jetty:run-war`, `exec:java`). */
const isMavenInProcessGoal = (a: string) => /^[\w.-]+(:[\w.-]+)*:(run|run-war|run-exploded|java)$/.test(a);
const JAVA_ADAPTER = "java-debug";
function withOption(env: Record<string, string>, key: string, value: string): Record<string, string> {
const current = env[key]?.trim();
return { ...env, [key]: current ? `${current} ${value}` : value };
}
function withProperty(args: readonly string[], key: string, value: string): string[] {
const prefix = `-D${key}=`;
@@ -49,17 +38,12 @@ export function jdwpLaunch(config: RunConfig): RunConfig | null {
if (failsafe) out = withProperty(out, "maven.failsafe.debug", JDWP_AGENT);
return { ...config, args: out };
}
if (config.debugAdapter === JAVA_ADAPTER || args.some(isMavenInProcessGoal))
return { ...config, env: withOption(config.env, "MAVEN_OPTS", JDWP_AGENT) };
return null;
}
if (config.kind === "gradle" || /(^|\/)gradlew?(\.bat)?$/.test(config.command)) {
if (!args.some(isGradleJvmTask)) return null;
return args.includes("--debug-jvm") ? config : { ...config, args: [...args, "--debug-jvm"] };
}
// Application / Spring Boot configurations are launched by java-debug itself.
if (config.debugAdapter === JAVA_ADAPTER && !isJvmApplication(config))
return { ...config, env: withOption(config.env, "JAVA_TOOL_OPTIONS", JDWP_AGENT) };
return null;
}
-5
Переглянути файл
@@ -18,7 +18,6 @@ import {
import { EDITOR_EXTRA_DEFAULTS, validateEditorExtras, type EditorExtras } from "@/platform/editorSettings";
import { DEFAULT_WORKFLOW, validateWorkflow, type WorkflowSettings } from "@/platform/workflowSettings";
import { DEFAULT_INSPECTIONS, validateInspections, type InspectionSettingsValid } from "@/platform/inspections";
import { DEFAULT_PROXY, validateProxy, type ProxySettingsValid } from "@/platform/proxySettings";
import {
DEFAULT_APPEARANCE_EXTRAS,
DEFAULT_GENERAL_EXTRAS,
@@ -78,8 +77,6 @@ export interface ValidSettings extends WorkflowSettings {
keymapOverrides: Record<string, string[]>;
customKeymaps: Record<string, CustomKeymapSettings>;
notifications: NotificationsValid;
/** System Settings › HTTP Proxy (global). */
proxy: ProxySettingsValid;
languages: LanguagesValid;
projectStructure: ProjectStructureValid;
inspections: InspectionSettingsValid;
@@ -146,7 +143,6 @@ export const DEFAULT_SETTINGS: ValidSettings = {
keymapOverrides: {},
customKeymaps: {},
notifications: DEFAULT_NOTIFICATIONS,
proxy: DEFAULT_PROXY,
languages: DEFAULT_LANGUAGES,
projectStructure: DEFAULT_PROJECT_STRUCTURE,
inspections: DEFAULT_INSPECTIONS,
@@ -249,7 +245,6 @@ export function validateSettings(raw: Settings | unknown): ValidSettings {
keymapOverrides: overrides,
customKeymaps,
notifications: validateNotifications(root.notifications),
proxy: validateProxy(root.proxy),
languages: validateLanguages(root.languages),
projectStructure: validateProjectStructure(root.projectStructure),
inspections: validateInspections(root.inspections),
-88
Переглянути файл
@@ -1,88 +0,0 @@
.page {
display: flex;
flex-direction: column;
gap: 4px;
}
.modes {
display: flex;
flex-direction: column;
}
.radio {
display: inline-flex;
align-items: center;
gap: 6px;
min-height: 28px;
}
.radio input {
margin: 0;
accent-color: var(--accent);
}
.disabled {
color: var(--fg-subtle);
}
.hint {
padding-left: 20px;
color: var(--fg-subtle);
}
/* Manual configuration, indented under its radio button. */
.manual {
display: flex;
flex-direction: column;
padding-left: 20px;
}
.kinds {
display: flex;
align-items: center;
gap: 16px;
}
.hostRow {
display: flex;
align-items: flex-start;
gap: 24px;
}
.host {
width: 220px;
}
.port {
width: 64px;
}
.wide {
width: 360px;
}
.toggle {
display: flex;
align-items: center;
min-height: 28px;
}
.auth {
display: flex;
flex-direction: column;
padding-left: 20px;
}
.error {
color: var(--danger);
}
.ok {
color: var(--success, var(--fg-muted));
}
.check {
margin-top: 12px;
}
.popup {
display: flex;
flex-direction: column;
gap: 8px;
padding: 10px 14px;
max-width: 480px;
}
.urlRow {
display: flex;
align-items: center;
gap: 8px;
}
.result {
min-height: 1lh;
overflow-wrap: anywhere;
}
+1 -3
Переглянути файл
@@ -1,6 +1,6 @@
/**
* Appearance & Behavior pages, laid out like IntelliJ IDEA / PyCharm:
* Appearance, System Settings (+ Language and Region, Date Formats, HTTP Proxy) and
* Appearance, System Settings (+ Language and Region, Date Formats) and
* Notifications. Every option is wired (see `appearanceRuntime`, workbench
* theme / tool windows / notifications, app title / windows, `platform/dateFormat`).
*/
@@ -26,7 +26,6 @@ import {
} from "../model/behaviorSchema";
import { ACCENT_PRESETS, LIMITS, type ThemeId } from "../model/schema";
import type { PageSpec } from "./spec";
import { HTTP_PROXY_PAGE } from "./httpProxy";
import styles from "./Behavior.module.css";
import { tx, useT } from "@/platform/i18n";
@@ -674,7 +673,6 @@ export const BEHAVIOR_PAGES: PageSpec[] = [
},
],
},
HTTP_PROXY_PAGE,
{
id: "notifications",
title: "Notifications",
-1
Переглянути файл
@@ -180,7 +180,6 @@ export const EXECUTION_PAGES: PageSpec[] = [
label: "Show value tooltip on mouse hover",
hint: "Hovering a variable while suspended evaluates it in the selected frame.",
},
{ kind: "toggle", key: "debugger.valueTooltipOnSelection", label: "Show value tooltip on code selection" },
{ kind: "custom", label: "Value tooltip delay (ms)", component: TooltipDelayRow },
],
},
-297
Переглянути файл
@@ -1,297 +0,0 @@
/**
* Appearance & Behavior › System Settings › HTTP Proxy: how the IDE's own
* connections (HTTP Client, tool / JDK / agent downloads, update checks) reach
* the network. A manual proxy also reaches child processes as `HTTP_PROXY`.
*/
import { useId, useRef, useState } from "react";
import clsx from "clsx";
import { call, commands, isTauri } from "@/platform/ipc";
import { tx, useTx } from "@/platform/i18n";
import {
PROXY_PORT_LIMITS,
proxyProblem,
withProxyKind,
type ProxyKindValid,
type ProxyModeValid,
type ProxySettingsValid,
} from "@/platform/proxySettings";
import { Button, Checkbox, Input, Popup, T } from "@/ui";
import { NumberInput, Row, SearchLabel } from "../components/Form";
import { usePageContext, useSetting } from "../components/context";
import { stage } from "../model/staging";
import type { PageSpec } from "./spec";
import styles from "./HttpProxy.module.css";
const MODES: Array<{ value: ProxyModeValid; label: string; hint?: string }> = [
{ value: "none", label: "No proxy" },
{
value: "auto",
label: "Auto-detect proxy settings",
hint: "Uses the system proxy: the HTTP_PROXY, HTTPS_PROXY and NO_PROXY environment variables.",
},
{ value: "manual", label: "Manual proxy configuration" },
];
const KINDS: Array<{ value: ProxyKindValid; label: string }> = [
{ value: "http", label: "HTTP" },
{ value: "socks", label: "SOCKS" },
];
/** The staged proxy settings and a setter per field (each written as its own key). */
function useProxy(): [ProxySettingsValid, (patch: Partial<ProxySettingsValid>) => void] {
const [proxy] = useSetting<ProxySettingsValid>("proxy", "global");
const { pageId } = usePageContext();
const update = (patch: Partial<ProxySettingsValid>) => {
for (const [field, value] of Object.entries(patch)) stage(pageId, "global", `proxy.${field}`, value);
};
return [proxy, update];
}
function Radio({
name,
checked,
onSelect,
label,
disabled,
}: {
name: string;
checked: boolean;
onSelect: () => void;
label: string;
disabled?: boolean;
}) {
return (
<label className={clsx(styles.radio, disabled && styles.disabled)}>
<input type="radio" name={name} checked={checked} disabled={disabled} onChange={onSelect} />
<SearchLabel text={label} />
</label>
);
}
function ProxyOptions() {
const [proxy, update] = useProxy();
const name = useId();
const kindName = useId();
const ids = {
host: useId(),
port: useId(),
noProxy: useId(),
login: useId(),
password: useId(),
};
const manual = proxy.mode === "manual";
const auth = manual && proxy.authenticate;
const problem = proxyProblem(proxy);
return (
<div className={styles.page}>
<div className={styles.modes} role="radiogroup" aria-label={tx("Proxy")}>
{MODES.map((m) => (
<div key={m.value}>
<Radio
name={name}
checked={proxy.mode === m.value}
onSelect={() => update({ mode: m.value })}
label={m.label}
/>
{m.hint && (
<div className={styles.hint}>
<T>{m.hint}</T>
</div>
)}
</div>
))}
</div>
<div className={styles.manual}>
<div className={styles.kinds} role="radiogroup" aria-label={tx("Proxy type")}>
{KINDS.map((k) => (
<Radio
key={k.value}
name={kindName}
checked={proxy.kind === k.value}
disabled={!manual}
onSelect={() => update(withProxyKind(proxy, k.value))}
label={k.label}
/>
))}
</div>
<div className={styles.hostRow}>
<Row label="Host name" htmlFor={ids.host}>
<Input
id={ids.host}
className={styles.host}
disabled={!manual}
value={proxy.host}
onChange={(e) => update({ host: e.target.value })}
/>
</Row>
<Row label="Port number" htmlFor={ids.port}>
{manual ? (
<NumberInput
id={ids.port}
value={proxy.port}
onChange={(port) => update({ port })}
{...PROXY_PORT_LIMITS}
integer
aria-label="Port number"
/>
) : (
<Input id={ids.port} className={styles.port} value={String(proxy.port)} disabled readOnly />
)}
</Row>
</div>
<Row
label="No proxy for"
htmlFor={ids.noProxy}
hint="Comma-separated host names; * matches any characters, e.g. *.example.com, 192.168.*"
>
<Input
id={ids.noProxy}
className={styles.wide}
disabled={!manual}
value={proxy.noProxy}
onChange={(e) => update({ noProxy: e.target.value })}
/>
</Row>
<div className={styles.toggle}>
<Checkbox
checked={proxy.authenticate}
disabled={!manual}
onChange={(authenticate) => update({ authenticate })}
label={<SearchLabel text="Proxy authentication" />}
/>
</div>
<div className={styles.auth}>
<Row label="Login" htmlFor={ids.login}>
<Input
id={ids.login}
className={styles.host}
disabled={!auth}
value={proxy.login}
onChange={(e) => update({ login: e.target.value })}
/>
</Row>
<Row label="Password" htmlFor={ids.password}>
<Input
id={ids.password}
type="password"
className={styles.host}
disabled={!auth}
value={proxy.password}
onChange={(e) => update({ password: e.target.value })}
/>
</Row>
</div>
{problem && (
<div className={styles.error} role="alert">
<T>{problem}</T>
</div>
)}
</div>
<CheckConnection proxy={proxy} />
</div>
);
}
type CheckState = { status: "idle" | "running" } | { status: "ok" | "failed"; text: string };
/** Check connection…: asks for a URL and GETs it with the settings as edited. */
function CheckConnection({ proxy }: { proxy: ProxySettingsValid }) {
const t = useTx();
const anchor = useRef<HTMLButtonElement>(null);
const urlId = useId();
const [open, setOpen] = useState(false);
const [url, setUrl] = useState("http://");
const [state, setState] = useState<CheckState>({ status: "idle" });
const check = async () => {
setState({ status: "running" });
try {
const status = await call(commands.proxyCheckConnection(proxy, url));
setState({ status: "ok", text: t`Connection successful: ${status}` });
} catch (e) {
const message = e instanceof Error ? e.message : String(e);
setState({
status: "failed",
text: t`Problem with connection: ${message}`,
});
}
};
const running = state.status === "running";
return (
<div className={styles.check}>
<Button
ref={anchor}
size="small"
disabled={!isTauri() || !!proxyProblem(proxy)}
aria-expanded={open}
onClick={() => setOpen((v) => !v)}
>
<T>Check connection…</T>
</Button>
<Popup
open={open}
onClose={() => setOpen(false)}
anchor={anchor}
placement="bottom-start"
offset={4}
aria-label="Check connection"
>
<form
className={styles.popup}
onSubmit={(e) => {
e.preventDefault();
if (!running && url.trim()) void check();
}}
>
<label htmlFor={urlId}>
<T>Enter any URL to check connection to:</T>
</label>
<span className={styles.urlRow}>
<Input id={urlId} autoFocus className={styles.wide} value={url} onChange={(e) => setUrl(e.target.value)} />
<Button size="small" type="submit" disabled={running || !url.trim()}>
<T>Check</T>
</Button>
</span>
<span
role="status"
className={clsx(
styles.result,
state.status === "ok" && styles.ok,
state.status === "failed" && styles.error,
)}
>
{state.status === "ok" || state.status === "failed" ? state.text : running ? t("Connecting…") : ""}
</span>
</form>
</Popup>
</div>
);
}
export const HTTP_PROXY_PAGE: PageSpec = {
id: "general.httpProxy",
title: "HTTP Proxy",
order: 2,
keywords: ["proxy", "network", "socks", "http_proxy", "no_proxy", "connection"],
sections: [
{
options: [
{
kind: "custom",
label: "Manual proxy configuration",
keywords: [
"No proxy",
"Auto-detect proxy settings",
"Host name",
"Port number",
"No proxy for",
"Proxy authentication",
"Login",
"Password",
"Check connection…",
],
component: ProxyOptions,
},
],
},
],
};
-16
Переглянути файл
@@ -70,22 +70,6 @@ describe("tools store", () => {
expect(useTools.getState().tools.find((t) => t.name === "gopls")?.status).toBe("missing");
});
it("installs one at a time; one cancelled while it waits never starts", async () => {
backend.stepMs = 10;
await refreshTools();
const install = vi.spyOn(backend, "install");
const first = installTool("gopls");
const queued = installTool("vtsls");
expect(useTasks.getState().tasks.find((t) => t.id === "tools:vtsls")).toMatchObject({ queued: true });
cancelInstall("vtsls");
expect(useTasks.getState().tasks.find((t) => t.id === "tools:vtsls")).toBeUndefined();
expect(await queued).toBeNull();
expect(useTools.getState().logs["vtsls"]?.error).toBe("Cancelled");
expect((await first)?.status).toBe("installed");
expect(install.mock.calls.map((c) => c[0])).toEqual(["gopls"]);
expect(notes.filter((n) => n.level === "error")).toHaveLength(0);
});
it("uninstalls", async () => {
await refreshTools();
expect(await uninstallTool("rust-analyzer")).toBe(true);
+9 -14
Переглянути файл
@@ -17,12 +17,10 @@ import {
requiredJdk,
TEMURIN,
type DownloadJdkArgs,
type JdkDownload,
} from "@/platform/jdk";
import { useProject } from "@/platform/project";
import { notifications } from "@/workbench/contributions";
import { queueTask, upsertTask } from "@/workbench/tasks";
import { DOWNLOAD_QUEUE } from "./store";
import { upsertTask } from "@/workbench/tasks";
import { tx } from "@/platform/i18n";
const JAVA_SETTINGS = "languages.java";
@@ -44,19 +42,16 @@ export function downloadJdkFor(args: DownloadJdkArgs): Promise<Sdk | null> {
const title = `Downloading JDK ${args.version}`;
const taskId = `jdk-download:${args.version}`;
const key = `jdk-download-${args.version}`;
const cancel = () => job.cancel();
const job = downloadJdk(TEMURIN, args.version, null, (e) => {
const message = e.type === "line" ? e.text : e.message;
const fraction = e.type === "progress" ? e.fraction : null;
upsertTask({ id: taskId, title, message, fraction, done: false, cancel });
});
upsertTask({ id: taskId, title, message: "Eclipse Temurin", fraction: null, done: false, cancel });
const p = (async () => {
try {
// Waits for the downloads ahead of it; cancelling it there means it never starts.
const sdk = await queueTask(DOWNLOAD_QUEUE, { id: taskId, title }, () => {
const cancel = () => job.cancel();
upsertTask({ id: taskId, title, message: "Eclipse Temurin", fraction: null, done: false, cancel });
const job: JdkDownload = downloadJdk(TEMURIN, args.version, null, (e) => {
const message = e.type === "line" ? e.text : e.message;
const fraction = e.type === "progress" ? e.fraction : null;
upsertTask({ id: taskId, title, message, fraction, done: false, cancel });
});
return job.promise;
});
const sdk = await job.promise;
if (args.languageServer) await chooseForLanguageServer(sdk.path);
notifications().notify({
group: "tools",
+17 -23
Переглянути файл
@@ -4,13 +4,11 @@ import type { RequestId, ToolInfo } from "@/bindings";
import { executeAction } from "@/platform/actions";
import { isCancelled, nextRequestId } from "@/platform/ipc";
import { notifications } from "@/workbench/contributions";
import { cancelTask, queueTask, upsertTask, useTasks } from "@/workbench/tasks";
import { upsertTask } from "@/workbench/tasks";
import { toolsBackend } from "./backend";
import { tx } from "@/platform/i18n";
export const SETTINGS_PAGE_ID = "languages.servers";
/** Tool installs and JDK downloads take turns (one network download / package manager at a time). */
export const DOWNLOAD_QUEUE = "downloads";
const MAX_LOG_LINES = 400;
export interface InstallJob {
@@ -102,25 +100,24 @@ export function installTool(name: string, opts: { notificationKey?: string } = {
const taskId = `tools:${name}`;
const key = opts.notificationKey ?? `tools-install-${name}`;
useTools.setState((s) => ({ jobs: { ...s.jobs, [name]: { request, lines: [], fraction: null, message: null } } }));
const title = tx`Installing ${display}`;
const cancel = () => toolsBackend().cancel(request);
const task = (message: string | null, fraction: number | null) =>
upsertTask({ id: taskId, title, message, fraction, done: false, cancel });
upsertTask({ id: taskId, title: tx`Installing ${display}`, message: null, fraction: null, done: false });
const p = (async () => {
try {
// Downloads and package managers run one at a time; the rest wait, cancellable.
const info = await queueTask(DOWNLOAD_QUEUE, { id: taskId, title }, () => {
task(null, null);
return toolsBackend().install(name, request, (e) => {
if (e.type === "line") {
patchJob(name, (j) => ({ ...j, lines: [...j.lines, e.text].slice(-MAX_LOG_LINES), message: e.text }));
task(e.text, null);
} else {
patchJob(name, (j) => ({ ...j, fraction: e.fraction, message: e.message }));
task(e.message, e.fraction);
}
});
const info = await toolsBackend().install(name, request, (e) => {
if (e.type === "line") {
patchJob(name, (j) => ({ ...j, lines: [...j.lines, e.text].slice(-MAX_LOG_LINES), message: e.text }));
upsertTask({ id: taskId, title: tx`Installing ${display}`, message: e.text, fraction: null, done: false });
} else {
patchJob(name, (j) => ({ ...j, fraction: e.fraction, message: e.message }));
upsertTask({
id: taskId,
title: tx`Installing ${display}`,
message: e.message,
fraction: e.fraction,
done: false,
});
}
});
upsertTool(info);
endJob(name, null);
@@ -154,7 +151,7 @@ export function installTool(name: string, opts: { notificationKey?: string } = {
});
return null;
} finally {
upsertTask({ id: taskId, title, message: null, fraction: 1, done: true });
upsertTask({ id: taskId, title: tx`Installing ${display}`, message: null, fraction: 1, done: true });
running.delete(name);
}
})();
@@ -162,10 +159,7 @@ export function installTool(name: string, opts: { notificationKey?: string } = {
return p;
}
/** Cancels the install of `name`, queued or running (as the task's Cancel does). */
export function cancelInstall(name: string) {
const taskId = `tools:${name}`;
if (useTasks.getState().tasks.some((t) => t.id === taskId)) return cancelTask(taskId);
const job = useTools.getState().jobs[name];
if (job) toolsBackend().cancel(job.request);
}
+5 -86
Переглянути файл
@@ -182,100 +182,19 @@
.noHighlight :global(.cm-changedText) {
background: none !important;
}
/* Side-by-side without alignment (IDEA's default): each pane scrolls itself. */
.unaligned :global(.cm-mergeView) {
.unsynced :global(.cm-mergeView) {
overflow: hidden;
}
.unaligned :global(.cm-mergeViewEditors) {
.unsynced :global(.cm-mergeViewEditors) {
height: 100%;
min-height: 0;
}
.unaligned :global(.cm-mergeViewEditor) {
.unsynced :global(.cm-mergeViewEditor) {
height: 100%;
min-height: 0;
overflow: hidden;
}
/* Overrides MergeView's base theme, which leaves scrolling to the outer view. */
.unaligned :global(.cm-mergeViewEditor > .cm-editor),
.unaligned :global(.cm-mergeViewEditor > .cm-editor > .cm-scroller) {
height: 100% !important;
}
.unaligned :global(.cm-mergeViewEditor > .cm-editor > .cm-scroller) {
overflow: auto !important;
}
.host :global(.cm-diffDivider) {
position: relative;
flex: none;
width: 30px;
overflow: hidden;
background: var(--bg-app);
border-left: 1px solid var(--border);
border-right: 1px solid var(--border);
}
.host :global(.cm-diffDivider svg) {
position: absolute;
inset: 0;
}
/* Opaque mixes of the line backgrounds (cm.ts), so bands and their midlines read as one shape. */
.host :global(.cm-diffBand-inserted) {
--band: color-mix(in srgb, var(--success) 26%, var(--bg-app));
}
.host :global(.cm-diffBand-deleted) {
--band: color-mix(in srgb, var(--danger) 26%, var(--bg-app));
}
.host :global(.cm-diffBand-modified) {
--band: color-mix(in srgb, var(--gutter-added) 20%, var(--bg-app));
}
.host :global(.cm-diffBand:not(.cm-diffBand-modified)) {
fill: var(--band);
}
.host :global(.cm-diffBandLine) {
fill: none;
stroke: var(--band);
stroke-width: 1px;
}
.host :global(.cm-diffBandStopA) {
stop-color: color-mix(in srgb, var(--gutter-deleted) 20%, var(--bg-app));
}
.host :global(.cm-diffBandStopB) {
stop-color: color-mix(in srgb, var(--gutter-added) 20%, var(--bg-app));
}
.host :global(.cm-diffDivider button.cm-diffArrow) {
position: absolute;
display: flex;
align-items: center;
justify-content: center;
width: 14px;
height: 16px;
padding: 0;
border: 0;
border-radius: var(--radius-small);
background: none;
color: var(--fg-subtle);
cursor: pointer;
}
.host :global(.cm-diffDivider button.cm-diffArrow-a-to-b) {
left: 1px;
}
.host :global(.cm-diffDivider button.cm-diffArrow-b-to-a) {
right: 1px;
}
.host :global(.cm-diffDivider button.cm-diffArrow:hover) {
color: var(--fg-strong);
background: var(--bg-hover);
}
/* Where the other pane has lines this one lacks. */
.host :global(.cm-diffGap-inserted) {
box-shadow: inset 0 1px 0 var(--success);
}
.host :global(.cm-diffGap-deleted) {
box-shadow: inset 0 1px 0 var(--danger);
}
.host :global(.cm-diffGap-inserted.cm-diffGapEnd) {
box-shadow: inset 0 -1px 0 var(--success);
}
.host :global(.cm-diffGap-deleted.cm-diffGapEnd) {
box-shadow: inset 0 -1px 0 var(--danger);
.unsynced :global(.cm-mergeViewEditor > .cm-editor) {
height: 100%;
}
/* Review comments under diff lines (pull requests). */
+15 -72
Переглянути файл
@@ -49,7 +49,6 @@ import {
type DiffSide,
} from "./diffInput";
import { diffAnnotations } from "./diffAnnotations";
import { UnalignedPanes } from "./diffScroll";
import { groupOf } from "./changes";
import { inclusionGutter } from "./hunkInclusion";
import { hunksOverlapping } from "./hunks";
@@ -66,8 +65,6 @@ interface Views {
b: EditorView;
a: EditorView | null;
merge: MergeView | null;
/** Unpadded side-by-side panes with synchronized scrolling (IDEA). */
panes: UnalignedPanes | null;
destroy(): void;
}
@@ -230,23 +227,18 @@ export function DiffEditor({ input }: { input: EditorInput }) {
const editableB = !!attached?.b && !attached.b.readOnly;
const ready = !!attached && !!statics && lang !== null;
// Read when the views are built; toggling it later goes through `setSync`.
const syncScroll = useRef(opts.syncScroll);
syncScroll.current = opts.syncScroll;
// (Re)build the CodeMirror views.
useEffect(() => {
const host = hostRef.current;
if (!host || !attached || !statics || lang === null) return;
const textA = attached.a?.text() ?? statics.a ?? "";
const textB = attached.b?.text() ?? statics.b ?? "";
const prev = viewsRef.current;
const scrollTop = prev
? prev.merge && !prev.panes
? (prev.merge.dom as HTMLElement).scrollTop
: prev.b.scrollDOM.scrollTop
const scrollTop = viewsRef.current
? viewsRef.current.merge
? (viewsRef.current.merge.dom as HTMLElement).scrollTop
: viewsRef.current.b.scrollDOM.scrollTop
: null;
prev?.destroy();
viewsRef.current?.destroy();
host.textContent = "";
const listener = EditorView.updateListener.of((u) => {
if (u.selectionSet || u.docChanged) updateChunkInfo();
@@ -280,21 +272,11 @@ export function DiffEditor({ input }: { input: EditorInput }) {
let views: Views;
if (opts.mode === "split") {
let merge: MergeView | null = null;
const panes = opts.alignChanges
? null
: new UnalignedPanes({
sync: syncScroll.current,
arrows:
editableA || editableB
? { toA: editableA, toB: editableB, apply: (i, source) => merge && applyChunk(merge, i, source) }
: undefined,
});
const mv = new MergeView({
a: {
doc: textA,
extensions: [
side(attached.a, editableA, "left"),
panes?.extension ?? [],
focusTracker("a"),
findWatch("a"),
editableA ? hoverRevert((_v, i) => merge && applyChunk(merge, i, "b")) : [],
@@ -304,7 +286,6 @@ export function DiffEditor({ input }: { input: EditorInput }) {
doc: textB,
extensions: [
side(attached.b, editableB, "right"),
panes?.extension ?? [],
listener,
focusTracker("b"),
findWatch("b"),
@@ -313,36 +294,17 @@ export function DiffEditor({ input }: { input: EditorInput }) {
],
},
parent: host,
// Unaligned panes draw their arrows on their own divider.
revertControls: panes ? undefined : editableB ? "a-to-b" : editableA ? "b-to-a" : undefined,
revertControls: editableB ? "a-to-b" : editableA ? "b-to-a" : undefined,
renderRevertControl:
!panes && (editableA || editableB)
? arrowControls(() => merge, { toA: editableA, toB: editableB })
: undefined,
editableA || editableB ? arrowControls(() => merge, { toA: editableA, toB: editableB }) : undefined,
highlightChanges,
// Unpadded panes tint the gutters of changed lines instead of a change bar.
gutter: !panes,
gutter: true,
collapseUnchanged,
diffConfig,
});
merge = mv;
panes?.attach(mv);
views = {
a: mv.a,
b: mv.b,
merge: mv,
panes,
destroy: () => {
panes?.destroy();
mv.destroy();
},
};
if (scrollTop != null)
requestAnimationFrame(() => {
// The left pane of unpadded panes follows by itself.
if (!panes) (mv.dom as HTMLElement).scrollTop = scrollTop;
else mv.b.scrollDOM.scrollTop = scrollTop;
});
views = { a: mv.a, b: mv.b, merge: mv, destroy: () => mv.destroy() };
if (scrollTop != null) requestAnimationFrame(() => ((mv.dom as HTMLElement).scrollTop = scrollTop));
} else {
const view = new EditorView({
doc: textB,
@@ -376,7 +338,7 @@ export function DiffEditor({ input }: { input: EditorInput }) {
}),
],
});
views = { a: null, b: view, merge: null, panes: null, destroy: () => view.destroy() };
views = { a: null, b: view, merge: null, destroy: () => view.destroy() };
if (scrollTop != null) requestAnimationFrame(() => (view.scrollDOM.scrollTop = scrollTop));
}
viewsRef.current = views;
@@ -387,7 +349,6 @@ export function DiffEditor({ input }: { input: EditorInput }) {
statics,
lang,
opts.mode,
opts.alignChanges,
opts.collapse,
opts.ignore,
opts.highlight,
@@ -399,8 +360,6 @@ export function DiffEditor({ input }: { input: EditorInput }) {
path,
]);
useEffect(() => viewsRef.current?.panes?.setSync(opts.syncScroll), [opts.syncScroll]);
useEffect(
() => () => {
viewsRef.current?.destroy();
@@ -644,10 +603,9 @@ export function DiffEditor({ input }: { input: EditorInput }) {
if (neighbour) void openDiff(neighbour, { preview: true });
};
const toolbarRef = useRef<HTMLDivElement | null>(null);
/** The viewer settings menu, under the toolbar's gear (`from`) or its start. */
const showSettings = (from?: HTMLElement) => {
const r = (from ?? toolbarRef.current)?.getBoundingClientRect();
showContextMenu({ x: r ? r.left + (from ? 0 : 8) : 120, y: r ? r.bottom : 120 }, [
const showSettings = () => {
const r = toolbarRef.current?.getBoundingClientRect();
showContextMenu({ x: r ? r.left + 8 : 120, y: r ? r.bottom : 120 }, [
{ kind: "header", label: "Viewer" },
{
id: "split",
@@ -696,13 +654,6 @@ export function DiffEditor({ input }: { input: EditorInput }) {
disabled: opts.mode !== "split",
run: () => setOpts({ syncScroll: !opts.syncScroll }),
},
{
id: "align",
label: "Align Changes",
checked: opts.alignChanges,
disabled: opts.mode !== "split",
run: () => setOpts({ alignChanges: !opts.alignChanges }),
},
]);
};
const nav = useRef<DiffNavigator>({
@@ -854,14 +805,6 @@ export function DiffEditor({ input }: { input: EditorInput }) {
? tx`${chunkInfo.count} difference`
: tx`${chunkInfo.count} differences`}
</span>
<IconButton
icon="settings"
title="Settings"
shortcut={shortcutLabel("diff.showSettings")}
size="small"
aria-haspopup="menu"
onClick={(e) => showSettings(e.currentTarget)}
/>
</div>
{opts.mode === "split" ? (
<div className={styles.labels}>
@@ -917,7 +860,7 @@ export function DiffEditor({ input }: { input: EditorInput }) {
className={clsx(
styles.host,
opts.highlight === "none" && styles.noHighlight,
opts.mode === "split" && (opts.alignChanges ? !opts.syncScroll && styles.unsynced : styles.unaligned),
opts.mode === "split" && !opts.syncScroll && styles.unsynced,
)}
hidden={!!error || !ready}
aria-label={diffTitle(data)}
+3 -37
Переглянути файл
@@ -11,7 +11,7 @@ import {
} from "../diffOptions";
import { clipboardDiffData, compareFilesData, parseTextsArg } from "../compare";
import { diffInput, diffTitle, sideFile, sideKey } from "../diffInput";
import { changedLineGutters, viewerBase } from "../cm";
import { viewerBase } from "../cm";
const doc = (s: string) => Text.of(s.split("\n"));
@@ -24,22 +24,8 @@ describe("diff options", () => {
it("parses stored options with per-field defaults", () => {
expect(parseDiffOptions(null)).toEqual(DEFAULT_DIFF_OPTIONS);
expect(
parseDiffOptions({
mode: "split",
ignore: "trim",
highlight: "lines",
collapse: false,
syncScroll: false,
alignChanges: false,
}),
).toEqual({
mode: "split",
ignore: "trim",
highlight: "lines",
collapse: false,
syncScroll: false,
alignChanges: false,
});
parseDiffOptions({ mode: "split", ignore: "trim", highlight: "lines", collapse: false, syncScroll: false }),
).toEqual({ mode: "split", ignore: "trim", highlight: "lines", collapse: false, syncScroll: false });
expect(parseDiffOptions({ ignore: "bogus", highlight: 3, collapse: "x" })).toEqual(DEFAULT_DIFF_OPTIONS);
});
@@ -169,26 +155,6 @@ describe("diff options", () => {
parent.remove();
});
it("carries the change background into the line number gutter", () => {
const parent = document.createElement("div");
document.body.appendChild(parent);
const extensions = [viewerBase({ readOnly: true }), changedLineGutters];
const mv = new MergeView({
a: { doc: "keep\nlet x = 1;\nend\n", extensions },
b: { doc: "keep\nlet x = 2;\nadded\nend\n", extensions },
parent,
gutter: false,
diffConfig: { override: whitespaceDiff("none") },
});
const numbers = (v: typeof mv.a, cls: string) =>
[...v.dom.querySelectorAll(`.cm-lineNumbers .${cls}`)].map((e) => e.textContent);
expect(numbers(mv.a, "cm-diffChangedGutter")).toEqual(["2"]);
expect(numbers(mv.b, "cm-diffChangedGutter")).toEqual(["2", "3"]);
expect(numbers(mv.b, "cm-diffWholeGutter")).toEqual(["3"]);
mv.destroy();
parent.remove();
});
it("marks a deleted last line as a whole line", () => {
const parent = document.createElement("div");
document.body.appendChild(parent);
-97
Переглянути файл
@@ -1,97 +0,0 @@
import { describe, expect, it } from "vitest";
import { Chunk, MergeView } from "@codemirror/merge";
import { Text } from "@codemirror/state";
import { bandAt, bandPath, transferY, type Band } from "../diffScroll";
const doc = (s: string) => Text.of(s.split("\n"));
const LINE = 20;
/** The band at `y` of side `from` in two texts with every line LINE px tall. */
function bands(a: string, b: string) {
const da = doc(a);
const db = doc(b);
const ext = (d: Text, from: number, to: number): [number, number] => {
if (from > d.length) return [d.lines * LINE, d.lines * LINE];
const top = (d.lineAt(from).number - 1) * LINE;
return from >= to ? [top, top] : [top, d.lineAt(Math.min(to - 1, d.length)).number * LINE];
};
const chunks = Chunk.build(da, db);
return (y: number, from: "a" | "b"): Band =>
bandAt(
chunks,
(c) => ext(da, c.fromA, c.toA),
(c) => ext(db, c.fromB, c.toB),
da.lines * LINE,
db.lines * LINE,
y,
from,
);
}
describe("unaligned side-by-side scrolling", () => {
// Right side inserts three lines after line 2 and changes line 5 into two lines.
const a = "1\n2\n3\n4\n5\n6\n7";
const b = "1\n2\nx\ny\nz\n3\n4\nfive\nfive'\n6\n7";
const bandOf = bands(a, b);
const at = (y: number, from: "a" | "b") => transferY([bandOf(y, from)], y, from);
it("splits both documents into unchanged and changed bands", () => {
const row = (x: Band) => [x.a0, x.a1, x.b0, x.b1, x.changed];
expect([0, 39, 40, 79, 80, 99, 100, 139].map((y) => row(bandOf(y, "a")))).toEqual([
[0, 40, 0, 40, false],
[0, 40, 0, 40, false],
[40, 80, 100, 140, false],
[40, 80, 100, 140, false],
[80, 100, 140, 180, true],
[80, 100, 140, 180, true],
[100, 140, 180, 220, false],
[100, 140, 180, 220, false],
]);
expect([0, 40, 99, 100, 140, 179, 180].map((y) => row(bandOf(y, "b")))).toEqual([
[0, 40, 0, 40, false],
[40, 40, 40, 100, true],
[40, 40, 40, 100, true],
[40, 80, 100, 140, false],
[80, 100, 140, 180, true],
[80, 100, 140, 180, true],
[100, 140, 180, 220, false],
]);
});
it("maps unchanged text straight through", () => {
expect(at(10, "a")).toBe(10);
expect(at(50, "a")).toBe(110);
expect(at(130, "a")).toBe(210);
expect(at(210, "b")).toBe(130);
});
it("jumps over an insertion when scrolling the side without it", () => {
expect(at(39, "a")).toBe(39);
expect(at(40, "a")).toBe(100);
});
it("waits at the boundary while the inserted lines scroll by", () => {
for (const y of [40, 60, 99]) expect(at(y, "b")).toBe(40);
});
it("follows line by line inside a change, then waits at the shorter end", () => {
expect(at(150, "b")).toBe(90);
expect(at(170, "b")).toBe(100);
expect(at(90, "a")).toBe(150);
});
it("scales unchanged text of different heights (wrapped lines)", () => {
const stretched = [{ a0: 0, a1: 100, b0: 0, b1: 200, changed: false }];
expect(transferY(stretched, 50, "a")).toBe(100);
expect(transferY(stretched, 50, "b")).toBe(25);
});
it("draws an empty side as a sliver on its boundary", () => {
expect(bandPath(30, 40, 40, 40, 100)).toBe("M0 39C9 39 21 40 30 40L30 100C21 100 9 41 0 41Z");
});
it("can keep MergeView from padding the panes", () => {
// UnalignedPanes replaces this (private) method; a rename upstream would bring the padding back.
expect(typeof (MergeView.prototype as unknown as { measure: unknown }).measure).toBe("function");
});
});
+1 -35
Переглянути файл
@@ -4,7 +4,7 @@ import type { EditorInput } from "@/workbench/contributions";
import { Chunk } from "@codemirror/merge";
import { Text } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { ContextMenuHost, iconMarkup } from "@/ui";
import { iconMarkup } from "@/ui";
const probe = vi.fn();
const openFile = vi.fn();
@@ -80,40 +80,6 @@ describe("Diff toolbar", () => {
expect(probe).toHaveBeenCalledWith("/p/a.ts");
});
it("turns on aligned changes from the settings menu (off by default)", async () => {
localStorage.clear();
texts.HEAD = "a\nb\n";
texts.abc123 = "a\nnew\nb\n";
render(
<>
<DiffEditor input={input} />
<ContextMenuHost />
</>,
);
await waitFor(() => expect(document.querySelectorAll(".cm-mergeViewEditor .cm-editor")).toHaveLength(2));
// Unpadded panes joined by the divider.
await waitFor(() => expect(document.querySelector(".cm-diffDivider")).not.toBeNull());
expect(document.querySelector(".cm-changeGutter")).toBeNull();
expect(document.querySelector(".cm-merge-b .cm-lineNumbers .cm-diffWholeGutter")?.textContent).toBe("2");
// The lock turns scrolling together off without rebuilding the panes.
const divider = document.querySelector(".cm-diffDivider");
(await screen.findByRole("button", { name: "Synchronize Scrolling" })).click();
await waitFor(() => expect(JSON.parse(localStorage.getItem("openidea.vcs.diffOptions")!).syncScroll).toBe(false));
expect(document.querySelector(".cm-diffDivider")).toBe(divider);
(await screen.findByRole("button", { name: "Settings" })).click();
const item = await screen.findByRole("menuitemcheckbox", { name: "Align Changes" });
expect(item.getAttribute("aria-checked")).toBe("false");
item.click();
// Padded panes with a change bar.
await waitFor(() => expect(document.querySelector(".cm-diffDivider")).toBeNull());
expect(document.querySelector(".cm-changeGutter")).not.toBeNull();
expect(JSON.parse(localStorage.getItem("openidea.vcs.diffOptions")!)).toMatchObject({
alignChanges: true,
syncScroll: false,
});
localStorage.clear();
});
it("has no Jump to Source when the file is gone from the working tree", async () => {
probe.mockRejectedValue(new Error("no such file"));
render(<DiffEditor input={input} />);
+11 -68
Переглянути файл
@@ -3,21 +3,11 @@
* based theme + syntax colours and lazy language loading by file name.
*/
import { HighlightStyle, LanguageDescription, syntaxHighlighting, type LanguageSupport } from "@codemirror/language";
import {
Compartment,
EditorState,
RangeSet,
RangeSetBuilder,
StateField,
type Extension,
type Line,
} from "@codemirror/state";
import { Compartment, EditorState, RangeSetBuilder, type Extension, type Line } from "@codemirror/state";
import {
Decoration,
EditorView,
GutterMarker,
ViewPlugin,
gutterLineClass,
highlightActiveLine,
keymap,
lineNumbers,
@@ -37,16 +27,17 @@ import { useProject } from "@/platform/project";
const wholeLine = Decoration.line({ class: "cm-diffWholeLine" });
/**
* Calls `f` for the changed lines of a side-by-side pane between `vpFrom` and
* `vpTo`, with whether the line has no counterpart on the other side (inserted
* or deleted as a whole). Lines paired with a line on the other side keep the
* line tint plus word-level highlights.
* Marks the changed lines that have no counterpart on the other side (inserted
* or deleted as a whole) so they get a solid background. Lines paired with a
* line on the other side keep the line tint plus word-level highlights.
*/
function forChangedLines(state: EditorState, vpFrom: number, vpTo: number, f: (line: Line, whole: boolean) => void) {
const info = getChunks(state);
if (!info || !info.side) return;
function wholeLineDeco(view: EditorView): DecorationSet {
const info = getChunks(view.state);
if (!info || !info.side) return Decoration.none;
const isA = info.side === "a";
const { doc } = state;
const { doc } = view.state;
const { from: vpFrom, to: vpTo } = view.viewport;
const builder = new RangeSetBuilder<Decoration>();
for (const chunk of info.chunks) {
const from = isA ? chunk.fromA : chunk.fromB;
const to = isA ? chunk.toA : chunk.toB;
@@ -58,46 +49,11 @@ function forChangedLines(state: EditorState, vpFrom: number, vpTo: number, f: (l
const covered = (line: Line) =>
ranges.some(([f = 0, t = 0]) => (f <= line.from && t > line.to) || (f < line.from && t >= line.to));
for (let line = doc.lineAt(Math.max(from, vpFrom)); line.from < Math.min(to, vpTo);) {
f(line, otherEmpty || covered(line));
if (otherEmpty || covered(line)) builder.add(line.from, line.from, wholeLine);
if (line.number === doc.lines) break;
line = doc.line(line.number + 1);
}
}
}
/** Solid background for the lines changed as a whole. */
function wholeLineDeco(view: EditorView): DecorationSet {
const builder = new RangeSetBuilder<Decoration>();
forChangedLines(view.state, view.viewport.from, view.viewport.to, (line, whole) => {
if (whole) builder.add(line.from, line.from, wholeLine);
});
return builder.finish();
}
class LineClassMarker extends GutterMarker {
constructor(readonly elementClass: string) {
super();
}
}
const changedGutter = new LineClassMarker("cm-diffChangedGutter");
const wholeGutter = new LineClassMarker("cm-diffChangedGutter cm-diffWholeGutter");
/** The line background of changed lines carried into the gutters (line numbers, inclusion boxes), as in IDEA. */
export const changedLineGutters = StateField.define<RangeSet<GutterMarker>>({
create: (state) => changedGutterMarkers(state),
update: (value, tr) =>
tr.docChanged || getChunks(tr.startState)?.chunks !== getChunks(tr.state)?.chunks
? changedGutterMarkers(tr.state)
: value,
provide: (f) => gutterLineClass.from(f),
});
function changedGutterMarkers(state: EditorState): RangeSet<GutterMarker> {
const builder = new RangeSetBuilder<GutterMarker>();
forChangedLines(state, 0, state.doc.length + 1, (line, whole) =>
builder.add(line.from, line.from, whole ? wholeGutter : changedGutter),
);
return builder.finish();
}
@@ -187,19 +143,6 @@ export const viewerTheme = EditorView.theme(
"&.cm-merge-b .cm-changedText, .cm-insertedLine .cm-changedText": {
background: "color-mix(in srgb, var(--success) 26%, transparent)",
},
// Gutters of changed lines take the line background (changedLineGutters).
"&.cm-merge-a .cm-diffChangedGutter": {
backgroundColor: "color-mix(in srgb, var(--gutter-deleted) 12%, transparent)",
},
"&.cm-merge-b .cm-diffChangedGutter": {
backgroundColor: "color-mix(in srgb, var(--gutter-added) 12%, transparent)",
},
"&.cm-merge-a .cm-diffWholeGutter": {
backgroundColor: "color-mix(in srgb, var(--danger) 26%, transparent)",
},
"&.cm-merge-b .cm-diffWholeGutter": {
backgroundColor: "color-mix(in srgb, var(--success) 26%, transparent)",
},
".cm-changeGutter": { width: "3px", paddingLeft: "0" },
"&.cm-merge-a .cm-changedLineGutter, .cm-deletedLineGutter": { background: "var(--gutter-deleted)" },
"&.cm-merge-b .cm-changedLineGutter": { background: "var(--gutter-modified)" },
+1 -2
Переглянути файл
@@ -17,8 +17,7 @@ export function applyChunk(mv: MergeView, index: number, source: "a" | "b") {
dst.dispatch({ changes: transferChunk(chunk, source, src.state.doc, dst.state.doc), userEvent: "revert" });
}
/** A ">>" / "<<" button; the chunk index comes from the nearest `data-chunk` (itself included). */
export function arrowButton(dir: "a-to-b" | "b-to-a", run: (chunkIndex: number) => void): HTMLButtonElement {
function arrowButton(dir: "a-to-b" | "b-to-a", run: (chunkIndex: number) => void): HTMLButtonElement {
const btn = document.createElement("button");
btn.type = "button";
btn.className = `cm-diffArrow cm-diffArrow-${dir}`;
-8
Переглянути файл
@@ -15,13 +15,7 @@ export interface DiffViewOptions {
ignore: IgnorePolicy;
highlight: HighlightPolicy;
collapse: boolean;
/** Side-by-side panes scroll together. */
syncScroll: boolean;
/**
* Side-by-side panes are padded so that unchanged lines line up. Off, each pane
* keeps its own height and a curved divider joins the changes (IDEA's default).
*/
alignChanges: boolean;
}
export const IGNORE_OPTIONS: ReadonlyArray<{ value: IgnorePolicy; label: string }> = [
@@ -43,7 +37,6 @@ export const DEFAULT_DIFF_OPTIONS: DiffViewOptions = {
highlight: "words",
collapse: true,
syncScroll: true,
alignChanges: false,
};
const KEY = "openidea.vcs.diffOptions";
@@ -61,7 +54,6 @@ export function parseDiffOptions(raw: unknown): DiffViewOptions {
highlight: oneOf(o.highlight, HIGHLIGHT_OPTIONS, d.highlight),
collapse: typeof o.collapse === "boolean" ? o.collapse : d.collapse,
syncScroll: typeof o.syncScroll === "boolean" ? o.syncScroll : d.syncScroll,
alignChanges: typeof o.alignChanges === "boolean" ? o.alignChanges : d.alignChanges,
};
}
Loaded 100 of 116 files, more files were not shown because too many files have changed in this diff. Show more