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

...
Автор SHA1 Повідомлення Дата
l0ng-ai e5a51f8c33 test(vim): count Select in Project View as a known action
#7011 mapped IDEA's SelectInProjectView to navigate.selectInProjectView, which has no default shortcut in any preset, so the :action id check failed.
2026-11-30 20:39:44 +08:00
Anka Tamaтаxirf 53a1e9255e fix(vcs): reopen the repository after its volume was remounted (#6949)
The cached gitoxide handle kept pack mappings from the old mount; after a remount with the same device, inodes and mtimes it was reused and reading it raised SIGBUS. The cache now detects the remount and reopens the repository. A volume lost in the middle of a git operation is not covered.

Refs #6948

Co-authored-by: xirf <[email protected]>
2026-11-30 20:27:43 +08:00
audichuang 40ab249cb8 fix(http): route WebSocket tunnels through the macOS PAC in Auto mode (#6939)
In Auto mode the TCP/CONNECT tunnel used for WebSockets resolved the proxy with the system matcher only, so a macOS PAC script was ignored. It now asks the PAC resolver first on a blocking thread and falls back to the matcher when there is no PAC or an env proxy is set.

Co-authored-by: audichuang <[email protected]>
2026-11-30 20:27:28 +08:00
LU XIANGRUIтаwildcatDownstairs 9da3d6d9b5 feat(typescript): Go to Source Definition, Project Configuration, Move to File and TS Server log through vtsls (#6935)
Five vtsls commands, run through workspace/executeCommand on a vtsls server that advertises them (other TypeScript servers report that vtsls is needed). Go to Source Definition opens the JavaScript implementation instead of the .d.ts; Go to Project Configuration opens the file's tsconfig.json or jsconfig.json; Move to File appears in Refactor > Move and the intention menu, offering tsserver's suggested target files and Choose File, and applies the move with its import updates as one workspace edit; Open TS Server Log offers to turn on logging through the new languages.typescript.tsserverLog setting, which restarts vtsls, and then opens the log.

Closes #6922

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 20:24:55 +08:00
l0ng-ai 0df7cb1da2 fix(keymap): list Select Opened File in the VS Code preset (#7038)
project.selectOpenedFile (#7011) was added to the IntelliJ presets only, so the keymap test that the VS Code preset covers every IntelliJ action id failed on main.
2026-11-30 20:23:48 +08:00
LU XIANGRUIтаwildcatDownstairs ee9b50179e feat(welcome): import recent projects and groups from a JetBrains IDE (#6979)
Import Recent Projects from JetBrains IDE (Welcome screen more menu, File > Manage IDE Settings) reads the IDE's options/recentProjects.xml and merges its recent projects and project groups into OpenIDEA's. Entries keep their custom or display name and the later of their open and activation times; hidden (LightEdit) entries are skipped, $USER_HOME$ and $APPLICATION_CONFIG_DIR$ are expanded, and projects whose folder is gone are skipped and counted. Existing entries and groups are kept, a taken group name gets a number, and importing twice adds nothing. Import Settings from JetBrains IDE lists the recent projects as a row of its confirmation and merges them too.

Closes #6970

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 20:15:11 +08:00
Muuтаmuutot baab92c804 feat(vcs): create patches from selected historical files (#6981)
Git Log and File History changed files get Create Patch and Copy as Patch to Clipboard, in the toolbar and the context menu. Only the selected repository-relative paths are exported, as path-filtered revision diffs with Git's empty tree on the missing side of additions and deletions and both names for renames. The existing patch dialog, base directory defaults, reverse option and clipboard flow are reused; empty, malformed, no-op, mixed-repository and external-repository selections are disabled.

Co-authored-by: muutot <[email protected]>
2026-11-30 20:08:11 +08:00
l0ng-ai 2b7a18ffd7 fix(search): start Find in Files from the selection in its preview (#7033)
Find in Files and Search Everywhere took the selection only from the active editor tab, so text selected in the Find in Files preview (or another focused editor, such as a diff pane) was ignored when the action ran again. The focused editor's selection now comes first, then the active editor's.

Fixes #6992
2026-11-30 20:04:14 +08:00
53 змінених файлів з 2243 додано та 69 видалено

No files matched your search

Створено
+1
Переглянути файл
@@ -5116,6 +5116,7 @@ dependencies = [
"ide-text",
"ide-vfs",
"parking_lot 0.12.5",
"quick-xml 0.42.0",
"semver",
"serde",
"serde_json",
+36 -1
Переглянути файл
@@ -1975,6 +1975,10 @@ pub struct TypeScriptSettings {
/// plugin (hybrid mode; a Vue project's program alone needs ~3 GiB, and the
/// vtsls default 3072 dies in a GC death spiral), else unset (vtsls default).
pub tsserver_max_memory: u32,
/// tsserver's log (`typescript.tsserver.log`). TypeScript: Open TS Server Log opens it.
#[serde(deserialize_with = "or_default")]
#[specta(type = TsServerLog)]
pub tsserver_log: TsServerLog,
/// Problems › TypeScript project errors: the project's own `tsc --watch` per root
/// `tsconfig.json` reports the errors of files that are not open.
pub watch_problems: bool,
@@ -1982,10 +1986,27 @@ pub struct TypeScriptSettings {
impl Default for TypeScriptSettings {
fn default() -> Self {
Self { version: "bundled".into(), tsserver_max_memory: 0, watch_problems: false }
Self {
version: "bundled".into(),
tsserver_max_memory: 0,
tsserver_log: TsServerLog::Off,
watch_problems: false,
}
}
}
/// tsserver's log verbosity, as vtsls' `typescript.tsserver.log` spells it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum TsServerLog {
#[default]
Off,
Terse,
Normal,
RequestTime,
Verbose,
}
/// Dependency scope for a module dependency or project library (IDEA's Modules › Dependencies).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
@@ -2168,6 +2189,20 @@ mod tests {
assert_eq!(serde_json::to_value(&on).unwrap()["languages"]["ruff"]["fixOnSave"], true);
}
#[test]
fn tsserver_log_reads_known_levels_and_drops_anything_else() {
let log = |v: &str| {
let s: Settings =
serde_json::from_str(&format!(r#"{{"languages":{{"typescript":{{"tsserverLog":{v}}}}}}}"#)).unwrap();
s.languages.typescript.tsserver_log
};
assert_eq!(log(r#""requestTime""#), TsServerLog::RequestTime);
assert_eq!(log(r#""verbose""#), TsServerLog::Verbose);
assert_eq!(log(r#""--trace""#), TsServerLog::Off);
assert_eq!(log("3"), TsServerLog::Off);
assert_eq!(serde_json::to_value(TsServerLog::RequestTime).unwrap(), "requestTime");
}
#[test]
fn python_interpreter_may_name_a_run_target() {
let python = |interpreter: &str| PythonSettings { interpreter: interpreter.into(), ..Default::default() };
+2
Переглянути файл
@@ -277,6 +277,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
act("file.exportSettings", "Export Settings…"),
act("file.importSettings", "Import Settings…"),
act("file.importJetBrainsSettings", "Import Settings from JetBrains IDE…"),
act("file.importJetBrainsRecentProjects", "Import Recent Projects from JetBrains IDE…"),
act("file.syncSettings", "Sync Settings Now"),
],
),
@@ -484,6 +485,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
act("navigate.declaration", "Declaration or Usages"),
act("navigate.implementation", "Implementation(s)"),
act("navigate.typeDeclaration", "Type Declaration"),
act("navigate.sourceDefinition", "Source Definition"),
act("navigate.superMethod", "Super Method"),
act("navigate.gotoTest", "Test"),
act("navigate.relatedSymbol", "Related Symbol…"),
+50
Переглянути файл
@@ -675,6 +675,53 @@ pub async fn lsp_switch_source_header(
Ok(result?.map(|path| path.to_string_lossy().into_owned()))
}
/// Go to Source Definition (vtsls): the JavaScript implementation of the symbol at `pos`
/// instead of its `.d.ts`. Cancel with `cancel_request(request)`.
#[command(trust = trusted)]
pub async fn lsp_source_definition(
host: &Host,
window: &str,
request: RequestId,
doc: DocId,
pos: Pos,
) -> IdeResult<Vec<Location>> {
let lsp = host.project(window)?.lsp.clone();
let cancel = host.begin_request(request);
let result = tokio::select! {
result = lsp.source_definition(doc, pos, cancel.clone()) => result,
_ = cancel.cancelled() => Err(ide_core::IdeError::cancelled()),
};
host.end_request(request);
result
}
/// Has vtsls open the document's `tsconfig.json` / `jsconfig.json` or the TS Server log.
#[command(trust = trusted)]
pub async fn lsp_open_typescript_file(host: &Host, window: &str, doc: DocId, what: TypeScriptFile) -> IdeResult<()> {
let lsp = host.project(window)?.lsp.clone();
lsp.open_typescript_file(doc, what).await
}
/// The files tsserver suggests for vtsls' Move to File code action `command`. Cancel with
/// `cancel_request(request)`.
#[command(trust = trusted)]
pub async fn lsp_move_to_file_targets(
host: &Host,
window: &str,
request: RequestId,
doc: DocId,
command: Command,
) -> IdeResult<Vec<ide_core::IpcPath>> {
let lsp = host.project(window)?.lsp.clone();
let cancel = host.begin_request(request);
let result = tokio::select! {
result = lsp.move_to_file_targets(doc, command, cancel.clone()) => result,
_ = cancel.cancelled() => Err(ide_core::IdeError::cancelled()),
};
host.end_request(request);
Ok(result?.into_iter().map(ide_core::IpcPath::from).collect())
}
/// Implementations of the symbols at `positions`, one list per position (the
/// editor's "is implemented / overridden" gutter markers). Cancel with
/// `cancel_request(request)`.
@@ -3344,6 +3391,9 @@ ide_command::domain!(
lsp_implementation_locations,
lsp_file_references,
lsp_switch_source_header,
lsp_source_definition,
lsp_open_typescript_file,
lsp_move_to_file_targets,
lsp_implementations,
lsp_inlay_hints,
lsp_inline_completion,
+121 -15
Переглянути файл
@@ -2,6 +2,7 @@
//! speak (a WebSocket): direct, or through an HTTP proxy's `CONNECT` tunnel.
use base64::Engine;
use hyper_util::client::proxy::matcher::Matcher;
use ide_core::proxy_settings::ProxyRoute;
use ide_core::{IdeError, IdeResult};
use std::time::Duration;
@@ -10,30 +11,68 @@ use tokio::net::TcpStream;
const CONNECT_TIMEOUT: Duration = Duration::from_secs(30);
/// The PAC lookup of the system proxy settings; none outside macOS.
#[cfg(target_os = "macos")]
const SYSTEM_PAC: fn(&str) -> Option<ProxyRoute> = crate::system_pac_route;
#[cfg(not(target_os = "macos"))]
const SYSTEM_PAC: fn(&str) -> Option<ProxyRoute> = |_| None;
/// A connection to `url`'s host and port, through the proxy System Settings › HTTP Proxy
/// (or, in Auto mode, the system) routes that host to.
pub async fn connect(url: &reqwest::Url) -> IdeResult<TcpStream> {
let route = ide_core::proxy_settings::proxy().route(url.host_str());
connect_with(url, route, SYSTEM_PAC, Matcher::from_system).await
}
/// The URI the system proxy settings are asked about: the scheme reqwest would use (`ws` → `http`).
fn system_uri(url: &reqwest::Url) -> IdeResult<http::Uri> {
let host = url.host_str().ok_or_else(|| IdeError::invalid("the URL has no host"))?;
let port = url.port_or_known_default().ok_or_else(|| IdeError::invalid("the URL has no port"))?;
let target = if host.contains(':') { format!("[{host}]:{port}") } else { format!("{host}:{port}") };
let proxy = match ide_core::proxy_settings::proxy().route(Some(host)) {
let scheme = if url.scheme() == "wss" || url.scheme() == "https" { "https" } else { "http" };
format!("{scheme}://{target}/").parse().map_err(|_| IdeError::invalid("invalid host"))
}
/// `connect` with the proxy settings' `route`, the PAC lookup and the system matcher injected.
async fn connect_with(
url: &reqwest::Url,
route: ProxyRoute,
pac: impl FnOnce(&str) -> Option<ProxyRoute> + Send + 'static,
matcher: impl FnOnce() -> Matcher,
) -> IdeResult<TcpStream> {
let host = url.host_str().ok_or_else(|| IdeError::invalid("the URL has no host"))?;
let port = url.port_or_known_default().ok_or_else(|| IdeError::invalid("the URL has no port"))?;
let target = if host.contains(':') { format!("[{host}]:{port}") } else { format!("{host}:{port}") };
let proxy = match route {
ProxyRoute::Direct => None,
ProxyRoute::Via(via) => Some(via),
ProxyRoute::System => {
// The system proxy of the scheme reqwest would use (`ws` → `http`).
let scheme = if url.scheme() == "wss" || url.scheme() == "https" { "https" } else { "http" };
let uri: http::Uri =
format!("{scheme}://{target}/").parse().map_err(|_| IdeError::invalid("invalid host"))?;
hyper_util::client::proxy::matcher::Matcher::from_system().intercept(&uri).map(|intercept| {
let auth =
intercept.raw_auth().map(|(user, password)| format!("{user}:{password}@")).unwrap_or_default();
let uri = intercept.uri();
format!(
"{}://{auth}{}",
uri.scheme_str().unwrap_or("http"),
uri.authority().map(|a| a.as_str()).unwrap_or_default()
)
})
let uri = system_uri(url)?;
// On macOS the resolver may run the PAC script (`dnsResolve`), so it stays off the async threads. A
// script still loading answers with the matcher's route.
let probe = uri.to_string();
#[cfg(target_os = "macos")]
let pac = tokio::task::spawn_blocking(move || pac(&probe))
.await
.map_err(|error| IdeError::unavailable(format!("proxy lookup failed: {error}")))?;
// Nothing to evaluate outside macOS: no hop to the blocking pool.
#[cfg(not(target_os = "macos"))]
let pac = pac(&probe);
match pac {
Some(ProxyRoute::Via(via)) if via.starts_with("http://") => Some(via),
Some(ProxyRoute::Direct) => None,
// No PAC applies, or it names a proxy this tunnel cannot speak to (SOCKS): the matcher's route.
_ => matcher().intercept(&uri).map(|intercept| {
let auth =
intercept.raw_auth().map(|(user, password)| format!("{user}:{password}@")).unwrap_or_default();
let uri = intercept.uri();
format!(
"{}://{auth}{}",
uri.scheme_str().unwrap_or("http"),
uri.authority().map(|a| a.as_str()).unwrap_or_default()
)
}),
}
}
};
let connecting = async {
@@ -157,6 +196,73 @@ mod tests {
assert!(error.message.contains("needs a login"), "{}", error.message);
}
use std::sync::{Arc, Mutex};
fn matcher_via(address: &str) -> impl FnOnce() -> Matcher {
let address = address.to_owned();
move || Matcher::builder().all(format!("http://{address}")).build()
}
/// The CONNECT line a proxy was asked for, or `None` when nothing connected within a moment.
async fn asked(task: tokio::task::JoinHandle<String>) -> Option<String> {
tokio::time::timeout(Duration::from_millis(300), task).await.ok().map(|head| head.unwrap())
}
#[tokio::test]
async fn the_pac_route_wins_over_the_matcher_and_ws_is_looked_up_as_http() {
let (pac_proxy, pac_asked) = proxy("HTTP/1.1 200 Connection established\r\n\r\n").await;
let (matcher_proxy, matcher_asked) = proxy("HTTP/1.1 200 Connection established\r\n\r\n").await;
let seen = Arc::new(Mutex::new(String::new()));
let recorded = Arc::clone(&seen);
let pac = move |probe: &str| {
*recorded.lock().unwrap() = probe.to_owned();
Some(ProxyRoute::Via(format!("http://{pac_proxy}")))
};
let url = reqwest::Url::parse("ws://pac-target.invalid:8080/s").unwrap();
connect_with(&url, ProxyRoute::System, pac, matcher_via(&matcher_proxy)).await.unwrap();
assert_eq!(*seen.lock().unwrap(), "http://pac-target.invalid:8080/");
assert!(asked(pac_asked).await.unwrap().starts_with("CONNECT pac-target.invalid:8080 HTTP/1.1\r\n"));
assert_eq!(asked(matcher_asked).await, None, "the matcher's proxy must not be used");
}
#[tokio::test]
async fn wss_is_looked_up_as_https() {
let (pac_proxy, _) = proxy("HTTP/1.1 200 Connection established\r\n\r\n").await;
let seen = Arc::new(Mutex::new(String::new()));
let recorded = Arc::clone(&seen);
let pac = move |probe: &str| {
*recorded.lock().unwrap() = probe.to_owned();
Some(ProxyRoute::Via(format!("http://{pac_proxy}")))
};
let url = reqwest::Url::parse("wss://pac-target.invalid/s").unwrap();
connect_with(&url, ProxyRoute::System, pac, || Matcher::builder().build()).await.unwrap();
assert_eq!(*seen.lock().unwrap(), "https://pac-target.invalid:443/");
}
#[tokio::test]
async fn a_resolved_direct_route_skips_the_matchers_proxy() {
let (matcher_proxy, matcher_asked) = proxy("HTTP/1.1 200 Connection established\r\n\r\n").await;
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = reqwest::Url::parse(&format!("ws://{}/s", listener.local_addr().unwrap())).unwrap();
connect_with(&url, ProxyRoute::System, |_| Some(ProxyRoute::Direct), matcher_via(&matcher_proxy))
.await
.unwrap();
tokio::time::timeout(Duration::from_millis(300), listener.accept())
.await
.expect("no direct connection")
.unwrap();
assert_eq!(asked(matcher_asked).await, None, "the matcher's proxy must not be used");
}
#[tokio::test]
async fn a_socks_pac_route_keeps_the_matchers_route() {
let (matcher_proxy, matcher_asked) = proxy("HTTP/1.1 200 Connection established\r\n\r\n").await;
let url = reqwest::Url::parse("ws://pac-target.invalid:8080/s").unwrap();
let pac = |_: &str| Some(ProxyRoute::Via("socks5h://127.0.0.1:1080".into()));
connect_with(&url, ProxyRoute::System, pac, matcher_via(&matcher_proxy)).await.unwrap();
assert!(asked(matcher_asked).await.unwrap().starts_with("CONNECT pac-target.invalid:8080 HTTP/1.1\r\n"));
}
#[test]
fn proxy_credentials_are_percent_decoded() {
assert_eq!(percent_decode("a%40b%3Ac"), "a@b:c");
+73
Переглянути файл
@@ -2811,6 +2811,79 @@ impl LspManager {
Ok(ts_file_moves::file_references(&result))
}
/// Runs vtsls' own `command` for `doc`. typescript-language-server, TypeScript 7 and the
/// Vue / Astro servers have none of these commands: they need vtsls.
async fn vtsls_command(
&self,
doc: DocId,
command: &str,
arguments: impl FnOnce(&DocSnap, &Target) -> Option<Value>,
cancel: Option<&CancellationToken>,
) -> IdeResult<(Target, Value)> {
let snap = self.snapshot(doc)?;
let t = self
.ready_targets(&snap.servers, |c| c.commands().iter().any(|c| c == command))
.await
.into_iter()
.find(|t| t.server.name == "vtsls")
.ok_or_else(|| IdeError::unavailable("This needs the vtsls TypeScript language server"))?;
let arguments =
arguments(&snap, &t).ok_or_else(|| IdeError::invalid(format!("invalid `{command}` arguments")))?;
let params = json!({ "command": command, "arguments": arguments });
let result = self.call(&t, "workspace/executeCommand", params, cancel, LONG_TIMEOUT).await?;
Ok((t, result))
}
/// Go to Source Definition: the JavaScript implementation of what `pos` refers to, not its
/// `.d.ts` declaration (vtsls' `typescript.goToSourceDefinition`).
pub async fn source_definition(&self, doc: DocId, pos: Pos, cancel: CancellationToken) -> IdeResult<Vec<Location>> {
let (t, result) = self
.vtsls_command(
doc,
"typescript.goToSourceDefinition",
|snap, t| Some(json!([snap.uri, snap.position(t, pos)])),
Some(&cancel),
)
.await?;
let locs: Vec<lsp::Location> = serde_json::from_value::<Option<_>>(result)
.map_err(|e| IdeError::internal(format!("typescript.goToSourceDefinition: {e}")))?
.unwrap_or_default();
let conv = self.conv(t.enc());
Ok(locs.iter().filter_map(|l| conv.location(l)).collect())
}
/// Opens the `tsconfig.json` / `jsconfig.json` of `doc`'s project, or the TS Server log:
/// vtsls answers with `window/showDocument` (or a message when there is none).
pub async fn open_typescript_file(&self, doc: DocId, what: TypeScriptFile) -> IdeResult<()> {
let (command, with_uri) = match what {
TypeScriptFile::ProjectConfig => {
let snap = self.snapshot(doc)?;
let js = snap.language.as_str().starts_with("javascript");
(if js { "javascript.goToProjectConfig" } else { "typescript.goToProjectConfig" }, true)
}
TypeScriptFile::ServerLog => ("typescript.openTsServerLog", false),
};
self.vtsls_command(doc, command, |snap, _| Some(if with_uri { json!([snap.uri]) } else { json!([]) }), None)
.await?;
Ok(())
}
/// The files tsserver suggests for vtsls' Move to File `command` (from a code action).
pub async fn move_to_file_targets(
&self,
doc: DocId,
command: Command,
cancel: CancellationToken,
) -> IdeResult<Vec<PathBuf>> {
let snap = self.snapshot(doc)?;
let request = ts_file_moves::move_to_file_suggestions_request(&snap.path, &command.arguments)
.ok_or_else(|| IdeError::invalid("invalid Move to File command"))?;
let (_, result) = self
.vtsls_command(doc, ts_file_moves::COMMAND, |_, _| request.get("arguments").cloned(), Some(&cancel))
.await?;
Ok(ts_file_moves::move_to_file_suggestions(&result))
}
/// Whether a server of `doc` (`server`, when given) provides the command `name`. Code actions
/// can carry commands other editors' extensions run themselves after the edit (vtsls'
/// `_typescript.didOrganizeImports`): no server provides those.
+46
Переглянути файл
@@ -87,10 +87,56 @@ pub(crate) fn file_references(result: &Value) -> Vec<ide_core::Location> {
.collect()
}
/// The `typescript.tsserverRequest` arguments asking where the selection of vtsls' Move to File
/// command (`_typescript.moveToFileRefactoring` with `[action, uri, range]`, run with the target
/// file appended) can go.
pub(crate) fn move_to_file_suggestions_request(file: &std::path::Path, arguments: &[Value]) -> Option<Value> {
let range: lsp_types::Range = serde_json::from_value(arguments.get(2)?.clone()).ok()?;
// tsserver: 1-based lines and UTF-16 offsets; vtsls speaks UTF-16.
Some(json!({
"command": COMMAND,
"arguments": ["getMoveToRefactoringFileSuggestions", {
"file": file,
"startLine": range.start.line + 1,
"startOffset": range.start.character + 1,
"endLine": range.end.line + 1,
"endOffset": range.end.character + 1,
}],
}))
}
/// The files tsserver suggests in its `getMoveToRefactoringFileSuggestions` answer.
pub(crate) fn move_to_file_suggestions(result: &Value) -> Vec<PathBuf> {
let body = result.get("body").unwrap_or(result);
serde_json::from_value(body.get("files").cloned().unwrap_or_default()).unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn asks_tsserver_where_the_move_to_file_selection_can_go() {
let action = json!({ "name": "Move to file", "kind": "refactor.move.file" });
let range = json!({ "start": { "line": 6, "character": 16 }, "end": { "line": 8, "character": 1 } });
let request = move_to_file_suggestions_request(
std::path::Path::new("/p/src/util.ts"),
&[action.clone(), json!("file:///p/src/util.ts"), range],
)
.unwrap();
assert_eq!(
request["arguments"],
json!(["getMoveToRefactoringFileSuggestions", {
"file": "/p/src/util.ts", "startLine": 7, "startOffset": 17, "endLine": 9, "endOffset": 2,
}])
);
assert!(move_to_file_suggestions_request(std::path::Path::new("/p/a.ts"), &[action]).is_none());
let answer =
json!({ "success": true, "body": { "newFileName": "/p/src/greet.ts", "files": ["/p/src/app.ts"] } });
assert_eq!(move_to_file_suggestions(&answer), vec![PathBuf::from("/p/src/app.ts")]);
assert!(move_to_file_suggestions(&json!({ "success": false })).is_empty());
}
#[test]
fn converts_tsserver_file_references() {
let result = json!({ "success": true, "body": { "symbolName": "\"./Hello.vue\"", "refs": [
+8
Переглянути файл
@@ -109,6 +109,14 @@ pub struct Signature {
pub parameters: Vec<(u32, u32)>,
}
/// A file vtsls opens for a document: its project's configuration or the TS Server log.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum TypeScriptFile {
ProjectConfig,
ServerLog,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum GotoKind {
+129
Переглянути файл
@@ -969,6 +969,135 @@ async fn bundler_path_aliases_resolve_below_tsconfig_paths() {
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
}
/// vtsls' own commands (#6922): Go to Source Definition opens a library's JavaScript instead
/// of its `.d.ts`, Go to Project Configuration and Open TS Server Log answer with
/// `window/showDocument`, JSDoc `{@link}` in hovers is a `file://…#L1,1` link, and Move to File
/// suggests the project's files and moves a function with its imports in one applied edit. Set
/// `OPENIDEA_TEST_NPM_TOOLS` to a dir with `npm i @vtsls/[email protected] typescript@6`.
#[tokio::test(flavor = "multi_thread")]
#[ignore = "requires @vtsls/language-server and typescript@6 (OPENIDEA_TEST_NPM_TOOLS)"]
async fn vtsls_commands_open_sources_configs_logs_and_move_to_file() {
let tools = std::path::PathBuf::from(std::env::var("OPENIDEA_TEST_NPM_TOOLS").expect("OPENIDEA_TEST_NPM_TOOLS"));
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap();
for dir in ["src", "node_modules/greeting"] {
std::fs::create_dir_all(root.join(dir)).unwrap();
}
let files = [
("package.json", "{\"name\":\"app\",\"private\":true}"),
("tsconfig.json", "{\"files\":[],\"references\":[{\"path\":\"./src/tsconfig.app.json\"}]}"),
(
"src/tsconfig.app.json",
"{\"compilerOptions\":{\"strict\":true,\"composite\":true,\"module\":\"ESNext\",\"moduleResolution\":\"Bundler\"},\"include\":[\"./**/*.ts\"]}",
),
(
"node_modules/greeting/package.json",
"{\"name\":\"greeting\",\"main\":\"index.js\",\"types\":\"index.d.ts\"}",
),
("node_modules/greeting/index.d.ts", "export declare function shout(s: string): string;\n"),
("node_modules/greeting/index.js", "export function shout(s) {\n return s.toUpperCase();\n}\n"),
(
"src/main.ts",
"import { shout } from \"greeting\";\nimport { greet, Greeter } from \"./util\";\n\n/** Uses {@link Greeter} to say hello. */\nexport function hello(name: string) {\n return shout(greet(name));\n}\n\nexport const g = new Greeter();\n",
),
(
"src/util.ts",
"export class Greeter {\n greet(name: string) {\n return `Hello, ${name}`;\n }\n}\n\nexport function greet(name: string) {\n return new Greeter().greet(name);\n}\n",
),
("src/strings.ts", "export const upper = (s: string) => s.toUpperCase();\n"),
("src/app.ts", "import { greet } from \"./util\";\n\nconsole.log(greet(\"app\"));\n"),
];
for (path, text) in files {
std::fs::write(root.join(path), text).unwrap();
}
// The IDE's settings hook: Move to File on, a TypeScript 6 lib, the log on.
let init = serde_json::json!({
"vtsls": { "enableMoveToFileCodeAction": true, "autoUseWorkspaceTsdk": true },
"typescript": {
"tsdk": tools.join("node_modules/typescript/lib").to_string_lossy(),
"tsserver": { "log": "verbose" },
},
});
let ts = lang("typescript", "ts", npm_server(&tools, "vtsls", "vtsls", Some(init)));
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![ts]));
let applied: Arc<Mutex<Vec<ide_core::WorkspaceEdit>>> = Arc::default();
mgr.set_apply_edit_hook(Box::new({
let applied = applied.clone();
move |edit| {
applied.lock().push(edit);
true
}
}));
let open = |path: &str| {
let doc = DocId::next();
let file = root.join(path);
mgr.did_open(doc, &file, &LanguageId::new("typescript"), 1, &std::fs::read_to_string(&file).unwrap());
doc
};
let (main, util) = (open("src/main.ts"), open("src/util.ts"));
// `shout`: Go to Declaration is the `.d.ts`, Go to Source Definition the `.js`.
let at = Pos::new(0, 10);
// The syntax server answers with the import itself until the project is loaded.
let dts = |d: &ide_core::Location| d.path.to_string_lossy().ends_with("greeting/index.d.ts");
let declaration = retry("declaration", Duration::from_secs(90), || {
let mgr = mgr.clone();
async move { mgr.goto(main, at, GotoKind::Definition).await.ok().filter(|d| d.iter().any(dts)) }
})
.await;
assert!(declaration.iter().all(dts), "{declaration:?}");
let source = mgr.source_definition(main, at, Default::default()).await.unwrap();
assert_eq!(source.len(), 1, "{source:?}");
assert_eq!(*source[0].path, *root.join("node_modules/greeting/index.js"));
assert_eq!(source[0].range.start, Pos::new(0, 16));
let shown = |events: &Events, suffix: &str| {
events
.lock()
.iter()
.any(|e| matches!(e, IdeEvent::LspShowDocument { path: Some(path), .. } if path.to_string_lossy().ends_with(suffix)))
};
mgr.open_typescript_file(main, ide_lsp::types::TypeScriptFile::ProjectConfig).await.unwrap();
retry("tsconfig.app.json shown", Duration::from_secs(10), || {
let found = shown(&events, "src/tsconfig.app.json").then_some(());
async move { found }
})
.await;
mgr.open_typescript_file(main, ide_lsp::types::TypeScriptFile::ServerLog).await.unwrap();
retry("tsserver.log shown", Duration::from_secs(10), || {
let found = shown(&events, "tsserver.log").then_some(());
async move { found }
})
.await;
let hover = mgr.hover(main, Pos::new(4, 17), Default::default()).await.unwrap();
let hover = format!("{hover:?}");
assert!(hover.contains("src/util.ts#L1%2C1"), "{hover}");
// Move to File on `greet`: tsserver suggests the other files, the move updates the importers.
let caret = Pos::new(6, 16);
let actions = mgr.code_actions(util, Range::new(caret, caret), vec!["refactor.move".into()]).await.unwrap();
let command = actions
.iter()
.find_map(|a| a.command.clone().filter(|c| c.command == "_typescript.moveToFileRefactoring"))
.unwrap_or_else(|| panic!("no Move to File: {actions:?}"));
let targets = mgr.move_to_file_targets(util, command.clone(), Default::default()).await.unwrap();
let strings = root.join("src/strings.ts");
assert!(targets.contains(&strings) && targets.contains(&root.join("src/app.ts")), "{targets:?}");
let mut moving = command;
moving.arguments.push(serde_json::json!(strings));
mgr.execute_command(util, moving).await.unwrap();
let edits = applied.lock().clone();
assert_eq!(edits.len(), 1, "{edits:?}");
let edit = format!("{:?}", edits[0]);
for file in ["src/util.ts", "src/strings.ts", "src/app.ts", "src/main.ts"] {
assert!(edit.contains(&*root.join(file).to_string_lossy()), "{file}: {edit}");
}
assert!(edit.contains("export function greet(name: string)"), "{edit}");
assert!(edit.contains("import { greet } from \\\"./strings\\\""), "{edit}");
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
}
/// CSS Modules Kit (`@css-modules-kit/ts-plugin`) on vtsls, which serves the `.module.css`
/// files too (`languages: ["css"]`): definition and completion from TSX, references and rename
/// from the stylesheet (#6071), with the settings hook's own plugin configuration. Exactly the
+25 -1
Переглянути файл
@@ -6,7 +6,7 @@ use crate::exec::{path_with, search_path, which};
use crate::npm::{has_ts_api, native_typescript, own_typescript};
use crate::{angular, astro, godot, pinned, vue};
use crate::{bin_dir, exe, venv_of};
use ide_core::settings::{InspectionLevel, InspectionSettings, LanguageServerSettings, Settings};
use ide_core::settings::{InspectionLevel, InspectionSettings, LanguageServerSettings, Settings, TsServerLog};
use ide_core::version_managers::Tool;
use ide_core::{IdeError, IdeResult};
use ide_language::{LanguageConfig, LanguageServerConfig};
@@ -1508,6 +1508,14 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
if name == "vtsls" && memory > 0 {
merge_init_options(cfg, json!({ "typescript": { "tsserver": { "maxTsServerMemory": memory } } }));
}
if name == "vtsls" {
// Move to File asks the IDE for the target file (vtsls hides the action by default).
merge_init_options(cfg, json!({ "vtsls": { "enableMoveToFileCodeAction": true } }));
let log = s.languages.typescript.tsserver_log;
if log != TsServerLog::Off {
merge_init_options(cfg, json!({ "typescript": { "tsserver": { "log": log } } }));
}
}
if name == "vtsls"
&& cfg.tsserver_project
&& !server_root.ancestors().any(|d| d.join("tsconfig.json").is_file() || d.join("jsconfig.json").is_file())
@@ -2778,6 +2786,22 @@ mod maven_linkage_tests {
assert_eq!(options.pointer("/typescript/tsserver/maxTsServerMemory"), Some(&json!(6144)));
}
#[test]
fn vtsls_offers_move_to_file_and_logs_only_when_asked() {
let tmp = tempfile::tempdir().unwrap();
let mut s = Settings::default();
let options = |s: &Settings| {
let mut cfg = custom_server("vtsls", &LanguageServerSettings::default());
configure_server(&mut cfg, tmp.path(), tmp.path(), s);
serde_json::to_value(cfg.initialization_options).unwrap()
};
let off = options(&s);
assert_eq!(off.pointer("/vtsls/enableMoveToFileCodeAction"), Some(&json!(true)));
assert!(off.pointer("/typescript/tsserver/log").is_none());
s.languages.typescript.tsserver_log = TsServerLog::Verbose;
assert_eq!(options(&s).pointer("/typescript/tsserver/log"), Some(&json!("verbose")));
}
#[test]
fn vtsls_probes_the_tsconfig_plugins_but_not_its_global_ones() {
let tmp = tempfile::tempdir().unwrap();
+116 -5
Переглянути файл
@@ -20,7 +20,12 @@ pub(crate) fn gx(e: impl std::fmt::Display) -> IdeError {
}
pub(crate) struct Cache {
repo: gix::ThreadSafeRepository,
/// `None` after the repository was replaced or went away. gitoxide memory-maps packs, and
/// reading a mapping whose volume was unmounted raises SIGBUS, so that handle is never reused.
repo: Option<gix::ThreadSafeRepository>,
/// The git and common directories `repo` was opened from.
dirs: [PathBuf; 2],
handles: Option<DirHandles>,
files: [PathBuf; 4],
stamp: Vec<Option<(SystemTime, u64)>>,
/// `objects/pack` directory and its modification time. An external
@@ -49,6 +54,49 @@ fn stamp(files: &[PathBuf]) -> Vec<Option<(SystemTime, u64)>> {
.collect()
}
/// Tells whether the repository's directories are still the ones its handle was opened from.
///
/// Comparing paths is not enough: a remounted volume can have the same device, inodes and
/// modification times. A descriptor opened before the unmount stays invalid after it.
#[cfg(unix)]
struct DirHandles([std::fs::File; 2]);
#[cfg(unix)]
impl DirHandles {
fn open(dirs: &[PathBuf; 2]) -> Option<Self> {
let mut options = std::fs::OpenOptions::new();
options.read(true);
// Any other descriptor makes a normal unmount (Eject) fail because the volume is busy.
#[cfg(target_os = "macos")]
std::os::unix::fs::OpenOptionsExt::custom_flags(&mut options, libc::O_EVTONLY);
Some(Self([options.open(&dirs[0]).ok()?, options.open(&dirs[1]).ok()?]))
}
fn is_current(&self, dirs: &[PathBuf; 2]) -> bool {
use std::os::unix::fs::MetadataExt;
self.0.iter().zip(dirs).all(|(held, dir)| match (held.metadata(), std::fs::metadata(dir)) {
(Ok(held), Ok(now)) => (held.dev(), held.ino()) == (now.dev(), now.ino()),
_ => false,
})
}
}
// ponytail: existence only, because an open directory handle blocks renaming it on Windows.
// A volume that returns between two calls goes unnoticed; compare file ids if that matters.
#[cfg(not(unix))]
struct DirHandles;
#[cfg(not(unix))]
impl DirHandles {
fn open(dirs: &[PathBuf; 2]) -> Option<Self> {
Self.is_current(dirs).then_some(Self)
}
fn is_current(&self, dirs: &[PathBuf; 2]) -> bool {
dirs.iter().all(|dir| dir.is_dir())
}
}
/// The pack directory's modification time: adding or removing a pack file
/// updates it. `None` when the directory can't be read.
fn pack_stamp(pack_dir: &Path) -> Option<SystemTime> {
@@ -77,7 +125,16 @@ pub(crate) fn discover(path: &Path) -> IdeResult<Option<Repo>> {
let common_dir = absolute(repo.common_dir())?;
let files = cache_files(&git_dir, &common_dir);
let pack_dir = common_dir.join("objects").join("pack");
let cache = Cache { stamp: stamp(&files), files, repo: ts, pack_stamp: pack_stamp(&pack_dir), pack_dir };
let dirs = [git_dir.clone(), common_dir];
let cache = Cache {
stamp: stamp(&files),
files,
repo: Some(ts),
handles: DirHandles::open(&dirs),
dirs,
pack_stamp: pack_stamp(&pack_dir),
pack_dir,
};
Ok(Some(Repo {
execution_allowed: std::sync::atomic::AtomicBool::new(false),
git_executable: std::sync::RwLock::new(crate::opening_git_executable()),
@@ -141,6 +198,8 @@ impl Repo {
/// A thread-local gitoxide handle; reopened when configuration or packed refs change.
/// gitoxide's packed-ref snapshot only reloads for a newer mtime, which a replacement may preserve.
/// A volume lost after this returns can still raise SIGBUS in the caller: gitoxide can't read
/// packs without mapping them.
pub(crate) fn gix(&self) -> IdeResult<gix::Repository> {
let _scope = self.execution_scope();
self.check_valid()?;
@@ -149,12 +208,20 @@ impl Repo {
.map_err(gx);
}
let mut cache = self.inner.lock().unwrap_or_else(|p| p.into_inner());
if !cache.handles.as_ref().is_some_and(|handles| handles.is_current(&cache.dirs)) {
cache.repo = None;
// Before the repository is opened, so that losing the volume meanwhile is noticed.
cache.handles = DirHandles::open(&cache.dirs);
if cache.handles.is_none() {
return Err(self.stale_error());
}
}
let now = stamp(&cache.files);
let pack_now = pack_stamp(&cache.pack_dir);
if now != cache.stamp || pack_now != cache.pack_stamp {
if cache.repo.is_none() || now != cache.stamp || pack_now != cache.pack_stamp {
match gix::ThreadSafeRepository::open(&self.git_dir) {
Ok(fresh) => {
cache.repo = fresh;
cache.repo = Some(fresh);
cache.stamp = now;
cache.pack_stamp = pack_now;
}
@@ -163,11 +230,14 @@ impl Repo {
cache.stamp = now;
cache.pack_stamp = pack_now;
self.check_valid()?;
if cache.repo.is_none() {
return Err(gx(e));
}
tracing::warn!("reopening repository failed: {e}");
}
}
}
let mut repo = cache.repo.to_thread_local();
let mut repo = cache.repo.as_ref().ok_or_else(|| self.stale_error())?.to_thread_local();
repo.object_cache_size_if_unset(4 * 1024 * 1024);
Ok(repo)
}
@@ -577,3 +647,44 @@ pub(crate) fn is_ignored(repo: &gix::Repository, rel: &str) -> IdeResult<bool> {
pub(crate) fn to_string(b: &BStr) -> String {
b.to_str_lossy().into_owned()
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
use std::process::Command;
use std::sync::Arc;
fn run(cmd: &mut Command) {
assert!(cmd.status().unwrap().success(), "{cmd:?}");
}
/// What a remounted volume looks like: every path and modification time is the same, but
/// the files that the old handle mapped are gone. `tests/volume_loss.rs` does it for real.
#[test]
fn a_replaced_repository_is_reopened_even_when_its_stamps_are_the_same() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("repo");
let copy = tmp.path().join("copy");
run(Command::new("git").args(["init", "-q"]).arg(&root));
let repo = discover(&root).unwrap().unwrap();
repo.set_execution_allowed(true);
let store = || repo.gix().unwrap().objects.store();
let stamps = || {
let cache = repo.inner.lock().unwrap();
(stamp(&cache.files), pack_stamp(&cache.pack_dir))
};
let (first, before) = (store(), stamps());
assert!(Arc::ptr_eq(&first, &store()), "an unchanged repository keeps its handle");
run(Command::new("cp").arg("-pR").arg(&root).arg(&copy));
std::fs::rename(&root, tmp.path().join("old")).unwrap();
assert!(repo.gix().is_err());
assert!(repo.gix().is_err());
std::fs::rename(&copy, &root).unwrap();
assert_eq!(stamps(), before, "the stamps must not be what triggers the reopen");
let second = store();
assert!(!Arc::ptr_eq(&first, &second), "the handle to the replaced repository was reused");
assert!(Arc::ptr_eq(&second, &store()), "it is reopened once");
}
}
+139
Переглянути файл
@@ -0,0 +1,139 @@
//! Status after the repository's volume disappears. A stale memory-mapped pack index raises
//! SIGBUS there, which kills the process instead of failing the call.
#![cfg(target_os = "macos")]
use ide_vcs::Repo;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
fn run(cmd: &mut Command) {
let out = cmd.output().unwrap();
assert!(out.status.success(), "{cmd:?}: {}", String::from_utf8_lossy(&out.stderr));
}
fn git(dir: &Path, args: &[&str]) {
run(Command::new("git")
.current_dir(dir)
.args(["-c", "user.name=t", "-c", "[email protected]", "-c", "commit.gpgsign=false"])
.args(args));
}
/// A repository whose objects are all packed, with one staged change so that status has
/// to read the `HEAD` tree.
fn packed_repo(dir: &Path, files: usize) {
std::fs::create_dir_all(dir).unwrap();
git(dir, &["init", "-q"]);
for i in 0..files {
std::fs::write(dir.join(format!("f{i}")), format!("{i}\n")).unwrap();
}
git(dir, &["add", "."]);
git(dir, &["commit", "-qm", "init"]);
git(dir, &["repack", "-adq"]);
git(dir, &["pack-refs", "--all"]);
std::fs::write(dir.join("f0"), "changed\n").unwrap();
git(dir, &["add", "f0"]);
}
/// An APFS disk image mounted in a temporary directory, detached when dropped.
struct Image {
tmp: tempfile::TempDir,
}
impl Image {
fn new() -> Self {
let image = Self { tmp: tempfile::tempdir().unwrap() };
std::fs::create_dir(image.mount()).unwrap();
run(Command::new("hdiutil")
.args(["create", "-quiet", "-size", "200m", "-fs", "APFS", "-volname", "openidea-test"])
.arg(image.file()));
image.attach();
image
}
fn file(&self) -> PathBuf {
self.tmp.path().join("t.dmg")
}
fn mount(&self) -> PathBuf {
self.tmp.path().join("mnt")
}
fn attach(&self) {
run(Command::new("hdiutil")
.args(["attach", "-nobrowse", "-quiet", "-mountpoint"])
.arg(self.mount())
.arg(self.file()));
}
fn force_detach(&self) {
run(Command::new("hdiutil").args(["detach", "-force", "-quiet"]).arg(self.mount()));
}
/// Unmounts like Eject does: refused while a process keeps the volume busy.
fn unmount(&self) -> Output {
Command::new("diskutil").arg("unmount").arg(self.mount()).output().unwrap()
}
}
impl Drop for Image {
fn drop(&mut self) {
// After a normal unmount the image is still attached, and only a mounted volume can
// be detached by its path.
let _ = Command::new("hdiutil")
.args(["attach", "-nobrowse", "-quiet", "-mountpoint"])
.arg(self.mount())
.arg(self.file())
.output();
let _ = Command::new("hdiutil").args(["detach", "-force", "-quiet"]).arg(self.mount()).output();
}
}
/// Run with `cargo test -p ide-vcs --test volume_loss -- --ignored`: needs `hdiutil`.
#[test]
#[ignore = "mounts and force-detaches a disk image"]
fn a_force_detached_volume_does_not_crash_status() {
let image = Image::new();
let root = image.mount().join("repo");
packed_repo(&root, 5000);
// Start with cold pages, as after a real reconnect.
image.force_detach();
image.attach();
let repo = Repo::discover(&root).unwrap().unwrap();
repo.set_execution_allowed(true);
assert_eq!(repo.status().unwrap().len(), 1);
image.force_detach();
for _ in 0..2 {
assert!(repo.status().is_err());
assert!(repo.head().is_err());
}
image.attach();
assert_eq!(repo.status().unwrap().len(), 1);
// Gone and back between two calls: same path, same modification times.
image.force_detach();
image.attach();
assert_eq!(repo.status().unwrap().len(), 1);
assert!(repo.head().unwrap().1.is_some());
}
/// Only the descriptors: this reads nothing, so gitoxide has not mapped any packs yet.
#[test]
#[ignore = "mounts and unmounts a disk image"]
fn the_directory_descriptors_do_not_block_a_normal_unmount() {
let image = Image::new();
let root = image.mount().join("repo");
packed_repo(&root, 3);
image.force_detach();
image.attach();
let repo = Repo::discover(&root).unwrap().unwrap();
repo.set_execution_allowed(true);
let out = image.unmount();
assert!(out.status.success(), "{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
assert!(repo.status().is_err());
image.attach();
assert_eq!(repo.status().unwrap().len(), 1);
}
+1
Переглянути файл
@@ -24,6 +24,7 @@ globset.workspace = true
uuid.workspace = true
zip.workspace = true
encoding_rs.workspace = true
quick-xml = "0.42"
[target.'cfg(windows)'.dependencies]
winreg = "0.56"
+344 -5
Переглянути файл
@@ -162,6 +162,127 @@ fn is_missing(path: &Path) -> bool {
path.is_absolute() && !text.contains("://") && !wsl && !path.exists()
}
fn folder_name(path: &Path) -> String {
path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| path.display().to_string())
}
/// What importing a JetBrains IDE's recent projects did (or, as a preview, would do).
#[derive(Clone, Debug, Default, PartialEq, Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct JetBrainsRecentImport {
/// Projects added to the recent projects.
pub imported: u32,
/// Projects left out because their folder no longer exists.
pub missing: u32,
/// Project groups added.
pub groups: u32,
}
/// A recent project as a JetBrains IDE keeps it in `options/recentProjects.xml`.
#[derive(Debug, Default, PartialEq)]
struct JetBrainsRecent {
path: String,
name: Option<String>,
opened_at_ms: f64,
/// Opened but not listed (LightEdit, a file opened alone): the IDE does not show it.
hidden: bool,
}
#[derive(Debug, Default, PartialEq)]
struct JetBrainsGroup {
name: String,
paths: Vec<String>,
expanded: bool,
}
/// The `RecentProjectsManager` state: `additionalInfo` entries (path → `RecentProjectMetaInfo`) and
/// `groups` (`ProjectGroup` with `name`, `expanded` and its `projects`).
fn parse_jetbrains_recent(xml: &str) -> (Vec<JetBrainsRecent>, Vec<JetBrainsGroup>) {
use quick_xml::{Reader, XmlVersion, events::Event};
let mut reader = Reader::from_str(xml);
let (mut projects, mut groups) = (Vec::new(), Vec::new());
let mut project: Option<JetBrainsRecent> = None;
let mut group: Option<JetBrainsGroup> = None;
loop {
let (tag, empty) = match reader.read_event() {
Ok(Event::Start(tag)) => (tag, false),
Ok(Event::Empty(tag)) => (tag, true),
Ok(Event::End(tag)) => {
match tag.local_name().as_ref() {
"entry" => projects.extend(project.take()),
"ProjectGroup" => groups.extend(group.take()),
_ => {}
}
continue;
}
Ok(Event::Eof) | Err(_) => break,
_ => continue,
};
let attr = |key: &str| {
tag.attributes()
.flatten()
.find(|a| a.key.as_ref() == key)
.and_then(|a| a.normalized_value(XmlVersion::Implicit1_0).ok().map(|v| v.into_owned()))
};
match tag.local_name().as_ref() {
"entry" if !empty && group.is_none() => {
project = attr("key").map(|path| JetBrainsRecent { path, ..Default::default() });
}
"RecentProjectMetaInfo" => {
if let Some(p) = &mut project {
p.hidden = attr("hidden").as_deref() == Some("true");
}
}
"ProjectGroup" if !empty => group = Some(JetBrainsGroup::default()),
"option" => {
let (name, value) = (attr("name"), attr("value"));
if let Some(g) = &mut group {
match (name.as_deref(), value) {
(Some("name"), Some(v)) => g.name = v,
(Some("expanded"), Some(v)) => g.expanded = v == "true",
// `<option name="projects"><list><option value="…"/>`.
(None, Some(v)) => g.paths.push(v),
_ => {}
}
} else if let Some(p) = &mut project {
match (name.as_deref(), value) {
(Some("customProjectName"), Some(v)) => p.name = Some(v),
// Older IDEs.
(Some("displayName"), Some(v)) if p.name.is_none() => p.name = Some(v),
(Some("projectOpenTimestamp" | "activationTimestamp"), Some(v)) => {
p.opened_at_ms = p.opened_at_ms.max(v.parse().unwrap_or(0.0));
}
_ => {}
}
}
}
_ => {}
}
}
(projects, groups)
}
/// A path of `recentProjects.xml`: `$USER_HOME$` is `home`, `$APPLICATION_CONFIG_DIR$` the IDE's settings
/// folder `config`; Windows paths are stored with `/`. `None` for other path variables or a relative path.
fn expand_jetbrains_path(raw: &str, home: Option<&Path>, config: &Path) -> Option<PathBuf> {
let (base, rest) = if let Some(rest) = raw.strip_prefix("$USER_HOME$") {
(Some(home?), rest)
} else if let Some(rest) = raw.strip_prefix("$APPLICATION_CONFIG_DIR$") {
(Some(config), rest)
} else {
(None, raw)
};
if rest.contains('$') {
return None;
}
let rest = if cfg!(windows) { rest.replace('/', "\\") } else { rest.to_owned() };
let path = match base {
Some(base) => base.join(rest.trim_start_matches(['/', '\\'])),
None => PathBuf::from(rest),
};
path.is_absolute().then_some(path)
}
impl RecentProjects {
pub fn load(config_dir: &Path) -> Self {
let file = config_dir.join("recent.json");
@@ -208,8 +329,7 @@ impl RecentProjects {
pub fn touch(&self, path: &Path, branch: Option<String>) -> IdeResult<()> {
let mut items = self.items.lock();
items.retain(|p| p.path != path);
let name =
path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| path.display().to_string());
let name = folder_name(path);
items.insert(0, RecentProject { path: path.into(), name, opened_at_ms: now_ms(), branch, missing: false });
cap(&mut items, &self.groups.lock());
self.persist(&items)
@@ -219,9 +339,7 @@ impl RecentProjects {
pub fn rename(&self, path: &Path, name: Option<&str>) -> IdeResult<()> {
let mut items = self.items.lock();
let Some(item) = items.iter_mut().find(|p| p.path == path) else { return Ok(()) };
let name = name.map(str::to_owned).unwrap_or_else(|| {
path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| path.display().to_string())
});
let name = name.map(str::to_owned).unwrap_or_else(|| folder_name(path));
if item.name == name {
return Ok(());
}
@@ -247,6 +365,91 @@ impl RecentProjects {
Ok(())
}
/// Adds the recent projects and project groups of a JetBrains IDE (`xml`: its
/// `options/recentProjects.xml`; `config`: its settings folder). Projects already recent keep their
/// entry, folders that are gone are left out, and the groups made here are kept: an imported group
/// whose name is taken gets a number, and one whose projects are all grouped already is not added.
/// `dry_run` only counts.
pub fn import_jetbrains(
&self,
xml: &str,
home: Option<&Path>,
config: &Path,
dry_run: bool,
) -> IdeResult<JetBrainsRecentImport> {
let (projects, jetbrains_groups) = parse_jetbrains_recent(xml);
let mut summary = JetBrainsRecentImport::default();
let mut items = self.items.lock();
let mut groups = self.groups.lock();
let mut new_items = items.clone();
let mut added = Vec::new();
for p in projects.into_iter().filter(|p| !p.hidden) {
let Some(path) = expand_jetbrains_path(&p.path, home, config).filter(|path| !is_missing(path)) else {
summary.missing += 1;
continue;
};
if new_items.iter().any(|i| i.path == path) {
continue;
}
let name = p.name.filter(|n| !n.trim().is_empty()).unwrap_or_else(|| folder_name(&path));
new_items.push(RecentProject {
path: path.as_path().into(),
name,
opened_at_ms: p.opened_at_ms,
branch: None,
missing: false,
});
added.push(path);
}
new_items.sort_by(|a, b| b.opened_at_ms.total_cmp(&a.opened_at_ms));
let mut new_groups = groups.clone();
for g in jetbrains_groups {
let base = g.name.trim().to_owned();
if base.is_empty() {
continue;
}
let mut name = base.clone();
for n in 2.. {
if !new_groups.iter().any(|existing| existing.name == name) {
break;
}
name = format!("{base} {n}");
}
let paths = g
.paths
.iter()
.filter_map(|raw| expand_jetbrains_path(raw, home, config))
.filter(|path| new_items.iter().any(|i| i.path == *path))
.map(|path| path.as_path().into())
.collect();
new_groups.push(RecentProjectGroup { name, paths, expanded: g.expanded });
}
// Existing groups are normalized already, so they keep their place and their projects.
let mut new_groups = normalize(new_groups);
let existing = groups.len();
let mut index = 0;
new_groups.retain(|g| {
index += 1;
index <= existing || !g.paths.is_empty()
});
cap(&mut new_items, &new_groups);
summary.imported = added.iter().filter(|p| new_items.iter().any(|i| i.path == **p)).count() as u32;
summary.groups = (new_groups.len() - existing) as u32;
if dry_run {
return Ok(summary);
}
if summary.imported > 0 {
self.persist(&new_items)?;
*items = new_items;
}
if summary.groups > 0 {
write_json(&self.groups_file, &new_groups)?;
*groups = new_groups;
}
Ok(summary)
}
pub fn paths(&self) -> Vec<PathBuf> {
self.list().into_iter().map(|p| p.path.into_path_buf()).collect()
}
@@ -344,6 +547,142 @@ mod tests {
assert_eq!(recent.list().len(), 1);
}
const JETBRAINS_RECENT: &str = r#"<application>
<component name="RecentProjectsManager">
<option name="additionalInfo">
<map>
<entry key="$USER_HOME$/code/alpha">
<value>
<RecentProjectMetaInfo frameTitle="alpha – main.rs" projectWorkspaceId="w1">
<option name="activationTimestamp" value="1700000005000" />
<option name="colorInfo"><RecentProjectColorInfo associatedIndex="1" /></option>
<option name="customProjectName" value="Alpha Service" />
<option name="projectOpenTimestamp" value="1700000001000" />
</RecentProjectMetaInfo>
</value>
</entry>
<entry key="$USER_HOME$/code/beta">
<value>
<RecentProjectMetaInfo>
<option name="displayName" value="beta-old-name" />
<option name="projectOpenTimestamp" value="1700000003000" />
</RecentProjectMetaInfo>
</value>
</entry>
<entry key="$USER_HOME$/code/gone">
<value><RecentProjectMetaInfo /></value>
</entry>
<entry key="$APPLICATION_CONFIG_DIR$/light-edit">
<value><RecentProjectMetaInfo hidden="true" /></value>
</entry>
<entry key="$PROJECT_DIR$/x">
<value><RecentProjectMetaInfo /></value>
</entry>
</map>
</option>
<option name="groups">
<list>
<ProjectGroup>
<option name="expanded" value="true" />
<option name="name" value="Work" />
<option name="projects">
<list>
<option value="$USER_HOME$/code/alpha" />
<option value="$USER_HOME$/code/gone" />
</list>
</option>
</ProjectGroup>
<ProjectGroup>
<option name="name" value="Empty" />
</ProjectGroup>
</list>
</option>
<option name="lastOpenedProject" value="$USER_HOME$/code/alpha" />
</component>
</application>"#;
#[test]
fn parses_jetbrains_recent_projects_and_groups() {
let (projects, groups) = parse_jetbrains_recent(JETBRAINS_RECENT);
assert_eq!(projects.len(), 5);
assert_eq!(
projects[0],
JetBrainsRecent {
path: "$USER_HOME$/code/alpha".into(),
name: Some("Alpha Service".into()),
opened_at_ms: 1700000005000.0,
hidden: false,
}
);
assert_eq!(projects[1].name.as_deref(), Some("beta-old-name"));
assert!(projects[3].hidden);
assert_eq!(
groups,
vec![
JetBrainsGroup {
name: "Work".into(),
paths: vec!["$USER_HOME$/code/alpha".into(), "$USER_HOME$/code/gone".into()],
expanded: true,
},
JetBrainsGroup { name: "Empty".into(), paths: vec![], expanded: false },
]
);
}
#[test]
fn expands_jetbrains_path_variables() {
let (home, config) = (Path::new("/home/me"), Path::new("/cfg/IDE"));
assert_eq!(expand_jetbrains_path("$USER_HOME$/a/b", Some(home), config), Some(home.join("a").join("b")));
assert_eq!(expand_jetbrains_path("$APPLICATION_CONFIG_DIR$/x", Some(home), config), Some(config.join("x")));
assert_eq!(expand_jetbrains_path("$USER_HOME$", Some(home), config), Some(home.to_path_buf()));
assert_eq!(expand_jetbrains_path("$USER_HOME$/a", None, config), None);
assert_eq!(expand_jetbrains_path("$PROJECT_DIR$/a", Some(home), config), None);
assert_eq!(expand_jetbrains_path("relative/a", Some(home), config), None);
#[cfg(windows)]
assert_eq!(expand_jetbrains_path("C:/Users/me/a", Some(home), config), Some(PathBuf::from(r"C:\Users\me\a")));
}
#[test]
fn jetbrains_import_merges_without_touching_existing_groups() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("home");
for p in ["code/alpha", "code/beta", "mine"] {
std::fs::create_dir_all(home.join(p)).unwrap();
}
let (alpha, beta, mine) = (home.join("code/alpha"), home.join("code/beta"), home.join("mine"));
let cfg = tmp.path().join("config");
let recent = RecentProjects::load(&cfg);
recent.touch(&mine, None).unwrap();
recent.touch(&beta, None).unwrap();
let own = RecentProjectGroup { name: "Work".into(), paths: vec![mine.as_path().into()], expanded: true };
recent.set_groups(vec![own.clone()]).unwrap();
let ide = tmp.path().join("IDE");
let preview = recent.import_jetbrains(JETBRAINS_RECENT, Some(&home), &ide, true).unwrap();
let expected = JetBrainsRecentImport { imported: 1, missing: 2, groups: 1 };
assert_eq!(preview, expected);
assert_eq!(recent.list().len(), 2, "a preview changes nothing");
assert_eq!(recent.import_jetbrains(JETBRAINS_RECENT, Some(&home), &ide, false).unwrap(), expected);
let reloaded = RecentProjects::load(&cfg);
let list = reloaded.list();
let item = |p: &Path| list.iter().find(|i| i.path.as_ref() == p).unwrap();
assert_eq!(item(&alpha).name, "Alpha Service");
assert_eq!(item(&alpha).opened_at_ms, 1700000005000.0);
// Already recent: keeps its own entry.
assert_eq!(item(&beta).name, "beta");
assert_eq!(list.len(), 3);
// The group made here stays; the imported one gets a free name and only the imported projects.
let imported =
RecentProjectGroup { name: "Work 2".into(), paths: vec![alpha.as_path().into()], expanded: true };
assert_eq!(reloaded.groups(), vec![own.clone(), imported.clone()]);
// Importing again adds nothing.
let again = recent.import_jetbrains(JETBRAINS_RECENT, Some(&home), &ide, false).unwrap();
assert_eq!(again, JetBrainsRecentImport { imported: 0, missing: 2, groups: 0 });
assert_eq!(RecentProjects::load(&cfg).groups(), vec![own, imported]);
}
fn write_head(git_dir: &Path, contents: &str) {
std::fs::create_dir_all(git_dir).unwrap();
std::fs::write(git_dir.join("HEAD"), contents).unwrap();
+113
Переглянути файл
@@ -99,3 +99,116 @@ test("File History opens its revision and compares only that file with the worki
.poll(async () => ipcCalls(page, "vcs_file_at"))
.toContainEqual({ path: `${ROOT}/src/old-name.ts`, rev: REVISION });
});
test("File History creates and copies a patch for only the selected changed file", async ({ workbench: page }) => {
const parent = "b".repeat(40);
const selectedPath = "src/selected.ts";
const otherPath = "src/other.ts";
const patch = `diff --git a/${selectedPath} b/${selectedPath}\n`;
await stubDesktop(page);
await page.evaluate(
async ({ root, path, revision, parent, selectedPath, otherPath }) => {
const h = window.__ipc.handlers;
h.vcs_roots = () => [{ root, head: "main", headCommit: revision, operation: null }];
h.vcs_branch_info = () => ({
head: "main",
headCommit: revision,
upstream: null,
ahead: 0,
behind: 0,
operation: null,
});
h.vcs_branches = () => [];
h.vcs_status = () => [];
h.vcs_log = ({ query }) =>
(query as { path?: string }).path
? [
{
id: revision,
shortId: revision.slice(0, 8),
parents: [parent],
refs: [],
author: "Author",
email: "[email protected]",
timeMs: 1,
summary: "Export selected history file",
message: "Export selected history file",
historyPath: selectedPath,
},
]
: [];
h.vcs_log_refs = () => ({});
h.vcs_log_users = () => ["Author <[email protected]>"];
h.vcs_log_details_batch = () => [];
h.vcs_commit_files = () => [
{ path: selectedPath, kind: "modified", oldPath: null },
{ path: otherPath, kind: "modified", oldPath: null },
];
h.vcs_create_patch = ({ source }) => {
const paths = (source as { paths?: string[] }).paths ?? [];
return paths.map((entry) => `diff --git a/${entry} b/${entry}\n`).join("");
};
h.vcs_write_patch = () => null;
h.clipboard_write_text = () => null;
const projectModule = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ projectModule);
useProject.setState((state: { settings: Record<string, unknown> }) => ({
settings: {
...state.settings,
vcs: { confirmation: { onPatchCreated: "no" } },
},
}));
const storeModule = "/src/features/vcs/store.ts";
const { useVcs } = await import(/* @vite-ignore */ storeModule);
useVcs.setState({ available: true, root, repo: root, roots: [root], branchesLoaded: true, statusLoaded: true });
const contextModule = "/src/platform/context.ts";
const { setContext } = await import(/* @vite-ignore */ contextModule);
setContext("vcsAvailable", true);
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
await executeAction("vcs.showHistory", { path });
},
{ root: ROOT, path: `${ROOT}/${selectedPath}`, revision: REVISION, parent, selectedPath, otherPath },
);
const row = page.getByRole("listbox", { name: "Commits" }).getByRole("option", {
name: /Export selected history file/,
});
await expect(row).toBeVisible();
await row.click();
const tree = page.getByRole("tree", { name: "Changed files" });
const selected = tree.getByText("selected.ts", { exact: true });
await expect(selected).toBeVisible();
await expect(tree.getByText("other.ts", { exact: true })).toBeVisible();
const toolbar = page.getByRole("toolbar", { name: "Changed files" });
const create = toolbar.getByRole("button", { name: "Create Patch…", exact: true });
await expect(create).toBeDisabled();
await selected.click();
await expect(create).toBeEnabled();
await create.click();
const dialog = page.getByRole("dialog", { name: "Create Patch", exact: true });
await expect(dialog.getByRole("textbox", { name: "Base directory" })).toHaveValue(ROOT);
const destination = await dialog.getByRole("textbox", { name: "Patch file" }).inputValue();
expect(destination).toBe(`${ROOT}/Export_selected_history_file.patch`);
await dialog.getByRole("button", { name: "Create", exact: true }).click();
const source = { from: "revisions", before: parent, after: REVISION, paths: [selectedPath] };
await expect.poll(() => ipcCalls(page, "vcs_create_patch")).toEqual([{ repo: ROOT, base: ROOT, source }]);
await expect
.poll(() => ipcCalls(page, "vcs_write_patch"))
.toEqual([expect.objectContaining({ path: destination, patch })]);
await selected.click({ button: "right" });
await page
.getByRole("menu", { name: "Context menu" })
.getByRole("menuitem", { name: "Copy as Patch to Clipboard", exact: true })
.click();
await expect.poll(() => ipcCalls(page, "clipboard_write_text")).toEqual([{ text: patch }]);
await expect
.poll(() => ipcCalls(page, "vcs_create_patch"))
.toEqual([
{ repo: ROOT, base: ROOT, source },
{ repo: ROOT, base: null, source },
]);
});
+31
Переглянути файл
@@ -382,6 +382,36 @@ pub async fn settings_list_jetbrains_ides() -> IdeResult<Vec<ide_host::plugins::
.map_err(|e| IdeError::internal(e.to_string()))?
}
/// Import Recent Projects from JetBrains IDE: merges the recent projects and project groups of the IDE
/// whose settings folder is `path` (nothing when it has none); `dry_run` only counts them.
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub async fn recent_import_jetbrains(
state: State<'_, AppState>,
path: PathBuf,
dry_run: bool,
) -> IdeResult<ide_workspace::recent::JetBrainsRecentImport> {
let app = state.app.clone();
tauri::async_runtime::spawn_blocking(move || {
let xml = match std::fs::read_to_string(path.join("options").join("recentProjects.xml")) {
Ok(xml) => xml,
Err(e) if matches!(e.kind(), std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory) => {
return Ok(Default::default());
}
Err(e) => return Err(e.into()),
};
let state = app.state::<AppState>();
let summary = state.recent.import_jetbrains(&xml, dirs::home_dir().as_deref(), &path, dry_run)?;
if summary.imported > 0 {
crate::jump_list::refresh(&state.app, state.recent.list());
}
Ok(summary)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
}
pub(crate) fn project_current(window: Window) -> Option<ProjectInfo> {
let state = window.state::<AppState>();
state.project(window.label()).ok().filter(|p| !p.light).map(|p| project_info(&p))
@@ -466,6 +496,7 @@ ide_command::desktop_domain!(
log_frontend,
project_rename,
project_trust_add_location,
recent_import_jetbrains,
recent_project_groups,
recent_projects,
remove_recent_project,
+1
Переглянути файл
@@ -1533,6 +1533,7 @@ mod tests {
"file.exportSettings",
"file.importSettings",
"file.importJetBrainsSettings",
"file.importJetBrainsRecentProjects",
"file.syncSettings",
"file.togglePowerSave",
"macro.startRecording",
+4
Переглянути файл
@@ -440,6 +440,8 @@ lsp_java_move_destinations trusted project_host bin
lsp_java_source_types trusted project_host bindings async
lsp_library_sources trusted project_host bindings async
lsp_message_request_answer trusted project_host bindings sync
lsp_move_to_file_targets trusted project_host bindings async
lsp_open_typescript_file trusted project_host bindings async
lsp_prepare_rename trusted project_host bindings async
lsp_prepare_type_hierarchy trusted project_host bindings async
lsp_references trusted project_host bindings async
@@ -458,6 +460,7 @@ lsp_signature_info trusted project_host bin
lsp_snapshot_completion trusted project_host bindings async
lsp_snapshot_diagnostics trusted project_host bindings async
lsp_source_action_text trusted project_host bindings async
lsp_source_definition trusted project_host bindings async
lsp_stop trusted project_host bindings async
lsp_switch_source_header trusted project_host bindings async
lsp_type_hierarchy trusted project_host bindings async
@@ -613,6 +616,7 @@ pypi_search outside_restricted project_host bin
python_requirements trusted project_host bindings async
python_route_sources trusted desktop bindings async
recent_files always project_host bindings sync
recent_import_jetbrains always desktop bindings async
recent_project_groups always desktop bindings sync
recent_projects always desktop bindings async
redo_workspace_edit always project_host bindings async
+89 -5
Переглянути файл
@@ -1145,6 +1145,13 @@ export const commands = {
* language server runs: the question waits in that process, a remote project's server included.
*/
lspMessageRequestAnswer: (id: number, choice: string | null) => typedError<null, IdeError>(__TAURI_INVOKE("lsp_message_request_answer", { id, choice })),
/**
* The files tsserver suggests for vtsls' Move to File code action `command`. Cancel with
* `cancel_request(request)`.
*/
lspMoveToFileTargets: (request: RequestId, doc: DocId, command: Command) => typedError<IpcPath[], IdeError>(__TAURI_INVOKE("lsp_move_to_file_targets", { request, doc, command })),
/** Has vtsls open the document's `tsconfig.json` / `jsconfig.json` or the TS Server log. */
lspOpenTypescriptFile: (doc: DocId, what: TypeScriptFile) => typedError<null, IdeError>(__TAURI_INVOKE("lsp_open_typescript_file", { doc, what })),
lspPrepareRename: (doc: DocId, pos: Pos) => typedError<{
start: Pos,
end: Pos,
@@ -1208,6 +1215,11 @@ export const commands = {
lspSnapshotCompletion: (path: string, text: string, pos: Pos, request: RequestId) => typedError<CompletionItem[], IdeError>(__TAURI_INVOKE("lsp_snapshot_completion", { path, text, pos, request })),
lspSnapshotDiagnostics: (path: string, text: string, request: RequestId) => typedError<Diagnostic[], IdeError>(__TAURI_INVOKE("lsp_snapshot_diagnostics", { path, text, request })),
lspSourceActionText: (path: string, text: string, kind: string, request: RequestId) => typedError<TextEdit[], IdeError>(__TAURI_INVOKE("lsp_source_action_text", { path, text, kind, request })),
/**
* Go to Source Definition (vtsls): the JavaScript implementation of the symbol at `pos`
* instead of its `.d.ts`. Cancel with `cancel_request(request)`.
*/
lspSourceDefinition: (request: RequestId, doc: DocId, pos: Pos) => typedError<Location[], IdeError>(__TAURI_INVOKE("lsp_source_definition", { request, doc, pos })),
/** Stops a language server; it starts again when a file it serves is opened. */
lspStop: (server: ServerId) => typedError<null, IdeError>(__TAURI_INVOKE("lsp_stop", { server })),
/**
@@ -1744,6 +1756,11 @@ export const commands = {
pythonRouteSources: () => typedError<RouteSource[], IdeError>(__TAURI_INVOKE("python_route_sources")),
/** Recently opened files, most recent first (⌘E). */
recentFiles: () => typedError<IpcPath[], IdeError>(__TAURI_INVOKE("recent_files")),
/**
* Import Recent Projects from JetBrains IDE: merges the recent projects and project groups of the IDE
* whose settings folder is `path` (nothing when it has none); `dry_run` only counts them.
*/
recentImportJetbrains: (path: string, dryRun: boolean) => typedError<JetBrainsRecentImport, IdeError>(__TAURI_INVOKE("recent_import_jetbrains", { path, dryRun })),
/** The welcome screen's project groups. */
recentProjectGroups: () => __TAURI_INVOKE<RecentProjectGroup[]>("recent_project_groups"),
recentProjects: () => __TAURI_INVOKE<RecentProject[]>("recent_projects"),
@@ -10141,6 +10158,16 @@ export type JdkVendor = {
name: string,
};
/** What importing a JetBrains IDE's recent projects did (or, as a preview, would do). */
export type JetBrainsRecentImport = {
/** Projects added to the recent projects. */
imported: number,
/** Projects left out because their folder no longer exists. */
missing: number,
/** Project groups added. */
groups: number,
};
/**
* A JetBrains IDE's settings folder or exported archive: every
* entry name, and the text of the entries OpenIDEA maps (the frontend does the mapping).
@@ -10620,7 +10647,9 @@ export type LanguageServerSettings_Serialize = {
codeActionKinds?: string[] | null,
};
export type LanguagesSettings = {
export type LanguagesSettings = LanguagesSettings_Serialize | LanguagesSettings_Deserialize;
export type LanguagesSettings_Deserialize = {
/** Explicit plugin formatter, by language id. Empty entries use the normal formatter policy. */
pluginFormatters?: { [key in string]: string },
python?: PythonSettings,
@@ -10628,7 +10657,7 @@ export type LanguagesSettings = {
php?: PhpSettings,
rust?: RustSettings,
go?: GoSettings,
typescript?: TypeScriptSettings,
typescript?: TypeScriptSettings_Deserialize,
prettier?: ExternalFormatterSettings,
oxfmt?: ExternalFormatterSettings,
biome?: ExternalFormatterSettings,
@@ -10644,6 +10673,30 @@ export type LanguagesSettings = {
flutter?: FlutterSettings,
};
export type LanguagesSettings_Serialize = {
/** Explicit plugin formatter, by language id. Empty entries use the normal formatter policy. */
pluginFormatters: { [key in string]: string },
python: PythonSettings,
node: NodeSettings,
php: PhpSettings,
rust: RustSettings,
go: GoSettings,
typescript: TypeScriptSettings_Serialize,
prettier: ExternalFormatterSettings,
oxfmt: ExternalFormatterSettings,
biome: ExternalFormatterSettings,
/** dprint formats every file its configuration covers: `languages` is unused. */
dprint: ExternalFormatterSettings,
ruff: ExternalFormatterSettings,
black: ExternalFormatterSettings,
java: JavaSettings,
ruby: RubySettings,
markdown: MarkdownSettings,
arduino: ArduinoSettings,
zig: ZigSettings,
flutter: FlutterSettings,
};
export type LargeCommitFile = {
path: IpcPath,
size: number,
@@ -14718,7 +14771,7 @@ export type Settings_Deserialize = {
/** System Settings › HTTP Proxy (global only). */
proxy?: ProxySettings,
/** Interpreters / toolchains per language (Python, Node.js, Rust, Go, TypeScript). */
languages?: LanguagesSettings,
languages?: LanguagesSettings_Deserialize,
/** Project Structure: source / test / resource / excluded folders (project-relative). */
projectStructure?: ProjectStructureSettings,
/** Version Control (Git, Commit, Confirmation, Issue Navigation). */
@@ -14799,7 +14852,7 @@ export type Settings_Serialize = {
/** System Settings › HTTP Proxy (global only). */
proxy: ProxySettings,
/** Interpreters / toolchains per language (Python, Node.js, Rust, Go, TypeScript). */
languages: LanguagesSettings,
languages: LanguagesSettings_Serialize,
/** Project Structure: source / test / resource / excluded folders (project-relative). */
projectStructure: ProjectStructureSettings,
/** Version Control (Git, Commit, Confirmation, Issue Navigation). */
@@ -15952,7 +16005,15 @@ export type TrustStatus = {
decided: boolean,
};
export type TypeScriptSettings = {
/** tsserver's log verbosity, as vtsls' `typescript.tsserver.log` spells it. */
export type TsServerLog = "off" | "terse" | "normal" | "requestTime" | "verbose";
/** A file vtsls opens for a document: its project's configuration or the TS Server log. */
export type TypeScriptFile = "projectConfig" | "serverLog";
export type TypeScriptSettings = TypeScriptSettings_Serialize | TypeScriptSettings_Deserialize;
export type TypeScriptSettings_Deserialize = {
/**
* `bundled` (the server's own TypeScript), `workspace` (`node_modules/typescript`),
* or a path to a TypeScript `lib` directory.
@@ -15964,6 +16025,8 @@ export type TypeScriptSettings = {
* vtsls default 3072 dies in a GC death spiral), else unset (vtsls default).
*/
tsserverMaxMemory?: number,
/** tsserver's log (`typescript.tsserver.log`). TypeScript: Open TS Server Log opens it. */
tsserverLog?: TsServerLog,
/**
* Problems › TypeScript project errors: the project's own `tsc --watch` per root
* `tsconfig.json` reports the errors of files that are not open.
@@ -15971,6 +16034,27 @@ export type TypeScriptSettings = {
watchProblems?: boolean,
};
export type TypeScriptSettings_Serialize = {
/**
* `bundled` (the server's own TypeScript), `workspace` (`node_modules/typescript`),
* or a path to a TypeScript `lib` directory.
*/
version: string,
/**
* tsserver heap limit in MB. `0` = automatic: 8192 when vtsls hosts the Vue
* plugin (hybrid mode; a Vue project's program alone needs ~3 GiB, and the
* vtsls default 3072 dies in a GC death spiral), else unset (vtsls default).
*/
tsserverMaxMemory: number,
/** tsserver's log (`typescript.tsserver.log`). TypeScript: Open TS Server Log opens it. */
tsserverLog: TsServerLog,
/**
* Problems › TypeScript project errors: the project's own `tsc --watch` per root
* `tsconfig.json` reports the errors of files that are not open.
*/
watchProblems: boolean,
};
/** A misspelt word. */
export type Typo = {
/** UTF-16 range of the word. */
+8 -3
Переглянути файл
@@ -627,10 +627,14 @@ describe("EditorController", () => {
expect(openFilePaths(useTabs.getState())).toEqual(["/p/a.ts"]);
});
it("offers Find Usages immediately before Go To in the editor context menu", async () => {
ctrl = new EditorController(createMemoryBackend({ "/p/a.ts": "one\n" }));
// Go to Source Definition is vtsls': only in JavaScript and TypeScript files.
it.each([
["/p/a.ts", ["navigate.sourceDefinition"]],
["/p/a.py", []],
])("offers Find Usages immediately before Go To in the editor context menu (%s)", async (path, typescript) => {
ctrl = new EditorController(createMemoryBackend({ [path]: "one\n" }));
ctrl.start();
await ctrl.openFile("/p/a.ts", { focus: false });
await ctrl.openFile(path, { focus: false });
const slot = ctrl.activeSlot!;
const host = document.createElement("div");
document.body.appendChild(host);
@@ -646,6 +650,7 @@ describe("EditorController", () => {
"navigate.declaration",
"navigate.implementation",
"navigate.typeDeclaration",
...typescript,
"navigate.superMethod",
"navigate.relatedSymbol",
"navigate.gotoTest",
+3
Переглянути файл
@@ -1007,6 +1007,9 @@ export class EditorController implements SlotHost {
{ kind: "action", action: "navigate.declaration", label: "Declaration or Usages" },
{ kind: "action", action: "navigate.implementation", label: "Implementation(s)" },
{ kind: "action", action: "navigate.typeDeclaration", label: "Type Declaration" },
...(/^(java|type)script(react)?$/.test(slot.model.getMeta()?.language ?? "")
? [{ kind: "action" as const, action: "navigate.sourceDefinition", label: "Source Definition" }]
: []),
{ kind: "action", action: "navigate.superMethod", label: "Super Method" },
{ kind: "action", action: "navigate.relatedSymbol", label: "Related Symbol…" },
{ kind: "action", action: "navigate.gotoTest", label: "Test" },
+13
Переглянути файл
@@ -1,4 +1,5 @@
/** Actions of the LSP editor layer (ids from keymaps/intellij-macos.ts). */
import { gotoSourceDefinition, openProjectConfig, openTsServerLog, TYPESCRIPT_WHEN } from "./typescriptCommands";
import { generateActionIcon, isGenerateAction } from "./generate";
import type { EditorView } from "@codemirror/view";
import { executeAction, registerActions, type Action } from "@/platform/actions";
@@ -435,6 +436,18 @@ export function registerLspActions(): () => void {
editorAction("navigate.typeDeclaration", "Go to Type Declaration", "Navigate", (v) =>
gotoTargets(v, "typeDefinition"),
),
editorAction("navigate.sourceDefinition", "Go to Source Definition", "Navigate", gotoSourceDefinition, {
when: `${EDITOR_WHEN} && (${TYPESCRIPT_WHEN})`,
keywords: ["implementation", "javascript", "node_modules", "d.ts"],
}),
editorAction("typescript.goToProjectConfig", "Go to Project Configuration", "TypeScript", openProjectConfig, {
when: `${EDITOR_WHEN} && (${TYPESCRIPT_WHEN})`,
keywords: ["tsconfig", "jsconfig"],
}),
editorAction("typescript.openTsServerLog", "Open TS Server Log", "TypeScript", openTsServerLog, {
when: `${EDITOR_WHEN} && (${TYPESCRIPT_WHEN})`,
keywords: ["tsserver", "vtsls", "log"],
}),
editorAction("navigate.nextError", "Next Highlighted Error", "Navigate", (v) => gotoDiagnostic(v, 1)),
editorAction("navigate.prevError", "Previous Highlighted Error", "Navigate", (v) => gotoDiagnostic(v, -1)),
editorAction("code.showErrorDescription", "Error Description", "View", showErrorDescription, {
+2
Переглянути файл
@@ -1,3 +1,4 @@
import { MOVE_TO_FILE_COMMAND, moveToFile } from "./typescriptCommands";
import { serverCodeLenses } from "./serverCodeLens";
/**
* LSP-backed editor features: completion, diagnostics, hover / quick docs,
@@ -134,6 +135,7 @@ export function activate(): () => void {
registerOverlay({ id: "editor-lsp.extractInterfaceDialog", component: ExtractInterfaceDialog }),
registerOverlay({ id: "editor-lsp.memberChooser", component: MemberChooserDialog }),
registerClientCommand(JAVA_REFACTORING_COMMAND, runJavaRefactoringCommand),
registerClientCommand(MOVE_TO_FILE_COMMAND, moveToFile),
registerEditorBanner(outsideProjectBanner),
registerStatusItem({ id: "editor-lsp.usagesStatus", align: "left", priority: 10, component: UsagesStatus }),
// IDEA's Documentation tool window: right side, listed once F1 moved documentation there.
+51
Переглянути файл
@@ -0,0 +1,51 @@
import { describe, expect, it, vi } from "vitest";
import type { Command } from "@/bindings";
const lspMoveToFileTargets = vi.fn(async (_request: number, _doc: number, _command: Command) => ({
status: "ok" as const,
data: ["/p/src/util.ts", "/p/src/strings.ts", "/p/src/app.ts"],
}));
const lspExecuteCommand = vi.fn(async (_doc: number, _command: Command) => ({ status: "ok" as const, data: null }));
vi.mock("@/platform/ipc", async (orig) => {
const actual = await orig<typeof import("@/platform/ipc")>();
return { ...actual, isTauri: () => true, commands: { ...actual.commands, lspMoveToFileTargets, lspExecuteCommand } };
});
vi.mock("@/editor/api", async (orig) => ({
...(await orig<typeof import("@/editor/api")>()),
whenSynced: async () => {},
}));
const popups: { items: { label: string; run: () => void }[] }[] = [];
vi.mock("./popupStore", async (orig) => ({
...(await orig<typeof import("./popupStore")>()),
caretAnchor: () => ({ x: 0, y: 0 }),
openPopup: (p: (typeof popups)[number]) => popups.push(p),
}));
vi.mock("./lsp", async (orig) => ({
...(await orig<typeof import("./lsp")>()),
docOf: () => ({ doc: 7, path: "/p/src/util.ts", language: "typescript" }),
}));
const { moveToFile } = await import("./typescriptCommands");
describe("Move to File", () => {
it("offers tsserver's files but the source, then runs the command with the chosen one", async () => {
const action = { name: "Move to file", kind: "refactor.move.file" };
const range = { start: { line: 6, character: 16 }, end: { line: 6, character: 16 } };
const args = [action, "file:///p/src/util.ts", range];
const view = { state: { selection: { main: { head: 0 } } } } as never;
expect(await moveToFile(view, args)).toBe(true);
expect(lspMoveToFileTargets.mock.calls[0]![2].arguments).toEqual(args);
const items = popups[0]!.items;
expect(items.map((i) => i.label)).toEqual(["strings.ts", "app.ts", "Choose File…"]);
items[0]!.run();
await vi.waitFor(() => expect(lspExecuteCommand).toHaveBeenCalled());
expect(lspExecuteCommand.mock.calls[0]).toEqual([
7,
{
title: "Move to file",
command: "_typescript.moveToFileRefactoring",
arguments: [...args, "/p/src/strings.ts"],
},
]);
});
});
+162
Переглянути файл
@@ -0,0 +1,162 @@
/**
* vtsls' own TypeScript commands (`workspace/executeCommand`): Go to Source Definition, Go to
* Project Configuration, Open TS Server Log and the target file of Move to File. vtsls opens the
* configuration and the log itself (`window/showDocument`). typescript-language-server, TypeScript 7
* and the Vue / Astro servers have none of them.
*/
import type { EditorView } from "@codemirror/view";
import type { Command, Location } from "@/bindings";
import { whenSynced } from "@/editor/api";
import { tx } from "@/platform/i18n";
import { call, commands, isCancelled, nextRequestId } from "@/platform/ipc";
import { basename, dirname, relativePath, useProject } from "@/platform/project";
import { choosePath } from "@/platform/choosePath";
import { fileIconName } from "@/ui";
import { confirm } from "@/workbench/messages";
import { notifications } from "@/workbench/contributions";
import { showHint } from "./hint";
import { docOf, isUnavailable, lspRequest, reportLspError } from "./lsp";
import { locationItems, navigateTo } from "./navigation";
import { caretAnchor, openPopup } from "./popupStore";
import { offsetToPos } from "./positions";
export const TYPESCRIPT_LANGUAGES = ["typescript", "typescriptreact", "javascript", "javascriptreact"];
export const TYPESCRIPT_WHEN = TYPESCRIPT_LANGUAGES.map((id) => `editorLangId == ${id}`).join(" || ");
export const MOVE_TO_FILE_COMMAND = "_typescript.moveToFileRefactoring";
function report(view: EditorView, e: unknown) {
if (isUnavailable(e)) showHint(view, "This needs the vtsls TypeScript language server", { tone: "error" });
else reportLspError(view, e, true);
}
/** Navigate › Source Definition: the library's JavaScript instead of its `.d.ts`. */
export async function gotoSourceDefinition(view: EditorView) {
const ctx = docOf(view);
if (!ctx) return;
const head = view.state.selection.main.head;
let locs: Location[];
try {
await whenSynced(view);
const pos = offsetToPos(view.state.doc, head);
locs = await lspRequest(() => commands.lspSourceDefinition(nextRequestId(), ctx.doc, pos));
} catch (e) {
report(view, e);
return;
}
if (!locs.length) {
showHint(view, "Cannot find source definition", { tone: "error" });
return;
}
if (locs.length === 1) {
await navigateTo(locs[0]!);
return;
}
openPopup({
kind: "list",
anchor: caretAnchor(view, head),
title: tx("Choose Source Definition"),
items: await locationItems(locs),
});
}
/** Opens the `tsconfig.json` / `jsconfig.json` the file belongs to. */
export async function openProjectConfig(view: EditorView) {
const ctx = docOf(view);
if (!ctx) return;
try {
await lspRequest(() => commands.lspOpenTypescriptFile(ctx.doc, "projectConfig"));
} catch (e) {
report(view, e);
}
}
/** Opens the TS Server log, after offering to turn logging on (which restarts vtsls). */
export async function openTsServerLog(view: EditorView) {
const ctx = docOf(view);
if (!ctx) return;
const level = useProject.getState().settings?.languages?.typescript?.tsserverLog ?? "off";
if (level === "off") {
const ok = await confirm({
title: "Open TS Server Log",
message: tx("TS Server logging is off. Turn on verbose logging (typescript.tsserver.log) and restart vtsls?"),
ok: "Enable Logging",
});
if (!ok) return;
try {
const settings = await call(commands.settingsSet("global", "languages.typescript.tsserverLog", '"verbose"'));
useProject.setState({ settings });
} catch (e) {
reportLspError(view, e, true);
return;
}
notifications().notify({
level: "info",
title: "TS Server logging is on",
body: tx("vtsls restarts with logging. Run Open TS Server Log again to open the log."),
});
return;
}
try {
await lspRequest(() => commands.lspOpenTypescriptFile(ctx.doc, "serverLog"));
} catch (e) {
report(view, e);
}
}
/**
* vtsls' Move to File code action (`[action, uri, range]`): asks for the target file, tsserver's
* suggestions first, then runs the command with it appended. vtsls applies the moves and import
* updates as one workspace edit (one Undo).
*/
export async function moveToFile(view: EditorView, args: readonly unknown[]): Promise<boolean> {
const ctx = docOf(view);
if (!ctx) return false;
const command = (target?: string): Command => ({
title: "Move to file",
command: MOVE_TO_FILE_COMMAND,
// The arguments are JSON values (the bindings type them as strings).
arguments: (target === undefined ? args : [...args, target]) as string[],
});
let files: string[];
try {
await whenSynced(view);
files = await lspRequest(() => commands.lspMoveToFileTargets(nextRequestId(), ctx.doc, command()));
} catch (e) {
report(view, e);
return true;
}
const move = async (target: string) => {
try {
await whenSynced(view);
await lspRequest(() => commands.lspExecuteCommand(ctx.doc, command(target)));
} catch (e) {
if (!isCancelled(e)) report(view, e);
}
};
const root = useProject.getState().project?.root ?? "";
openPopup({
kind: "list",
anchor: caretAnchor(view, view.state.selection.main.head),
title: tx("Move to File"),
items: [
...files
.filter((f) => f !== ctx.path)
.map((f, i) => ({
id: `${i}`,
label: basename(f),
detail: relativePath(root, f),
icon: fileIconName(basename(f), f),
run: () => void move(f),
})),
{
id: "choose",
label: tx("Choose File…"),
run: () =>
void choosePath({ directory: false, title: tx("Move to File"), defaultPath: dirname(ctx.path) }).then((f) => {
if (f && f !== ctx.path) void move(f);
}),
},
],
});
return true;
}
+59 -3
Переглянути файл
@@ -7,19 +7,28 @@ import listStyles from "@/ui/List.module.css";
const listIdes = vi.fn();
const importJetBrainsSettings = vi.fn();
const notify = vi.fn();
const importRecent = vi.fn();
const loadRecent = vi.fn();
vi.mock("@/platform/ipc", async (original) => ({
...(await original<typeof import("@/platform/ipc")>()),
call: <T,>(result: Promise<T>) => result,
commands: { settingsListJetbrainsIdes: () => listIdes() },
commands: {
settingsListJetbrainsIdes: () => listIdes(),
recentImportJetbrains: (path: string, dryRun: boolean) => importRecent(path, dryRun),
},
}));
vi.mock("../jetbrainsSettings", () => ({ importJetBrainsSettings: (path: string) => importJetBrainsSettings(path) }));
vi.mock("../jetbrainsSettings", async (original) => ({
...(await original<typeof import("../jetbrainsSettings")>()),
importJetBrainsSettings: (path: string) => importJetBrainsSettings(path),
}));
vi.mock("@/features/welcome/recent", () => ({ loadRecent: () => loadRecent() }));
vi.mock("@/workbench/contributions", async (original) => ({
...(await original<typeof import("@/workbench/contributions")>()),
notifications: () => ({ notify }),
}));
const { importFromJetBrainsIde } = await import("../projectActions");
const { importFromJetBrainsIde, importJetBrainsRecentProjects } = await import("../projectActions");
const idea = {
ide: "IntelliJ IDEA 2025.2",
@@ -110,3 +119,50 @@ describe("Manage IDE Settings › Import Settings from JetBrains IDE…", () =>
expect(importJetBrainsSettings).toHaveBeenCalledExactlyOnceWith(ides[59]!.path);
});
});
describe("Import Recent Projects from JetBrains IDE…", () => {
async function pickFirst(run: () => Promise<void>) {
let done!: Promise<void>;
await act(async () => {
done = run();
});
const list = screen.getByRole("listbox", { name: "Import Recent Projects from JetBrains IDE" });
await act(async () => {
fireEvent.keyDown(list, { key: "Enter" });
await done;
});
}
it("merges the chosen IDE's recent projects, refreshes the list and says what it did", async () => {
listIdes.mockResolvedValue([idea, studio]);
importRecent.mockResolvedValue({ imported: 3, missing: 2, groups: 1 });
await pickFirst(importJetBrainsRecentProjects);
expect(importRecent).toHaveBeenCalledExactlyOnceWith(idea.path, false);
expect(loadRecent).toHaveBeenCalled();
expect(notify).toHaveBeenCalledWith(
expect.objectContaining({
level: "info",
title: "Recent projects imported",
body: "Imported 3 recent projects and 1 project groups, skipped 2 whose folder is missing.",
}),
);
});
it("warns when there is nothing new", async () => {
listIdes.mockResolvedValue([idea]);
importRecent.mockResolvedValue({ imported: 0, missing: 1, groups: 0 });
await pickFirst(importJetBrainsRecentProjects);
expect(notify).toHaveBeenCalledWith(
expect.objectContaining({ level: "warning", title: "No new recent projects to import" }),
);
});
it("reports a failure", async () => {
listIdes.mockResolvedValue([idea]);
importRecent.mockRejectedValue(new Error("denied"));
await pickFirst(importJetBrainsRecentProjects);
expect(notify).toHaveBeenCalledWith(
expect.objectContaining({ level: "error", title: "Cannot import recent projects" }),
);
});
});
+30
Переглянути файл
@@ -6,6 +6,8 @@ const set = vi.fn();
const notify = vi.fn();
const execute = vi.fn();
const marketCall = vi.fn();
const importRecent = vi.fn();
const loadRecent = vi.fn();
const market = [
{ id: "ruyimg.codeglance-pro", name: "CodeGlance Pro", installed: null, compatible: true },
{ id: "solhovoy.grep-console", name: "Grep Console", installed: null, compatible: true },
@@ -22,9 +24,11 @@ vi.mock("@/platform/ipc", async (original) => {
settingsGetGlobal: async () => ({ editor }),
settingsSet: (scope: string, key: string, value: string) => set(scope, key, value),
pluginMarket: () => marketCall(),
recentImportJetbrains: (path: string, dryRun: boolean) => importRecent(path, dryRun),
},
};
});
vi.mock("@/features/welcome/recent", () => ({ loadRecent: () => loadRecent() }));
vi.mock("@/platform/actions", async (original) => ({
...(await original<typeof import("@/platform/actions")>()),
executeAction: (id: string, arg?: unknown) => execute(id, arg),
@@ -58,6 +62,7 @@ beforeEach(() => {
});
set.mockResolvedValue({ status: "ok", data: { editor } });
marketCall.mockResolvedValue({ status: "ok", data: market });
importRecent.mockResolvedValue({ status: "ok", data: { imported: 0, missing: 0, groups: 0 } });
// jsdom has no canvas: the import falls back to the font size for the line height.
vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(null);
});
@@ -150,3 +155,28 @@ it("says so when the plugin marketplace cannot be reached, without blaming the p
expect(screen.getByText(/Plugins without a counterpart/)).not.toHaveTextContent("CodeGlancePro");
await act(async () => fireEvent.click(screen.getByRole("button", { name: "Cancel" })));
});
it("lists an IDE's recent projects and merges them on Import", async () => {
read.mockResolvedValue({ status: "ok", data: { entries: [], files: {} } });
importRecent.mockResolvedValue({ status: "ok", data: { imported: 4, missing: 1, groups: 2 } });
render(<MessagesHost />);
let done!: Promise<void>;
await act(async () => {
done = importJetBrainsSettings("/settings/IDE");
});
expect(importRecent).toHaveBeenCalledExactlyOnceWith("/settings/IDE", true);
expect(screen.getByText("Recent projects")).toBeInTheDocument();
expect(screen.getByText("4 new, 2 new project groups, 1 skipped (folder missing)")).toBeInTheDocument();
await act(async () => {
fireEvent.click(screen.getByRole("button", { name: "Import" }));
await done;
});
expect(importRecent).toHaveBeenLastCalledWith("/settings/IDE", false);
expect(loadRecent).toHaveBeenCalled();
expect(notify).toHaveBeenCalledWith(
expect.objectContaining({
title: "Settings imported",
body: "Imported 4 recent projects and 2 project groups, skipped 1 whose folder is missing.",
}),
);
});
+1
Переглянути файл
@@ -27,6 +27,7 @@ vi.mock("@/platform/ipc", async (original) => {
settingsGetGlobal: async () => ({ editor }),
settingsSet: (scope: string, key: string, value: string) => set(scope, key, value),
languages: async () => [python],
recentImportJetbrains: async () => ({ status: "ok", data: { imported: 0, missing: 0, groups: 0 } }),
},
};
});
+32 -3
Переглянути файл
@@ -6,7 +6,13 @@
* out). The rest is listed as not imported.
*/
import { Fragment, useEffect, useState } from "react";
import type { CustomKeymap, JetBrainsSettings, LanguageCodeStyle, LanguageInfo } from "@/bindings";
import type {
CustomKeymap,
JetBrainsRecentImport,
JetBrainsSettings,
LanguageCodeStyle,
LanguageInfo,
} from "@/bindings";
import { actionToggled, executeAction, getAction } from "@/platform/actions";
import { customSchemes } from "@/platform/colorScheme";
import { createFontProbeCanvas, fontsLoaded, monoFontFamily } from "@/platform/fonts";
@@ -18,6 +24,7 @@ import { guessOs } from "@/platform/platformInfo";
import { useProject } from "@/platform/project";
import { notifications } from "@/workbench/contributions";
import { ask } from "@/workbench/messages";
import { loadRecent } from "@/features/welcome/recent";
import { parseJetBrainsTemplates, type JetBrainsTemplateImport } from "@/features/templates/live/jetbrains";
import { saveImportedTemplates } from "@/features/templates/live/store";
import styles from "./app.module.css";
@@ -480,10 +487,25 @@ function Summary({ plan, pending }: { plan: JetBrainsImportPlan; pending?: Promi
);
}
/** What importing a JetBrains IDE's recent projects did. */
export function recentImportSummary({ imported, groups, missing }: JetBrainsRecentImport): string {
return tx`Imported ${imported} recent projects and ${groups} project groups, skipped ${missing} whose folder is missing.`;
}
/** Reads `path`, asks, then writes the mapped settings to the global layer. */
export async function importJetBrainsSettings(path: string) {
const bundle = await call(commands.settingsReadJetbrains(path));
const plan = await planJetBrainsImport(bundle, await commands.settingsGetGlobal());
// An IDE's settings folder (not an exported archive) has its recent projects.
const recent = await call(commands.recentImportJetbrains(path, true)).catch(() => null);
const hasRecent = !!recent && (recent.imported > 0 || recent.groups > 0);
if (hasRecent) {
const { imported, groups, missing } = recent;
plan.rows.push({
label: tx("Recent projects"),
value: tx`${imported} new, ${groups} new project groups, ${missing} skipped (folder missing)`,
});
}
const plugins = plan.plugins;
// Looked up while the confirmation is open; it shows the answer when it comes.
const pending = plugins?.candidates.length
@@ -491,7 +513,7 @@ export async function importJetBrainsSettings(path: string) {
.then((market) => suggestPlugins(plugins.candidates, market))
.catch(() => null)
: undefined;
if (!plan.writes.length && !plan.liveTemplates?.templates.length && !pending && !plugins?.vim) {
if (!plan.writes.length && !plan.liveTemplates?.templates.length && !pending && !plugins?.vim && !hasRecent) {
const details = [...plan.invalid, ...(plan.liveTemplates?.skipped ?? [])].join(", ");
notifications().notify({
level: "warning",
@@ -515,7 +537,14 @@ export async function importJetBrainsSettings(path: string) {
if (plan.liveTemplates?.templates.length) saveImportedTemplates(plan.liveTemplates.templates);
useProject.setState({ settings });
if (plugins?.vim && !actionToggled(getAction("vim.toggle"))) void executeAction("vim.toggle");
notifications().notify({ level: "info", title: "Settings imported", body: path, key: "app.settingsImport" });
const imported = hasRecent ? await call(commands.recentImportJetbrains(path, false)).catch(() => null) : null;
if (imported) void loadRecent();
notifications().notify({
level: "info",
title: "Settings imported",
body: imported ? recentImportSummary(imported) : path,
key: "app.settingsImport",
});
if (useProject.getState().project && plan.inspectionProfiles?.length)
offerInspectionProfiles(plan.inspectionProfiles);
void pending?.then((s) => s?.install.length && offerPlugins(s.install));
+53 -16
Переглянути файл
@@ -9,7 +9,8 @@ import { call, commands, isTauri } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { notifications, registerEditorBanner } from "@/workbench/contributions";
import { pickItems, promptInput } from "@/workbench/inputDialogs";
import { importJetBrainsSettings } from "./jetbrainsSettings";
import { loadRecent } from "@/features/welcome/recent";
import { importJetBrainsSettings, recentImportSummary } from "./jetbrainsSettings";
import { showNewProject } from "./NewProject";
import { tx } from "@/platform/i18n";
@@ -114,24 +115,30 @@ async function importSettings() {
}
}
/** The settings folder of the JetBrains IDE the user picks; undefined when none is installed or the pick is cancelled. */
async function pickJetBrainsIde(title: string): Promise<string | undefined> {
const ides = await call(commands.settingsListJetbrainsIdes());
if (!ides.length) {
notifications().notify({
level: "warning",
title: "No JetBrains IDE settings were found on this computer",
key: "app.settingsImport",
});
return;
}
const picked = await pickItems({
title,
items: ides.map((ide) => ({ key: ide.path, label: ide.ide })),
multiple: false,
});
return picked?.[0];
}
/** Import Settings from a JetBrains IDE installed on this computer, without exporting a `settings.zip` first. */
export async function importFromJetBrainsIde() {
try {
const ides = await call(commands.settingsListJetbrainsIdes());
if (!ides.length) {
notifications().notify({
level: "warning",
title: "No JetBrains IDE settings were found on this computer",
key: "app.settingsImport",
});
return;
}
const picked = await pickItems({
title: tx("Import Settings from JetBrains IDE"),
items: ides.map((ide) => ({ key: ide.path, label: ide.ide })),
multiple: false,
});
if (picked?.[0]) await importJetBrainsSettings(picked[0]);
const path = await pickJetBrainsIde(tx("Import Settings from JetBrains IDE"));
if (path) await importJetBrainsSettings(path);
} catch (e) {
notifications().notify({
level: "error",
@@ -142,6 +149,29 @@ export async function importFromJetBrainsIde() {
}
}
/** Adds the recent projects and project groups of a JetBrains IDE to the Welcome screen's. */
export async function importJetBrainsRecentProjects() {
try {
const path = await pickJetBrainsIde(tx("Import Recent Projects from JetBrains IDE"));
if (!path) return;
const result = await call(commands.recentImportJetbrains(path, false));
void loadRecent();
notifications().notify({
level: result.imported || result.groups ? "info" : "warning",
title: result.imported || result.groups ? "Recent projects imported" : "No new recent projects to import",
body: recentImportSummary(result),
key: "app.recentImport",
});
} catch (e) {
notifications().notify({
level: "error",
title: "Cannot import recent projects",
body: errorText(e),
key: "app.recentImport",
});
}
}
async function renameProject() {
const project = useProject.getState().project;
if (!project) return;
@@ -219,6 +249,13 @@ export function projectActions(): Action[] {
keywords: ["intellij", "pycharm", "webstorm", "android studio", "migrate", "manage ide settings"],
run: desktop(importFromJetBrainsIde),
},
{
id: "file.importJetBrainsRecentProjects",
title: "Import Recent Projects from JetBrains IDE…",
category: "File",
keywords: ["intellij", "pycharm", "webstorm", "android studio", "migrate", "project groups"],
run: desktop(importJetBrainsRecentProjects),
},
{
id: "file.togglePowerSave",
title: "Power Save Mode",
+30
Переглянути файл
@@ -0,0 +1,30 @@
import { afterEach, expect, it } from "vitest";
import { EditorSelection, EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { _setActiveEditor, type TextEditorHandle } from "@/editor/api";
import { editorSelectionText } from "../index";
const views: EditorView[] = [];
const view = (doc: string, from: number, to: number) => {
const v = new EditorView({
state: EditorState.create({ doc, selection: EditorSelection.single(from, to) }),
parent: document.body,
});
views.push(v);
return v;
};
afterEach(() => {
_setActiveEditor(null);
views.splice(0).forEach((v) => v.destroy());
});
it("takes the selection of the focused editor, such as the Find in Files preview, over the active one", () => {
const main = view("val first = 1", 4, 9);
_setActiveEditor({ view: main } as unknown as TextEditorHandle);
expect(editorSelectionText()).toBe("first");
const preview = view("fun second() {}", 4, 10);
preview.contentDOM.focus();
expect(editorSelectionText()).toBe("second");
preview.contentDOM.blur();
expect(editorSelectionText()).toBe("first");
});
+8 -2
Переглянути файл
@@ -3,6 +3,7 @@
* Recent Files / Recent Locations, Find / Replace in Files + the Find tool
* window, the Structure tool window + File Structure popup, and bookmarks.
*/
import { EditorView } from "@codemirror/view";
import { lazyComponent, lazyWhen } from "@/ui";
import { activeEditor, focusedCellEditor, registerEditorContribution } from "@/editor/api";
import { executeAction, registerActions } from "@/platform/actions";
@@ -82,8 +83,13 @@ async function removeMissingBookmarks(removed: readonly string[]) {
}
/** Single-line editor selection, used to prefill search fields. */
function editorSelectionText(): string | null {
const view = activeEditor()?.view;
/**
* The single-line selection a search starts from: the focused editor's (a Find in Files preview,
* a diff pane), else the active editor's, as IDEA reads it from the editor in the action's context.
*/
export function editorSelectionText(): string | null {
const focused = document.activeElement?.closest(".cm-editor");
const view = (focused instanceof HTMLElement ? EditorView.findFromDOM(focused) : null) ?? activeEditor()?.view;
if (!view) return null;
const { from, to } = view.state.selection.main;
if (from === to || to - from > 200) return null;
+15
Переглянути файл
@@ -738,9 +738,18 @@ export function MavenPage() {
// ---------------------------------------------------------------------------
// TypeScript
const LOG_LEVELS: SelectOption[] = [
{ value: "off", label: "Off" },
{ value: "terse", label: "Terse" },
{ value: "normal", label: "Normal" },
{ value: "requestTime", label: "Request time" },
{ value: "verbose", label: "Verbose" },
];
export function TypeScriptPage() {
const [version, setVersion] = useSetting<string>("languages.typescript.version");
const [memory, setMemory] = useSetting<number>("languages.typescript.tsserverMaxMemory");
const [log, setLog] = useSetting<string>("languages.typescript.tsserverLog");
const { list } = useDetected("typeScript");
const workspace = list.find((s) => s.source === "workspace");
const options = useMemo<SelectOption[]>(() => {
@@ -798,6 +807,12 @@ export function TypeScriptPage() {
aria-label="tsserver memory limit"
/>
</Row>
<Row
label="tsserver log"
hint="tsserver's log (typescript.tsserver.log), opened by TypeScript: Open TS Server Log. Changing it restarts vtsls; Off stops writing it."
>
<Select value={log ?? "off"} options={LOG_LEVELS} onChange={setLog} aria-label="tsserver log" />
</Row>
</Section>
</div>
);
+1 -1
Переглянути файл
@@ -398,7 +398,7 @@ export const LANGUAGE_PAGES: PageSpec[] = [
title: "TypeScript",
group: LANGUAGES_GROUP,
order: 405,
keywords: ["typescript version", "tsdk", "tsserver", "node_modules", "vtsls"],
keywords: ["typescript version", "tsdk", "tsserver", "node_modules", "vtsls", "tsserver log"],
component: TypeScriptPage,
},
{
+7
Переглянути файл
@@ -308,6 +308,13 @@ describe("Git Log commit actions", () => {
"Fix_crash_on_start.patch",
);
expect(suggestedPatchName({ kind: "commits", commits: [commit("a"), commit("b")] }, "x")).toBe("2_commits.patch");
expect(
suggestedPatchName({ kind: "logChanges", changes: [], commits: [commit("Fix: historical file!")] }, "x"),
).toBe("Fix_historical_file.patch");
expect(suggestedPatchName({ kind: "logChanges", changes: [], commits: [commit("a"), commit("b")] }, "x")).toBe(
"2_commits.patch",
);
expect(suggestedPatchName({ kind: "logChanges", changes: [], commits: [] }, "Changes")).toBe("0_files.patch");
expect(suggestedPatchName({ kind: "changes", files: [] }, "///")).toBe("changes.patch");
});
});
+83
Переглянути файл
@@ -42,10 +42,12 @@ import { graphOptionsMenu } from "../log/FilterBar";
import {
EMPTY_TREE,
assignLineStats,
canCreatePatchFromLogChanges,
filesUnder,
filterPatch,
flatFileNodes,
lineStatRanges,
logPatchRanges,
toLogChanges,
useLogChanges,
} from "../logChanges";
@@ -122,6 +124,78 @@ describe("changed files model", () => {
expect(rootFile!.statsFrom).toBe(EMPTY_TREE);
});
it("builds path-filtered historical patch ranges, including empty trees and both rename paths", () => {
const previous = useVcs.getState();
useVcs.setState({ root: "/repo", repo: "/repo", roots: ["/repo"] });
try {
const older: Commit = { ...commit, id: "a".repeat(40), parents: ["9".repeat(40)], timeMs: 1 };
const newer: Commit = { ...commit, id: "b".repeat(40), parents: [older.id], timeMs: 2 };
const changes = [
...toLogChanges([{ path: "added.ts", kind: "added", oldPath: null }], older, "/repo"),
...toLogChanges([{ path: "edited.ts", kind: "modified", oldPath: null }], newer, "/repo"),
...toLogChanges([{ path: "new.ts", kind: "renamed", oldPath: "old.ts" }], newer, "/repo"),
...toLogChanges([{ path: "deleted.ts", kind: "deleted", oldPath: null }], newer, "/repo"),
];
const paths = ["edited.ts", "new.ts", "old.ts"];
expect(canCreatePatchFromLogChanges(changes)).toBe(true);
expect(logPatchRanges(changes)).toEqual([
{ repo: "/repo", before: EMPTY_TREE, after: older.id, paths: ["added.ts"] },
{ repo: "/repo", before: older.id, after: newer.id, paths },
{ repo: "/repo", before: older.id, after: EMPTY_TREE, paths: ["deleted.ts"] },
]);
expect(logPatchRanges(changes, true)).toEqual([
{ repo: "/repo", before: older.id, after: EMPTY_TREE, paths: ["added.ts"] },
{ repo: "/repo", before: newer.id, after: older.id, paths },
{ repo: "/repo", before: EMPTY_TREE, after: older.id, paths: ["deleted.ts"] },
]);
const other = { ...changes[1]!, repo: "/other" };
useVcs.setState({ roots: ["/repo", "/other"] });
expect(canCreatePatchFromLogChanges([changes[0]!, other])).toBe(false);
expect(logPatchRanges([changes[0]!, other])).toEqual([]);
const ambiguous = { ...changes[0]!, repo: null };
expect(canCreatePatchFromLogChanges([ambiguous])).toBe(false);
expect(canCreatePatchFromLogChanges([{ ...changes[0]!, readOnly: true }])).toBe(true);
expect(canCreatePatchFromLogChanges([{ ...changes[0]!, repo: "/external", readOnly: true }])).toBe(false);
expect(canCreatePatchFromLogChanges([{ ...changes[0]!, oldPath: 42 as unknown as string }])).toBe(false);
expect(canCreatePatchFromLogChanges([{ ...changes[0]!, before: newer.id, after: newer.id }])).toBe(false);
expect(canCreatePatchFromLogChanges([])).toBe(false);
} finally {
useVcs.setState(previous);
}
});
it("enables changed-file patch actions and menu rows only for an applicable selection", () => {
const previous = useVcs.getState();
useVcs.setState({ root: "/repo", repo: "/repo", roots: ["/repo", "/other"] });
const files = toLogChanges(
[
{ path: "a.ts", kind: "modified", oldPath: null },
{ path: "b.ts", kind: "modified", oldPath: null },
],
commit,
"/repo",
);
const dispose = registerLogPaneActions();
try {
for (const id of ["vcs.log.changes.createPatch", "vcs.log.changes.copyPatch"]) {
const action = getAction(id)!;
expect(action.enabled!({ ctx: {}, arg: [] })).toBe(false);
expect(action.enabled!({ ctx: {}, arg: files })).toBe(true);
expect(action.enabled!({ ctx: {}, arg: [{ ...files[0]!, repo: "/other" }] })).toBe(true);
expect(action.enabled!({ ctx: {}, arg: [{ ...files[0]!, repo: "/external" }] })).toBe(false);
const item = (changes: ReturnType<typeof toLogChanges>) =>
changesMenu(changes).find((entry) => "action" in entry && entry.action === id);
expect(item(files)).toMatchObject({ arg: files, disabled: false });
expect(item([])).toMatchObject({ disabled: true });
expect(item([{ ...files[0]!, repo: "/external" }])).toMatchObject({ disabled: true });
}
} finally {
dispose();
useVcs.setState(previous);
}
});
it("asks for one numstat per revision pair and matches a rename by either name", () => {
const files = toLogChanges(
[
@@ -265,6 +339,8 @@ describe("rename label", () => {
describe("changed files pane", () => {
it("shows the files flat or by directory and shares the selection with its actions", async () => {
const previous = useVcs.getState();
useVcs.setState({ root: "/repo", repo: "/repo", roots: ["/repo"] });
vcsCommitFiles.mockResolvedValue({
status: "ok",
data: [
@@ -275,10 +351,16 @@ describe("changed files pane", () => {
useGitLog.setState({ commits: [commit], selected: commit.id, selection: [commit.id] });
const { unmount } = render(<CommitDetails commits={[commit]} />);
expect(await screen.findByText("src")).toBeInTheDocument();
const createPatch = screen.getByRole("button", { name: "Create Patch…" });
const copyPatch = screen.getByRole("button", { name: "Copy as Patch to Clipboard" });
expect(createPatch).toBeDisabled();
expect(copyPatch).toBeDisabled();
fireEvent.mouseDown(screen.getByText("a.ts"));
expect(useLogChanges.getState().selected.map((c) => c.path)).toEqual(["src/a.ts"]);
expect(useLogChanges.getState().commits).toEqual([commit]);
expect(screen.getByRole("button", { name: "Show Diff" })).toBeEnabled();
expect(createPatch).toBeEnabled();
expect(copyPatch).toBeEnabled();
useLogOptions.setState({ groupByDirectory: false });
expect(await screen.findByText("b.ts")).toBeInTheDocument();
@@ -286,6 +368,7 @@ describe("changed files pane", () => {
expect(screen.getAllByText("src")).toHaveLength(2);
unmount();
expect(useLogChanges.getState().selected).toEqual([]);
useVcs.setState(previous);
});
it("shows added and deleted lines when the log option is on", async () => {
+118
Переглянути файл
@@ -0,0 +1,118 @@
import type { Commit, PatchSource } from "@/bindings";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
createPatch: vi.fn(),
writeClipboardText: vi.fn(),
openDialog: vi.fn(),
notify: vi.fn(),
}));
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
return {
...real,
commands: {
...real.commands,
vcsCreatePatch: (repo: string | null, source: PatchSource, base: string | null) =>
mocks.createPatch(repo, source, base),
},
};
});
vi.mock("@/platform/clipboard", async (importOriginal) => ({
...(await importOriginal<typeof import("@/platform/clipboard")>()),
writeClipboardText: mocks.writeClipboardText,
}));
vi.mock("../dialogs", async (importOriginal) => ({
...(await importOriginal<typeof import("../dialogs")>()),
openDialog: mocks.openDialog,
}));
vi.mock("@/workbench/contributions", async (importOriginal) => ({
...(await importOriginal<typeof import("@/workbench/contributions")>()),
notifications: () => ({ notify: mocks.notify }),
}));
import { EMPTY_TREE, toLogChanges } from "../logChanges";
import { copyLogChangesAsPatch } from "../patches";
import { useVcs } from "../store";
const commit = (id: string, parents: string[], timeMs: number): Commit => ({
id: id.repeat(40),
shortId: id.repeat(8),
parents,
author: "A",
email: "[email protected]",
timeMs,
summary: `Commit ${id}`,
message: `Commit ${id}`,
refs: [],
});
const originalVcs = useVcs.getState();
beforeEach(() => {
mocks.createPatch.mockReset();
mocks.writeClipboardText.mockReset();
mocks.openDialog.mockReset();
mocks.notify.mockReset();
mocks.writeClipboardText.mockResolvedValue(undefined);
useVcs.setState({ root: "/repo", repo: "/repo", roots: ["/repo"] });
});
afterEach(() => useVcs.setState(originalVcs));
describe("Git Log changed-file patches", () => {
it("copies exactly the selected revision/path ranges, with both names of a rename", async () => {
const older = commit("a", ["9".repeat(40)], 1);
const newer = commit("b", [older.id], 2);
const changes = [
...toLogChanges([{ path: "added.ts", kind: "added", oldPath: null }], older, "/repo"),
...toLogChanges([{ path: "edited.ts", kind: "modified", oldPath: null }], newer, "/repo"),
...toLogChanges([{ path: "new.ts", kind: "renamed", oldPath: "old.ts" }], newer, "/repo"),
];
mocks.createPatch.mockImplementation(async (_repo: string, source: PatchSource) => ({
status: "ok" as const,
data: source.from === "revisions" ? `patch ${source.before} ${source.after} ${source.paths.join(",")}\n` : "",
}));
await copyLogChangesAsPatch(changes);
expect(mocks.createPatch.mock.calls).toEqual([
["/repo", { from: "revisions", before: EMPTY_TREE, after: older.id, paths: ["added.ts"] }, null],
[
"/repo",
{
from: "revisions",
before: older.id,
after: newer.id,
paths: ["edited.ts", "new.ts", "old.ts"],
},
null,
],
]);
expect(mocks.writeClipboardText).toHaveBeenCalledExactlyOnceWith(
`patch ${EMPTY_TREE} ${older.id} added.ts\npatch ${older.id} ${newer.id} edited.ts,new.ts,old.ts\n`,
);
expect(mocks.openDialog).not.toHaveBeenCalled();
});
it("does not touch the clipboard for empty, mixed-repository or external read-only selections", async () => {
const c = commit("c", ["9".repeat(40)], 1);
const files = toLogChanges([{ path: "a.ts", kind: "modified", oldPath: null }], c, "/repo");
await copyLogChangesAsPatch([]);
await copyLogChangesAsPatch([files[0]!, { ...files[0]!, repo: "/other" }]);
await copyLogChangesAsPatch([{ ...files[0]!, repo: "/external", readOnly: true }]);
expect(mocks.createPatch).not.toHaveBeenCalled();
expect(mocks.writeClipboardText).not.toHaveBeenCalled();
});
it("leaves the clipboard untouched when Git returns an empty patch", async () => {
const c = commit("c", ["9".repeat(40)], 1);
const files = toLogChanges([{ path: "a.ts", kind: "modified", oldPath: null }], c, "/repo");
mocks.createPatch.mockResolvedValue({ status: "ok", data: "" });
await copyLogChangesAsPatch(files);
expect(mocks.writeClipboardText).not.toHaveBeenCalled();
expect(mocks.notify).toHaveBeenCalledWith(
expect.objectContaining({ group: "vcs", level: "info", title: "No changes to create a patch from" }),
);
});
});
+30
Переглянути файл
@@ -40,6 +40,7 @@ import { buildFileTree, dirKeys, type FileTreeNode } from "../fileTree";
import styles from "../GitLog.module.css";
import {
canApplySelectedChanges,
canCreatePatchFromLogChanges,
canOpenRepositoryVersion,
absolutePath,
changesArg,
@@ -412,6 +413,22 @@ export function CommitDetails({ commits, fileHistory = false }: { commits: Commi
actionArg={chosenChanges}
disabled={!chosenChanges.length}
/>
<IconButton
icon="patch"
size="small"
title="Create Patch…"
action="vcs.log.changes.createPatch"
actionArg={chosenChanges}
disabled={!canCreatePatchFromLogChanges(chosenChanges)}
/>
<IconButton
icon="copy"
size="small"
title="Copy as Patch to Clipboard"
action="vcs.log.changes.copyPatch"
actionArg={chosenChanges}
disabled={!canCreatePatchFromLogChanges(chosenChanges)}
/>
<IconButton
icon="revert"
size="small"
@@ -590,6 +607,19 @@ export function changesMenu(changes: LogChange[], source?: { commit: Commit; tot
disabled: !canOpenRepositoryVersion(changes),
},
{ kind: "separator" },
{
kind: "action",
action: "vcs.log.changes.createPatch",
arg: changes,
disabled: !canCreatePatchFromLogChanges(changes),
},
{
kind: "action",
action: "vcs.log.changes.copyPatch",
arg: changes,
disabled: !canCreatePatchFromLogChanges(changes),
},
{ kind: "separator" },
{
kind: "action",
action: "vcs.log.changes.apply",
+61 -1
Переглянути файл
@@ -23,7 +23,7 @@ import type { FileTreeNode } from "./fileTree";
import { baseName } from "./model";
import { readWorkingText, runOp, saveAll, writeFileText } from "./ops";
import { reportApply } from "./shelf";
import { currentRepoRoot } from "./store";
import { currentRepoRoot, useVcs } from "./store";
import { commitRepo } from "./multiRoot";
import { repositoryPath } from "./repositoryPaths";
import { confirmDialog } from "./dialogs";
@@ -156,6 +156,66 @@ export async function withLineStats(files: LogChange[]): Promise<LogChange[]> {
return assignLineStats(files, loaded);
}
/** One repository's selected historical files between the same two revisions. */
export interface LogPatchRange {
repo: string;
before: string;
after: string;
paths: string[];
}
/**
* The repository a historical patch can safely use. A missing row repository is
* unambiguous only when the project has one root; otherwise callers must retain it.
*/
export function logPatchRepository(changes: readonly LogChange[]): string | null {
if (!changes.length) return null;
const state = useVcs.getState();
const fallback = state.roots.length === 1 ? state.roots[0]! : state.roots.length ? null : (state.repo ?? state.root);
const repo = changes[0]!.repo ?? fallback;
if (!repo || changes.some((change) => (change.repo ?? fallback) !== repo)) return null;
return state.roots.length && !state.roots.includes(repo) ? null : repo;
}
/** Create Patch is an export: empty, malformed, read-only external and mixed-repository selections cannot use it. */
export function canCreatePatchFromLogChanges(changes: readonly LogChange[]): boolean {
if (!changes.length || !logPatchRepository(changes)) return false;
return (
changes.every(
(change) =>
typeof change.path === "string" &&
change.path.length > 0 &&
(change.oldPath === null || (typeof change.oldPath === "string" && change.oldPath.length > 0)) &&
(change.before === null || (typeof change.before === "string" && change.before.length > 0)) &&
(change.after === null || (typeof change.after === "string" && change.after.length > 0)) &&
(change.before !== null || change.after !== null),
) && changes.some((change) => (change.before ?? EMPTY_TREE) !== (change.after ?? EMPTY_TREE))
);
}
/**
* Path-filtered revision diffs for exactly the selected rows. Added and deleted
* files use Git's empty tree on their missing side; renames include both names.
* Reversing swaps each range's endpoints, including the empty tree.
*/
export function logPatchRanges(changes: readonly LogChange[], reverse = false): LogPatchRange[] {
if (!canCreatePatchFromLogChanges(changes)) return [];
const repo = logPatchRepository(changes)!;
const ranges = new Map<string, LogPatchRange>();
for (const change of changes) {
const before = (reverse ? change.after : change.before) ?? EMPTY_TREE;
const after = (reverse ? change.before : change.after) ?? EMPTY_TREE;
if (before === after) continue;
const key = `${before}\0${after}`;
let range = ranges.get(key);
if (!range) ranges.set(key, (range = { repo, before, after, paths: [] }));
for (const path of change.oldPath ? [change.path, change.oldPath] : [change.path]) {
if (path && !range.paths.includes(path)) range.paths.push(path);
}
}
return [...ranges.values()];
}
/** Files without directory grouping: by name, each node's path shown next to it. */
export function flatFileNodes<F>(files: readonly F[], relPath: (f: F) => string): FileTreeNode<F>[] {
return files
+24
Переглянути файл
@@ -18,6 +18,7 @@ import {
import { isFavoriteBranch } from "./branches";
import {
applySelectedChanges,
canCreatePatchFromLogChanges,
canOpenRepositoryVersion,
changesArg,
compareChangesWithLocal,
@@ -32,6 +33,7 @@ import { logOptions } from "./logOptions";
import { goToRef, selectedCommits, toggleCherryHighlight, updateLogOptions, useGitLog } from "./logStore";
import { commitKey, commitRepo } from "./multiRoot";
import { dropSelectedChanges, extractSelectedChanges } from "./rebase";
import { copyLogChangesAsPatch, showCreatePatchForLogChanges } from "./patches";
import { openRevisionFile } from "./revisionInput";
import { currentRepoRoot, focusRepo } from "./store";
import { showCompareBranches, type BranchComparisonTarget, type BranchComparisonData } from "./CompareBranches";
@@ -301,6 +303,28 @@ export function registerLogPaneActions(): () => void {
}
},
},
{
id: "vcs.log.changes.createPatch",
title: "Create Patch…",
category: "Git Log",
icon: "patch",
when: LOG,
hidden: true,
keyWhen: "vcsLogChangesFocus",
enabled: ({ arg }) => canCreatePatchFromLogChanges(changesArg(arg)),
run: ({ arg }) => showCreatePatchForLogChanges(changesArg(arg), useLogChanges.getState().commits),
},
{
id: "vcs.log.changes.copyPatch",
title: "Copy as Patch to Clipboard",
category: "Git Log",
icon: "copy",
when: LOG,
hidden: true,
keyWhen: "vcsLogChangesFocus",
enabled: ({ arg }) => canCreatePatchFromLogChanges(changesArg(arg)),
run: ({ arg }) => copyLogChangesAsPatch(changesArg(arg)),
},
{
id: "vcs.log.changes.getFromRevision",
title: "Get from Revision",
+49 -5
Переглянути файл
@@ -1,5 +1,6 @@
import { readClipboardPlainText, writeClipboardText } from "@/platform/clipboard";
import { commitRepo } from "./multiRoot";
import { canCreatePatchFromLogChanges, logPatchRanges, logPatchRepository, type LogChange } from "./logChanges";
/** Create Patch… (from local changes or commits) and Apply Patch… (file or clipboard, with a preview). */
import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
import type {
@@ -68,15 +69,20 @@ import { useDiffSource } from "./diffSource";
export type PatchOrigin =
| { kind: "changes"; files: FileStatus[]; staging?: readonly StagingPatchEntry[] }
| { kind: "commits"; commits: Commit[] }
| { kind: "logChanges"; changes: LogChange[]; commits: Commit[] }
| { kind: "shelf"; entry: ShelvedChangeList; path?: string };
/** File name IDEA suggests: the change list or commit subject, sanitised. */
export function suggestedPatchName(origin: PatchOrigin, listName: string): string {
const base =
origin.kind === "commits"
origin.kind === "commits" || origin.kind === "logChanges"
? origin.commits.length === 1
? origin.commits[0]!.summary
: `${origin.commits.length} commits`
: origin.commits.length > 1
? `${origin.commits.length} commits`
: origin.kind === "logChanges"
? `${origin.changes.length} files`
: "0 commits"
: origin.kind === "shelf"
? origin.entry.name
: listName;
@@ -160,6 +166,38 @@ export function showCreatePatchForCommits(commits: Commit[]) {
openDialog((close) => <CreatePatchDialog origin={{ kind: "commits", commits }} onClose={close} />);
}
async function createLogChangesPatch(changes: readonly LogChange[], reverse: boolean, base: string | null) {
const patches = await Promise.all(
logPatchRanges(changes, reverse).map(({ repo, before, after, paths }) =>
call(commands.vcsCreatePatch(repo, { from: "revisions", before, after, paths }, base)),
),
);
return patches.join("");
}
export function showCreatePatchForLogChanges(changes: LogChange[], commits: Commit[]) {
if (!canCreatePatchFromLogChanges(changes)) return;
openDialog((close) => <CreatePatchDialog origin={{ kind: "logChanges", changes, commits }} onClose={close} />);
}
/** Copy the selected historical files as a patch directly, without the Create Patch dialog. */
export async function copyLogChangesAsPatch(changes: readonly LogChange[]) {
if (!canCreatePatchFromLogChanges(changes)) return;
await runOp(
tx("Create patch"),
async () => {
const patch = await createLogChangesPatch(changes, false, null);
if (!patch) {
noPatchChanges();
return false;
}
await writeClipboardText(patch);
return true;
},
{ success: (copied) => (copied ? "Patch copied to the clipboard" : ""), refresh: false },
);
}
export function showCreatePatchForShelf(entry: ShelvedChangeList, path?: string) {
openDialog((close) => <CreatePatchDialog origin={{ kind: "shelf", entry, path }} onClose={close} />);
}
@@ -220,7 +258,11 @@ function CreatePatchDialog({ origin, onClose }: { origin: PatchOrigin; onClose:
const root = useVcs((s) => s.root) ?? "";
const roots = useVcs((s) => s.roots);
const [repo] = useState(() =>
origin.kind === "commits" ? (commitRepo(origin.commits[0]!) ?? currentRepoRoot()) : currentRepoRoot(),
origin.kind === "commits"
? (commitRepo(origin.commits[0]!) ?? currentRepoRoot())
: origin.kind === "logChanges"
? (logPatchRepository(origin.changes) ?? currentRepoRoot())
: currentRepoRoot(),
);
const listName = useChangelists((s) => activeList(s.state).name);
const [selected, setSelected] = useState(
@@ -254,7 +296,7 @@ function CreatePatchDialog({ origin, onClose }: { origin: PatchOrigin; onClose:
setPending(true);
setError("");
const source: PatchSource | null =
origin.kind === "shelf"
origin.kind === "shelf" || origin.kind === "logChanges"
? null
: origin.kind === "changes"
? localPatchSource(origin, selected, reverse)
@@ -273,7 +315,9 @@ function CreatePatchDialog({ origin, onClose }: { origin: PatchOrigin; onClose:
? await call(
commands.vcsShelfPatch(origin.entry.id, origin.path ?? null, baseInput === null ? null : directory),
)
: await call(commands.vcsCreatePatch(origin.kind === "commits" ? repo : null, source!, directory));
: origin.kind === "logChanges"
? await createLogChangesPatch(origin.changes, reverse, directory)
: await call(commands.vcsCreatePatch(origin.kind === "commits" ? repo : null, source!, directory));
if (!patch) {
noPatchChanges();
return false;
+1
Переглянути файл
@@ -206,6 +206,7 @@ describe(":action ids", () => {
"editor.splitDown",
"vcs.update",
"vcs.copyBranchName",
"navigate.selectInProjectView",
]);
const missing = Object.entries(IDEA_ACTIONS).filter(([, id]) => !known.has(id));
expect(missing).toEqual([]);
+7
Переглянути файл
@@ -70,6 +70,13 @@ function HeaderButtons() {
const secondary: MenuItem[] = [
{ kind: "action", action: "file.newUntitled", label: "New File", disabled: opening },
{ kind: "action", action: "file.openFile", label: "Open File", disabled: opening },
{ kind: "separator" },
{
kind: "action",
action: "file.importJetBrainsRecentProjects",
label: "Import Recent Projects from JetBrains IDE…",
disabled: opening,
},
];
return (
<div className={styles.headerButtons} role="group" aria-label={tx("Project actions")}>
+2
Переглянути файл
@@ -122,6 +122,8 @@ describe("IDEA keymap parity", () => {
// Vcs.Log.GoToRef: Find in the Git Log table.
["vcs.log.goToRef", ["Meta+F"], ["Ctrl+F"]],
["vcs.log.maximizeCommitMessage", [], []],
["vcs.log.changes.createPatch", [], []],
["vcs.log.changes.copyPatch", [], []],
["vcs.log.refresh", ["Meta+R"], ["Ctrl+F5"]],
["vcs.log.focusTextFilter", ["Ctrl+L"], ["Ctrl+L"]],
// Back / Forward also carry the mouse side buttons (`<mouse-shortcut keystroke="button4"/>`).
+2
Переглянути файл
@@ -389,6 +389,8 @@ export const intellijMacos: Record<string, string[]> = {
"vcs.addToVcs": ["Meta+Alt+A"],
"vcs.showDiff": ["Meta+D"],
"vcs.log.changes.showDiff": ["Meta+D"],
"vcs.log.changes.createPatch": [],
"vcs.log.changes.copyPatch": [],
"vcs.showDiffInNewWindow": [],
"vcs.nextChange": ["Ctrl+Alt+Shift+Down"],
"vcs.prevChange": ["Ctrl+Alt+Shift+Up"],
+2
Переглянути файл
@@ -383,6 +383,8 @@ export const intellijWindows: Record<string, string[]> = {
"vcs.addToVcs": ["Ctrl+Alt+A"],
"vcs.showDiff": ["Ctrl+D"],
"vcs.log.changes.showDiff": ["Ctrl+D"],
"vcs.log.changes.createPatch": [],
"vcs.log.changes.copyPatch": [],
"vcs.showDiffInNewWindow": [],
"vcs.nextChange": ["Ctrl+Alt+Shift+Down"],
"vcs.prevChange": ["Ctrl+Alt+Shift+Up"],
+3
Переглянути файл
@@ -402,6 +402,8 @@ export const vscodeMacos: Record<string, string[]> = {
"vcs.addToVcs": [],
"vcs.showDiff": [],
"vcs.log.changes.showDiff": [],
"vcs.log.changes.createPatch": [],
"vcs.log.changes.copyPatch": [],
"vcs.showDiffInNewWindow": [],
"vcs.nextChange": ["Alt+F5"],
"vcs.prevChange": ["Alt+Shift+F5"],
@@ -513,6 +515,7 @@ export const vscodeMacos: Record<string, string[]> = {
"db.showDiagram": [],
"db.showDiagramPopup": [],
"db.selectOpened": [],
"project.selectOpenedFile": [],
"db.expandAll": [],
"db.collapseAll": [],
// Find in Files popup (findPopupOpen): after the editor's keys, so these win while it is open.
+2
Переглянути файл
@@ -307,6 +307,7 @@
"menu.navigate.showBookmarks": "Show Bookmarks",
"menu.navigate.toggleBookmark": "Toggle Bookmark",
"menu.navigate.typeDeclaration": "Type Declaration",
"menu.navigate.sourceDefinition": "Source Definition",
"menu.navigate.typeHierarchy": "Type Hierarchy",
"menu.navigate.superMethod": "Super Method",
"menu.navigate.gotoTest": "Test",
@@ -465,6 +466,7 @@
"menu.file.exportSettings": "Export Settings…",
"menu.file.importSettings": "Import Settings…",
"menu.file.importJetBrainsSettings": "Import Settings from JetBrains IDE…",
"menu.file.importJetBrainsRecentProjects": "Import Recent Projects from JetBrains IDE…",
"menu.file.syncSettings": "Sync Settings Now",
"menu.file.togglePowerSave": "Power Save Mode",
"menu.macros": "Macros",
+8
Переглянути файл
@@ -4812,5 +4812,13 @@
"xcodebuild doesn't compile it until it's in a target of {name}. Add it in Xcode or convert the group to a folder.": "xcodebuild doesn't compile it until it's in a target of {name}. Add it in Xcode or convert the group to a folder.",
"xcodebuild doesn't compile {files} until they're in a target of {name}. Add them in Xcode or convert the group to a folder.": "xcodebuild doesn't compile {files} until they're in a target of {name}. Add them in Xcode or convert the group to a folder.",
"Open in Xcode": "Open in Xcode",
"Import Recent Projects from JetBrains IDE": "Import Recent Projects from JetBrains IDE",
"Import Recent Projects from JetBrains IDE…": "Import Recent Projects from JetBrains IDE…",
"Recent projects imported": "Recent projects imported",
"No new recent projects to import": "No new recent projects to import",
"Cannot import recent projects": "Cannot import recent projects",
"Recent projects": "Recent projects",
"Imported {imported} recent projects and {groups} project groups, skipped {missing} whose folder is missing.": "Imported {imported} recent projects and {groups} project groups, skipped {missing} whose folder is missing.",
"{imported} new, {groups} new project groups, {missing} skipped (folder missing)": "{imported} new, {groups} new project groups, {missing} skipped (folder missing)",
"Plugin navigation covers {count} of {total} files in {project}; exclude folders to narrow it": "Plugin navigation covers {count} of {total} files in {project}; exclude folders to narrow it"
}
+27 -1
Переглянути файл
@@ -11465,5 +11465,31 @@
"xcodebuild doesn't compile it until it's in a target of {name}. Add it in Xcode or convert the group to a folder.": "在加入 {name} 的某个 target 之前,xcodebuild 不会编译它。请在 Xcode 中添加,或把该组转换为文件夹。",
"xcodebuild doesn't compile {files} until they're in a target of {name}. Add them in Xcode or convert the group to a folder.": "在加入 {name} 的某个 target 之前,xcodebuild 不会编译 {files}。请在 Xcode 中添加,或把该组转换为文件夹。",
"Open in Xcode": "在 Xcode 中打开",
"Plugin navigation covers {count} of {total} files in {project}; exclude folders to narrow it": "插件导航仅覆盖 {project} 中 {total} 个文件里的 {count} 个;可排除文件夹以缩小范围"
"Plugin navigation covers {count} of {total} files in {project}; exclude folders to narrow it": "插件导航仅覆盖 {project} 中 {total} 个文件里的 {count} 个;可排除文件夹以缩小范围",
"Source Definition": "源定义",
"Go to Source Definition": "转到源定义",
"Go to Project Configuration": "转到项目配置",
"Open TS Server Log": "打开 TS Server 日志",
"This needs the vtsls TypeScript language server": "此功能需要 vtsls TypeScript 语言服务器",
"Cannot find source definition": "找不到源定义",
"Choose Source Definition": "选择源定义",
"TS Server logging is off. Turn on verbose logging (typescript.tsserver.log) and restart vtsls?": "TS Server 日志已关闭。是否开启详细日志(typescript.tsserver.log)并重启 vtsls?",
"Enable Logging": "开启日志",
"TS Server logging is on": "TS Server 日志已开启",
"vtsls restarts with logging. Run Open TS Server Log again to open the log.": "vtsls 将开启日志并重启。再次运行“打开 TS Server 日志”即可打开日志。",
"Move to file": "移动到文件",
"Move to File": "移动到文件",
"Terse": "简略",
"Normal": "普通",
"Request time": "请求耗时",
"Verbose": "详细",
"tsserver log": "tsserver 日志",
"tsserver's log (typescript.tsserver.log), opened by TypeScript: Open TS Server Log. Changing it restarts vtsls; Off stops writing it.": "tsserver 的日志(typescript.tsserver.log),由“TypeScript: 打开 TS Server 日志”打开。更改后会重启 vtsls;选“关”则停止写入。",
"Import Recent Projects from JetBrains IDE": "从 JetBrains IDE 导入最近项目",
"Import Recent Projects from JetBrains IDE…": "从 JetBrains IDE 导入最近项目…",
"Recent projects imported": "已导入最近项目",
"No new recent projects to import": "没有可导入的新最近项目",
"Cannot import recent projects": "无法导入最近项目",
"Imported {imported} recent projects and {groups} project groups, skipped {missing} whose folder is missing.": "已导入 {imported} 个最近项目和 {groups} 个项目分组,跳过 {missing} 个文件夹已不存在的项目。",
"{imported} new, {groups} new project groups, {missing} skipped (folder missing)": "新增 {imported} 个,新增 {groups} 个项目分组,跳过 {missing} 个(文件夹已不存在)"
}
+2
Переглянути файл
@@ -307,6 +307,7 @@
"menu.navigate.showBookmarks": "显示书签",
"menu.navigate.toggleBookmark": "切换书签",
"menu.navigate.typeDeclaration": "类型声明",
"menu.navigate.sourceDefinition": "源定义",
"menu.navigate.typeHierarchy": "类型层次结构",
"menu.navigate.superMethod": "super 方法",
"menu.navigate.gotoTest": "测试",
@@ -465,6 +466,7 @@
"menu.file.exportSettings": "导出设置…",
"menu.file.importSettings": "导入设置…",
"menu.file.importJetBrainsSettings": "从 JetBrains IDE 导入设置…",
"menu.file.importJetBrainsRecentProjects": "从 JetBrains IDE 导入最近项目…",
"menu.file.syncSettings": "立即同步设置",
"menu.file.togglePowerSave": "省电模式",
"menu.macros": "宏",
+15 -1
Переглянути файл
@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { getContext } from "./context";
import { executeAction, isActionKeyEnabled, registerAction } from "./actions";
import { commands } from "./ipc";
import { openProject, relativeDir, useProject } from "./project";
import { dirname, openProject, relativeDir, useProject } from "./project";
import { confirmProjectTrust } from "./projectTrust";
vi.mock("./projectTrust", () => ({ confirmProjectTrust: vi.fn(async () => {}) }));
@@ -78,3 +78,17 @@ describe("relativeDir", () => {
expect(relativeDir("/p/app", "/other/x.ts")).toBe("/other");
});
});
describe("dirname", () => {
it("splits POSIX paths on / only", () => {
expect(dirname("/p/src/util.ts")).toBe("/p/src");
expect(dirname("/p/a\\b.ts")).toBe("/p");
expect(dirname("/util.ts")).toBe("/");
});
it("splits Windows paths on \\ and /", () => {
expect(dirname("C:\\p\\src\\util.ts")).toBe("C:\\p\\src");
expect(dirname("C:/p/src/util.ts")).toBe("C:/p/src");
expect(dirname("\\\\server\\share\\util.ts")).toBe("\\\\server\\share");
});
});
+3 -1
Переглянути файл
@@ -122,7 +122,9 @@ export function basename(path: string): string {
export function dirname(path: string): string {
if (isVirtualUri(path)) return virtualParent(path);
const i = path.lastIndexOf("/");
// Windows paths (`C:\p\src`, `\\server\share`) separate with `\` too; on POSIX it is a file-name character.
const windows = /^([A-Za-z]:[\\/]|\\\\)/.test(path);
const i = windows ? Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")) : path.lastIndexOf("/");
return i <= 0 ? "/" : path.slice(0, i);
}