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

...
Автор SHA1 Повідомлення Дата
l0ng-ai 418422547d fix(debugger): coloured Spring Boot output, Soft-Wrap and Scroll to End in the debug console
Debugging a Spring Boot configuration showed its log uncoloured: Run adds
-Dspring.output.ansi.enabled=always (Spring only colours output for a
terminal, the process runs on pipes), the java-debug and Kotlin debug
launches built their VM options without it. They now add the same console
VM options as Run, unless the configuration sets the property itself.

The debug console also gets the Run console's Soft-Wrap toggle (default
from Settings › Console › Use soft wraps) and Scroll to End, which
follows new output, turns off when scrolling up and on again at the end.

Fixes #1262
2026-11-05 02:58:37 +08:00
l0ng-ai 2fc3535300 fix(editor): no lookbehind in the color preview's pattern (#1352)
The color preview's name pattern used a lookbehind, which WebKit before
16.4 cannot parse: on older macOS the module fails to load. The
preceding character of a name is now checked in code, with the same
result (`.red`, `$white`, `off-white` are not colors).
2026-11-05 02:52:44 +08:00
Łukasz Kosickiтаkosaa d96ff8e881 feat(i18n): add Polish translations (#1344)
Polish joins the UI languages (Settings › Appearance › Language), with
the key catalog and the source-text catalog; pl / pl-PL system locales
resolve to it.

Co-authored-by: kosaa <[email protected]>
2026-11-05 02:51:25 +08:00
l0ng-ai 3b02e6899d feat(markdown): show YAML front matter as a table in the preview (#1351)
A Markdown file starting with YAML front matter (agent SKILL.md files,
static site pages) showed it in the preview as a thematic break and a run
of text. The preview now shows every top-level field in a key / value
table above the body; nested lists and mappings keep their YAML layout.
Blocks after it keep their source lines for scroll sync. Text between two
thematic breaks that isn't a mapping is rendered as before.

Fixes #1239
2026-11-05 02:48:51 +08:00
fuqiuluoтаfuqiuluo 948e93e1a2 fix(search): Find / Replace in Files popup layout, footer and platform shortcuts (#1227)
The Find / Replace in Files popup gets the popup surface and spacing,
the match count and empty states ("Clear option(s)"), the footer with
"Open results in new tab", a resizable popup with a remembered results /
preview split, file mask suggestions from the project's file types
(new index_file_extensions), mnemonics and inline icons. Shortcuts are
spelled for the platform: Linux showed macOS glyphs in the popup, the
shared SearchField, the find bars and Search Everywhere. Replace keeps
its Preview diff.

Closes #1219

Co-authored-by: fuqiuluo <[email protected]>
2026-11-05 02:45:36 +08:00
l0ng-ai 5d19baf06b fix(ssh): report a failed backend upload instead of waiting forever (#1350)
The IDE backend is uploaded by streaming it into `gzip -dc > file` on the
host. When that command exits early (no gzip, a folder it cannot write, a
full disk), it stops reading: once the channel window (about 2 MB) is
used up, the next write waited for window space forever, so Remote
Development stayed on "Installing the IDE backend on the host…" at a few
percent and never showed the host's error. Each write, and closing the
input, now races the command's exit; an early exit ends the upload with
the command's status and stderr.

Refs #1330
2026-11-05 02:39:20 +08:00
l0ng-ai 89309e40ba fix(project): Open in Terminal from the editor opens the edited file's folder (#1348)
Open in Terminal and Reveal in Finder / Explorer invoked without a target
(a shortcut, Find Action) always used the Project view's selection, so in
the editor they opened the folder of whatever was selected there (the
project root after reopening a project) instead of the edited file's.
Without a target they now use the Project view's selection only while it
has focus, and the active editor's file otherwise.

Refs #1327
2026-11-05 02:35:25 +08:00
Shohruh Ismoilovтаshohruh-genius 9f2e6b570f feat(vcs): correct Git log graph projection and expand history views (#1076)
Git Log could lose commits when filtering by several paths, draw wrong
ancestry after filtering or collapsing rows, and open the wrong
repository in multi-root views. The graph is now projected over the full
commit DAG and laid out in Bek order, so filtered and collapsed views keep
the real ancestry; each log view keeps its own filters and requests.

Commit metadata, messages and path changes are kept in a persistent index
(by object id, in the IDE's cache directory) with seekable paging, and the
log gains parent-aware merge comparisons, a lazy revision browser,
read-only logs of repositories outside the project (opened with command
execution disabled), commit bookmarks, configurable built-in columns and
batched commit details. The adapted IntelliJ algorithms are attributed in
THIRD_PARTY_LICENSES.md.

Closes #872

Co-authored-by: shohruh-genius <[email protected]>
2026-11-05 02:31:32 +08:00
l0ng-ai 2d20e5a203 fix(lsp): update TypeScript imports when files move (#1346)
vtsls has no workspace/willRenameFiles: after didRenameFiles it updates
imports itself, behind a prompt sent as window/showMessageRequest. The
IDE shows that request as a message without choices, so moving a
TypeScript or JavaScript file never updated the imports of the files
that use it.

For a tsserver-backed server without willRename filters, the IDE now
asks tsserver for the edits up front (getEditsForFileRename through
typescript.tsserverRequest). The edits join the move's preview and undo
like any server's. The server's own update is turned off
(updateImportsOnFileMove.enabled = "never"), so it no longer prompts.
2026-11-05 02:26:28 +08:00
l0ng-ai 7c60737b69 fix(lsp): apply code actions whose follow-up command no server provides (#1343)
vtsls offers Organize Imports as an edit plus
`_typescript.didOrganizeImports`, a command VS Code's TypeScript
extension runs itself. Optimize Imports in a TypeScript file asked the
servers to resolve and run that command and failed with "no language
server provides command" before applying the edit.

A command that follows a code action's edit and that no server provides
is now skipped: the edit is applied, and resolving the command asks
nothing. An action that is only a command still reports it can't run.
2026-11-05 02:19:25 +08:00
Hacbit 7e9acdc59b feat(unity): detect projects and preserve asset metadata (#1207)
Unity projects (a folder with Assets and ProjectSettings/ProjectVersion.txt)
are detected without a generated solution: Assets / Packages become source
roots, ProjectSettings resources, and Unity's cache and build folders are
excluded before they exist. A Unity pane in the Project view shows the
editor version and hides .meta files, generated C# project files and
caches (each can be shown again).

Operations on assets under Assets keep their .meta files consistent:
rename and move carry the metadata (same GUID), delete removes both, copy
generates new GUIDs and updates references inside the copied group, and
file-move undo and workspace edits include the metadata. Destination
metadata conflicts and links inside the project are rejected before
anything changes.

Co-authored-by: hacbit <[email protected]>
2026-11-05 02:16:06 +08:00
l0ng-ai 2013ddaac2 feat(editor): color preview swatches in the gutter (#1341)
Lines with a color literal show a swatch of the (first) color in the
gutter: `#rgb` / `#rrggbb` with or without alpha, `rgb()` / `rgba()` /
`hsl()` / `hsla()`, and CSS named colors in property values of style
sheets. Outside style sheets and markup only quoted hex values and color
functions count, so `#123` issue numbers and `#add` comments get none;
prose files get none at all.

Clicking a swatch in an editable file opens the system color picker; the
picked color replaces the literal in its own format (hex case and length,
the function's name and separators, the original alpha), as one undoable
edit per pick. Settings › Editor › General › Gutter Icons › Color preview
turns the swatches off.

Fixes #1206
2026-11-05 02:10:42 +08:00
l0ng-ai ce898ea0c6 feat(vcs): fill the commit message with the repository's commit template (#1340)
An empty commit message field now starts with the file `commit.template`
names (any git config level; `~/` and repository-relative paths resolve
as git resolves them), without its `#` comment lines, since commits keep
the message as written. It is filled when the repository opens or
changes and when a commit clears the field; a typed message is never
replaced, and a prepared merge / cherry-pick / revert message still
takes precedence.

Fixes #1285
2026-11-05 02:05:07 +08:00
l0ng-ai c219c81bd8 fix(run): report Gradle tests in the test tree as they run (#1339)
Gradle prints only failed tests, so the live test tree only filled in
after the run from the XML reports, and stayed empty when the test task
was UP-TO-DATE and wrote no new reports.

Gradle test runs now get an init script that reports each test's start,
output, failure (with the stack trace), skip and finish as TeamCity
service messages and keeps test tasks from being UP-TO-DATE. The console
hides those lines; the JVM parser turns them into `[class, method]`
results, named as in the XML reports, and drops Gradle's own repeated
`Class > test() FAILED` lines. Tests the run already reported keep their
output instead of getting the report's copy appended. The TeamCity
message parsing moves out of the PHPUnit parser so both share it.

Fixes #1268
2026-11-05 02:02:06 +08:00
l0ng-ai 70a7c6dd2c fix(run): run Python modules with relative imports with -m (#1338)
Run or Debug on a Python file started it as a script
(`python src/tasks/cli.py`), so a module of a package that imports
relatively (`from .models import TaskList`) always failed with
"attempted relative import with no known parent package".

A file with relative imports now runs as `python -m package.module`
from the directory above its top package (the enclosing directories
with `__init__.py`, read once and re-read when one is added or
removed), with a venv-relative interpreter resolved against the project
root. Files without relative imports still run as scripts.
2026-11-05 02:01:35 +08:00
pravdomil fd69664ca7 fix(editor): follow local Markdown anchor links (#1328)
Go to Declaration and modifier-click on a fragment-only Markdown or HTML link such as [artist::order](#Artist-order) said there was nothing to go to: the text-reference fallback rejected fragment-only targets, and Markdown fragment lookup checked headings only, never HTML id / name anchors. Fragment-only href targets are now recognized and resolve in the same file (the current buffer, so unsaved anchors count), and Markdown files fall back to id / name anchors after headings.

Co-authored-by: pravdomil <[email protected]>
2026-11-05 01:48:06 +08:00
191 змінених файлів з 18627 додано та 1408 видалено

No files matched your search

Створено
+3
Переглянути файл
@@ -4662,12 +4662,14 @@ dependencies = [
name = "ide-vcs"
version = "0.1.36"
dependencies = [
"blake3",
"dunce",
"encoding_rs",
"gix",
"ide-core",
"ignore",
"libc",
"redb",
"regex-lite",
"serde",
"serde_json",
@@ -4735,6 +4737,7 @@ dependencies = [
"toml 0.9.12+spec-1.1.0",
"toml_edit 0.25.17+spec-1.1.0",
"tracing",
"uuid",
"zip",
]
+9
Переглянути файл
@@ -52,6 +52,15 @@ Their original copyright headers and Apache-2.0 licensing are retained.
At render time `src/ui/icons.tsx` may recolour monochrome icons to `currentColor`.
## JetBrains IntelliJ Platform VCS log graph algorithms
`crates/ide-vcs/src/bek.rs` and `src/features/vcs/graph.ts` adapt the Bek ordering,
graph layout and LinearBek merge linearization algorithms from
[intellij-community](https://github.com/JetBrains/intellij-community/tree/1d70d5c54302d655758edbd2f808fb8dea8b1764/platform/vcs-log/graph/src/com/intellij/vcs/log/graph)
(`impl/facade/sort/bek`, `impl/permanent/GraphLayoutBuilder.kt` and
`linearBek/LinearBekGraphBuilder.java`). Modified from the originals.
Copyright 2000-2026 JetBrains s.r.o. and contributors. Apache License 2.0 (below).
## JetBrains IntelliJ Platform diff algorithm
`src/features/vcs/comparison/**` is a TypeScript port of the text comparison of
+14 -5
Переглянути файл
@@ -79,6 +79,7 @@ pub struct Host {
pub runtime: tokio::runtime::Handle,
/// One project per window, keyed by window label.
projects: RwLock<HashMap<String, Arc<Project>>>,
pub(crate) external_logs: RwLock<HashMap<String, Vec<Arc<ide_vcs::Repo>>>>,
requests: requests::Requests,
project_requests: RwLock<HashMap<String, Vec<RequestId>>>,
}
@@ -122,6 +123,7 @@ impl Host {
owner,
runtime,
projects: RwLock::default(),
external_logs: RwLock::default(),
requests: Default::default(),
project_requests: RwLock::default(),
};
@@ -178,6 +180,10 @@ impl Host {
}
pub fn close_project(&self, window: &str) {
self.external_logs.write().remove(self.owner_window(window));
for request in self.project_requests.write().remove(self.owner_window(window)).unwrap_or_default() {
self.cancel_request(request);
}
let project = self.projects.write().remove(window);
if let Some(project) = project {
if !project.light {
@@ -193,9 +199,6 @@ impl Host {
// asked for, its runs, its shells and its debug sessions — and the language
// servers finish shutting down before the window is gone, as IDEA closes a
// project's processes.
for request in self.project_requests.write().remove(self.owner_window(window)).unwrap_or_default() {
self.cancel_request(request);
}
self.processes.kill_project(&project.root);
self.terminals.kill_key(self.owner_window(window));
self.shutdown_project_workers_blocking(
@@ -311,14 +314,20 @@ impl Host {
}
pub fn begin_project_request(&self, window: &str, id: RequestId) -> CancellationToken {
let token = self.begin_request(id);
self.project_requests.write().entry(self.owner_window(window).to_owned()).or_default().push(id);
let token = self.begin_project_read_request(window, id);
if self.project(window).is_ok_and(|p| !p.is_trusted()) {
token.cancel();
}
token
}
/// Read-only work remains cancellable/disposed with its window in restricted projects.
pub fn begin_project_read_request(&self, window: &str, id: RequestId) -> CancellationToken {
let token = self.begin_request(id);
self.project_requests.write().entry(self.owner_window(window).to_owned()).or_default().push(id);
token
}
pub fn end_request(&self, id: RequestId) {
for ids in self.project_requests.write().values_mut() {
ids.retain(|entry| *entry != id);
+1 -1
Переглянути файл
@@ -18,7 +18,7 @@ pub async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send
/// editor buffer, so syntax features and language-server requests work in it.
pub async fn doc_open_virtual(host: &Host, window: &str, uri: String) -> IdeResult<DocumentInfo> {
let project = host.project(window)?;
let vd = project.lsp.virtual_document(&uri).await?;
let vd = crate::ops::lsp::lsp_virtual_document(host, window, uri).await?;
blocking(move || project.documents.open_virtual(&vd.uri, vd.language_id, &vd.text)).await
}
+10 -3
Переглянути файл
@@ -137,16 +137,23 @@ pub fn set_writable(host: &Host, window: &str, path: PathBuf, writable: bool) ->
pub async fn delete(host: &Host, window: &str, path: PathBuf) -> IdeResult<()> {
let history = host.project(window).ok().map(|p| p.history.clone());
host.blocking(move || {
let paths = ide_workspace::file_ops::deletion_paths(&path)?;
if let Some(h) = history {
h.record_deletion(&path, DELETE_SNAPSHOT_LIMIT);
for p in paths {
h.record_deletion(&p, DELETE_SNAPSHOT_LIMIT);
}
}
ide_vfs::delete(&path)
ide_workspace::file_ops::delete(&path)
})
.await
}
pub async fn copy(host: &Host, from: PathBuf, to: PathBuf) -> IdeResult<()> {
host.blocking(move || ide_vfs::copy(&from, &to)).await
host.blocking(move || ide_workspace::file_ops::copy(&from, &to)).await
}
pub async fn rename(host: &Host, from: PathBuf, to: PathBuf) -> IdeResult<()> {
host.blocking(move || ide_workspace::file_ops::rename(&from, &to)).await
}
/// Reads a text file without opening it as a document; prefers the unsaved buffer.
+26 -1
Переглянути файл
@@ -260,6 +260,9 @@ pub async fn lsp_implementations(
/// Contents of a read-only language-server document, including JDT library
/// classes and disk class files. Cached per project.
pub async fn lsp_virtual_document(host: &Host, window: &str, uri: String) -> IdeResult<VirtualDocument> {
if uri.starts_with("git-revision:") {
return crate::ops::vcs::revision_virtual_document(host, window, &uri).await;
}
host.project(window)?.lsp.virtual_document(&uri).await
}
@@ -438,12 +441,30 @@ pub async fn lsp_apply_code_action(host: &Host, window: &str, doc: DocId, action
let edit = edit.clone();
blocking(move || apply_edit(&documents, &edit)).await?;
}
if let Some(command) = action.command {
if let Some(command) = action.command
&& !(action.edit.is_some() && is_client_follow_up(&project, doc, None, &command).await)
{
project.lsp.execute_command(doc, command).await?;
}
Ok(())
}
/// A command after a code action's edit that no server provides: what other editors'
/// extensions do once the edit is applied (vtsls' `_typescript.didOrganizeImports`). The edit
/// is the action; there is nothing to run.
async fn is_client_follow_up(
project: &crate::project::Project,
doc: DocId,
server: Option<ide_core::ServerId>,
command: &Command,
) -> bool {
let provided = project.lsp.provides_command(doc, server, &command.command).await;
if !provided {
tracing::debug!("skipping `{}` after the code action's edit: no server provides it", command.command);
}
!provided
}
pub async fn lsp_prepare_rename(host: &Host, window: &str, doc: DocId, pos: Pos) -> IdeResult<Option<Range>> {
host.project(window)?.lsp.prepare_rename(doc, pos).await
}
@@ -676,6 +697,7 @@ pub async fn lsp_execute_code_action(
if cancel.is_cancelled() {
return Err(ide_core::IdeError::cancelled());
}
let edited = action.edit.is_some();
if let Some(edit) = action.edit {
let documents = project.documents.clone();
tokio::task::spawn_blocking(move || apply_edit(&documents, &edit))
@@ -683,6 +705,9 @@ pub async fn lsp_execute_code_action(
.map_err(|e| ide_core::IdeError::internal(e.to_string()))??;
}
match action.command {
Some(command) if edited && is_client_follow_up(&project, doc, Some(action.server), &command).await => {
Ok(Vec::new())
}
Some(command) => project
.lsp
.execute_action_command(doc, action.server, command, answers, cancel)
+7 -1
Переглянути файл
@@ -3,7 +3,7 @@ use crate::Host;
use crate::Project;
use crate::rpc::Dispatcher;
use ide_core::{DocId, IdeResult, IpcPath, Location, Pos};
use ide_index::{FileMatch, IndexStatus, SymbolFilter, SymbolMatch};
use ide_index::{ExtensionCount, FileMatch, IndexStatus, SymbolFilter, SymbolMatch};
use ide_language::{FileReference, WebReference};
use ide_workspace::file_refs::{self, PathCompletion};
use serde::{Deserialize, Serialize};
@@ -32,6 +32,11 @@ pub fn index_status(host: &Host, window: &str) -> IdeResult<IndexStatus> {
Ok(host.project(window)?.index.status())
}
/// The project's file extensions, most common first.
pub fn index_file_extensions(host: &Host, window: &str) -> IdeResult<Vec<ExtensionCount>> {
Ok(host.project(window)?.index.file_extensions())
}
pub fn find_files(host: &Host, window: &str, query: String, limit: u32) -> IdeResult<Vec<FileMatch>> {
Ok(host.project(window)?.index.find_files(&query, limit as usize))
}
@@ -160,6 +165,7 @@ pub async fn web_unresolved_references(host: &Host, window: &str, doc: DocId) ->
/// Commands of this module the remote server answers.
pub(crate) fn register(d: &mut Dispatcher) {
d.add("index_status", |c| async move { index_status(&c.host, &c.window) });
d.add("index_file_extensions", |c| async move { index_file_extensions(&c.host, &c.window) });
d.add("find_files", |c| async move { find_files(&c.host, &c.window, c.arg("query")?, c.arg("limit")?) });
d.add("find_dirs", |c| async move { find_dirs(&c.host, &c.window, c.arg("query")?, c.arg("limit")?) });
d.add("find_symbols", |c| async move {
+3
Переглянути файл
@@ -17,6 +17,8 @@ pub struct ProjectInfo {
pub settings: Settings,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub workspace: Option<ide_workspace::workspace::Workspace>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub unity: Option<ide_workspace::unity::UnityProjectInfo>,
}
pub fn info(project: &Project) -> ProjectInfo {
@@ -33,6 +35,7 @@ pub fn info(project: &Project) -> ProjectInfo {
settings,
root: project.root.clone().into(),
workspace: ide_workspace::workspace::Workspace::load(&project.root).ok().flatten(),
unity: ide_workspace::unity::detect(&project.root),
}
}
+239 -22
Переглянути файл
@@ -12,6 +12,76 @@ use std::path::{Path, PathBuf};
use crate::apply_git_executable;
/// Read-only repository access also works in a standalone log window.
struct LogAccess {
project: Option<std::sync::Arc<Project>>,
external: Option<std::sync::Arc<Repo>>,
cache: PathBuf,
}
/// Immutable Git objects exposed through the editor's ordinary read-only VFS.
pub async fn revision_virtual_document(
host: &Host,
window: &str,
uri: &str,
) -> IdeResult<ide_lsp::types::VirtualDocument> {
#[derive(Deserialize)]
struct Target {
repo: PathBuf,
revision: String,
path: PathBuf,
}
let encoded = uri
.strip_prefix("git-revision:")
.and_then(|s| s.split('/').next())
.ok_or_else(|| ide_core::IdeError::invalid("invalid Git revision URI"))?;
if encoded.len() > 32768 || encoded.len() % 2 != 0 || !encoded.bytes().all(|b| b.is_ascii_hexdigit()) {
return Err(ide_core::IdeError::invalid("invalid Git revision URI"));
}
let bytes = (0..encoded.len())
.step_by(2)
.map(|i| {
u8::from_str_radix(&encoded[i..i + 2], 16)
.map_err(|_| ide_core::IdeError::invalid("invalid Git revision URI"))
})
.collect::<IdeResult<Vec<_>>>()?;
let target: Target = serde_json::from_slice(&bytes).map_err(|e| ide_core::IdeError::invalid(e.to_string()))?;
let path = target.repo.join(&target.path);
let text = vcs_file_at(host, window, path, Some(target.revision.clone()))
.await?
.ok_or_else(|| ide_core::IdeError::not_found("file is absent at this revision"))?;
Ok(ide_lsp::types::VirtualDocument {
uri: uri.into(),
language_id: host.languages.detect(&target.path, text.lines().next()),
text,
title: target.path.file_name().unwrap_or_default().to_string_lossy().into_owned(),
description: Some(format!("{} · {}", target.repo.display(), target.revision)),
decompiled: false,
})
}
impl LogAccess {
fn new(host: &Host, window: &str, at: Option<&Path>) -> Self {
let project = host.project(window).ok();
let external = host
.external_logs
.read()
.get(host.owner_window(window))
.and_then(|rs| rs.iter().find(|r| Some(r.root()) == at).cloned())
.filter(|repo| project.as_ref().is_none_or(|p| p.repos().at_root(repo.root()).is_none()));
Self { project, external, cache: host.local_data_dir.join("cache/git-log") }
}
fn with_log_repo_at<T>(&self, at: Option<&Path>, f: impl FnOnce(&Repo) -> IdeResult<T>) -> IdeResult<T> {
if let Some(repo) = &self.external {
repo.enable_log_index(&self.cache);
return f(repo);
}
self.project
.as_ref()
.ok_or_else(|| ide_core::IdeError::unavailable("external Git log is not open"))?
.with_log_repo_at(at, f)
}
}
/// A repository of the project (IDEA's VCS root).
#[derive(Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
@@ -182,8 +252,8 @@ pub fn vcs_roots(host: &Host, window: &str) -> IdeResult<Vec<VcsRoot>> {
}
pub async fn vcs_branch_info(host: &Host, window: &str, repo: Option<PathBuf>) -> IdeResult<BranchInfo> {
let project = host.project(window)?;
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.branch_info())).await
let project = LogAccess::new(host, window, repo.as_deref());
blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.branch_info())).await
}
/// Gutter change markers for a file, computed against its current (unsaved) text.
@@ -197,9 +267,21 @@ pub async fn vcs_line_hunks(host: &Host, window: &str, path: PathBuf) -> IdeResu
}
pub async fn vcs_file_at(host: &Host, window: &str, path: PathBuf, rev: Option<String>) -> IdeResult<Option<String>> {
let project = host.project(window)?;
let project = host.project(window).ok();
let external = host.external_logs.read().get(host.owner_window(window)).and_then(|rs| {
rs.iter().filter(|r| path.starts_with(r.root())).max_by_key(|r| r.root().components().count()).cloned()
});
blocking(move || {
project.with_repo_of(&path, |r| r.file_at(&path, rev.as_deref(), project.vcs_encoding(&path, rev.as_deref())?))
if let Some(project) = project {
return project.with_log_repo_of(&path, |r| {
r.file_at(&path, rev.as_deref(), project.vcs_encoding(&path, rev.as_deref())?)
});
}
external.ok_or_else(|| ide_core::IdeError::unavailable("external Git log is not open"))?.file_at(
&path,
rev.as_deref(),
encoding_rs::UTF_8,
)
})
.await
}
@@ -246,8 +328,124 @@ pub async fn vcs_block_history(
}
pub async fn vcs_log(host: &Host, window: &str, repo: Option<PathBuf>, query: LogQuery) -> IdeResult<Vec<Commit>> {
let project = host.project(window)?;
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.log(&query))).await
let project = LogAccess::new(host, window, repo.as_deref());
let request = query.request;
let cancel =
request.map_or_else(ide_core::CancellationToken::new, |id| host.begin_project_read_request(window, id));
let result = blocking(move || {
project.with_log_repo_at(repo.as_deref(), |r| {
r.enable_log_index(&project.cache);
r.log_cancellable(&query, &cancel)
})
})
.await;
if let Some(id) = request {
host.end_request(id);
}
result
}
pub async fn vcs_log_refs(
host: &Host,
window: &str,
repo: Option<PathBuf>,
) -> IdeResult<std::collections::BTreeMap<String, String>> {
let project = LogAccess::new(host, window, repo.as_deref());
blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.log_refs())).await
}
pub async fn vcs_log_users(host: &Host, window: &str, repo: Option<PathBuf>) -> IdeResult<Vec<String>> {
let project = LogAccess::new(host, window, repo.as_deref());
blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.log_users())).await
}
pub async fn vcs_open_external_log(host: &Host, window: &str, path: PathBuf) -> IdeResult<ide_core::IpcPath> {
let path = dunce::canonicalize(path)?;
let repo = Repo::discover(&path)?.ok_or_else(|| ide_core::IdeError::unavailable("folder is not a Git worktree"))?;
let root = repo.root().to_path_buf();
repo.set_execution_allowed(false);
repo.enable_log_index(&host.local_data_dir.join("cache/git-log"));
if let Ok(project) = host.project(window) {
project.open_external_log(&root)?;
}
let mut logs = host.external_logs.write();
let roots = logs.entry(host.owner_window(window).to_string()).or_default();
if !roots.iter().any(|r| r.root() == root) {
roots.push(std::sync::Arc::new(repo));
}
Ok(root.into())
}
pub async fn vcs_log_details(
host: &Host,
window: &str,
repo: Option<PathBuf>,
revision: String,
) -> IdeResult<LogDetails> {
let project = LogAccess::new(host, window, repo.as_deref());
blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.log_details(&revision))).await
}
pub async fn vcs_log_details_batch(
host: &Host,
window: &str,
repo: Option<PathBuf>,
revisions: Vec<String>,
request: RequestId,
) -> IdeResult<Vec<LogDetails>> {
let project = LogAccess::new(host, window, repo.as_deref());
let cancel = host.begin_project_read_request(window, request);
let result = blocking(move || {
project.with_log_repo_at(repo.as_deref(), |r| {
revisions.iter().map(|id| r.log_details_cancellable(id, &cancel)).collect()
})
})
.await;
host.end_request(request);
result
}
pub async fn vcs_log_index(
host: &Host,
window: &str,
repo: Option<PathBuf>,
request: Option<RequestId>,
) -> IdeResult<LogIndexProgress> {
let project = LogAccess::new(host, window, repo.as_deref());
let cancel =
request.map_or_else(ide_core::CancellationToken::new, |id| host.begin_project_read_request(window, id));
let result = blocking(move || {
project.with_log_repo_at(repo.as_deref(), |r| {
r.enable_log_index(&project.cache);
if request.is_some() { r.index_log(&cancel) } else { Ok(r.log_index_progress()) }
})
})
.await;
if let Some(request) = request {
host.end_request(request);
}
result
}
pub async fn vcs_revision_children(
host: &Host,
window: &str,
repo: Option<PathBuf>,
revision: String,
directory: String,
) -> IdeResult<Vec<String>> {
let project = LogAccess::new(host, window, repo.as_deref());
blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.revision_children(&revision, &directory))).await
}
pub async fn vcs_revision_files(
host: &Host,
window: &str,
repo: Option<PathBuf>,
revision: String,
) -> IdeResult<Vec<String>> {
let project = LogAccess::new(host, window, repo.as_deref());
blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.revision_files(&revision))).await
}
pub async fn vcs_commit_files(
@@ -256,8 +454,8 @@ pub async fn vcs_commit_files(
repo: Option<PathBuf>,
commit: String,
) -> IdeResult<Vec<ChangedFile>> {
let project = host.project(window)?;
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.commit_files(&commit))).await
let project = LogAccess::new(host, window, repo.as_deref());
blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.commit_files(&commit))).await
}
/// Combined changes of several commits, `commits` oldest first.
@@ -267,13 +465,13 @@ pub async fn vcs_commits_changes(
repo: Option<PathBuf>,
commits: Vec<String>,
) -> IdeResult<Vec<RevisionChange>> {
let project = host.project(window)?;
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.commits_changes(&commits))).await
let project = LogAccess::new(host, window, repo.as_deref());
blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.commits_changes(&commits))).await
}
pub async fn vcs_branches(host: &Host, window: &str, repo: Option<PathBuf>) -> IdeResult<Vec<Branch>> {
let project = host.project(window)?;
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.branches())).await
let project = LogAccess::new(host, window, repo.as_deref());
blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.branches())).await
}
pub async fn vcs_stashes(host: &Host, window: &str, repo: Option<PathBuf>) -> IdeResult<Vec<Stash>> {
@@ -628,8 +826,8 @@ pub async fn vcs_config_get(
repo: Option<PathBuf>,
key: String,
) -> IdeResult<Option<String>> {
let project = host.project(window)?;
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.config_get(&key))).await
let project = LogAccess::new(host, window, repo.as_deref());
blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.config_get(&key))).await
}
/// Local history operation that may take a while (hooks, large checkouts); git's
@@ -690,8 +888,8 @@ pub async fn vcs_create_tag(
}
pub async fn vcs_tags(host: &Host, window: &str, repo: Option<PathBuf>) -> IdeResult<Vec<String>> {
let project = host.project(window)?;
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.tags())).await
let project = LogAccess::new(host, window, repo.as_deref());
blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.tags())).await
}
/// Merge dialog: merges `branches` into the current branch.
@@ -727,8 +925,8 @@ pub async fn vcs_rebase_with(
}
pub async fn vcs_remotes(host: &Host, window: &str, repo: Option<PathBuf>) -> IdeResult<Vec<Remote>> {
let project = host.project(window)?;
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.remotes())).await
let project = LogAccess::new(host, window, repo.as_deref());
blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.remotes())).await
}
pub async fn vcs_edit_remote(host: &Host, window: &str, repo: Option<PathBuf>, edit: RemoteEdit) -> IdeResult<()> {
@@ -815,8 +1013,8 @@ pub async fn vcs_diff_with_worktree(
repo: Option<PathBuf>,
rev: String,
) -> IdeResult<Vec<ChangedFile>> {
let project = host.project(window)?;
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.diff_with_worktree(&rev))).await
let project = LogAccess::new(host, window, repo.as_deref());
blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.diff_with_worktree(&rev))).await
}
/// Files that differ between two revisions (the "N files updated" of Update Project).
@@ -827,8 +1025,8 @@ pub async fn vcs_diff_revisions(
from: String,
to: String,
) -> IdeResult<Vec<ChangedFile>> {
let project = host.project(window)?;
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.diff_revisions(&from, &to))).await
let project = LogAccess::new(host, window, repo.as_deref());
blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.diff_revisions(&from, &to))).await
}
/// The best common ancestor of `a` and `b` (`git merge-base`), if any: the New Pull
@@ -1015,6 +1213,25 @@ pub(crate) fn register(d: &mut Dispatcher) {
vcs_block_history(&c.host, &c.window, request, path, text, lines).await
});
d.add("vcs_log", |c| async move { vcs_log(&c.host, &c.window, c.arg("repo")?, c.arg("query")?).await });
d.add("vcs_log_refs", |c| async move { vcs_log_refs(&c.host, &c.window, c.arg("repo")?).await });
d.add("vcs_log_users", |c| async move { vcs_log_users(&c.host, &c.window, c.arg("repo")?).await });
d.add("vcs_open_external_log", |c| async move { vcs_open_external_log(&c.host, &c.window, c.arg("path")?).await });
d.add("vcs_log_details", |c| async move {
vcs_log_details(&c.host, &c.window, c.arg("repo")?, c.arg("revision")?).await
});
d.add("vcs_log_details_batch", |c| async move {
vcs_log_details_batch(&c.host, &c.window, c.arg("repo")?, c.arg("revisions")?, c.arg("request")?).await
});
d.add(
"vcs_log_index",
|c| async move { vcs_log_index(&c.host, &c.window, c.arg("repo")?, c.arg("request")?).await },
);
d.add("vcs_revision_children", |c| async move {
vcs_revision_children(&c.host, &c.window, c.arg("repo")?, c.arg("revision")?, c.arg("directory")?).await
});
d.add("vcs_revision_files", |c| async move {
vcs_revision_files(&c.host, &c.window, c.arg("repo")?, c.arg("revision")?).await
});
d.add("vcs_commit_files", |c| async move {
vcs_commit_files(&c.host, &c.window, c.arg("repo")?, c.arg("commit")?).await
});
+58 -2
Переглянути файл
@@ -34,6 +34,8 @@ pub struct Project {
pub lsp: Arc<LspManager>,
/// Git repositories: the one containing the project root and those nested below it.
pub repos: Arc<RwLock<Repos>>,
/// Explicitly opened external logs remain read-only and outside project indexing.
pub(crate) external_log_repos: RwLock<Vec<Arc<Repo>>>,
/// Incrementally maintained syntax trees of the open documents.
pub syntax: Arc<SyntaxCache>,
/// Tree-sitter structure queries (LSP fallback) over `syntax`.
@@ -462,6 +464,7 @@ impl Host {
index,
lsp,
repos,
external_log_repos: RwLock::default(),
structure: Arc::new(StructureService::new(syntax.clone())),
syntax,
detected_roots,
@@ -595,6 +598,7 @@ impl Host {
index,
lsp,
repos: Arc::default(),
external_log_repos: RwLock::default(),
structure: Arc::new(StructureService::new(syntax.clone())),
syntax,
detected_roots: Arc::default(),
@@ -692,7 +696,14 @@ fn scan_repositories(
build_cache: &Path,
) {
let ignored = settings.effective().ignored_names();
let skip = |p: &Path| p.file_name().is_some_and(|n| ignored.is_ignored_name(&n.to_string_lossy()));
let skip = |p: &Path| {
p.file_name().is_some_and(|n| {
let name = n.to_string_lossy();
ignored.is_ignored_name(&name)
|| (ide_workspace::unity::GENERATED_DIRS.contains(&name.as_ref())
&& p.parent().is_some_and(ide_workspace::unity::is_project))
})
};
let mut roots = vec![root.to_path_buf()];
roots.extend(content_roots(&settings.effective(), root, build_cache));
match Repos::discover_roots(&roots, &skip) {
@@ -739,6 +750,51 @@ impl Project {
}
}
pub fn open_external_log(&self, path: &Path) -> IdeResult<PathBuf> {
let root = dunce::canonicalize(path)?;
let repo = Repo::discover(&root)?.ok_or_else(|| IdeError::unavailable("folder is not a Git worktree"))?;
let root = repo.root().to_path_buf();
repo.set_execution_allowed(false);
let mut external = self.external_log_repos.write();
if !external.iter().any(|r| r.root() == root) {
external.push(Arc::new(repo));
}
Ok(root)
}
/// Log read operations may also use an explicitly opened external worktree.
/// Mutations continue to use `with_repo_at` and cannot reach these repositories.
pub fn with_log_repo_at<T>(&self, at: Option<&Path>, f: impl FnOnce(&Repo) -> IdeResult<T>) -> IdeResult<T> {
if let Some(path) = at
&& self.repos().at_root(path).is_none()
{
let repo = self
.external_log_repos
.read()
.iter()
.find(|r| r.root() == path)
.cloned()
.ok_or_else(|| IdeError::unavailable("external Git log is not open"))?;
return f(&repo);
}
self.with_repo_at(at, f)
}
pub fn with_log_repo_of<T>(&self, path: &Path, f: impl FnOnce(&Repo) -> IdeResult<T>) -> IdeResult<T> {
if self.repos().for_path(path).is_some() {
return self.with_repo_of(path, f);
}
let repo = self
.external_log_repos
.read()
.iter()
.filter(|r| path.starts_with(r.root()))
.max_by_key(|r| r.root().components().count())
.cloned()
.ok_or_else(|| IdeError::unavailable("path is not in an open Git log"))?;
f(&repo)
}
/// Runs `f` with the repository `path` (a file or folder) belongs to.
pub fn with_repo_of<T>(&self, path: &Path, f: impl FnOnce(&Repo) -> IdeResult<T>) -> IdeResult<T> {
match self.repos().for_path(path) {
@@ -955,7 +1011,7 @@ impl Project {
return encoding_rs::Encoding::for_label(loaded.encoding.as_bytes())
.ok_or_else(|| ide_core::IdeError::invalid("unknown file encoding"));
}
let bytes = self.with_repo_of(path, |r| r.file_bytes_at(path, rev))?.unwrap_or_default();
let bytes = self.with_log_repo_of(path, |r| r.file_bytes_at(path, rev))?.unwrap_or_default();
Ok(ide_vfs::detect_encoding(&bytes, fallback))
}
+1 -1
Переглянути файл
@@ -188,7 +188,7 @@ impl Dispatcher {
ops::fs::create_file_bytes(&c.host, c.arg("path")?, c.arg("data")?).await
})
.add("fs_create_dir", |c| async move { ide_vfs::create_dir(&c.arg::<PathBuf>("path")?) })
.add("fs_rename", |c| async move { ide_vfs::rename(&c.arg::<PathBuf>("from")?, &c.arg::<PathBuf>("to")?) })
.add("fs_rename", |c| async move { ops::fs::rename(&c.host, c.arg("from")?, c.arg("to")?).await })
.add("fs_set_writable", |c| async move {
ops::fs::set_writable(&c.host, &c.window, c.arg("path")?, c.arg("writable")?)
})
+9
Переглянути файл
@@ -222,6 +222,7 @@ pub fn restricted_command_allowed(cmd: &str) -> bool {
| "project_current"
| "project_roots"
| "index_status"
| "index_file_extensions"
| "jvm_file_presentations"
| "deploy_coverage"
| "deploy_test_connection"
@@ -307,6 +308,14 @@ pub fn restricted_command_allowed(cmd: &str) -> bool {
| "vcs_blame"
| "vcs_block_history"
| "vcs_log"
| "vcs_log_refs"
| "vcs_log_users"
| "vcs_log_details"
| "vcs_log_details_batch"
| "vcs_log_index"
| "vcs_revision_children"
| "vcs_revision_files"
| "vcs_open_external_log"
| "vcs_commit_files"
| "vcs_commits_changes"
| "vcs_branches"
+115
Переглянути файл
@@ -0,0 +1,115 @@
//! Explicit external logs allow history reads without adding a writable project root.
use ide_core::NullSink;
use ide_host::{Host, HostConfig, ops::vcs};
use std::{path::Path, process::Command, sync::Arc};
fn git(root: &Path, args: &[&str]) -> String {
let output = Command::new("git")
.current_dir(root)
.args(["-c", "user.name=Test", "-c", "[email protected]", "-c", "commit.gpgsign=false"])
.args(args)
.output()
.unwrap();
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
String::from_utf8(output.stdout).unwrap().trim().to_owned()
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn external_history_is_readable_and_never_becomes_a_write_target() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
let external = base.join("external");
std::fs::create_dir_all(&root).unwrap();
std::fs::create_dir_all(&external).unwrap();
git(&external, &["init", "-b", "main"]);
let deleted = external.join("deleted.txt");
std::fs::write(&deleted, "historical content\n").unwrap();
git(&external, &["add", "."]);
git(&external, &["commit", "-m", "initial"]);
let first = git(&external, &["rev-parse", "HEAD"]);
git(&external, &["rm", "deleted.txt"]);
git(&external, &["commit", "-m", "delete"]);
let head = git(&external, &["rev-parse", "HEAD"]);
let host = Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
// A standalone editor needs no project, indexer, or writable VCS root.
vcs::vcs_open_external_log(&host, "standalone", external.clone()).await.unwrap();
let standalone = vcs::vcs_log(&host, "standalone", Some(external.clone()), Default::default()).await.unwrap();
assert_eq!(standalone[0].id, head);
let details = vcs::vcs_log_details_batch(
&host,
"standalone",
Some(external.clone()),
vec![head.clone(), first.clone()],
ide_core::RequestId(987),
)
.await
.unwrap();
assert!(details.iter().all(|d| d.signature == "N"));
assert_eq!(
vcs::vcs_revision_children(&host, "standalone", Some(external.clone()), first.clone(), String::new())
.await
.unwrap(),
vec!["deleted.txt"]
);
assert!(host.project("standalone").is_err());
host.trust.decide(&external, false, false).unwrap();
let restricted = host.open_project("restricted", &external).unwrap();
assert!(!restricted.is_trusted());
vcs::vcs_open_external_log(&host, "restricted", external.clone()).await.unwrap();
let restricted_log = vcs::vcs_log(
&host,
"restricted",
Some(external.clone()),
ide_vcs::LogQuery { request: Some(ide_core::RequestId(988)), summary_only: true, ..Default::default() },
)
.await
.unwrap();
assert_eq!(restricted_log[0].id, head);
assert_eq!(
vcs::vcs_log_details_batch(
&host,
"restricted",
Some(external.clone()),
vec![head.clone()],
ide_core::RequestId(989)
)
.await
.unwrap()[0]
.signature,
"N"
);
host.close_project("restricted");
let payload =
serde_json::to_vec(&serde_json::json!({ "repo": external, "revision": first, "path": "deleted.txt" })).unwrap();
let hex = payload.iter().map(|b| format!("{b:02x}")).collect::<String>();
let document =
vcs::revision_virtual_document(&host, "standalone", &format!("git-revision:{hex}/deleted.txt")).await.unwrap();
assert_eq!(document.text, "historical content\n");
host.trust.decide(&root, true, false).unwrap();
let project = host.open_project("main", &root).unwrap();
assert!(vcs::vcs_log(&host, "main", Some(external.clone()), Default::default()).await.is_err());
vcs::vcs_open_external_log(&host, "main", external.clone()).await.unwrap();
let log = vcs::vcs_log(&host, "main", Some(external.clone()), Default::default()).await.unwrap();
assert_eq!(log.iter().map(|c| c.id.as_str()).collect::<Vec<_>>(), vec![head.as_str(), first.as_str()]);
assert_eq!(
vcs::vcs_file_at(&host, "main", deleted.clone(), Some(first.clone())).await.unwrap().as_deref(),
Some("historical content\n")
);
assert!(project.repos().at_root(&external).is_none());
assert!(vcs::vcs_checkout(&host, "main", Some(external.clone()), first.clone(), false, None).await.is_err());
assert!(vcs::vcs_apply_patch(&host, "main", Some(external.clone()), String::new()).await.is_err());
assert_eq!(git(&external, &["rev-parse", "HEAD"]), head);
assert!(!deleted.exists());
host.close_project("main");
}
+100
Переглянути файл
@@ -0,0 +1,100 @@
use ide_core::{NullSink, RequestId};
use ide_host::{Host, HostConfig, ops};
use std::{sync::Arc, time::Duration};
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn opens_unity_without_generated_solutions_and_excludes_caches_from_the_index() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("Game");
for name in ["Assets/Scripts", "Packages", "ProjectSettings", "Library/PackageCache", "Temp", "Logs"] {
std::fs::create_dir_all(root.join(name)).unwrap();
}
std::fs::write(root.join("ProjectSettings/ProjectVersion.txt"), "m_EditorVersion: 6000.0.62f1\n").unwrap();
std::fs::write(root.join("Assets/Scripts/Player.cs"), "class Player {}\n").unwrap();
std::fs::write(root.join("Packages/manifest.json"), "{}\n").unwrap();
std::fs::write(root.join("Library/PackageCache/Cached.cs"), "class Cached {}\n").unwrap();
std::fs::write(root.join("Temp/Temporary.cs"), "class Temporary {}\n").unwrap();
std::fs::write(root.join("Logs/Editor.log"), "log\n").unwrap();
let host = Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
let project = host.open_project("main", &root).unwrap();
let info = ops::project::info(&project);
assert_eq!(info.name, "Game");
let unity = info.unity.unwrap();
assert_eq!(unity.editor_version.as_deref(), Some("6000.0.62f1"));
assert!(unity.projects.is_empty() && unity.solutions.is_empty());
assert!(project.index.wait_idle(Duration::from_secs(20)));
assert_eq!(project.index.find_files("Player.cs", 100).len(), 1);
for name in ["Cached.cs", "Temporary.cs", "Editor.log"] {
assert!(project.index.find_files(name, 100).is_empty(), "indexed generated file {name}");
}
let hits = Arc::new(std::sync::Mutex::new(Vec::new()));
let out = hits.clone();
let query = serde_json::from_value(serde_json::json!({
"pattern": "class", "isRegex": false, "caseSensitive": false, "wholeWord": false,
"include": [], "exclude": [], "scope": { "kind": "project" }, "maxMatches": 100,
}))
.unwrap();
ops::search::start(
&host,
"main",
RequestId::next(),
query,
Arc::new(move |event| {
if let ops::search::SearchEvent::File { file } = event {
out.lock().unwrap().push(file.rel_path);
}
}),
)
.await
.unwrap();
assert_eq!(*hits.lock().unwrap(), ["Assets/Scripts/Player.cs"]);
let listing = ops::fs::read_dir(&host, "main", root.clone()).await.unwrap();
assert!(listing.iter().any(|e| e.name == "Library" && e.excluded));
assert!(project.exclude_globs().contains(&"/Obj".to_owned()));
// Project metadata refreshes without reopening when Unity generates its solution.
std::fs::write(root.join("Game.sln"), "").unwrap();
std::fs::write(root.join("Assembly-CSharp.csproj"), "").unwrap();
let unity = ops::project::info(&project).unity.unwrap();
assert_eq!(unity.solutions, ["Game.sln"]);
assert_eq!(unity.projects, ["Assembly-CSharp.csproj"]);
// Desktop commands and remote RPC share these host operations.
let original = root.join("Assets/Scripts/Player.cs");
let renamed = root.join("Assets/Scripts/Hero.cs");
let copied = root.join("Assets/Scripts/HeroCopy.cs");
let meta = |path: &std::path::Path| -> std::path::PathBuf {
let mut name = path.as_os_str().to_os_string();
name.push(".meta");
name.into()
};
let original_metadata = "fileFormatVersion: 2\nguid: 11111111111111111111111111111111\n";
std::fs::write(meta(&original), original_metadata).unwrap();
ops::fs::rename(&host, original.clone(), renamed.clone()).await.unwrap();
assert!(!original.exists() && !meta(&original).exists());
assert_eq!(std::fs::read_to_string(meta(&renamed)).unwrap(), original_metadata);
ops::fs::copy(&host, renamed.clone(), copied.clone()).await.unwrap();
assert!(copied.exists());
assert_ne!(std::fs::read_to_string(meta(&copied)).unwrap(), original_metadata);
assert_eq!(std::fs::read_to_string(meta(&renamed)).unwrap(), original_metadata);
host.close_project("main");
let ordinary = base.join("ConsoleApp");
std::fs::create_dir(&ordinary).unwrap();
std::fs::write(ordinary.join("App.csproj"), "").unwrap();
let project = host.open_project("main", &ordinary).unwrap();
assert!(ops::project::info(&project).unity.is_none());
assert!(!project.exclude_globs().contains(&"/Library".to_owned()));
host.close_project("main");
}
+63
Переглянути файл
@@ -175,3 +175,66 @@ async fn contended_version_reads_do_not_block_the_async_worker() {
assert!(watchdog.join().unwrap(), "request {request_kind} blocked the only async worker");
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn code_actions_skip_a_command_no_server_provides_after_their_edit() {
use ide_lsp::types::{CodeAction, Command};
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("imports.txt");
std::fs::write(&file, "unused\nused\n").unwrap();
let host = Host::new(HostConfig {
config_dir: tmp.path().join("config"),
data_dir: tmp.path().join("data"),
local_data_dir: tmp.path().join("local-data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(|_| {})),
owner: |window| window,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
host.open_light("main", &file).unwrap();
let info = ops::doc::open(&host, "main", file.clone()).await.unwrap();
// Optimize Imports as vtsls offers it: the edit, then a command its client runs itself.
let action = |edit: bool| CodeAction {
title: "Organize Imports".into(),
kind: Some("source.organizeImports".into()),
is_preferred: false,
disabled_reason: None,
edit: edit.then(|| {
serde_json::from_value(json!({ "files": [{ "kind": "edit", "path": file, "edits": [
{ "range": { "start": { "line": 0, "col": 0 }, "end": { "line": 1, "col": 0 } }, "new_text": "" }
] }] }))
.unwrap()
}),
command: Some(Command {
title: String::new(),
command: "_typescript.didOrganizeImports".into(),
arguments: vec![],
}),
data: None,
server: ide_core::ServerId(1),
};
let follow_up = action(true).command.unwrap();
let asked = ops::lsp::lsp_resolve_command(
&host,
"main",
ide_core::RequestId(1),
info.id,
ide_core::ServerId(1),
follow_up,
vec![],
)
.await;
assert!(matches!(asked, Ok(None)), "{asked:?}");
ops::lsp::lsp_execute_code_action(&host, "main", ide_core::RequestId(2), info.id, action(true), vec![])
.await
.unwrap();
assert_eq!(ops::doc::snapshot(&host, "main", info.id).await.unwrap().text, "used\n");
ops::lsp::lsp_apply_code_action(&host, "main", info.id, action(true)).await.unwrap();
assert_eq!(ops::doc::snapshot(&host, "main", info.id).await.unwrap().text, "");
// Without an edit the command is the action: it still can't run.
let ran =
ops::lsp::lsp_execute_code_action(&host, "main", ide_core::RequestId(3), info.id, action(false), vec![]).await;
assert!(ran.is_err(), "{ran:?}");
}
+30
Переглянути файл
@@ -8,6 +8,7 @@ use ide_language::{LanguageRegistry, Syntax};
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::Ordering;
@@ -64,6 +65,14 @@ pub struct IndexStatus {
pub symbols: u32,
}
/// How many indexed files share an extension (lower case, without the dot).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct ExtensionCount {
pub extension: String,
pub files: u32,
}
pub struct ProjectIndex {
shared: Arc<Shared>,
worker: Mutex<Option<JoinHandle<()>>>,
@@ -159,6 +168,27 @@ impl ProjectIndex {
}
}
/// The extensions of the indexed files, most common first: the project's file
/// types, for suggestions such as Find in Files' file masks. Dotfiles
/// (`.gitignore`) have no extension.
pub fn file_extensions(&self) -> Vec<ExtensionCount> {
let d = self.shared.data.read();
let mut counts: HashMap<String, u32> = HashMap::new();
for file in d.files.iter().flatten() {
let name = &file.rel[file.name_start as usize..];
if let Some((stem, extension)) = name.rsplit_once('.')
&& !stem.is_empty()
&& !extension.is_empty()
{
*counts.entry(extension.to_ascii_lowercase()).or_default() += 1;
}
}
let mut out: Vec<ExtensionCount> =
counts.into_iter().map(|(extension, files)| ExtensionCount { extension, files }).collect();
out.sort_by(|a, b| b.files.cmp(&a.files).then_with(|| a.extension.cmp(&b.extension)));
out
}
/// Fuzzy file search. IDEA-like ranking: file-name matches beat directory
/// matches; `/` in the query matches path segments; recently opened files boost.
pub fn find_files(&self, query: &str, limit: usize) -> Vec<FileMatch> {
+22
Переглянути файл
@@ -111,6 +111,28 @@ fn indexes_files_and_symbols_honouring_excludes() {
assert_eq!(m.path, fx.root.join("src/main.rs"));
}
#[test]
fn counts_file_extensions_most_common_first() {
let fx = Fixture::new(&[
("src/a.rs", "fn a() {}\n"),
("src/b.RS", "fn b() {}\n"),
("src/lib.rs", "fn c() {}\n"),
("Cargo.toml", "[package]\n"),
("README.md", "# r\n"),
("docs/guide.md", "# g\n"),
(".gitignore", "target\n"),
("Makefile", "all:\n"),
("target/debug/gen.rs", "fn generated() {}\n"),
]);
let idx = fx.open();
let counts: Vec<(String, u32)> = idx.file_extensions().into_iter().map(|c| (c.extension, c.files)).collect();
assert_eq!(
counts,
[("rs".into(), 3), ("md".into(), 2), ("toml".into(), 1)],
"case-folded, excluded folders and extension-less files left out"
);
}
#[test]
fn file_ranking_is_idea_like() {
let fx = sample();
+43 -1
Переглянути файл
@@ -23,6 +23,7 @@ mod scope;
mod server;
mod tcp;
mod text;
mod ts_file_moves;
mod tsserver_bridge;
pub mod types;
mod uri;
@@ -1692,6 +1693,20 @@ impl LspManager {
Ok(())
}
/// 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.
pub async fn provides_command(&self, doc: DocId, server: Option<ide_core::ServerId>, name: &str) -> bool {
let servers = match self.snapshot(doc) {
Ok(snap) => snap.servers,
Err(_) => self.servers.lock().clone(),
};
self.ready_targets(&servers, |c| c.commands().iter().any(|c| c == name))
.await
.iter()
.any(|t| server.is_none_or(|s| t.server.id == s))
}
async fn command_target(&self, doc: DocId, server: ide_core::ServerId, name: &str) -> IdeResult<Target> {
let snap = self.snapshot(doc)?;
self.ready_targets(&snap.servers, |c| c.commands().iter().any(|c| c == name))
@@ -1710,6 +1725,10 @@ impl LspManager {
answers: Vec<FormAnswer>,
cancel: CancellationToken,
) -> IdeResult<Option<CommandForm>> {
// Nothing to ask for a command its server doesn't provide (executing it decides).
if !self.provides_command(doc, Some(server), &command.command).await {
return Ok(None);
}
let t = self.command_target(doc, server, &command.command).await?;
let interactive = t.server.name == "gopls"
&& t.caps()
@@ -1992,7 +2011,30 @@ impl LspManager {
servers.iter().zip(ready).filter_map(|(s, run)| Some(Target { server: s.clone(), run: run? })).collect();
let mut out = FileRenameEdits::default();
for t in targets {
let Some(params) = Self::file_op_params(&t, "willRename", &moves) else { continue };
let Some(params) = Self::file_op_params(&t, "willRename", &moves) else {
if t.server.config.tsserver_project && t.caps().commands().iter().any(|c| c == ts_file_moves::COMMAND) {
out.servers.push(t.server.name.clone());
let opened = self.open_for_file_op(&t, &moves);
for (from, to, _) in &moves {
let r: IdeResult<Value> = self
.call(
&t,
"workspace/executeCommand",
ts_file_moves::request(from, to),
Some(&cancel),
LONG_TIMEOUT,
)
.await;
match r {
Ok(result) => out.edit.files.extend(ts_file_moves::edit(&result).files),
Err(e) if e.kind == ErrorKind::Cancelled && cancel.is_cancelled() => return Err(e),
Err(e) => out.errors.push(e.message),
}
}
drop(opened);
}
continue;
};
out.servers.push(t.server.name.clone());
let opened = self.open_for_file_op(&t, &moves);
let r: IdeResult<Option<lsp::WorkspaceEdit>> =
+89
Переглянути файл
@@ -0,0 +1,89 @@
//! Reference updates for moved files from vtsls, which has no `workspace/willRenameFiles`:
//! it updates imports itself after `didRenameFiles`, behind a prompt the client answers. The
//! IDE asks tsserver for the same edits up front (`getEditsForFileRename`, through
//! `typescript.tsserverRequest`), so they join the move's preview and undo, and the server's
//! own update is off (`updateImportsOnFileMove.enabled = "never"` in `languages/*.toml`).
use ide_core::{FileEdit, Pos, Range, TextEdit, WorkspaceEdit};
use serde::Deserialize;
use serde_json::{Value, json};
use std::path::PathBuf;
pub(crate) const COMMAND: &str = "typescript.tsserverRequest";
/// The `typescript.tsserverRequest` arguments asking for the edits of moving `from` to `to`.
pub(crate) fn request(from: &std::path::Path, to: &std::path::Path) -> Value {
json!({
"command": COMMAND,
"arguments": ["getEditsForFileRename", { "oldFilePath": from, "newFilePath": to }],
})
}
#[derive(Deserialize)]
struct Location {
line: u32,
offset: u32,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Change {
start: Location,
end: Location,
new_text: String,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct FileChanges {
file_name: PathBuf,
text_changes: Vec<Change>,
}
/// tsserver's `FileCodeEdits[]` (the command's `body`; 1-based lines and UTF-16 offsets) as an edit.
pub(crate) fn edit(result: &Value) -> WorkspaceEdit {
let body = result.get("body").unwrap_or(result);
let files: Vec<FileChanges> = serde_json::from_value(body.clone()).unwrap_or_default();
let pos = |l: &Location| Pos::new(l.line.saturating_sub(1), l.offset.saturating_sub(1));
WorkspaceEdit {
files: files
.into_iter()
.filter(|f| !f.text_changes.is_empty())
.map(|f| FileEdit::Edit {
path: f.file_name.into(),
edits: f
.text_changes
.into_iter()
.map(|c| TextEdit { range: Range::new(pos(&c.start), pos(&c.end)), new_text: c.new_text })
.collect(),
version: None,
})
.collect(),
preconditions: Vec::new(),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn converts_tsserver_file_code_edits() {
let result = json!({ "success": true, "body": [
{ "fileName": "/p/src/index.ts", "textChanges": [
{ "start": { "line": 2, "offset": 31 }, "end": { "line": 2, "offset": 41 }, "newText": "./lib/money.ts" }
] },
{ "fileName": "/p/src/unchanged.ts", "textChanges": [] }
] });
let edit = edit(&result);
assert_eq!(edit.files.len(), 1);
let FileEdit::Edit { path, edits, version } = &edit.files[0] else { panic!("{edit:?}") };
assert_eq!(**path, *std::path::Path::new("/p/src/index.ts"));
assert_eq!(
edits,
&[TextEdit { range: Range::new(Pos::new(1, 30), Pos::new(1, 40)), new_text: "./lib/money.ts".into() }]
);
assert!(version.is_none());
assert!(super::edit(&json!({ "success": false })).files.is_empty());
}
}
+35
Переглянути файл
@@ -2336,6 +2336,41 @@ async fn will_and_did_rename_files_honour_filters() {
);
}
#[tokio::test(flavor = "multi_thread")]
async fn will_rename_files_asks_tsserver_when_the_server_has_no_file_operations() {
// vtsls: no `willRename` filters, but tsserver's `getEditsForFileRename` through its command.
let mut caps = incremental_caps();
caps["executeCommandProvider"] = json!({ "commands": ["typescript.tsserverRequest"] });
let h = harness_configured("typescript", "ts", &[("vtsls", caps)], |cfg| cfg.tsserver_project = true);
let money = h.root.join("money.ts");
let index = h.root.join("index.ts");
std::fs::write(&money, "export const one = 1;\n").unwrap();
std::fs::write(&index, "import { one } from \"./money\";\n").unwrap();
let s = h.launcher.state("vtsls");
*s.responder.lock() = Some(Arc::new(move |_, method, p| {
(method == "workspace/executeCommand" && p["arguments"][0] == "getEditsForFileRename").then(|| {
json!({ "success": true, "body": [{ "fileName": p["arguments"][1]["oldFilePath"].as_str().unwrap().replace("money.ts", "index.ts"),
"textChanges": [{ "start": { "line": 1, "offset": 22 }, "end": { "line": 1, "offset": 29 }, "newText": "./lib/money" }] }] })
})
}));
let to = h.root.join("lib/money.ts");
let result =
h.mgr.will_rename_files(&[(money.clone(), to.clone())], ide_core::CancellationToken::new()).await.unwrap();
assert_eq!(result.servers, vec!["vtsls".to_owned()]);
assert!(result.errors.is_empty(), "{:?}", result.errors);
match &result.edit.files[..] {
[FileEdit::Edit { path, edits, version: None }] => {
assert_eq!(path, &index);
assert_eq!(edits[0].range, rng(0, 21, 0, 28));
assert_eq!(edits[0].new_text, "./lib/money");
}
other => panic!("unexpected edit {other:?}"),
}
let asked = s.requested("workspace/executeCommand");
let asked = asked.iter().find(|r| r["arguments"][0] == "getEditsForFileRename").unwrap();
assert_eq!(asked["arguments"][1], json!({ "oldFilePath": money, "newFilePath": to }));
}
// ------------------------------------------------------------------ inspect code
struct InspectTestHost {
+41 -1
Переглянути файл
@@ -143,7 +143,10 @@ impl Mappings {
}
let (l, rest, _) = best?;
// A `..` from the server must not leave the local folder.
if rest.split('/').any(|s| s == ".." || s == ".") {
if rest.split('/').filter(|s| !s.is_empty()).any(|s| {
let mut components = Path::new(s).components();
!matches!(components.next(), Some(Component::Normal(_))) || components.next().is_some()
}) {
return None;
}
Some(rest.split('/').filter(|s| !s.is_empty()).fold(l.clone(), |p, s| p.join(s)))
@@ -307,6 +310,43 @@ mod tests {
assert_eq!(local_folder("/src/", &root), Some(root.join("src")));
}
#[cfg(windows)]
#[test]
fn native_anchors_never_replace_the_project_relative_fallback() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("project");
let inside = root.join("src");
let outside = tmp.path().join("outside");
let missing = tmp.path().join("missing");
std::fs::create_dir_all(&inside).unwrap();
std::fs::create_dir(&outside).unwrap();
for slash in ["\\", "/"] {
let spelling = |path: &Path| path.to_string_lossy().replace('\\', slash);
assert_eq!(local_folder(&spelling(&inside), &root), Some(inside.clone()));
assert_eq!(local_folder(&spelling(&outside), &root), None);
assert_eq!(local_folder(&spelling(&missing), &root), Some(root.join(posix(&missing))));
assert_eq!(local_folder(&format!("{slash}src{slash}"), &root), Some(inside.clone()));
}
}
#[test]
fn remote_paths_cannot_replace_or_leave_a_local_mapping() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let m = Mappings::new(&server(vec![]), root, "/srv");
for remote in ["/srv/../outside", "/srv/./file"] {
assert_eq!(m.local(remote), None, "{remote}");
}
#[cfg(windows)]
for remote in
["/srv/..\\outside", "/srv/C:\\outside", "/srv/\\outside", "/srv/dir\\..\\outside", "/srv/C:/outside"]
{
assert_eq!(m.local(remote), None, "{remote}");
}
assert_eq!(m.local("/srv/dir/file"), Some(root.join("dir/file")));
assert_eq!(m.local("/srv"), Some(root.to_path_buf()));
}
#[cfg(unix)]
#[test]
fn absolute_symlink_inside_project_resolves_to_the_project_spelling() {
+17 -7
Переглянути файл
@@ -267,19 +267,29 @@ impl Session {
}),
)
.await?;
let failed = |code: Option<u32>| {
let err = String::from_utf8_lossy(&stderr.lock()).trim().to_owned();
io(format!("cannot write {remote} on {} ({code:?}): {err}", self.label))
};
// A command that exits early (no gzip, a folder it cannot write) stops reading: a
// write would wait for channel window forever, so each one races the exit.
let mut exit = std::pin::pin!(process.wait());
let mut sent = 0;
for chunk in packed.chunks(256 * 1024) {
process.write(chunk).await?;
tokio::select! {
written = process.write(chunk) => written?,
code = &mut exit => return Err(failed(code)),
}
sent += chunk.len();
progress(sent as f64 / packed.len().max(1) as f64);
}
process.eof().await?;
match process.wait().await {
tokio::select! {
closed = process.eof() => closed?,
code = &mut exit => return Err(failed(code)),
}
match exit.await {
Some(0) => Ok(()),
code => {
let err = String::from_utf8_lossy(&stderr.lock()).trim().to_owned();
Err(io(format!("cannot write {remote} on {} ({code:?}): {err}", self.label)))
}
code => Err(failed(code)),
}
}
+23
Переглянути файл
@@ -269,3 +269,26 @@ async fn runs_commands_and_streams_processes() {
assert_eq!(process.wait().await, Some(3));
assert_eq!(*seen.lock(), ("ran: python3 main.py".to_owned(), "oops".to_owned()));
}
#[tokio::test]
async fn upload_reports_a_command_that_stops_reading() {
let env = env().await;
let session = env.connect_trusted(&env.target(SshAuth::Password), Some("secret")).await.ok().unwrap();
// Incompressible and larger than the channel window: the command exits (status 3, `oops`)
// without reading it, as when the host has no gzip or the folder is not writable.
let mut state = 0x9e37_79b9_7f4a_7c15_u64;
let data: Vec<u8> = (0..8 << 20)
.map(|_| {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
state as u8
})
.collect();
let put = session.put("/home/dev/.openidea/server/openidea-server", &data);
let err = tokio::time::timeout(std::time::Duration::from_secs(20), put)
.await
.expect("the upload must end when the command exits")
.unwrap_err();
assert!(err.message.contains("oops"), "{}", err.message);
}
+2
Переглянути файл
@@ -15,6 +15,8 @@ serde_json.workspace = true
specta.workspace = true
gix = { workspace = true, features = ["sha1", "sha256", "status", "blob-diff", "revision", "index", "dirwalk", "parallel"] }
tracing.workspace = true
redb.workspace = true
blake3.workspace = true
tempfile.workspace = true
which = "8"
regex-lite = "0.1"
+192
Переглянути файл
@@ -0,0 +1,192 @@
//! Bek branch partitioning and bottom-up block merge.
//! Adapted from JetBrains intellij-community BekBranchCreator/BekBranch/Merger,
//! Copyright 2000-2026 JetBrains s.r.o. and contributors, Apache-2.0.
use std::cmp::Reverse;
use std::collections::{BinaryHeap, HashSet};
pub(crate) fn sort(parents: &[Vec<usize>], times: &[i64], heads: &[usize]) -> Vec<usize> {
let n = parents.len();
let mut children = vec![Vec::new(); n];
for (i, ps) in parents.iter().enumerate() {
for &p in ps {
children[p].push(i);
}
}
let mut layout = vec![0usize; n];
let mut important = Vec::new();
let mut next_layout = 1;
for &head in heads {
if layout[head] != 0 {
continue;
}
important.push(head);
let mut stack = vec![head];
while let Some(&node) = stack.last() {
let first = layout[node] == 0;
if first {
layout[node] = next_layout;
}
if let Some(&p) = parents[node].iter().find(|&&p| layout[p] == 0) {
stack.push(p);
} else {
if first {
next_layout += 1;
}
stack.pop();
}
}
}
let mut done = vec![false; n];
let mut restrictions = vec![HashSet::new(); n];
let mut releases = vec![Vec::new(); n];
let mut branches = Vec::new();
for head in important {
if done[head] {
continue;
}
let start = layout[head];
done[head] = true;
let mut branch = vec![head];
let mut stack = vec![head];
while let Some(&node) = stack.last() {
let mut next = None;
for &p in parents[node].iter().rev() {
if done[p] {
if layout[p] < start && restrictions[node].insert(p) {
releases[p].push(node);
}
} else if layout[node] <= layout[p] && !children[p].iter().any(|&c| !done[c] && layout[c] <= layout[p])
{
next = Some(p);
break;
}
}
if let Some(p) = next {
done[p] = true;
branch.push(p);
stack.push(p);
} else {
stack.pop();
}
}
branches.push(branch);
}
let mut owner = vec![0usize; n];
for (b, nodes) in branches.iter().enumerate() {
for &node in nodes {
owner[node] = b;
}
}
let mut remaining: Vec<_> = branches.iter().map(Vec::len).collect();
let mut prepared = vec![None; branches.len()];
let mut queue = BinaryHeap::new();
let prepare = |b: usize,
remaining: &[usize],
restrictions: &[HashSet<usize>],
prepared: &mut [Option<usize>],
queue: &mut BinaryHeap<Reverse<(i64, usize)>>| {
let end = remaining[b];
if end == 0 || prepared[b].is_some() || !restrictions[branches[b][end - 1]].is_empty() {
return;
}
let mut start = end - 1;
while start > 0 {
let up = branches[b][start - 1];
let down = branches[b][start];
if !restrictions[up].is_empty() {
break;
}
let connects = parents[up].contains(&down);
if !(parents[up].len() > 1 && connects) {
if !connects {
break;
}
let delta = times[up].abs_diff(times[down]);
if delta > 3 * 24 * 3600 || (start + 20 < end && delta > 4 * 3600) {
break;
}
}
start -= 1;
}
prepared[b] = Some(start);
queue.push(Reverse((times[branches[b][start]], b)));
};
for b in 0..branches.len() {
prepare(b, &remaining, &restrictions, &mut prepared, &mut queue);
}
let mut result = vec![0; n];
let mut offset = n;
while let Some(Reverse((_, b))) = queue.pop() {
let start = prepared[b].take().unwrap();
let part = &branches[b][start..remaining[b]];
offset -= part.len();
result[offset..offset + part.len()].copy_from_slice(part);
remaining[b] = start;
let mut released = HashSet::from([b]);
for &node in part {
for &up in &releases[node] {
restrictions[up].remove(&node);
let branch = owner[up];
if restrictions[up].is_empty() && remaining[branch] > 0 && branches[branch][remaining[branch] - 1] == up
{
released.insert(branch);
}
}
}
for branch in released {
prepare(branch, &remaining, &restrictions, &mut prepared, &mut queue);
}
}
debug_assert_eq!(offset, 0, "Bek must place every node");
result
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn branch_blocks_preserve_every_edge_under_clock_skew_and_interleaved_refs() {
let mut seed = 17u64;
let mut random = || {
seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1);
seed as usize
};
for _ in 0..200 {
let n = 70;
let parents: Vec<Vec<usize>> = (0..n)
.map(|i| {
let mut ps = Vec::new();
if i + 1 < n {
for _ in 0..(random() % 3 + 1) {
let p = i + 1 + random() % (n - i - 1);
if !ps.contains(&p) {
ps.push(p);
}
}
}
ps
})
.collect();
let times: Vec<_> = (0..n).map(|_| (random() % 1_000_000) as i64).collect();
let mut children = vec![0; n];
for ps in &parents {
for &p in ps {
children[p] += 1;
}
}
let mut heads: Vec<_> = (0..n).filter(|&i| children[i] == 0 || i % 11 == 0).collect();
heads.sort_by_cached_key(|_| random());
let result = sort(&parents, &times, &heads);
assert_eq!(result.iter().copied().collect::<HashSet<_>>().len(), n);
let mut positions = vec![0; n];
for (i, &node) in result.iter().enumerate() {
positions[node] = i;
}
for (node, ps) in parents.iter().enumerate() {
for &p in ps {
assert!(positions[node] < positions[p]);
}
}
}
}
}
File diff suppressed because it is too large. Load diff
+254 -3
Переглянути файл
@@ -112,22 +112,64 @@ pub struct Commit {
pub id: String,
pub short_id: String,
pub parents: Vec<String>,
/// Connections in the filtered graph; never use these as revision/diff parents.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub graph_parents: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub graph_dashed: Vec<bool>,
/// Repository-relative filename at this revision in rename-following history.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub history_path: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub log_position: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub log_total: Option<u32>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub graph_boundary_parents: Vec<String>,
/// Reachability from HEAD, computed independently of the visible filters.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub on_current_branch: Option<bool>,
pub author: String,
pub email: String,
#[serde(default)]
pub committer: String,
#[serde(default)]
pub committer_email: String,
pub time_ms: f64,
pub summary: String,
pub message: String,
#[serde(default)]
pub message_truncated: bool,
pub refs: Vec<String>,
/// Committer time (Log › View Options › Commit Timestamp).
#[serde(default)]
pub commit_time_ms: f64,
/// Per parent, under a user or text filter: the link passes commits the filter hides
/// (`parents` then name the nearest shown ancestors). Empty when no parent is rewritten.
/// Legacy alias of `graph_dashed`, indexed by displayed parents.
#[serde(default)]
#[specta(optional)]
pub dashed: Vec<bool>,
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct LogDetails {
pub message: String,
pub containing_branches: Vec<String>,
/// Git's verification code: G/U good, B bad, E error, N unsigned, X/Y expired, R revoked.
pub signature: String,
pub signer: String,
pub key: String,
pub fingerprint: String,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct LogIndexProgress {
pub indexed: u32,
pub total: u32,
pub running: bool,
}
/// Order of the Git Log (Graph Options › Sort).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
@@ -137,13 +179,29 @@ pub enum LogOrder {
Topo,
/// `--date-order`: commit time, but never a parent before its children.
Date,
// Topological grouping with incoming merge parents visited before the main line.
Standard,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct LogQuery {
#[serde(default)]
pub speed_search: Option<String>,
#[serde(default)]
pub search_fields: Vec<String>,
/// Jump directly to an indexed window containing this commit (50 rows of context).
#[serde(default)]
pub seek: Option<String>,
#[serde(default)]
pub retain_until: Option<String>,
pub branch: Option<String>,
pub path: Option<ide_core::IpcPath>,
#[serde(default)]
pub paths: Vec<ide_core::IpcPath>,
/// File history follows renames; structure filters retain fixed paths.
#[serde(default)]
pub follow: bool,
pub author: Option<String>,
pub text: Option<String>,
pub skip: u32,
@@ -152,6 +210,9 @@ pub struct LogQuery {
/// not the left). Takes precedence over `branch`.
#[serde(default)]
pub range: Option<String>,
/// Additional ranges unioned with each other and with selected branches.
#[serde(default)]
pub ranges: Vec<String>,
/// `text` is a regular expression (Log filter `.*`).
#[serde(default)]
pub text_regex: bool,
@@ -165,6 +226,8 @@ pub struct LogQuery {
#[serde(default)]
pub authors: Vec<String>,
#[serde(default)]
pub authors_exact: bool,
#[serde(default)]
pub order: LogOrder,
/// Follow only the first parent of merges (`--first-parent`).
#[serde(default)]
@@ -179,6 +242,13 @@ pub struct LogQuery {
pub since_ms: Option<f64>,
#[serde(default)]
pub until_ms: Option<f64>,
#[serde(default)]
pub request: Option<ide_core::RequestId>,
#[serde(default)]
pub summary_only: bool,
/// Inclusive refresh boundary. Clients join only verified linear prefixes.
#[serde(default)]
pub stop_at: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
@@ -487,6 +557,7 @@ pub struct ChangelistState {
pub files: std::collections::BTreeMap<String, String>,
}
mod bek;
mod blame;
mod block_history;
pub mod changelists;
@@ -496,6 +567,7 @@ mod diff;
mod history;
mod ignore;
mod index_writes;
mod log_index;
mod manage;
mod ops;
mod patch;
@@ -599,6 +671,9 @@ pub struct Repo {
git_dir: PathBuf,
inner: std::sync::Mutex<repo::Cache>,
ignored: std::sync::RwLock<IgnoredNames>,
log_index: std::sync::Mutex<log_index::LogIndex>,
index_progress: std::sync::Mutex<LogIndexProgress>,
log_signatures: std::sync::Mutex<std::collections::HashMap<String, LogDetails>>,
}
impl Repo {
@@ -738,7 +813,183 @@ impl Repo {
/// `refs` decorations are `HEAD`, branch names (`main`, `origin/main`) and `tag: <name>`.
pub fn log(&self, query: &LogQuery) -> IdeResult<Vec<Commit>> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
history::log(self, query)
history::log(self, query, &CancellationToken::new())
}
pub fn log_cancellable(&self, query: &LogQuery, cancel: &CancellationToken) -> IdeResult<Vec<Commit>> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
history::log(self, query, cancel)
}
/// Enables the disposable, content-addressed log cache outside the worktree.
pub fn enable_log_index(&self, cache_dir: &Path) {
let key = blake3::hash(self.git_dir.to_string_lossy().as_bytes()).to_hex().to_string();
self.log_index.lock().unwrap_or_else(|p| p.into_inner()).open(&cache_dir.join(key));
}
/// Reference names and peeled commit ids, including tags and detached HEAD.
pub fn log_refs(&self) -> IdeResult<std::collections::BTreeMap<String, String>> {
let repo = self.gix()?;
Ok(history::decorations(&repo)?
.into_iter()
.flat_map(|(id, names)| names.into_iter().map(move |name| (name, id.to_string())))
.collect())
}
pub fn log_users(&self) -> IdeResult<Vec<String>> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let out = cli::run(self.root(), &["log", "--all", "--format=%an <%ae>"], None)?;
Ok(out
.stdout_str()
.lines()
.filter(|line| !line.is_empty())
.map(str::to_string)
.collect::<std::collections::BTreeSet<_>>()
.into_iter()
.collect())
}
pub fn log_index_progress(&self) -> LogIndexProgress {
self.index_progress.lock().unwrap_or_else(|p| p.into_inner()).clone()
}
/// Incremental persistent inverted index; completed objects survive cancellation/restart.
pub fn index_log(&self, cancel: &CancellationToken) -> IdeResult<LogIndexProgress> {
{
let mut progress = self.index_progress.lock().unwrap_or_else(|p| p.into_inner());
if progress.running {
return Ok(progress.clone());
}
progress.running = true;
}
let result = (|| {
let repo = self.gix()?;
let out = cli::run_cancellable(self.root(), &["rev-list", "--all", "--topo-order"], cancel)?;
let ids: Vec<_> = out
.stdout_str()
.lines()
.map(|id| gix::ObjectId::from_hex(id.as_bytes()).map_err(repo::gx))
.collect::<IdeResult<_>>()?;
{
let mut p = self.index_progress.lock().unwrap_or_else(|p| p.into_inner());
p.total = ids.len() as u32;
p.indexed = 0;
}
for (i, id) in ids.iter().enumerate() {
if cancel.is_cancelled() {
return Err(ide_core::IdeError::cancelled());
}
let indexed = self.log_index.lock().unwrap_or_else(|p| p.into_inner()).indexed(&id.to_string());
if !indexed {
let files = self.commit_files(&id.to_string())?;
let paths =
files.into_iter().flat_map(|f| std::iter::once(f.path).chain(f.old_path)).collect::<Vec<_>>();
let mut index = self.log_index.lock().unwrap_or_else(|p| p.into_inner());
let c = index.get(&repo, *id)?;
let message = index.message(&repo, *id)?;
index.index_commit(&c.id, &message, &c.author, &c.email, &paths);
if i % 100 == 0 {
index.flush();
}
}
self.index_progress.lock().unwrap_or_else(|p| p.into_inner()).indexed = i as u32 + 1;
}
Ok(())
})();
self.log_index.lock().unwrap_or_else(|p| p.into_inner()).flush();
self.index_progress.lock().unwrap_or_else(|p| p.into_inner()).running = false;
result?;
Ok(self.log_index_progress())
}
pub fn log_details(&self, revision: &str) -> IdeResult<LogDetails> {
self.log_details_cancellable(revision, &CancellationToken::new())
}
pub fn log_details_cancellable(&self, revision: &str, cancel: &CancellationToken) -> IdeResult<LogDetails> {
let allowed = self.execution_allowed.load(std::sync::atomic::Ordering::Acquire);
let _scope = crate::ExecutionScope::enter(allowed);
let repo = self.gix()?;
let object =
repo.find_object(repo::resolve(&repo, revision)?).map_err(repo::gx)?.peel_to_commit().map_err(repo::gx)?;
let commit_id = object.id;
let id = commit_id.to_string();
let contains = format!("--contains={id}");
let branches =
cli::run_cancellable(self.root(), &["branch", "-a", &contains, "--format=%(refname:short)"], cancel)?;
let cache_key = format!("{allowed}:{id}");
let cached = self.log_signatures.lock().unwrap_or_else(|p| p.into_inner()).get(&cache_key).cloned();
let mut details = if let Some(details) = cached {
details
} else {
let end = object.data.windows(2).position(|s| s == b"\n\n").unwrap_or(object.data.len());
let headers = &object.data[..end];
let signed = headers.windows(8).any(|s| s == b"\ngpgsig ") || headers.windows(8).any(|s| s == b"\ngpgsig-");
let output = if allowed && signed {
Some(cli::run_cancellable(
self.root(),
&["log", "-1", "--format=%G?%x00%GS%x00%GK%x00%GF", "--end-of-options", &id],
cancel,
)?)
} else {
None
};
let text = output.as_ref().map(|out| out.stdout_str()).unwrap_or_default();
let fields: Vec<_> = text.trim_end().split('\0').collect();
let message = {
let mut index = self.log_index.lock().unwrap_or_else(|p| p.into_inner());
let message = index.message(&repo, commit_id)?;
index.flush();
message
};
let details = LogDetails {
message,
containing_branches: Vec::new(),
signature: if !signed {
"N".into()
} else {
fields.first().filter(|s| !s.is_empty()).unwrap_or(&"E").to_string()
},
signer: fields.get(1).unwrap_or(&"").to_string(),
key: fields.get(2).unwrap_or(&"").to_string(),
fingerprint: fields.get(3).unwrap_or(&"").to_string(),
};
self.log_signatures.lock().unwrap_or_else(|p| p.into_inner()).insert(cache_key, details.clone());
details
};
details.containing_branches =
branches.stdout_str().lines().filter(|s| !s.ends_with("/HEAD")).map(str::to_string).collect();
Ok(details)
}
/// Lists one immutable revision directory. Directory names end in `/`.
pub fn revision_children(&self, revision: &str, directory: &str) -> IdeResult<Vec<String>> {
let repo = self.gix()?;
let id = repo::resolve(&repo, revision)?.to_string();
let directory = self.rel_path(std::path::Path::new(directory))?;
let tree = if directory.is_empty() { id } else { format!("{id}:{directory}") };
let out = cli::run(self.root(), &["ls-tree", "-z", "--", &tree], None)?;
Ok(out
.stdout
.split(|b| *b == 0)
.filter_map(|line| {
let split = line.iter().position(|b| *b == b'\t')?;
let name = String::from_utf8_lossy(&line[split + 1..]);
let dir = line.starts_with(b"040000 ");
Some(format!(
"{}{name}{}",
if directory.is_empty() { String::new() } else { format!("{directory}/") },
if dir { "/" } else { "" }
))
})
.collect())
}
pub fn revision_files(&self, revision: &str) -> IdeResult<Vec<String>> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let repo = self.gix()?;
let id = repo::resolve(&repo, revision)?.to_string();
let out = cli::run(self.root(), &["ls-tree", "-r", "-z", "--name-only", "--", &id], None)?;
Ok(out
.stdout
.split(|b| *b == 0)
.filter(|p| !p.is_empty())
.map(|p| String::from_utf8_lossy(p).into_owned())
.collect())
}
/// Files changed by `commit` relative to its first parent (renames detected).
pub fn commit_files(&self, commit: &str) -> IdeResult<Vec<ChangedFile>> {
+385
Переглянути файл
@@ -0,0 +1,385 @@
//! Immutable commit metadata, persisted by object id. Ref decorations and graph
//! projections are deliberately never cached as commit metadata.
use crate::Commit;
use crate::repo::{gx, to_string};
use gix::ObjectId;
use gix::bstr::ByteSlice;
use ide_core::IdeResult;
use redb::{Database, MultimapTableDefinition, ReadableDatabase, TableDefinition};
use std::collections::{HashMap, HashSet};
use std::path::Path;
use std::sync::{Arc, Mutex, OnceLock, Weak};
use std::time::SystemTime;
const COMMITS: TableDefinition<&str, &[u8]> = TableDefinition::new("summaries-v2");
const MESSAGES: TableDefinition<&str, &str> = TableDefinition::new("messages-v1");
const PATHS: TableDefinition<&str, &[u8]> = TableDefinition::new("paths-v2");
const POSTINGS: MultimapTableDefinition<&str, &str> = MultimapTableDefinition::new("search-v1");
const INDEXED: TableDefinition<&str, bool> = TableDefinition::new("indexed-v1");
pub(crate) struct IndexedView {
pub commits: Vec<Commit>,
pub positions: HashMap<String, usize>,
}
impl IndexedView {
pub fn new(commits: Vec<Commit>) -> Self {
let positions = commits.iter().enumerate().map(|(i, c)| (c.id.clone(), i)).collect();
Self { commits, positions }
}
}
#[derive(Default)]
pub(crate) struct LogIndex {
opened: bool,
db: Option<Arc<Database>>,
memory: HashMap<ObjectId, Arc<Commit>>,
dirty: Vec<Arc<Commit>>,
dirty_messages: Vec<(String, String)>,
dirty_search: Vec<(String, Vec<String>)>,
path_memory: HashMap<(ObjectId, String), Option<(ObjectId, u16)>>,
dirty_paths: Vec<(String, Option<(String, u16)>)>,
pub head: Option<(ObjectId, Option<SystemTime>)>,
pub reachable: HashSet<ObjectId>,
pub views: HashMap<String, Arc<IndexedView>>,
pub nodes: HashMap<ObjectId, (Vec<ObjectId>, i64)>,
pub shallow: HashSet<ObjectId>,
}
impl LogIndex {
/// A permanent DAG: refresh discovers only new objects, then joins arbitrary
/// changed tips against known ancestry. Reachability is recomputed for resets/deleted refs.
pub fn graph(
&mut self,
repo: &gix::Repository,
tips: &[ObjectId],
shallow: &HashSet<ObjectId>,
first_parent: bool,
cancel: &ide_core::CancellationToken,
) -> IdeResult<Vec<ObjectId>> {
if &self.shallow != shallow {
self.nodes.clear();
self.shallow = shallow.clone();
}
let mut pending = tips.to_vec();
while let Some(id) = pending.pop() {
if cancel.is_cancelled() {
return Err(ide_core::IdeError::cancelled());
}
if self.nodes.contains_key(&id) {
continue;
}
let record = self.get(repo, id)?;
let parents: Vec<_> = if shallow.contains(&id) {
Vec::new()
} else {
record.parents.iter().map(|s| ObjectId::from_hex(s.as_bytes()).map_err(gx)).collect::<IdeResult<_>>()?
};
pending.extend(parents.iter().copied());
self.nodes.insert(id, (parents, (record.commit_time_ms / 1000.0) as i64));
}
let mut seen = HashSet::new();
let mut ids = Vec::new();
let mut pending = tips.to_vec();
while let Some(id) = pending.pop() {
if !seen.insert(id) {
continue;
}
ids.push(id);
if let Some((parents, _)) = self.nodes.get(&id) {
pending.extend(parents.iter().take(if first_parent { 1 } else { usize::MAX }).rev().copied());
}
}
Ok(ids)
}
pub fn indexed(&self, id: &str) -> bool {
self.db
.as_ref()
.and_then(|db| {
let txn = db.begin_read().ok()?;
let table = txn.open_table(INDEXED).ok()?;
Some(table.get(id).ok()??.value())
})
.unwrap_or(false)
}
pub fn index_commit(&mut self, id: &str, message: &str, author: &str, email: &str, paths: &[String]) {
let mut keys: HashSet<String> = Self::grams(message).into_iter().map(|s| format!("m:{s}")).collect();
for user in [author, email, email.split('@').next().unwrap_or(email)] {
keys.insert(format!("u:{}", normalize_user(user)));
}
for path in paths {
keys.insert(format!("p:{path}"));
}
self.dirty_search.push((id.into(), keys.into_iter().collect()));
}
fn grams(text: &str) -> Vec<String> {
let chars: Vec<_> = text.to_lowercase().chars().collect();
chars.windows(3).map(|s| s.iter().collect()).collect::<HashSet<_>>().into_iter().collect()
}
/// Missing/unindexed commits are always checked directly by the caller.
pub fn message_candidates(&self, text: &str) -> Option<HashSet<String>> {
let grams = Self::grams(text);
if grams.is_empty() {
return None;
}
let db = self.db.as_ref()?;
let txn = db.begin_read().ok()?;
let table = txn.open_multimap_table(POSTINGS).ok()?;
let mut candidates: Option<HashSet<String>> = None;
for gram in grams {
let values = table.get(format!("m:{gram}").as_str()).ok()?;
let ids: HashSet<_> = values.filter_map(Result::ok).map(|s| s.value().to_string()).collect();
candidates = Some(match candidates {
Some(old) => old.intersection(&ids).cloned().collect(),
None => ids,
});
if candidates.as_ref().is_some_and(HashSet::is_empty) {
break;
}
}
Some(candidates.unwrap_or_default())
}
pub fn user_candidates(&self, authors: &[String]) -> Option<HashSet<String>> {
let txn = self.db.as_ref()?.begin_read().ok()?;
let table = txn.open_multimap_table(POSTINGS).ok()?;
let mut ids = HashSet::new();
for author in authors {
let name = author.split('<').next().unwrap_or(author).trim();
let email = author.split('<').nth(1).map(|s| s.trim_end_matches('>')).unwrap_or(author);
for alias in [name, email, email.split('@').next().unwrap_or(email)] {
for value in table.get(format!("u:{}", normalize_user(alias)).as_str()).ok()?.filter_map(Result::ok) {
ids.insert(value.value().to_string());
}
}
}
Some(ids)
}
pub fn path_candidates(&self, paths: &[String]) -> Option<HashSet<String>> {
let txn = self.db.as_ref()?.begin_read().ok()?;
let table = txn.open_multimap_table(POSTINGS).ok()?;
let mut ids = HashSet::new();
for path in paths {
for value in table.get(format!("p:{path}").as_str()).ok()?.filter_map(Result::ok) {
ids.insert(value.value().to_string());
}
let prefix = format!("p:{path}/");
let end = format!("{prefix}{}", char::MAX);
for row in table.range(prefix.as_str()..end.as_str()).ok()?.filter_map(Result::ok) {
for value in row.1.filter_map(Result::ok) {
ids.insert(value.value().to_string());
}
}
}
Some(ids)
}
pub fn open(&mut self, dir: &Path) {
if self.opened {
return;
}
self.opened = true;
// Several windows can read the same worktree; redb permits one owning
// handle per file, shared here rather than silently disabling its index.
static DATABASES: OnceLock<Mutex<HashMap<std::path::PathBuf, Weak<Database>>>> = OnceLock::new();
let path = dir.join("commits.redb");
let mut databases = DATABASES.get_or_init(Mutex::default).lock().unwrap_or_else(|p| p.into_inner());
self.db = databases.get(&path).and_then(Weak::upgrade).or_else(|| {
let db = Arc::new(std::fs::create_dir_all(dir).ok().and_then(|_| Database::create(&path).ok())?);
databases.insert(path, Arc::downgrade(&db));
Some(db)
});
}
pub fn get(&mut self, repo: &gix::Repository, id: ObjectId) -> IdeResult<Arc<Commit>> {
if let Some(commit) = self.memory.get(&id) {
return Ok(commit.clone());
}
let key = id.to_string();
let cached = self.db.as_ref().and_then(|db| {
let txn = db.begin_read().ok()?;
let table = txn.open_table(COMMITS).ok()?;
let value = table.get(key.as_str()).ok()??;
serde_json::from_slice::<Commit>(value.value()).ok().filter(|c| c.id == key)
});
let commit = if let Some(commit) = cached {
Arc::new(commit)
} else {
let commit = repo.find_commit(id).map_err(gx)?;
let author = commit.author().map_err(gx)?;
let committer = commit.committer().map_err(gx)?;
let raw = commit.message_raw_sloppy();
let summary = raw.split(|b| *b == b'\n').find(|l| !l.trim().is_empty()).unwrap_or_default().trim();
let summary_text = to_string(summary.as_bstr());
let record = Arc::new(Commit {
id: key.clone(),
short_id: key[..key.len().min(8)].to_string(),
parents: commit.parent_ids().map(|p| p.to_string()).collect(),
graph_parents: None,
graph_dashed: Vec::new(),
dashed: Vec::new(),
on_current_branch: None,
author: to_string(author.name.trim().as_bstr()),
email: to_string(author.email.trim().as_bstr()),
committer: to_string(committer.name.trim().as_bstr()),
committer_email: to_string(committer.email.trim().as_bstr()),
time_ms: author.time().map(|t| t.seconds as f64 * 1000.0).unwrap_or(0.0),
commit_time_ms: committer.time().map(|t| t.seconds as f64 * 1000.0).unwrap_or(0.0),
summary: summary_text.clone(),
message: summary_text,
message_truncated: raw.trim() != summary,
history_path: None,
log_position: None,
log_total: None,
graph_boundary_parents: Vec::new(),
refs: Vec::new(),
});
if self.db.is_some() {
self.dirty.push(record.clone());
}
record
};
// Keep hot pages in memory; older metadata stays in the persistent index.
if self.memory.len() >= 4096 {
self.flush();
self.memory.clear();
}
self.memory.insert(id, commit.clone());
Ok(commit)
}
pub fn message(&mut self, repo: &gix::Repository, id: ObjectId) -> IdeResult<String> {
if let Some((_, message)) = self.dirty_messages.iter().find(|(key, _)| key == &id.to_string()) {
return Ok(message.clone());
}
let key = id.to_string();
let cached = self.db.as_ref().and_then(|db| {
let txn = db.begin_read().ok()?;
let table = txn.open_table(MESSAGES).ok()?;
Some(table.get(key.as_str()).ok()??.value().to_string())
});
if let Some(message) = cached {
return Ok(message);
}
let message = to_string(repo.find_commit(id).map_err(gx)?.message_raw_sloppy()).trim_end().to_string();
if self.db.is_some() {
self.dirty_messages.push((key, message.clone()));
}
Ok(message)
}
pub fn flush(&mut self) {
if self.dirty.is_empty()
&& self.dirty_paths.is_empty()
&& self.dirty_messages.is_empty()
&& self.dirty_search.is_empty()
{
return;
}
let result = (|| -> Result<(), Box<dyn std::error::Error>> {
let Some(db) = &self.db else {
return Ok(());
};
let txn = db.begin_write()?;
{
let mut table = txn.open_table(COMMITS)?;
for commit in &self.dirty {
let bytes = serde_json::to_vec(commit.as_ref())?;
table.insert(commit.id.as_str(), bytes.as_slice())?;
}
}
{
let mut table = txn.open_table(PATHS)?;
for (key, value) in &self.dirty_paths {
let bytes = serde_json::to_vec(value)?;
table.insert(key.as_str(), bytes.as_slice())?;
}
}
{
let mut table = txn.open_table(MESSAGES)?;
for (id, message) in &self.dirty_messages {
table.insert(id.as_str(), message.as_str())?;
}
}
{
let mut postings = txn.open_multimap_table(POSTINGS)?;
let mut indexed = txn.open_table(INDEXED)?;
for (id, keys) in &self.dirty_search {
for key in keys {
postings.insert(key.as_str(), id.as_str())?;
}
indexed.insert(id.as_str(), true)?;
}
}
txn.commit()?;
Ok(())
})();
if let Err(error) = result {
tracing::warn!("Git log cache write failed: {error}");
}
self.dirty_messages.clear();
self.dirty_search.clear();
self.dirty.clear();
self.dirty_paths.clear();
}
pub fn path_entry(
&mut self,
repo: &gix::Repository,
id: ObjectId,
path: &str,
) -> IdeResult<Option<(ObjectId, u16)>> {
let memory_key = (id, path.to_string());
if let Some(value) = self.path_memory.get(&memory_key) {
return Ok(*value);
}
let key = format!("{id}\0{path}");
let cached = self.db.as_ref().and_then(|db| {
let txn = db.begin_read().ok()?;
let table = txn.open_table(PATHS).ok()?;
let value = table.get(key.as_str()).ok()??;
serde_json::from_slice::<Option<(String, u16)>>(value.value()).ok()
});
let cached = match cached {
Some(None) => Some(None),
Some(Some((hex, mode))) => ObjectId::from_hex(hex.as_bytes()).ok().map(|id| Some((id, mode))),
None => None,
};
let value = if let Some(value) = cached {
value
} else {
let tree = repo.find_commit(id).map_err(gx)?.tree().map_err(gx)?;
let value = tree
.lookup_entry_by_path(Path::new(path))
.map_err(gx)?
.map(|entry| (entry.object_id(), entry.mode().value()));
if self.db.is_some() {
self.dirty_paths.push((key, value.map(|(id, mode)| (id.to_string(), mode))));
}
value
};
if self.path_memory.len() >= 4096 {
self.flush();
self.path_memory.clear();
}
self.path_memory.insert(memory_key, value);
Ok(value)
}
}
pub(crate) fn normalize_user(user: &str) -> String {
user.chars().filter(|c| c.is_alphanumeric()).flat_map(char::to_lowercase).collect()
}
pub(crate) fn matches_user(query: &str, name: &str, email: &str) -> bool {
let query_name = query.split('<').next().unwrap_or(query).trim();
let query_email = query.split('<').nth(1).map(|s| s.trim_end_matches('>')).unwrap_or(query);
let target =
[normalize_user(name), normalize_user(email), normalize_user(email.split('@').next().unwrap_or(email))];
[query_name, query_email, query_email.split('@').next().unwrap_or(query_email)]
.iter()
.any(|alias| target.contains(&normalize_user(alias)))
}
+3
Переглянути файл
@@ -64,6 +64,9 @@ pub(crate) fn discover(path: &Path) -> IdeResult<Option<Repo>> {
git_dir,
inner: std::sync::Mutex::new(cache),
ignored: Default::default(),
log_index: Default::default(),
index_progress: Default::default(),
log_signatures: Default::default(),
}))
}
+438
Переглянути файл
@@ -0,0 +1,438 @@
use ide_vcs::{LogOrder, LogQuery, Repo};
use std::io::Write;
use std::path::Path;
use std::process::{Command, Stdio};
fn git(dir: &Path, args: &[&str]) -> String {
let out = Command::new("git")
.current_dir(dir)
.args([
"-c",
"init.defaultBranch=main",
"-c",
"user.name=Test",
"-c",
"[email protected]",
"-c",
"commit.gpgsign=false",
])
.args(args)
.output()
.unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
String::from_utf8_lossy(&out.stdout).trim().to_string()
}
fn commit(dir: &Path, file: &str, message: &str) -> String {
std::fs::write(dir.join(file), message).unwrap();
git(dir, &["add", "-A"]);
git(dir, &["commit", "-qm", message]);
git(dir, &["rev-parse", "HEAD"])
}
#[test]
fn branch_and_independent_ranges_form_a_union() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
git(dir, &["init", "-q"]);
let root = commit(dir, "a", "root");
let first = commit(dir, "a", "first");
let second = commit(dir, "a", "second");
let third = commit(dir, "a", "third");
git(dir, &["checkout", "-qb", "side", &root]);
let side = commit(dir, "b", "side");
let repo = Repo::discover(dir).unwrap().unwrap();
for order in [LogOrder::Topo, LogOrder::Date, LogOrder::Standard] {
let log = repo
.log(&LogQuery {
branches: vec!["side".into()],
ranges: vec![format!("{root}..{first}"), format!("{second}..{third}")],
order,
..Default::default()
})
.unwrap();
let got: std::collections::HashSet<_> = log.iter().map(|c| c.id.clone()).collect();
assert_eq!(got, [root.clone(), first.clone(), third.clone(), side.clone()].into());
let ranges = repo
.log(&LogQuery {
ranges: vec![format!("{root}..{first}"), format!("{second}..{third}")],
order,
..Default::default()
})
.unwrap();
assert_eq!(
ranges.iter().map(|c| c.id.clone()).collect::<std::collections::HashSet<_>>(),
[first.clone(), third.clone()].into()
);
let positions: std::collections::HashMap<_, _> =
log.iter().enumerate().map(|(i, c)| (c.id.as_str(), i)).collect();
for (i, c) in log.iter().enumerate() {
for p in c.graph_parents.as_ref().unwrap() {
assert!(positions.get(p.as_str()).is_none_or(|p| *p > i));
}
}
}
}
#[test]
fn lazy_summaries_seek_and_index_survive_refresh_and_restart() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
git(dir, &["init", "-q"]);
let mut ids = Vec::new();
for i in 0..70 {
ids.push(commit(dir, "a", &format!("summary {i}\n\nneedle body {i}")));
}
let cache = tempfile::tempdir().unwrap();
let repo = Repo::discover(dir).unwrap().unwrap();
repo.enable_log_index(cache.path());
let query = LogQuery { summary_only: true, limit: 5, ..Default::default() };
let page = repo.log(&query).unwrap();
assert_eq!(page[0].message, "summary 69");
assert!(page[0].message_truncated);
assert_eq!(page[0].log_position, Some(0));
assert_eq!(page[0].log_total, Some(70));
let window = repo.log(&LogQuery { seek: Some(ids[5].clone()), limit: 20, ..query.clone() }).unwrap();
assert!(window.iter().any(|c| c.id == ids[5]));
assert!(window[0].log_position.unwrap() > 0);
assert!(repo.log(&LogQuery { request: Some(ide_core::RequestId(1)), ..query.clone() }).is_ok());
let cancel = ide_core::CancellationToken::new();
cancel.cancel();
assert!(repo.log_cancellable(&query, &cancel).is_err());
let progress = repo.index_log(&ide_core::CancellationToken::new()).unwrap();
assert_eq!((progress.indexed, progress.total, progress.running), (70, 70, false));
assert_eq!(repo.log(&LogQuery { text: Some("needle body 5".into()), ..query.clone() }).unwrap().len(), 5);
let new = commit(dir, "b", "new head");
let refreshed = repo.log(&LogQuery { retain_until: Some(ids[0].clone()), ..query.clone() }).unwrap();
assert_eq!(refreshed[0].id, new);
assert_eq!(refreshed.len(), 71);
drop(repo);
let repo = Repo::discover(dir).unwrap().unwrap();
repo.enable_log_index(cache.path());
let hit = repo.log(&LogQuery { text: Some("needle body 69".into()), ..query }).unwrap();
assert_eq!(hit[0].id, ids[69]);
assert_eq!(repo.log_details(&ids[69]).unwrap().message, "summary 69\n\nneedle body 69");
assert_eq!(repo.log_details(&ids[69]).unwrap().signature, "N");
}
#[test]
fn followed_history_carries_the_filename_at_each_revision() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
git(dir, &["init", "-q"]);
let first = commit(dir, "old.txt", "original");
git(dir, &["mv", "old.txt", "new.txt"]);
git(dir, &["commit", "-qm", "rename"]);
let renamed = git(dir, &["rev-parse", "HEAD"]);
let tip = commit(dir, "new.txt", "latest");
let repo = Repo::discover(dir).unwrap().unwrap();
let log = repo.log(&LogQuery { path: Some("new.txt".into()), follow: true, ..Default::default() }).unwrap();
assert_eq!(
log.iter().map(|c| (c.id.as_str(), c.history_path.as_deref())).collect::<Vec<_>>(),
vec![(tip.as_str(), Some("new.txt")), (renamed.as_str(), Some("new.txt")), (first.as_str(), Some("old.txt"))]
);
assert_eq!(repo.revision_children(&first, "").unwrap(), vec!["old.txt"]);
}
#[test]
fn detail_filters_connect_visible_ancestors_without_changing_revision_parents() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
git(dir, &["init", "-q"]);
let a = commit(dir, "a", "keep root");
commit(dir, "b", "hidden middle");
git(dir, &["commit", "--amend", "--no-edit", "--author=Other <[email protected]>"]);
let b = git(dir, &["rev-parse", "HEAD"]);
let c = commit(dir, "a", "keep tip");
let repo = Repo::discover(dir).unwrap().unwrap();
for q in [
LogQuery { text: Some("keep".into()), ..Default::default() },
LogQuery { path: Some("a".into()), ..Default::default() },
LogQuery { authors: vec!["Test".into()], authors_exact: true, ..Default::default() },
] {
let page = repo.log(&LogQuery { limit: 1, ..q.clone() }).unwrap();
assert_eq!(page[0].id, c);
assert_eq!(page[0].parents, vec![b.clone()]);
assert_eq!(page[0].graph_parents, Some(vec![a.clone()]));
assert_eq!(page[0].graph_dashed, vec![true]);
assert_eq!(page[0].on_current_branch, Some(true));
let next = repo.log(&LogQuery { skip: 1, limit: 1, ..q }).unwrap();
assert_eq!(next[0].id, a);
assert_eq!(next[0].graph_parents, Some(vec![]));
}
}
#[test]
fn all_history_includes_commits_reachable_only_from_tags() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
git(dir, &["init", "-q"]);
let root = commit(dir, "a", "root");
let tip = commit(dir, "a", "tagged tip");
git(dir, &["tag", "v1"]);
git(dir, &["reset", "--hard", &root]);
let repo = Repo::discover(dir).unwrap().unwrap();
let log = repo.log(&LogQuery::default()).unwrap();
let tagged = log.iter().find(|c| c.id == tip).unwrap();
assert!(tagged.refs.contains(&"tag: v1".into()));
assert_eq!(tagged.on_current_branch, Some(false));
}
#[test]
fn projection_does_not_truncate_long_hidden_chains() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
git(dir, &["init", "-q"]);
let mut stream = String::new();
for i in 0..4100 {
let message = if i == 0 || i == 4099 { "keep" } else { "hide" };
stream.push_str(&format!(
"commit refs/heads/main\ncommitter Test <[email protected]> {} +0000\ndata {}\n{}\n\n",
1000 + i,
message.len(),
message
));
}
let mut child = Command::new("git")
.current_dir(dir)
.args(["fast-import", "--quiet"])
.stdin(Stdio::piped())
.stdout(Stdio::null())
.spawn()
.unwrap();
child.stdin.take().unwrap().write_all(stream.as_bytes()).unwrap();
assert!(child.wait().unwrap().success());
let repo = Repo::discover(dir).unwrap().unwrap();
let log = repo.log(&LogQuery { text: Some("keep".into()), ..Default::default() }).unwrap();
assert_eq!(log.len(), 2);
assert_eq!(log[0].graph_parents, Some(vec![log[1].id.clone()]));
}
#[test]
fn path_and_shallow_history_remain_topological_with_clock_skew() {
let tmp = tempfile::tempdir().unwrap();
let source = tmp.path().join("source");
std::fs::create_dir(&source).unwrap();
git(&source, &["init", "-q"]);
let make = |message: &str, parent: Option<&str>, time: &str| {
std::fs::write(source.join("a.txt"), message).unwrap();
git(&source, &["add", "a.txt"]);
let tree = git(&source, &["write-tree"]);
let mut cmd = Command::new("git");
cmd.current_dir(&source).args([
"-c",
"user.name=Test",
"-c",
"[email protected]",
"commit-tree",
&tree,
"-m",
message,
]);
if let Some(p) = parent {
cmd.args(["-p", p]);
}
let out = cmd.env("GIT_AUTHOR_DATE", time).env("GIT_COMMITTER_DATE", time).output().unwrap();
assert!(out.status.success());
String::from_utf8(out.stdout).unwrap().trim().to_string()
};
let root = make("root", None, "@5000 +0000");
let left = make("left", Some(&root), "@1000 +0000");
let right = make("right", Some(&root), "@2000 +0000");
git(&source, &["update-ref", "refs/heads/main", &left]);
git(&source, &["update-ref", "refs/heads/side", &right]);
let shallow = tmp.path().join("shallow");
git(
tmp.path(),
&[
"clone",
"-q",
"--depth=2",
"--no-single-branch",
&format!("file://{}", source.display()),
shallow.to_str().unwrap(),
],
);
for dir in [&source, &shallow] {
let repo = Repo::discover(dir).unwrap().unwrap();
for order in [LogOrder::Date, LogOrder::Topo, LogOrder::Standard] {
let log = repo.log(&LogQuery { order, path: Some("a.txt".into()), ..Default::default() }).unwrap();
assert_eq!(log.len(), 3);
let positions: std::collections::HashMap<_, _> =
log.iter().enumerate().map(|(i, c)| (c.id.as_str(), i)).collect();
for (i, c) in log.iter().enumerate() {
for parent in c.graph_parents.as_ref().unwrap() {
assert!(positions.get(parent.as_str()).is_none_or(|p| *p > i));
}
}
}
}
}
#[test]
fn multiple_paths_exact_authors_patterns_and_rename_history() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
git(dir, &["init", "-q"]);
let root = commit(dir, "old.txt", "root");
git(dir, &["mv", "old.txt", "new.txt"]);
git(dir, &["commit", "-qm", "rename"]);
let rename = git(dir, &["rev-parse", "HEAD"]);
let tip = commit(dir, "other.txt", "another file");
git(dir, &["branch", "feature/log"]);
git(dir, &["branch", "feature/skip", &root]);
let repo = Repo::discover(dir).unwrap().unwrap();
let log = repo.log(&LogQuery { paths: vec!["new.txt".into(), "other.txt".into()], ..Default::default() }).unwrap();
assert_eq!(log.iter().map(|c| c.id.clone()).collect::<Vec<_>>(), vec![tip.clone(), rename.clone()]);
let log = repo.log(&LogQuery { path: Some("new.txt".into()), follow: true, ..Default::default() }).unwrap();
assert_eq!(log.iter().map(|c| c.id.clone()).collect::<Vec<_>>(), vec![rename, root.clone()]);
let log = repo
.log(&LogQuery { branches: vec!["feature/.*".into(), "-feature/skip".into()], ..Default::default() })
.unwrap();
assert_eq!(log[0].id, tip);
std::fs::write(dir.join("other.txt"), "different author").unwrap();
git(dir, &["add", "-A"]);
git(dir, &["-c", "user.name=Test User", "-c", "[email protected]", "commit", "-qm", "different author"]);
let log = repo.log(&LogQuery { authors: vec!["Test".into()], authors_exact: true, ..Default::default() }).unwrap();
assert_eq!(log.len(), 3);
assert!(log.iter().all(|c| c.author == "Test"));
assert!(repo.log_users().unwrap().contains(&"Test User <[email protected]>".to_string()));
}
#[test]
fn metadata_and_path_cache_survive_restart_without_caching_refs_or_filters() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("repo");
std::fs::create_dir(&dir).unwrap();
git(&dir, &["init", "-q"]);
let first = commit(&dir, "a", "first\n\nComplete commit body");
git(&dir, &["tag", "v1"]);
git(&dir, &["tag", "-a", "annotated", "-m", "release"]);
let cache = tmp.path().join("cache");
{
let repo = Repo::discover(&dir).unwrap().unwrap();
repo.enable_log_index(&cache);
let log = repo.log(&LogQuery { path: Some("a".into()), summary_only: true, ..Default::default() }).unwrap();
assert!(log[0].message_truncated);
assert_eq!(log[0].message, "first");
assert_eq!(repo.log_details(&first).unwrap().message, "first\n\nComplete commit body");
let details = repo.log_details("annotated").unwrap();
assert_eq!(details.message, "first\n\nComplete commit body");
assert_eq!(details.signature, "N");
assert!(details.containing_branches.contains(&"main".to_string()));
assert_eq!(repo.revision_files(&first).unwrap(), vec!["a"]);
}
let second = commit(&dir, "a", "second");
git(&dir, &["tag", "-f", "v1"]);
let repo = Repo::discover(&dir).unwrap().unwrap();
repo.enable_log_index(&cache);
let log = repo.log(&LogQuery { path: Some("a".into()), ..Default::default() }).unwrap();
assert_eq!(log[0].id, second);
assert!(log[0].refs.contains(&"tag: v1".into()));
assert!(!log[1].refs.contains(&"tag: v1".into()));
assert!(log[1].message.contains("Complete commit body"));
assert!(!log[1].message_truncated);
}
#[test]
fn cancelled_query_does_not_publish_a_partial_page() {
let tmp = tempfile::tempdir().unwrap();
git(tmp.path(), &["init", "-q"]);
commit(tmp.path(), "a", "root");
let repo = Repo::discover(tmp.path()).unwrap().unwrap();
let cancel = ide_core::CancellationToken::new();
cancel.cancel();
assert_eq!(
repo.log_cancellable(&LogQuery::default(), &cancel).unwrap_err().kind,
ide_core::error::ErrorKind::Cancelled
);
}
#[test]
fn shallow_boundaries_do_not_reconnect_to_locally_present_ancestors() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
git(dir, &["init", "-q"]);
let root = commit(dir, "a", "keep root");
let boundary = commit(dir, "a", "hidden boundary");
let tip = commit(dir, "a", "keep tip");
git(dir, &["tag", "root", &root]);
std::fs::write(dir.join(".git/shallow"), format!("{boundary}\n")).unwrap();
let repo = Repo::discover(dir).unwrap().unwrap();
for order in [LogOrder::Date, LogOrder::Topo, LogOrder::Standard] {
for text in [None, Some("keep".to_string())] {
let log = repo.log(&LogQuery { order, text, path: Some("a".into()), ..Default::default() }).unwrap();
let boundary_row = log.iter().find(|c| c.id == boundary);
if let Some(row) = boundary_row {
assert_eq!(row.parents, vec![root.clone()]);
assert_eq!(row.graph_parents, Some(vec![]));
} else {
assert_eq!(log.iter().find(|c| c.id == tip).unwrap().graph_parents, Some(vec![]));
}
}
}
}
#[test]
fn exact_branch_exclusions_treat_punctuation_literally() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
git(dir, &["init", "-q"]);
let root = commit(dir, "a", "root");
git(dir, &["branch", "release/1.0"]);
let tip = commit(dir, "a", "tip");
git(dir, &["branch", "release/1x0"]);
let repo = Repo::discover(dir).unwrap().unwrap();
let log = repo
.log(&LogQuery { branches: vec!["release/.*".into(), "-release/1.0".into()], ..Default::default() })
.unwrap();
assert_eq!(log.iter().map(|c| c.id.as_str()).collect::<Vec<_>>(), vec![tip.as_str(), root.as_str()]);
}
#[test]
fn mode_only_changes_appear_in_path_history() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
git(dir, &["init", "-q"]);
let root = commit(dir, "script", "root");
git(dir, &["update-index", "--chmod=+x", "script"]);
git(dir, &["commit", "-qm", "make executable"]);
let tip = git(dir, &["rev-parse", "HEAD"]);
let repo = Repo::discover(dir).unwrap().unwrap();
let log = repo.log(&LogQuery { path: Some("script".into()), ..Default::default() }).unwrap();
assert_eq!(log.iter().map(|c| c.id.as_str()).collect::<Vec<_>>(), vec![tip.as_str(), root.as_str()]);
}
#[test]
fn multiple_paths_are_simplified_together_at_merges() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
git(dir, &["init", "-q"]);
commit(dir, "a", "a0");
commit(dir, "b", "b0");
git(dir, &["branch", "side"]);
commit(dir, "a", "left");
git(dir, &["checkout", "side"]);
commit(dir, "b", "right");
git(dir, &["checkout", "main"]);
git(dir, &["merge", "--no-ff", "side", "-m", "merge both paths"]);
let repo = Repo::discover(dir).unwrap().unwrap();
let expected = git(dir, &["log", "--topo-order", "--format=%H", "--", "a", "b"]);
for order in [LogOrder::Topo, LogOrder::Date, LogOrder::Standard] {
let log = repo
.log(&LogQuery {
branch: Some("HEAD".into()),
paths: vec!["a".into(), "b".into()],
order,
..Default::default()
})
.unwrap();
assert_eq!(log[0].summary, "merge both paths");
assert_eq!(
log.iter().map(|c| c.id.as_str()).collect::<std::collections::HashSet<_>>(),
expected.lines().collect()
);
assert_eq!(log[0].parents.len(), 2);
assert_eq!(log[0].graph_parents.as_ref().unwrap().len(), 2);
}
}
+20 -4
Переглянути файл
@@ -64,7 +64,7 @@ fn ids(commits: &[Commit]) -> Vec<String> {
}
fn parents_of(commits: &[Commit], id: &str) -> Vec<String> {
commits.iter().find(|c| c.id == id).unwrap().parents.clone()
commits.iter().find(|c| c.id == id).unwrap().graph_parents.clone().unwrap()
}
#[test]
@@ -75,6 +75,14 @@ fn date_order_follows_commit_time_and_reports_it() {
assert_eq!(out[0].commit_time_ms, 5_000_000.0);
}
#[test]
fn incoming_order_groups_the_merged_branch_before_the_main_parent() {
let h = history();
let out = log(&h, LogQuery { order: LogOrder::Standard, ..Default::default() });
assert_eq!(ids(&out), vec![h.c3.clone(), h.m.clone(), h.s1.clone(), h.c2.clone(), h.c1.clone()]);
assert_eq!(out[1].parents, vec![h.c2.clone(), h.s1.clone()]);
}
#[test]
fn no_merges_links_children_to_the_merge_parents() {
let h = history();
@@ -90,6 +98,7 @@ fn first_parent_skips_merged_branches() {
let out = log(&h, LogQuery { first_parent: true, ..Default::default() });
assert_eq!(ids(&out), vec![h.c3.clone(), h.m.clone(), h.c2.clone(), h.c1.clone()]);
assert_eq!(parents_of(&out, &h.m), vec![h.c2.clone()]);
assert_eq!(out.iter().find(|c| c.id == h.m).unwrap().parents, vec![h.c2.clone(), h.s1.clone()]);
}
#[test]
@@ -201,19 +210,26 @@ fn a_user_filter_links_shown_commits_past_hidden_ones() {
let log = repo.log(&LogQuery { author: Some("me@".into()), ..Default::default() }).unwrap();
let links: Vec<(&str, Vec<&str>, Vec<bool>)> = log
.iter()
.map(|c| (c.summary.as_str(), c.parents.iter().map(String::as_str).collect(), c.dashed.clone()))
.map(|c| {
(
c.summary.as_str(),
c.graph_parents.as_ref().unwrap().iter().map(String::as_str).collect(),
if c.graph_dashed.iter().any(|d| *d) { c.graph_dashed.clone() } else { Vec::new() },
)
})
.collect();
assert_eq!(
links,
[("m3", vec![m2.as_str()], vec![]), ("m2", vec![m1.as_str()], vec![true]), ("m1", vec![], vec![]),],
"m2's parent o1 is hidden: m2 links to m1, dashed"
);
assert!(!log.iter().any(|c| c.parents.contains(&o1)));
assert!(!log.iter().any(|c| c.graph_parents.as_ref().unwrap().contains(&o1)));
assert_eq!(log[1].parents, vec![o1]);
// A page ends at m2: walking on still links it to m1.
let page = repo.log(&LogQuery { author: Some("me@".into()), limit: 2, ..Default::default() }).unwrap();
assert_eq!(page.len(), 2);
assert_eq!(page[1].parents, std::slice::from_ref(&m1));
assert_eq!(page[1].graph_parents.as_deref().unwrap(), std::slice::from_ref(&m1));
let next = repo.log(&LogQuery { author: Some("me@".into()), skip: 2, limit: 2, ..Default::default() }).unwrap();
assert_eq!(next.iter().map(|c| c.id.clone()).collect::<Vec<_>>(), std::slice::from_ref(&m1));
let _ = m3;
+5
Переглянути файл
@@ -256,6 +256,11 @@ pub fn set_writable(path: &Path, writable: bool) -> IdeResult<()> {
pub fn rename(from: &Path, to: &Path) -> IdeResult<()> {
ops::rename(from, to)
}
/// Checks source existence and destination conflicts without mutation, using
/// the same filesystem identity rules as [`rename`].
pub fn validate_rename(from: &Path, to: &Path) -> IdeResult<()> {
ops::validate_rename(from, to)
}
/// Moves to the OS trash (recoverable), like IDEA's safe delete for files.
/// Deletes permanently when the trash is unavailable.
pub fn delete(path: &Path) -> IdeResult<()> {
+9 -1
Переглянути файл
@@ -88,7 +88,7 @@ fn same_file(a: &Path, b: &Path) -> bool {
}
}
pub(crate) fn rename(from: &Path, to: &Path) -> IdeResult<()> {
pub(crate) fn validate_rename(from: &Path, to: &Path) -> IdeResult<()> {
if !exists(from) {
return Err(not_found(from));
}
@@ -99,6 +99,14 @@ pub(crate) fn rename(from: &Path, to: &Path) -> IdeResult<()> {
if exists(to) && !same_file(from, to) {
return Err(already_exists(to));
}
Ok(())
}
pub(crate) fn rename(from: &Path, to: &Path) -> IdeResult<()> {
validate_rename(from, to)?;
if from == to {
return Ok(());
}
ensure_parent(to)?;
match fs::rename(from, to) {
Ok(()) => Ok(()),
+1
Переглянути файл
@@ -21,6 +21,7 @@ blake3.workspace = true
tracing.workspace = true
tempfile.workspace = true
globset.workspace = true
uuid.workspace = true
[dev-dependencies]
tempfile.workspace = true
+3
Переглянути файл
@@ -401,8 +401,11 @@ impl Documents {
if edit.files.is_empty() {
return Ok(());
}
// Validate project rules before path resolution can erase linked components.
crate::file_ops::validate_workspace_edit_paths(edit)?;
let mut edit = normalize_edit(edit)?;
let captured = !edit.preconditions.is_empty();
crate::file_ops::expand_workspace_edit(&mut edit)?;
self.prepare_workspace_edit(&mut edit)?;
self.validate_preconditions(&edit.preconditions)?;
for file in &edit.files {
+16 -27
Переглянути файл
@@ -120,6 +120,8 @@ impl FileMoves {
if moves.is_empty() {
return Err(IdeError::invalid("nothing to move"));
}
let expanded = crate::file_ops::expand_moves(moves)?;
let moves = expanded.as_slice();
for m in moves {
if !m.from.exists() {
return Err(IdeError::not_found(format!("{} does not exist", m.from.display())));
@@ -145,16 +147,9 @@ impl FileMoves {
restore(documents, &paths, &before);
return Err(e);
}
let mut done: Vec<&FileMove> = Vec::new();
for m in moves {
if let Err(e) = ide_vfs::rename(&m.from, &m.to) {
for d in done.iter().rev() {
let _ = ide_vfs::rename(&d.to, &d.from);
}
restore(documents, &paths, &before);
return Err(e);
}
done.push(m);
if let Err(e) = crate::file_ops::move_files(moves) {
restore(documents, &paths, &before);
return Err(e);
}
let mut edited = Vec::with_capacity(paths.len());
for (p, before) in paths.iter().zip(before) {
@@ -196,27 +191,21 @@ impl FileMoves {
.ok_or_else(|| IdeError::not_found("the refactoring can no longer be undone"))?;
records.remove(i)
};
for m in &record.moves {
if !m.to.exists() {
return Err(IdeError::not_found(format!("{} no longer exists", m.to.display())));
}
if m.from.exists() {
return Err(IdeError::new(
ide_core::error::ErrorKind::AlreadyExists,
format!("{} exists again", m.from.display()),
));
}
let back: Vec<_> =
record.moves.iter().rev().map(|m| FileMove { from: m.to.clone(), to: m.from.clone() }).collect();
if let Err(e) = crate::file_ops::move_files(&back) {
self.records.lock().push(record);
return Err(e);
}
let mut outcome = UndoOutcome::default();
for m in record.moves.iter().rev() {
ide_vfs::rename(&m.to, &m.from)?;
outcome.moves.push(FileMove { from: m.to.clone(), to: m.from.clone() });
}
let back: Vec<FileMove> = outcome.moves.clone();
let mut outcome = UndoOutcome { moves: back.clone(), conflicts: Vec::new() };
for f in &record.edited {
let path = moved_path(&f.path, &back);
match read_text(documents, &path) {
Ok(now) if now == f.after => write_text(documents, &path, &f.before)?,
Ok(now) if now == f.after => {
if write_text(documents, &path, &f.before).is_err() {
outcome.conflicts.push(path.into());
}
}
Ok(now) if now == f.before => {}
_ => outcome.conflicts.push(path.into()),
}
+94
Переглянути файл
@@ -0,0 +1,94 @@
//! Project-aware file operations. Plain files retain the VFS behavior; project
//! rules may expand a resource operation before the common transaction runs.
use crate::FileMove;
use ide_core::{IdeError, IdeResult, WorkspaceEdit};
use std::path::{Path, PathBuf};
mod project;
pub fn copy(from: &Path, to: &Path) -> IdeResult<()> {
project::copy(from, to).unwrap_or_else(|| ide_vfs::copy(from, to))
}
pub fn delete(path: &Path) -> IdeResult<()> {
project::delete(path).unwrap_or_else(|| ide_vfs::delete(path))
}
/// Files Local History must capture before deletion.
pub fn deletion_paths(path: &Path) -> IdeResult<Vec<PathBuf>> {
project::deletion_paths(path).unwrap_or_else(|| Ok(vec![path.to_path_buf()]))
}
pub fn rename(from: &Path, to: &Path) -> IdeResult<()> {
if !project::has_move_rules(from, to) {
return ide_vfs::rename(from, to);
}
let moves = expand_moves(&[FileMove { from: from.into(), to: to.into() }])?;
move_files(&moves)
}
pub(crate) fn expand_moves(moves: &[FileMove]) -> IdeResult<Vec<FileMove>> {
let expanded = project::expand_moves(moves)?;
validate_moves(&expanded)?;
Ok(expanded)
}
fn path_key(path: &Path) -> PathBuf {
#[cfg(windows)]
return path.to_string_lossy().replace('\\', "/").to_lowercase().into();
#[cfg(not(windows))]
path.to_path_buf()
}
fn validate_moves(moves: &[FileMove]) -> IdeResult<()> {
let mut sources = std::collections::HashSet::new();
let mut targets = std::collections::HashSet::new();
for m in moves {
ide_vfs::validate_rename(&m.from, &m.to)?;
let from = path_key(&m.from);
let to = path_key(&m.to);
if to != from && to.starts_with(&from) {
return Err(IdeError::invalid("Cannot move a directory into itself"));
}
if !sources.insert(from) || !targets.insert(to) {
return Err(IdeError::invalid("Duplicate source or destination in file operation"));
}
}
Ok(())
}
pub(crate) fn move_files(moves: &[FileMove]) -> IdeResult<()> {
execute_moves(moves, &|from, to| project::rename_entry(from, to).unwrap_or_else(|| ide_vfs::rename(from, to)))
}
/// Executes an expanded batch. Rollback never overwrites a newly occupied path;
/// failures report where the caller can recover the remaining files.
pub(crate) fn execute_moves(moves: &[FileMove], rename: &dyn Fn(&Path, &Path) -> IdeResult<()>) -> IdeResult<()> {
validate_moves(moves)?;
for (i, m) in moves.iter().enumerate() {
if let Err(mut error) = rename(&m.from, &m.to) {
for done in moves[..i].iter().rev() {
if let Err(rollback) =
ide_vfs::validate_rename(&done.to, &done.from).and_then(|()| rename(&done.to, &done.from))
{
error.message.push_str(&format!(
"; rollback {} -> {} failed: {rollback}",
done.to.display(),
done.from.display()
));
}
}
return Err(error);
}
}
Ok(())
}
pub(crate) fn validate_workspace_edit_paths(edit: &WorkspaceEdit) -> IdeResult<()> {
project::validate_workspace_edit_paths(edit)
}
pub(crate) fn expand_workspace_edit(edit: &mut WorkspaceEdit) -> IdeResult<()> {
project::expand_workspace_edit(edit)
}
+52
Переглянути файл
@@ -0,0 +1,52 @@
//! The integration boundary for project-specific resource rules. These rules
//! never replace the plain VFS path unless an operation touches project assets.
use crate::{FileMove, unity::assets};
use ide_core::{FileEdit, IdeResult, WorkspaceEdit};
use std::path::{Path, PathBuf};
pub(super) fn has_move_rules(from: &Path, to: &Path) -> bool {
assets::project_root(from).is_some() || assets::project_root(to).is_some()
}
pub(super) fn copy(from: &Path, to: &Path) -> Option<IdeResult<()>> {
has_move_rules(from, to).then(|| assets::copy(from, to))
}
pub(super) fn delete(path: &Path) -> Option<IdeResult<()>> {
assets::project_root(path).map(|_| assets::delete(path))
}
pub(super) fn deletion_paths(path: &Path) -> Option<IdeResult<Vec<PathBuf>>> {
assets::project_root(path).map(|_| assets::deletion_paths(path))
}
pub(super) fn rename_entry(from: &Path, to: &Path) -> Option<IdeResult<()>> {
has_move_rules(from, to).then(|| assets::move_one(from, to))
}
pub(super) fn expand_moves(moves: &[FileMove]) -> IdeResult<Vec<FileMove>> {
if moves.iter().any(|m| has_move_rules(&m.from, &m.to)) { assets::expand_moves(moves) } else { Ok(moves.to_vec()) }
}
fn has_edit_rules(edit: &WorkspaceEdit) -> bool {
edit.files.iter().any(|file| match file {
FileEdit::Rename { from, to } => has_move_rules(from, to),
FileEdit::Delete { path, .. } => assets::project_root(path).is_some(),
_ => false,
})
}
pub(super) fn validate_workspace_edit_paths(edit: &WorkspaceEdit) -> IdeResult<()> {
if has_edit_rules(edit) {
assets::validate_workspace_edit_paths(edit)?;
}
Ok(())
}
pub(super) fn expand_workspace_edit(edit: &mut WorkspaceEdit) -> IdeResult<()> {
if has_edit_rules(edit) {
assets::expand_workspace_edit(edit)?;
}
Ok(())
}
+2
Переглянути файл
@@ -7,6 +7,7 @@ pub mod documents;
pub mod editorconfig;
pub mod file_defaults;
pub mod file_moves;
pub mod file_ops;
pub mod file_refs;
pub mod history;
pub mod memory;
@@ -15,6 +16,7 @@ pub mod recent;
pub mod roots;
pub mod settings;
pub mod text_refs;
pub mod unity;
pub mod window_groups;
pub mod workspace;
+64 -1
Переглянути файл
@@ -62,7 +62,10 @@ const ROOT_NAMES: &[&str] = &[
pub fn affects_roots(rel: &Path) -> bool {
let mut names = rel.iter().rev().filter_map(|c| c.to_str());
let Some(name) = names.next() else { return false };
BUILD_FILES.contains(&name) || ROOT_NAMES.contains(&name) || names.next() == Some("src")
BUILD_FILES.contains(&name)
|| ROOT_NAMES.contains(&name)
|| matches!(name, "Assets" | "Packages" | "ProjectSettings" | "ProjectVersion.txt")
|| names.next() == Some("src")
}
/// Detects roots below `root`; paths in the result are unique and sorted.
@@ -77,6 +80,29 @@ pub fn detect(root: &Path) -> Vec<SourceFolder> {
break;
}
let dir = if rel.is_empty() { root.to_path_buf() } else { root.join(&rel) };
if crate::unity::is_project(&dir) {
for (name, kind) in
[("Assets", RootKind::Source), ("Packages", RootKind::Source), ("ProjectSettings", RootKind::Resources)]
{
if dir.join(name).is_dir() {
out.push(SourceFolder {
path: join(&rel, name),
kind,
detected_from: Some(join(&rel, crate::unity::VERSION_FILE)),
});
}
}
// Exclude before the index/watchers start, even if Unity creates its caches later.
for name in crate::unity::GENERATED_DIRS {
out.push(SourceFolder {
path: join(&rel, name),
kind: RootKind::Excluded,
detected_from: Some(join(&rel, crate::unity::VERSION_FILE)),
});
}
// Assets and PackageCache may contain arbitrary build files; they aren't nested modules.
continue;
}
let Ok(entries) = std::fs::read_dir(&dir) else { continue };
let mut files: Vec<String> = Vec::new();
let mut dirs: Vec<String> = Vec::new();
@@ -244,6 +270,43 @@ mod tests {
roots.iter().map(|r| format!("{}={:?}@{}", r.path, r.kind, r.detected_from.as_deref().unwrap_or(""))).collect()
}
#[test]
fn unity_roots_exclude_future_caches_and_do_not_scan_assets_as_modules() {
let dir = tree(&[
"Assets/Scripts/Player.cs",
"Assets/Plugins/Tool/package.json",
"ProjectSettings/ProjectVersion.txt",
"Packages/manifest.json",
"Library/PackageCache/tool/Cargo.toml",
]);
let roots = detect(dir.path());
assert!(roots.iter().any(|r| r.path == "Assets" && r.kind == RootKind::Source));
assert!(roots.iter().any(|r| r.path == "Packages" && r.kind == RootKind::Source));
assert!(!roots.iter().any(|r| r.path.starts_with("Assets/") || r.path.starts_with("Library/")));
let effective = super::super::ProjectRoots::compute(roots, &Default::default());
for name in crate::unity::GENERATED_DIRS {
assert!(effective.excluded_globs().contains(&format!("/{name}")));
}
for path in ["Assets", "Packages", "ProjectSettings", crate::unity::VERSION_FILE] {
assert!(affects_roots(Path::new(path)));
}
}
#[test]
fn nested_unity_roots_are_anchored_without_excluding_other_projects() {
let dir = tree(&[
"game/Assets/Scripts/Player.cs",
"game/ProjectSettings/ProjectVersion.txt",
"server/Cargo.toml",
"server/src/main.rs",
"Library/Source.cs",
]);
let roots = super::super::ProjectRoots::compute(detect(dir.path()), &Default::default());
assert!(roots.excluded_globs().contains(&"/game/Library".to_owned()));
assert!(!roots.excluded_globs().contains(&"/Library".to_owned()));
assert!(roots.roots.iter().any(|r| r.path == "server/src" && r.kind == RootKind::Source));
}
#[test]
fn maven_conventional_roots_and_target() {
let dir = tree(&[
+94
Переглянути файл
@@ -0,0 +1,94 @@
//! Unity project identity. Generated C# solutions are optional, not root markers.
pub(crate) mod assets;
use serde::{Deserialize, Serialize};
use specta::Type;
use std::io::Read;
use std::path::Path;
pub const VERSION_FILE: &str = "ProjectSettings/ProjectVersion.txt";
/// Root-relative caches and build outputs, including folders not created yet.
pub const GENERATED_DIRS: &[&str] = &["Library", "Temp", "Obj", "obj", "Logs", "Build", "Builds", "UserSettings"];
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct UnityProjectInfo {
pub editor_version: Option<String>,
/// File names relative to the Unity root, in stable order.
pub solutions: Vec<String>,
pub projects: Vec<String>,
}
pub fn is_project(root: &Path) -> bool {
root.join("Assets").is_dir() && root.join(VERSION_FILE).is_file()
}
pub fn detect(root: &Path) -> Option<UnityProjectInfo> {
if !is_project(root) {
return None;
}
let mut text = String::new();
let _ = std::fs::File::open(root.join(VERSION_FILE)).and_then(|f| f.take(64 * 1024).read_to_string(&mut text));
let editor_version = text.lines().find_map(|line| {
let (key, value) = line.trim_start_matches('\u{feff}').split_once(':')?;
let value = value.trim();
(key.trim() == "m_EditorVersion" && !value.is_empty() && value.len() <= 128).then(|| value.to_owned())
});
let mut info = UnityProjectInfo { editor_version, solutions: Vec::new(), projects: Vec::new() };
if let Ok(entries) = std::fs::read_dir(root) {
for entry in entries.flatten() {
if !entry.file_type().is_ok_and(|t| t.is_file()) {
continue;
}
let name = entry.file_name().to_string_lossy().into_owned();
match entry.path().extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).as_deref() {
Some("sln" | "slnx") => info.solutions.push(name),
Some("csproj") => info.projects.push(name),
_ => {}
}
}
}
info.solutions.sort();
info.projects.sort();
Some(info)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn detects_fresh_and_legacy_projects_without_packages_or_solutions() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path();
std::fs::create_dir(root.join("Assets")).unwrap();
assert!(detect(root).is_none());
std::fs::create_dir(root.join("ProjectSettings")).unwrap();
std::fs::write(
root.join(VERSION_FILE),
"\u{feff}m_EditorVersion: 2022.3.62f1\r\nm_EditorVersionWithRevision: ignored\r\n",
)
.unwrap();
let info = detect(root).unwrap();
assert_eq!(info.editor_version.as_deref(), Some("2022.3.62f1"));
assert!(info.solutions.is_empty() && info.projects.is_empty());
std::fs::write(root.join("Game.sln"), "").unwrap();
std::fs::write(root.join("Game.slnx"), "").unwrap();
std::fs::write(root.join("Assembly-CSharp.csproj"), "").unwrap();
std::fs::create_dir(root.join("NotAProject.csproj")).unwrap();
let info = detect(root).unwrap();
assert_eq!(info.solutions, ["Game.sln", "Game.slnx"]);
assert_eq!(info.projects, ["Assembly-CSharp.csproj"]);
std::fs::write(root.join(VERSION_FILE), "malformed").unwrap();
assert_eq!(detect(root).unwrap().editor_version, None);
}
#[test]
fn ordinary_csharp_projects_are_not_unity_projects() {
let temp = tempfile::tempdir().unwrap();
std::fs::write(temp.path().join("App.csproj"), "").unwrap();
std::fs::create_dir(temp.path().join("Assets")).unwrap();
assert!(detect(temp.path()).is_none());
}
}
+254
Переглянути файл
@@ -0,0 +1,254 @@
//! Filesystem operations for assets under a Unity project's Assets directory.
//! Metadata moves with the asset; duplication gets new GUIDs before publication.
use crate::{file_moves::FileMove, file_ops::execute_moves};
use ide_core::{IdeError, IdeResult, error::ErrorKind};
use std::{
collections::HashMap,
fs,
path::{Component, Path, PathBuf},
};
mod duplicate;
mod workspace_edit;
pub(crate) use workspace_edit::{expand_workspace_edit, validate_workspace_edit_paths};
#[cfg(test)]
mod tests;
pub fn meta_path(path: &Path) -> PathBuf {
let mut name = path.as_os_str().to_os_string();
name.push(".meta");
name.into()
}
/// Includes Assets itself so callers can protect the asset root.
pub fn project_root(path: &Path) -> Option<PathBuf> {
path.ancestors().find_map(|p| {
(p.file_name().is_some_and(|n| if cfg!(windows) { n.eq_ignore_ascii_case("Assets") } else { n == "Assets" })
&& p.parent().is_some_and(super::is_project))
.then(|| p.parent().unwrap().to_path_buf())
})
}
fn exists(path: &Path) -> bool {
fs::symlink_metadata(path).is_ok()
}
fn is_meta(path: &Path) -> bool {
path.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("meta"))
}
fn validate_asset(path: &Path) -> IdeResult<()> {
if let Some(root) = project_root(path) {
if key(path) == key(&root.join("Assets")) {
return Err(IdeError::invalid("The Unity Assets root cannot be moved, copied or deleted"));
}
if is_meta(path) && exists(&path.with_extension("")) {
return Err(IdeError::invalid(
"Select the Unity asset instead of its .meta file; metadata is handled together",
));
}
}
no_links(path)
}
fn no_links(path: &Path) -> IdeResult<()> {
if path.components().any(|c| matches!(c, Component::ParentDir)) {
return Err(IdeError::invalid("Unity asset operations require paths without '..'"));
}
// Trust the opened project's location, including a linked root or parent
// (macOS /var and /tmp). Check inside it, including Library staging paths.
// The outermost root prevents a nested Unity project from hiding a link.
let root = path.ancestors().filter(|p| super::is_project(p)).last();
for p in path.ancestors().take_while(|p| Some(*p) != root) {
match fs::symlink_metadata(p) {
Ok(m) if is_link(&m) => {
return Err(IdeError::invalid(format!("Unity asset operations do not follow links: {}", p.display())));
}
Ok(_) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(e.into()),
}
}
Ok(())
}
fn is_link(metadata: &fs::Metadata) -> bool {
#[cfg(windows)]
{
use std::os::windows::fs::MetadataExt;
// Also reject directory junctions and other reparse points.
metadata.file_attributes() & 0x400 != 0
}
#[cfg(not(windows))]
{
metadata.file_type().is_symlink()
}
}
fn key(path: &Path) -> String {
let s = path.to_string_lossy().replace('\\', "/");
if cfg!(windows) { s.to_lowercase() } else { s }
}
fn vacant(from: &Path, to: &Path) -> IdeResult<()> {
if exists(to) {
if !exists(from) {
return Err(IdeError::new(ErrorKind::AlreadyExists, format!("{} already exists", to.display())));
}
ide_vfs::validate_rename(from, to)?;
}
Ok(())
}
/// Expand before applying reference edits, so orphan metadata conflicts cannot
/// leave a partially refactored asset. Metadata goes first on publication.
pub fn expand_moves(moves: &[FileMove]) -> IdeResult<Vec<FileMove>> {
let mut out = Vec::new();
for m in moves {
let unity = project_root(&m.from).is_some() || project_root(&m.to).is_some();
if unity {
// A caller may explicitly select both an asset and its metadata.
if is_meta(&m.from)
&& moves
.iter()
.any(|a| meta_path(&a.from) == m.from.to_path_buf() && meta_path(&a.to) == m.to.to_path_buf())
{
continue;
}
validate_asset(&m.from)?;
validate_asset(&m.to)?;
let from = meta_path(&m.from);
let to = meta_path(&m.to);
no_links(&from)?;
no_links(&to)?;
vacant(&from, &to)?;
if exists(&from) {
out.push(FileMove { from: from.into(), to: to.into() });
}
}
out.push(m.clone());
}
Ok(out)
}
pub(crate) fn move_one(from: &Path, to: &Path) -> IdeResult<()> {
if project_root(from).is_some() || project_root(to).is_some() {
no_links(from)?;
no_links(to)?;
if let Some(parent) = to.parent() {
fs::create_dir_all(parent)?;
}
// A failed cross-volume copy/delete cannot be rolled back reliably.
// Keep paired Unity moves atomic per entry and let rename report it.
fs::rename(from, to)?;
Ok(())
} else {
ide_vfs::rename(from, to)
}
}
/// The paths Local History must snapshot before an asset deletion.
pub fn deletion_paths(path: &Path) -> IdeResult<Vec<PathBuf>> {
validate_asset(path)?;
let meta = meta_path(path);
no_links(&meta)?;
let mut paths = vec![path.to_path_buf()];
if exists(&meta) {
paths.push(meta);
}
Ok(paths)
}
fn staging(root: &Path) -> IdeResult<PathBuf> {
let parent = root.join("Library/OpenIDEA/AssetOperations");
no_links(&parent)?;
fs::create_dir_all(&parent)?;
let dir = parent.join(uuid::Uuid::new_v4().simple().to_string());
fs::create_dir(&dir)?;
Ok(dir)
}
pub fn delete(path: &Path) -> IdeResult<()> {
delete_with(path, &ide_vfs::delete)
}
fn delete_with(path: &Path, remove: &dyn Fn(&Path) -> IdeResult<()>) -> IdeResult<()> {
let paths = deletion_paths(path)?;
let root = project_root(path).ok_or_else(|| IdeError::invalid("Expected a Unity asset path"))?;
let stage = staging(&root)?;
let payload = stage.join("files");
fs::create_dir(&payload)?;
let moves: Vec<_> = paths
.iter()
.map(|p| FileMove { from: p.clone().into(), to: payload.join(p.file_name().unwrap()).into() })
.collect();
// Recycle-bin restore returns the group to staging. Keep its destinations
// with it so originals can also be recovered without the IDE's history.
let manifest = stage.join("restore-paths.json");
fs::write(&manifest, serde_json::to_vec_pretty(&paths).map_err(|e| IdeError::internal(e.to_string()))?)?;
// Never automatically delete this staging directory on failure: it may
// contain originals when rollback fails.
if let Err(e) = execute_moves(&moves, &move_one) {
if fs::remove_dir(&payload).is_ok() {
let _ = fs::remove_file(&manifest);
let _ = fs::remove_dir(&stage);
}
return Err(e);
}
if let Err(mut e) = remove(&stage) {
let back: Vec<_> = moves.iter().rev().map(|m| FileMove { from: m.to.clone(), to: m.from.clone() }).collect();
if let Err(rollback) = execute_moves(&back, &move_one) {
e.message.push_str(&format!("; recovery files at {}: {rollback}", stage.display()));
}
if fs::remove_dir(&payload).is_ok() {
let _ = fs::remove_file(&manifest);
let _ = fs::remove_dir(&stage);
}
return Err(e);
}
Ok(())
}
pub fn copy(from: &Path, to: &Path) -> IdeResult<()> {
let root = project_root(to)
.or_else(|| project_root(from))
.ok_or_else(|| IdeError::invalid("Expected a Unity asset path"))?;
validate_asset(from)?;
validate_asset(to)?;
if key(from) == key(to) || key(to).starts_with(&(key(from) + "/")) {
return Err(IdeError::invalid("Cannot copy an asset onto or into itself"));
}
if exists(to) {
return Err(IdeError::new(ErrorKind::AlreadyExists, format!("{} already exists", to.display())));
}
let src_meta = meta_path(from);
let dst_meta = meta_path(to);
no_links(&src_meta)?;
no_links(&dst_meta)?;
// Copies never overwrite metadata, including orphan destination metadata.
if exists(&dst_meta) {
return Err(IdeError::new(ErrorKind::AlreadyExists, format!("{} already exists", dst_meta.display())));
}
let stage = staging(&root)?;
let result = (|| {
let asset = stage.join(from.file_name().ok_or_else(|| IdeError::invalid("Missing asset name"))?);
duplicate::copy_tree(from, &asset)?;
let meta = meta_path(&asset);
if exists(&src_meta) {
duplicate::copy_tree(&src_meta, &meta)?;
}
if project_root(to).is_some() {
duplicate::regenerate(&stage)?;
}
let mut moves = Vec::new();
if exists(&meta) {
moves.push(FileMove { from: meta.into(), to: dst_meta.into() });
}
moves.push(FileMove { from: asset.into(), to: to.into() });
execute_moves(&moves, &move_one)
})();
// Only disposable copies live here, never the source assets.
let _ = fs::remove_dir_all(&stage);
result
}
+236
Переглянути файл
@@ -0,0 +1,236 @@
use super::*;
use std::io::Read;
const TEXT_LIMIT: u64 = 32 * 1024 * 1024;
pub(super) fn copy_tree(from: &Path, to: &Path) -> IdeResult<()> {
no_links(from)?;
let metadata = fs::symlink_metadata(from)?;
if metadata.is_dir() {
fs::create_dir(to)?;
for entry in fs::read_dir(from)? {
let entry = entry?;
copy_tree(&entry.path(), &to.join(entry.file_name()))?;
}
} else if metadata.is_file() {
fs::copy(from, to)?;
} else {
return Err(IdeError::invalid(format!("Not a regular Unity asset: {}", from.display())));
}
Ok(())
}
fn files(dir: &Path, out: &mut Vec<PathBuf>) -> IdeResult<()> {
for entry in fs::read_dir(dir)? {
let entry = entry?;
if entry.file_type()?.is_dir() {
files(&entry.path(), out)?;
} else {
out.push(entry.path());
}
}
Ok(())
}
fn read_text(path: &Path) -> IdeResult<String> {
let mut bytes = Vec::new();
fs::File::open(path)?.take(TEXT_LIMIT + 1).read_to_end(&mut bytes)?;
if bytes.len() as u64 > TEXT_LIMIT {
return Err(IdeError::invalid(format!(
"Unity serialized asset exceeds the 32 MiB copy limit: {}",
path.display()
)));
}
String::from_utf8(bytes)
.map_err(|_| IdeError::invalid(format!("Cannot rewrite binary Unity metadata: {}", path.display())))
}
fn guid(value: &str) -> bool {
value.len() == 32 && value.bytes().all(|b| b.is_ascii_hexdigit()) && value.bytes().any(|b| b != b'0')
}
pub(super) fn regenerate(stage: &Path) -> IdeResult<()> {
let mut paths = Vec::new();
files(stage, &mut paths)?;
let mut ids = HashMap::new();
for path in paths.iter().filter(|p| is_meta(p)) {
let text = read_text(path)?;
let values: Vec<_> = text
.trim_start_matches('\u{feff}')
.lines()
.filter_map(|l| l.strip_prefix("guid:").map(str::trim))
.collect();
if values.len() != 1 || !guid(values[0]) {
return Err(IdeError::invalid(format!("Missing or invalid GUID in {}", path.display())));
}
if ids.insert(values[0].to_ascii_lowercase(), uuid::Uuid::new_v4().simple().to_string()).is_some() {
return Err(IdeError::invalid("Duplicate source GUIDs; resolve them in Unity before copying"));
}
}
for path in paths {
let ext = path.extension().unwrap_or_default().to_string_lossy().to_ascii_lowercase();
if ext == "asmdef" || ext == "asmref" {
let text = read_text(&path)?;
let mut json: serde_json::Value =
serde_json::from_str(&text).map_err(|e| IdeError::invalid(e.to_string()))?;
if rewrite_json(&mut json, &ids) {
fs::write(&path, serde_json::to_string_pretty(&json).map_err(|e| IdeError::internal(e.to_string()))?)?;
}
continue;
}
let mut header = [0; 32];
let n = fs::File::open(&path)?.read(&mut header)?;
let header = String::from_utf8_lossy(&header[..n]);
let header = header.trim_start_matches('\u{feff}');
let yaml = header.starts_with("%YAML") || header.starts_with("--- !u!");
if !yaml && !is_meta(&path) {
// These formats may be binary under Mixed/Force Binary. We cannot
// safely preserve internal references without Unity deserialization.
if matches!(
ext.as_str(),
"asset"
| "prefab"
| "unity"
| "mat"
| "anim"
| "controller"
| "overridecontroller"
| "playable"
| "mask"
| "rendertexture"
| "physicmaterial"
| "physicsmaterial2d"
| "lighting"
| "terrainlayer"
| "guiskin"
| "flare"
| "cubemap"
| "spriteatlas"
| "spriteatlasv2"
| "preset"
| "shadervariants"
| "giparams"
| "lightingdata"
| "fontsettings"
| "texture2d"
| "mesh"
) {
return Err(IdeError::invalid(format!(
"Cannot copy binary Unity serialized asset {}; use Force Text serialization in Unity",
path.display()
)));
}
continue;
}
let before = read_text(&path)?;
let after = rewrite_yaml(&before, &ids);
if before != after {
fs::write(&path, after)?;
}
}
Ok(())
}
fn rewrite_json(value: &mut serde_json::Value, ids: &HashMap<String, String>) -> bool {
match value {
serde_json::Value::String(s) => {
if let Some(id) = s.strip_prefix("GUID:").and_then(|id| ids.get(&id.to_ascii_lowercase())) {
*s = format!("GUID:{id}");
true
} else {
false
}
}
serde_json::Value::Array(a) => {
let mut changed = false;
for v in a {
changed |= rewrite_json(v, ids);
}
changed
}
serde_json::Value::Object(o) => {
let mut changed = false;
for v in o.values_mut() {
changed |= rewrite_json(v, ids);
}
changed
}
_ => false,
}
}
/// Patch GUID scalar tokens without reserializing Unity's YAML dialect. Quoted
/// strings, comments and indented block scalars are not asset references.
fn rewrite_yaml(text: &str, ids: &HashMap<String, String>) -> String {
let mut bytes = text.as_bytes().to_vec();
let mut offset = 0;
let mut block_indent = None;
let mut quote = None;
for line in text.split_inclusive('\n') {
let raw = line.as_bytes();
let indent = raw.iter().take_while(|b| **b == b' ').count();
if block_indent.is_some_and(|n| indent > n || line.trim().is_empty()) {
offset += raw.len();
continue;
}
block_indent = None;
let mut i = 0;
while i < raw.len() {
let b = raw[i];
if let Some(q) = quote {
if q == b'"' && b == b'\\' {
i += 2;
continue;
}
if b == q {
if q == b'\'' && raw.get(i + 1) == Some(&q) {
i += 2;
continue;
}
quote = None;
}
i += 1;
continue;
}
if b == b'#' && (i == 0 || raw[i - 1].is_ascii_whitespace()) {
break;
}
if b == b'"' || b == b'\'' {
let prefix = line[..i].trim();
// Apostrophes inside plain scalars (e.g. Hero's Sword) do not
// open a quoted scalar or suppress references on later lines.
if prefix.is_empty() || prefix.ends_with([':', '-', '[', '{', ',']) {
quote = Some(b);
i += 1;
continue;
}
}
if (b == b'|' || b == b'>') && line[..i].trim_end().ends_with([':', '-']) {
block_indent = Some(indent);
break;
}
if raw[i..].starts_with(b"guid:") {
let prefix = line[..i].trim_start_matches('\u{feff}').trim_end();
if prefix.is_empty() || prefix.ends_with(['{', ',']) {
let start = i + 5 + raw[i + 5..].iter().take_while(|b| **b == b' ' || **b == b'\t').count();
let end = start + 32;
if end <= raw.len()
&& raw[start..end].iter().all(u8::is_ascii_hexdigit)
&& (end == raw.len()
|| raw[end].is_ascii_whitespace()
|| matches!(raw[end], b',' | b'}' | b'#'))
&& let Some(new) = ids.get(&line[start..end].to_ascii_lowercase())
{
bytes[offset + start..offset + end].copy_from_slice(new.as_bytes());
i = end;
continue;
}
}
}
// Non-ASCII bytes cannot begin any token handled above.
i += 1;
}
offset += raw.len();
}
String::from_utf8(bytes).expect("GUID substitutions preserve UTF-8")
}
+217
Переглянути файл
@@ -0,0 +1,217 @@
use super::*;
use crate::file_ops::{move_files, rename};
use crate::{documents::Documents, file_moves::FileMoves};
use ide_core::{LanguageId, WorkspaceEdit};
use std::sync::Arc;
mod links;
const A: &str = "11111111111111111111111111111111";
const B: &str = "22222222222222222222222222222222";
const C: &str = "33333333333333333333333333333333";
fn project() -> tempfile::TempDir {
let tmp = tempfile::tempdir().unwrap();
fs::create_dir(tmp.path().join("Assets")).unwrap();
fs::create_dir(tmp.path().join("ProjectSettings")).unwrap();
fs::write(tmp.path().join(super::super::VERSION_FILE), "m_EditorVersion: 6000.0.1f1").unwrap();
tmp
}
fn asset(root: &Path, name: &str, content: &str, id: &str) -> PathBuf {
let path = root.join("Assets").join(name);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(&path, content).unwrap();
fs::write(meta_path(&path), format!("fileFormatVersion: 2\r\nguid: {id}\r\nImporter:\r\n setting: keep\r\n"))
.unwrap();
path
}
fn id(path: &Path) -> String {
fs::read_to_string(meta_path(path))
.unwrap()
.lines()
.find_map(|l| l.strip_prefix("guid: ").map(str::to_owned))
.unwrap()
}
#[test]
fn rename_preserves_metadata_and_undo_retries_after_conflict() {
let tmp = project();
let src = asset(tmp.path(), "Player.cs", "class Player {}", A);
let dst = src.with_file_name("Hero.cs");
let docs = Documents::new(Arc::new(|_| {}), Box::new(|_: &Path, _: Option<&str>| LanguageId::new("plaintext")));
let stack = FileMoves::new();
let moves = [FileMove { from: src.clone().into(), to: dst.clone().into() }];
let token = stack.perform(&docs, None, &moves, &WorkspaceEdit::default(), "Rename", &|_| Ok(())).unwrap();
assert_eq!(id(&dst), A);
assert!(!meta_path(&src).exists());
fs::write(meta_path(&src), "conflict").unwrap();
assert!(stack.undo(&docs, token).is_err());
assert!(stack.can_undo(token));
assert!(dst.exists());
fs::remove_file(meta_path(&src)).unwrap();
let undone = stack.undo(&docs, token).unwrap();
assert_eq!(undone.moves.len(), 2);
assert_eq!(id(&src), A);
assert!(!dst.exists());
}
#[test]
fn orphan_metadata_conflicts_and_standalone_metadata_are_protected() {
let tmp = project();
let src = asset(tmp.path(), "Player.cs", "code", A);
let dst = src.with_file_name("Hero.cs");
fs::write(meta_path(&dst), "orphan").unwrap();
assert!(rename(&src, &dst).is_err());
assert!(copy(&src, &dst).is_err());
assert!(src.exists() && !dst.exists());
assert_eq!(id(&src), A);
assert!(rename(&meta_path(&src), &src.with_file_name("Other.meta")).is_err());
assert!(delete_with(&meta_path(&src), &|_| panic!("must reject before deletion")).is_err());
assert!(rename(&tmp.path().join("Assets"), &tmp.path().join("Renamed")).is_err());
}
#[test]
fn folder_copy_regenerates_guids_and_only_internal_references() {
let tmp = project();
let root = tmp.path();
let text = format!(
"%YAML 1.1\n--- !u!1 &1\nObject:\n internal: {{fileID: 1, guid: {B}, type: 3}}\n external: {{fileID: 2, guid: {C}, type: 3}}\n quoted: \"guid: {B}\"\n block: |\n guid: {B}\n"
);
let src = asset(root, "Group/Scene.prefab", &text, A);
asset(root, "Group/Script.cs", "// untouched", B);
fs::write(root.join("Assets/Group.meta"), format!("guid: {C}\nfolderAsset: yes\n")).unwrap();
// An actual external id not copied into Group.
let external = "44444444444444444444444444444444";
fs::write(
&src,
text.replace(&format!("external: {{fileID: 2, guid: {C}"), &format!("external: {{fileID: 2, guid: {external}")),
)
.unwrap();
fs::write(root.join("Assets/Group/Assembly.asmdef"), format!(r#"{{"references":["GUID:{B}","GUID:{external}"]}}"#))
.unwrap();
let to = root.join("Assets/Group Copy");
copy(&root.join("Assets/Group"), &to).unwrap();
let script = id(&to.join("Script.cs"));
assert_ne!(script, B);
assert_ne!(id(&to.join("Scene.prefab")), A);
assert_ne!(id(&to), C);
assert_eq!(id(&src), A);
let copied = fs::read_to_string(to.join("Scene.prefab")).unwrap();
assert!(copied.contains(&format!("internal: {{fileID: 1, guid: {script}")));
assert!(copied.contains(&format!("external: {{fileID: 2, guid: {external}")));
assert!(copied.contains(&format!("quoted: \"guid: {B}\"")));
assert!(copied.contains(&format!("block: |\n guid: {B}")));
assert!(fs::read_to_string(meta_path(&to.join("Script.cs"))).unwrap().contains("setting: keep\r\n"));
let assembly = fs::read_to_string(to.join("Assembly.asmdef")).unwrap();
assert!(assembly.contains(&format!("GUID:{script}")) && assembly.contains(external));
}
#[test]
fn invalid_or_binary_copy_never_publishes_partial_assets() {
let tmp = project();
let src = asset(tmp.path(), "Group/Data.asset", "binary data", A);
let from = src.parent().unwrap();
let to = from.with_file_name("Copy");
assert!(copy(from, &to).is_err());
assert!(!to.exists() && !meta_path(&to).exists());
assert_eq!(id(&src), A);
fs::write(&src, "%YAML 1.1\n--- !u!1 &1\n").unwrap();
fs::write(meta_path(&src), "guid: invalid\n").unwrap();
assert!(copy(from, &to).is_err());
assert!(!to.exists());
}
#[test]
fn deletion_groups_sidecar_and_restores_both_on_trash_failure() {
let tmp = project();
let src = asset(tmp.path(), "Player.cs", "code", A);
assert_eq!(deletion_paths(&src).unwrap(), vec![src.clone(), meta_path(&src)]);
let error = delete_with(&src, &|stage| {
assert!(stage.join("files/Player.cs").exists());
assert!(stage.join("files/Player.cs.meta").exists());
let destinations: Vec<PathBuf> =
serde_json::from_slice(&fs::read(stage.join("restore-paths.json")).unwrap()).unwrap();
assert_eq!(destinations, vec![src.clone(), meta_path(&src)]);
Err(IdeError::internal("trash unavailable"))
})
.unwrap_err();
assert!(error.message.contains("trash unavailable"));
assert!(src.exists());
assert_eq!(id(&src), A);
delete_with(&src, &ide_vfs::delete_permanently).unwrap();
assert!(!src.exists() && !meta_path(&src).exists());
}
#[test]
fn selecting_both_asset_and_sidecar_does_not_move_twice() {
let tmp = project();
let src = asset(tmp.path(), "Player.cs", "code", A);
let dst = src.with_file_name("Hero.cs");
let expanded = expand_moves(&[
FileMove { from: src.clone().into(), to: dst.clone().into() },
FileMove { from: meta_path(&src).into(), to: meta_path(&dst).into() },
])
.unwrap();
assert_eq!(expanded.len(), 2);
move_files(&expanded).unwrap();
assert_eq!(id(&dst), A);
}
#[test]
fn non_unity_operations_do_not_touch_adjacent_metadata() {
let tmp = tempfile::tempdir().unwrap();
let src = tmp.path().join("file.txt");
let dst = tmp.path().join("copy.txt");
fs::write(&src, "text").unwrap();
fs::write(meta_path(&src), "unrelated").unwrap();
crate::file_ops::copy(&src, &dst).unwrap();
assert!(!meta_path(&dst).exists());
rename(&src, &tmp.path().join("moved.txt")).unwrap();
assert!(meta_path(&src).exists());
}
#[test]
fn failed_second_move_rolls_back_metadata() {
let tmp = project();
let src = asset(tmp.path(), "Player.cs", "code", A);
let meta_dst = src.with_file_name("Moved.cs.meta");
let blocker = tmp.path().join("Assets/blocked");
fs::write(&blocker, "not a directory").unwrap();
let moves = [
FileMove { from: meta_path(&src).into(), to: meta_dst.clone().into() },
FileMove { from: src.clone().into(), to: blocker.join("Moved.cs").into() },
];
assert!(move_files(&moves).is_err());
assert_eq!(id(&src), A);
assert!(src.exists() && !meta_dst.exists());
}
#[test]
fn yaml_scalar_text_does_not_change_reference_detection() {
let tmp = project();
let text = format!(
"%YAML 1.1\n--- !u!1 &1\nObject:\n name: Hero's Sword\n self: {{fileID: 1, guid: {A}, type: 3}}\n text: \"escaped \\\" guid: {A}\"\n multiline: 'value\n guid: {A}'\n selfAgain: {{fileID: 1, guid: {A}, type: 3}}\n"
);
let src = asset(tmp.path(), "Player.prefab", &text, A);
let dst = src.with_file_name("Copied.prefab");
copy(&src, &dst).unwrap();
let new_id = id(&dst);
let copied = fs::read_to_string(&dst).unwrap();
assert!(copied.contains(&format!("self: {{fileID: 1, guid: {new_id}")));
assert!(copied.contains(&format!("selfAgain: {{fileID: 1, guid: {new_id}")));
assert!(copied.contains(&format!("multiline: 'value\n guid: {A}'")));
assert!(copied.contains(&format!("text: \"escaped \\\" guid: {A}\"")));
}
#[cfg(windows)]
#[test]
fn case_only_rename_keeps_metadata() {
let tmp = project();
let src = asset(tmp.path(), "Player.cs", "code", A);
let dst = src.with_file_name("player.cs");
rename(&src, &dst).unwrap();
assert_eq!(id(&dst), A);
assert!(fs::read_dir(dst.parent().unwrap()).unwrap().any(|e| e.unwrap().file_name() == "player.cs.meta"));
}
+233
Переглянути файл
@@ -0,0 +1,233 @@
use super::*;
use ide_core::FileEdit;
fn dir_link(target: &Path, link: &Path) {
#[cfg(unix)]
std::os::unix::fs::symlink(target, link).unwrap();
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
let output = std::process::Command::new("cmd")
.args(["/c", "mklink", "/J"])
.arg(link.to_string_lossy().replace('/', "\\"))
.arg(target.to_string_lossy().replace('/', "\\"))
.creation_flags(0x08000000)
.output()
.unwrap();
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
}
}
#[test]
fn linked_parent_and_project_root_support_asset_operations_and_undo() {
for parent_alias in [false, true] {
let tmp = project();
let aliases = tempfile::tempdir().unwrap();
let link = aliases.path().join("alias");
let root = if parent_alias {
dir_link(tmp.path().parent().unwrap(), &link);
link.join(tmp.path().file_name().unwrap())
} else {
dir_link(tmp.path(), &link);
link.clone()
};
let from = asset(&root, "Player.cs", "class Player {}", A);
let to = root.join("Assets/New/Nested/Hero.cs");
let docs = Documents::new(Arc::new(|_| {}), Box::new(|_: &Path, _: Option<&str>| LanguageId::new("plaintext")));
let moves = FileMoves::new();
let token = moves
.perform(
&docs,
None,
&[FileMove { from: from.clone().into(), to: to.clone().into() }],
&WorkspaceEdit::default(),
"Move",
&|_| Ok(()),
)
.unwrap();
assert_eq!(id(&to), A);
moves.undo(&docs, token).unwrap();
assert_eq!(id(&from), A);
copy(&from, &to).unwrap();
assert_ne!(id(&to), A);
assert_eq!(id(&from), A);
delete_with(&to, &ide_vfs::delete_permanently).unwrap();
assert!(!to.exists() && !meta_path(&to).exists());
let intermediate = root.join("Assets/Intermediate.cs");
docs.apply_workspace_edit(&WorkspaceEdit {
files: vec![
FileEdit::Rename { from: from.clone().into(), to: intermediate.clone().into() },
FileEdit::Rename { from: intermediate.into(), to: to.clone().into() },
],
..Default::default()
})
.unwrap();
assert_eq!(id(&to), A);
assert!(!from.exists() && !meta_path(&from).exists());
}
}
#[test]
fn internal_directory_links_reject_asset_operations_before_mutation() {
for relative in ["Assets/Linked", "Library", "Library/OpenIDEA", "Library/OpenIDEA/AssetOperations"] {
let tmp = project();
let outside = tempfile::tempdir().unwrap();
fs::write(outside.path().join("sentinel"), "keep").unwrap();
let from = asset(tmp.path(), "Player.cs", "code", A);
let link = tmp.path().join(relative);
fs::create_dir_all(link.parent().unwrap()).unwrap();
dir_link(outside.path(), &link);
let to = if relative.starts_with("Assets") { link.join("Copy.cs") } else { from.with_file_name("Copy.cs") };
assert!(copy(&from, &to).unwrap_err().message.contains("do not follow links"));
if relative.starts_with("Assets") {
assert!(rename(&from, &to).is_err());
let docs =
Documents::new(Arc::new(|_| {}), Box::new(|_: &Path, _: Option<&str>| LanguageId::new("plaintext")));
assert!(
docs.apply_workspace_edit(&WorkspaceEdit {
files: vec![FileEdit::Rename { from: from.clone().into(), to: to.clone().into() },],
..Default::default()
})
.is_err()
);
let sentinel = link.join("sentinel");
assert!(
docs.apply_workspace_edit(&WorkspaceEdit {
files: vec![FileEdit::Delete { path: sentinel.into(), recursive: false },],
..Default::default()
})
.is_err()
);
} else {
assert!(delete_with(&from, &|_| panic!("must reject before removal")).is_err());
}
assert_eq!(id(&from), A);
assert!(from.exists() && !to.exists() && !meta_path(&to).exists());
assert_eq!(fs::read_to_string(outside.path().join("sentinel")).unwrap(), "keep");
assert_eq!(fs::read_dir(outside.path()).unwrap().count(), 1);
}
}
#[test]
fn linked_assets_root_and_recursive_copy_links_are_rejected() {
let tmp = project();
let outside = tempfile::tempdir().unwrap();
fs::remove_dir(tmp.path().join("Assets")).unwrap();
dir_link(outside.path(), &tmp.path().join("Assets"));
let from = asset(tmp.path(), "Player.cs", "code", A);
assert!(rename(&from, &from.with_file_name("Hero.cs")).is_err());
assert!(deletion_paths(&from).is_err());
assert_eq!(id(&from), A);
let tmp = project();
let from = asset(tmp.path(), "Group/Player.cs", "code", A);
dir_link(outside.path(), &tmp.path().join("Assets/Group/Linked"));
let to = tmp.path().join("Assets/Copy");
assert!(copy(from.parent().unwrap(), &to).is_err());
assert!(!to.exists() && !meta_path(&to).exists());
assert_eq!(id(&from), A);
}
#[cfg(unix)]
#[test]
fn linked_asset_and_sidecar_leaves_are_rejected() {
for sidecar in [false, true] {
let tmp = project();
let outside = tempfile::NamedTempFile::new().unwrap();
let from = asset(tmp.path(), "Player.cs", "code", A);
let path = if sidecar { meta_path(&from) } else { from.clone() };
fs::remove_file(&path).unwrap();
std::os::unix::fs::symlink(outside.path(), &path).unwrap();
assert!(rename(&from, &from.with_file_name("Hero.cs")).is_err());
assert!(copy(&from, &from.with_file_name("Copy.cs")).is_err());
assert!(deletion_paths(&from).is_err());
assert!(fs::symlink_metadata(&path).unwrap().file_type().is_symlink());
}
}
#[test]
fn cross_project_operations_validate_each_root_and_keep_metadata() {
let source = project();
let destination = project();
let aliases = tempfile::tempdir().unwrap();
let a = aliases.path().join("source");
let b = aliases.path().join("destination");
dir_link(source.path(), &a);
dir_link(destination.path(), &b);
let from = asset(&a, "Player.cs", "code", A);
let copied = b.join("Assets/Copied.cs");
copy(&from, &copied).unwrap();
assert_ne!(id(&copied), A);
assert_eq!(id(&from), A);
let moved = b.join("Assets/Moved.cs");
rename(&from, &moved).unwrap();
assert_eq!(id(&moved), A);
assert!(!from.exists() && !meta_path(&from).exists());
}
#[test]
fn external_links_do_not_become_trusted_by_importing_into_unity() {
let tmp = project();
let external = tempfile::tempdir().unwrap();
let aliases = tempfile::tempdir().unwrap();
fs::write(external.path().join("File.cs"), "code").unwrap();
let link = aliases.path().join("external");
dir_link(external.path(), &link);
let from = link.join("File.cs");
let to = tmp.path().join("Assets/Imported.cs");
assert!(copy(&from, &to).is_err());
assert!(rename(&from, &to).is_err());
assert!(from.exists() && !to.exists());
}
#[test]
fn folder_rename_cannot_hide_linked_children_in_later_transaction_operations() {
let tmp = project();
let outside = tempfile::tempdir().unwrap();
fs::write(outside.path().join("sentinel"), "keep").unwrap();
let from = tmp.path().join("Assets/Group");
fs::create_dir(&from).unwrap();
dir_link(outside.path(), &from.join("Linked"));
let to = tmp.path().join("Assets/Moved");
let docs = Documents::new(Arc::new(|_| {}), Box::new(|_: &Path, _: Option<&str>| LanguageId::new("plaintext")));
let error = docs
.apply_workspace_edit(&WorkspaceEdit {
files: vec![
FileEdit::Rename { from: from.clone().into(), to: to.clone().into() },
FileEdit::Delete {
path: (if cfg!(windows) { tmp.path().join("Assets/moved") } else { to.clone() })
.join("Linked/sentinel")
.into(),
recursive: false,
},
],
..Default::default()
})
.unwrap_err();
assert!(error.message.contains("do not follow links"));
assert!(from.exists() && !to.exists());
assert_eq!(fs::read_to_string(outside.path().join("sentinel")).unwrap(), "keep");
}
#[test]
fn directory_transactions_reject_nested_links_before_snapshotting() {
for delete in [false, true] {
let tmp = project();
let outside = tempfile::tempdir().unwrap();
fs::write(outside.path().join("sentinel"), "keep").unwrap();
let from = tmp.path().join("Assets/Group");
fs::create_dir(&from).unwrap();
dir_link(outside.path(), &from.join("Linked"));
let to = tmp.path().join("Assets/Moved");
let file = if delete {
FileEdit::Delete { path: from.clone().into(), recursive: true }
} else {
FileEdit::Rename { from: from.clone().into(), to: to.clone().into() }
};
let docs = Documents::new(Arc::new(|_| {}), Box::new(|_: &Path, _: Option<&str>| LanguageId::new("plaintext")));
let error = docs.apply_workspace_edit(&WorkspaceEdit { files: vec![file], ..Default::default() }).unwrap_err();
assert!(error.message.contains("do not follow links"));
assert!(from.exists() && !to.exists());
assert_eq!(fs::read_to_string(outside.path().join("sentinel")).unwrap(), "keep");
}
}
+99
Переглянути файл
@@ -0,0 +1,99 @@
//! Include sidecars in the document transaction's preflight, recovery and undo.
use super::{exists, fs, is_link, key, meta_path, no_links, project_root, validate_asset};
use ide_core::{FileEdit, IdeError, IdeResult, WorkspaceEdit};
use std::path::Path;
pub(crate) fn validate_workspace_edit_paths(edit: &WorkspaceEdit) -> IdeResult<()> {
for file in &edit.files {
let validate = |path: &Path| -> IdeResult<()> {
validate_asset(path)?;
no_links(&meta_path(path))?;
no_nested_links(path)
};
match file {
FileEdit::Rename { from, to } if project_root(from).is_some() || project_root(to).is_some() => {
validate(from)?;
validate(to)?;
}
FileEdit::Delete { path, .. } if project_root(path).is_some() => validate(path)?,
_ => {}
}
}
Ok(())
}
// Transactions snapshot directories recursively. Reject linked descendants
// before backup, including junctions and children renamed by a later operation.
fn no_nested_links(path: &Path) -> IdeResult<()> {
let metadata = match fs::symlink_metadata(path) {
Ok(metadata) => metadata,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(error.into()),
};
if is_link(&metadata) {
return Err(IdeError::invalid(format!("Unity asset operations do not follow links: {}", path.display())));
}
if metadata.is_dir() {
for entry in fs::read_dir(path)? {
no_nested_links(&entry?.path())?;
}
}
Ok(())
}
// Resolve against the state produced by earlier operations without touching disk.
// This also handles renaming a folder before renaming/deleting a child asset.
fn present(path: &Path, preceding: &[FileEdit]) -> bool {
let mut path = path.to_path_buf();
for op in preceding.iter().rev() {
match op {
FileEdit::Rename { from, to } => {
if let Ok(relative) = path.strip_prefix(to) {
// Joining an empty suffix adds a separator to a file path;
// that makes an existing sidecar look like a missing directory.
path = if relative.as_os_str().is_empty() { from.to_path_buf() } else { from.join(relative) };
} else if path.starts_with(from) {
return false;
}
}
FileEdit::Delete { path: deleted, .. } if path.starts_with(deleted) => return false,
FileEdit::Create { path: created, .. } if path == created.to_path_buf() => return true,
_ => {}
}
}
exists(&path)
}
pub(crate) fn expand_workspace_edit(edit: &mut WorkspaceEdit) -> IdeResult<()> {
let mut files = Vec::new();
for file in &edit.files {
match file {
FileEdit::Rename { from, to } if project_root(from).is_some() || project_root(to).is_some() => {
validate_asset(from)?;
validate_asset(to)?;
let source = meta_path(from);
let destination = meta_path(to);
no_links(&source)?;
no_links(&destination)?;
if present(&destination, &files) && key(&source) != key(&destination) {
return Err(IdeError::invalid(format!("{} already exists", destination.display())));
}
if present(&source, &files) {
files.push(FileEdit::Rename { from: source.into(), to: destination.into() });
}
}
FileEdit::Delete { path, .. } if project_root(path).is_some() => {
validate_asset(path)?;
let meta = meta_path(path);
no_links(&meta)?;
if present(&meta, &files) {
files.push(FileEdit::Delete { path: meta.into(), recursive: false });
}
}
_ => {}
}
files.push(file.clone());
}
edit.files = files;
Ok(())
}
+147
Переглянути файл
@@ -0,0 +1,147 @@
use ide_workspace::file_ops;
use std::{fs, path::Path};
fn metadata_path(path: &Path) -> std::path::PathBuf {
let mut name = path.as_os_str().to_os_string();
name.push(".meta");
name.into()
}
fn unity_project(root: &Path) {
fs::create_dir_all(root.join("Assets")).unwrap();
fs::create_dir_all(root.join("ProjectSettings")).unwrap();
fs::write(root.join("ProjectSettings/ProjectVersion.txt"), "m_EditorVersion: 2022.3.40f1").unwrap();
}
fn directory_alias(target: &Path, alias: &Path) {
#[cfg(unix)]
std::os::unix::fs::symlink(target, alias).unwrap();
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
let output = std::process::Command::new("cmd")
.args(["/c", "mklink", "/J"])
.arg(alias.to_string_lossy().replace('/', "\\"))
.arg(target.to_string_lossy().replace('/', "\\"))
.creation_flags(0x08000000)
.output()
.unwrap();
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
}
}
#[test]
fn ordinary_rename_through_an_alias_keeps_vfs_same_file_behavior() {
let dir = tempfile::tempdir().unwrap();
let aliases = tempfile::tempdir().unwrap();
let alias = aliases.path().join("project");
directory_alias(dir.path(), &alias);
let from = dir.path().join("File.txt");
let to = alias.join("File.txt");
fs::write(&from, "keep").unwrap();
ide_vfs::rename(&from, &to).unwrap();
file_ops::rename(&from, &to).unwrap();
let copied = alias.join("Copy.txt");
file_ops::copy(&to, &copied).unwrap();
assert_eq!(fs::read_to_string(copied).unwrap(), "keep");
assert_eq!(fs::read_to_string(from).unwrap(), "keep");
}
#[test]
fn plain_files_and_non_assets_in_unity_keep_adjacent_metadata_untouched() {
for unity in [false, true] {
let dir = tempfile::tempdir().unwrap();
if unity {
unity_project(dir.path());
}
let from = dir.path().join("File.txt");
let copied = dir.path().join("Copy.txt");
let renamed = dir.path().join("file.txt");
fs::write(&from, "data").unwrap();
fs::write(metadata_path(&from), "unrelated").unwrap();
file_ops::copy(&from, &copied).unwrap();
assert!(!metadata_path(&copied).exists());
file_ops::rename(&from, &renamed).unwrap();
assert_eq!(fs::read_to_string(&renamed).unwrap(), "data");
assert_eq!(file_ops::deletion_paths(&renamed).unwrap(), [renamed]);
assert_eq!(fs::read_to_string(metadata_path(&from)).unwrap(), "unrelated");
}
}
#[test]
fn mixed_move_and_undo_apply_rules_only_to_unity_assets() {
use ide_core::{LanguageId, WorkspaceEdit};
use ide_workspace::{Documents, FileMove, FileMoves};
use std::sync::Arc;
let unity = tempfile::tempdir().unwrap();
unity_project(unity.path());
let plain = tempfile::tempdir().unwrap();
let aliases = tempfile::tempdir().unwrap();
let alias = aliases.path().join("plain");
directory_alias(plain.path(), &alias);
let source = unity.path().join("Assets/Player.cs");
let destination = unity.path().join("Assets/Hero.cs");
let ordinary = alias.join("plain.txt");
let ordinary_to = alias.join("moved.txt");
fs::write(&source, "class Player {}").unwrap();
fs::write(metadata_path(&source), "guid: 11111111111111111111111111111111\n").unwrap();
fs::write(&ordinary, "plain").unwrap();
fs::write(metadata_path(&ordinary), "unrelated").unwrap();
let docs = Documents::new(Arc::new(|_| {}), Box::new(|_: &Path, _: Option<&str>| LanguageId::new("plaintext")));
let moves = FileMoves::new();
let token = moves
.perform(
&docs,
None,
&[
FileMove { from: ordinary.clone().into(), to: ordinary_to.clone().into() },
FileMove { from: source.clone().into(), to: destination.clone().into() },
],
&WorkspaceEdit::default(),
"Move",
&|_| Ok(()),
)
.unwrap();
assert!(destination.exists() && metadata_path(&destination).exists());
assert!(ordinary_to.exists() && !metadata_path(&ordinary_to).exists());
assert!(metadata_path(&ordinary).exists());
moves.undo(&docs, token).unwrap();
assert!(source.exists() && metadata_path(&source).exists());
assert!(ordinary.exists() && metadata_path(&ordinary).exists());
assert!(!destination.exists() && !metadata_path(&destination).exists());
let blocker = alias.join("blocked");
fs::write(&blocker, "not a directory").unwrap();
assert!(
moves
.perform(
&docs,
None,
&[
FileMove { from: source.clone().into(), to: destination.clone().into() },
FileMove { from: ordinary.clone().into(), to: blocker.join("file.txt").into() },
],
&WorkspaceEdit::default(),
"Move",
&|_| Ok(()),
)
.is_err()
);
assert!(source.exists() && metadata_path(&source).exists());
assert!(ordinary.exists() && metadata_path(&ordinary).exists());
assert!(!destination.exists() && !metadata_path(&destination).exists());
}
#[test]
fn vfs_operations_remain_unaware_of_unity_metadata() {
let dir = tempfile::tempdir().unwrap();
unity_project(dir.path());
let from = dir.path().join("Assets/Player.cs");
let to = dir.path().join("Assets/Hero.cs");
fs::write(&from, "code").unwrap();
fs::write(metadata_path(&from), "metadata").unwrap();
ide_vfs::rename(&from, &to).unwrap();
assert!(to.exists() && !metadata_path(&to).exists());
assert!(metadata_path(&from).exists());
}
+89
Переглянути файл
@@ -9,6 +9,95 @@ fn documents() -> Documents {
Documents::new(Arc::new(NullSink), Box::new(|_, _| LanguageId::plain_text()))
}
fn meta(path: &std::path::Path) -> std::path::PathBuf {
let mut name = path.as_os_str().to_os_string();
name.push(".meta");
name.into()
}
fn unity_project() -> tempfile::TempDir {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join("Assets")).unwrap();
std::fs::create_dir_all(tmp.path().join("ProjectSettings")).unwrap();
std::fs::write(tmp.path().join("ProjectSettings/ProjectVersion.txt"), "m_EditorVersion: 2022.3.40f1\n").unwrap();
tmp
}
#[test]
fn unity_rename_chain_and_delete_share_metadata_undo() {
let tmp = unity_project();
let original = tmp.path().join("Assets/Player.cs");
let renamed = tmp.path().join("Assets/Hero.cs");
std::fs::write(&original, "old").unwrap();
std::fs::write(meta(&original), "guid: unchanged").unwrap();
let (docs, events) = recorded_documents();
docs.apply_workspace_edit(&WorkspaceEdit {
files: vec![
FileEdit::Rename { from: original.clone().into(), to: renamed.clone().into() },
FileEdit::Delete { path: renamed.clone().into(), recursive: false },
],
..Default::default()
})
.unwrap();
for path in [&original, &renamed, &meta(&original), &meta(&renamed)] {
assert!(!path.exists(), "{} should be removed", path.display());
}
docs.undo_workspace_edit(undo_id(&events)).unwrap();
assert_eq!(std::fs::read_to_string(&original).unwrap(), "old");
assert_eq!(std::fs::read_to_string(meta(&original)).unwrap(), "guid: unchanged");
assert!(!renamed.exists() && !meta(&renamed).exists());
}
#[test]
fn unity_metadata_conflict_keeps_earlier_edits_unchanged() {
let tmp = unity_project();
let original = tmp.path().join("Assets/Player.cs");
let renamed = tmp.path().join("Assets/Hero.cs");
std::fs::write(&original, "old").unwrap();
std::fs::write(meta(&original), "guid: original").unwrap();
std::fs::write(meta(&renamed), "guid: orphan").unwrap();
assert!(
documents()
.apply_workspace_edit(&WorkspaceEdit {
files: vec![
edit(&original, "new"),
FileEdit::Rename { from: original.clone().into(), to: renamed.clone().into() }
],
..Default::default()
})
.is_err()
);
assert_eq!(std::fs::read_to_string(&original).unwrap(), "old");
assert_eq!(std::fs::read_to_string(meta(&original)).unwrap(), "guid: original");
assert_eq!(std::fs::read_to_string(meta(&renamed)).unwrap(), "guid: orphan");
}
#[test]
fn unity_folder_rename_then_child_rename_preserves_metadata() {
let tmp = unity_project();
let folder = tmp.path().join("Assets/Before");
let moved = tmp.path().join("Assets/After");
std::fs::create_dir(&folder).unwrap();
std::fs::write(meta(&folder), "folder guid").unwrap();
std::fs::write(folder.join("Player.cs"), "old").unwrap();
std::fs::write(meta(&folder.join("Player.cs")), "script guid").unwrap();
let (docs, events) = recorded_documents();
docs.apply_workspace_edit(&WorkspaceEdit {
files: vec![
FileEdit::Rename { from: folder.clone().into(), to: moved.clone().into() },
FileEdit::Rename { from: moved.join("Player.cs").into(), to: moved.join("Hero.cs").into() },
],
..Default::default()
})
.unwrap();
assert_eq!(std::fs::read_to_string(meta(&moved)).unwrap(), "folder guid");
assert_eq!(std::fs::read_to_string(meta(&moved.join("Hero.cs"))).unwrap(), "script guid");
assert!(!meta(&moved.join("Player.cs")).exists());
docs.undo_workspace_edit(undo_id(&events)).unwrap();
assert_eq!(std::fs::read_to_string(meta(&folder.join("Player.cs"))).unwrap(), "script guid");
assert!(!moved.exists() && !meta(&moved).exists());
}
fn edit(path: &Path, text: &str) -> FileEdit {
FileEdit::Edit {
path: path.to_owned().into(),
+23
Переглянути файл
@@ -0,0 +1,23 @@
# Unity projects
Open the folder containing `Assets` and `ProjectSettings/ProjectVersion.txt`.
OpenIDEA detects Unity without requiring a generated solution and shows the editor
version in the Unity project view.
The Unity view hides `.meta` files, generated C# project files and cache/build
folders. **Show Meta Files** and **Show Generated Files** reveal them independently;
the regular Project view is still available. Generated folders are excluded from
indexing and search, including folders Unity creates after the project is opened.
Operations on assets inside `Assets` include their `.meta` files. Rename and move
preserve GUIDs, deletion removes both files, and copy generates new GUIDs and updates
references within the copied group. References to assets outside the group stay
unchanged. File move undo and transactional workspace edits include metadata too.
Destination metadata conflicts are rejected before making changes.
Projects may be opened through a linked root or parent directory, including macOS
`/var` and `/tmp`. Links inside the project (including Windows junctions) are not
followed by asset operations. For moves/copies to or from ordinary directories,
the external path must have no linked ancestors. Cross-volume asset moves and
copies that require rewriting binary serialized assets are rejected; use Unity
for those operations.
+1 -1
Переглянути файл
@@ -10,7 +10,7 @@ tree-sitter = "csharp"
[[language-servers]]
name = "csharp-ls"
command = "csharp-ls"
root-markers = ["*.sln", "*.slnx", "*.csproj", "global.json", "Directory.Build.props"]
root-markers = ["*.sln", "*.slnx", "*.csproj", "global.json", "Directory.Build.props", "ProjectSettings/ProjectVersion.txt"]
install-hint = "dotnet tool install --global csharp-ls"
[debugger]
+8
Переглянути файл
@@ -24,6 +24,14 @@ useAliasesForRenames = false
[language-servers.initialization-options.javascript.preferences]
useAliasesForRenames = false
# Moving a file: the IDE asks for the import updates up front (preview, undo); the server
# doesn't prompt after the move.
[language-servers.initialization-options.typescript.updateImportsOnFileMove]
enabled = "never"
[language-servers.initialization-options.javascript.updateImportsOnFileMove]
enabled = "never"
[[language-servers]]
name = "typescript-language-server"
tsserver-project = true
+8
Переглянути файл
@@ -23,6 +23,14 @@ useAliasesForRenames = false
[language-servers.initialization-options.javascript.preferences]
useAliasesForRenames = false
# Moving a file: the IDE asks for the import updates up front (preview, undo); the server
# doesn't prompt after the move.
[language-servers.initialization-options.typescript.updateImportsOnFileMove]
enabled = "never"
[language-servers.initialization-options.javascript.updateImportsOnFileMove]
enabled = "never"
[[language-servers]]
name = "typescript-language-server"
tsserver-project = true
+8
Переглянути файл
@@ -23,6 +23,14 @@ useAliasesForRenames = false
[language-servers.initialization-options.javascript.preferences]
useAliasesForRenames = false
# Moving a file: the IDE asks for the import updates up front (preview, undo); the server
# doesn't prompt after the move.
[language-servers.initialization-options.typescript.updateImportsOnFileMove]
enabled = "never"
[language-servers.initialization-options.javascript.updateImportsOnFileMove]
enabled = "never"
[[language-servers]]
name = "typescript-language-server"
tsserver-project = true
+8
Переглянути файл
@@ -23,6 +23,14 @@ useAliasesForRenames = false
[language-servers.initialization-options.javascript.preferences]
useAliasesForRenames = false
# Moving a file: the IDE asks for the import updates up front (preview, undo); the server
# doesn't prompt after the move.
[language-servers.initialization-options.typescript.updateImportsOnFileMove]
enabled = "never"
[language-servers.initialization-options.javascript.updateImportsOnFileMove]
enabled = "never"
[[language-servers]]
name = "typescript-language-server"
tsserver-project = true
+8
Переглянути файл
@@ -30,6 +30,14 @@ useAliasesForRenames = false
[language-servers.initialization-options.javascript.preferences]
useAliasesForRenames = false
# Moving a file: the IDE asks for the import updates up front (preview, undo); the server
# doesn't prompt after the move.
[language-servers.initialization-options.typescript.updateImportsOnFileMove]
enabled = "never"
[language-servers.initialization-options.javascript.updateImportsOnFileMove]
enabled = "never"
[[language-servers]]
name = "oxlint"
command = "oxlint"
+2 -2
Переглянути файл
@@ -65,8 +65,8 @@ pub fn fs_create_dir(path: PathBuf) -> IdeResult<()> {
#[tauri::command]
#[specta::specta]
pub fn fs_rename(from: PathBuf, to: PathBuf) -> IdeResult<()> {
ide_vfs::rename(&from, &to)
pub async fn fs_rename(state: State<'_, AppState>, from: PathBuf, to: PathBuf) -> IdeResult<()> {
fs::rename(&state.host, from, to).await
}
/// Toggle Read-only Attribute: sets the writable bit (and the open document's
+9
Переглянути файл
@@ -186,6 +186,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
caches::caches_schedule_invalidation,
caches::app_restart,
nav::index_status,
nav::index_file_extensions,
nav::spring_route_sources,
nav::find_files,
nav::find_dirs,
@@ -249,6 +250,14 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
vcs::vcs_blame,
vcs::vcs_block_history,
vcs::vcs_log,
vcs::vcs_log_refs,
vcs::vcs_log_users,
vcs::vcs_open_external_log,
vcs::vcs_log_details,
vcs::vcs_log_details_batch,
vcs::vcs_log_index,
vcs::vcs_revision_children,
vcs::vcs_revision_files,
vcs::vcs_commit_files,
vcs::vcs_commits_changes,
vcs::vcs_branches,
+7 -1
Переглянути файл
@@ -4,7 +4,7 @@ use crate::state::AppState;
use ide_core::{DocId, IdeResult, IpcPath, Pos};
#[allow(unused_imports)]
pub use ide_host::ops::nav::*;
use ide_index::{FileMatch, IndexStatus, SymbolFilter, SymbolMatch};
use ide_index::{ExtensionCount, FileMatch, IndexStatus, SymbolFilter, SymbolMatch};
use ide_language::FileReference;
use ide_workspace::file_refs::PathCompletion;
use std::path::PathBuf;
@@ -16,6 +16,12 @@ pub fn index_status(window: Window, state: State<'_, AppState>) -> IdeResult<Ind
ide_host::ops::nav::index_status(&state.host, window.label())
}
#[tauri::command]
#[specta::specta]
pub fn index_file_extensions(window: Window, state: State<'_, AppState>) -> IdeResult<Vec<ExtensionCount>> {
ide_host::ops::nav::index_file_extensions(&state.host, window.label())
}
#[tauri::command]
#[specta::specta]
pub fn find_files(window: Window, state: State<'_, AppState>, query: String, limit: u32) -> IdeResult<Vec<FileMatch>> {
+85
Переглянути файл
@@ -88,6 +88,91 @@ pub async fn vcs_log(
ide_host::ops::vcs::vcs_log(&state.host, window.label(), repo, query).await
}
#[tauri::command]
#[specta::specta]
pub async fn vcs_log_refs(
window: Window,
state: State<'_, AppState>,
repo: Option<PathBuf>,
) -> IdeResult<std::collections::BTreeMap<String, String>> {
ide_host::ops::vcs::vcs_log_refs(&state.host, window.label(), repo).await
}
#[tauri::command]
#[specta::specta]
pub async fn vcs_log_users(
window: Window,
state: State<'_, AppState>,
repo: Option<PathBuf>,
) -> IdeResult<Vec<String>> {
ide_host::ops::vcs::vcs_log_users(&state.host, window.label(), repo).await
}
#[tauri::command]
#[specta::specta]
pub async fn vcs_open_external_log(
window: Window,
state: State<'_, AppState>,
path: PathBuf,
) -> IdeResult<ide_core::IpcPath> {
ide_host::ops::vcs::vcs_open_external_log(&state.host, window.label(), path).await
}
#[tauri::command]
#[specta::specta]
pub async fn vcs_log_details(
window: Window,
state: State<'_, AppState>,
repo: Option<PathBuf>,
revision: String,
) -> IdeResult<LogDetails> {
ide_host::ops::vcs::vcs_log_details(&state.host, window.label(), repo, revision).await
}
#[tauri::command]
#[specta::specta]
pub async fn vcs_log_details_batch(
window: Window,
state: State<'_, AppState>,
repo: Option<PathBuf>,
revisions: Vec<String>,
request: RequestId,
) -> IdeResult<Vec<LogDetails>> {
ide_host::ops::vcs::vcs_log_details_batch(&state.host, window.label(), repo, revisions, request).await
}
#[tauri::command]
#[specta::specta]
pub async fn vcs_log_index(
window: Window,
state: State<'_, AppState>,
repo: Option<PathBuf>,
request: Option<RequestId>,
) -> IdeResult<LogIndexProgress> {
ide_host::ops::vcs::vcs_log_index(&state.host, window.label(), repo, request).await
}
#[tauri::command]
#[specta::specta]
pub async fn vcs_revision_children(
window: Window,
state: State<'_, AppState>,
repo: Option<PathBuf>,
revision: String,
directory: String,
) -> IdeResult<Vec<String>> {
ide_host::ops::vcs::vcs_revision_children(&state.host, window.label(), repo, revision, directory).await
}
#[tauri::command]
#[specta::specta]
pub async fn vcs_revision_files(
window: Window,
state: State<'_, AppState>,
repo: Option<PathBuf>,
revision: String,
) -> IdeResult<Vec<String>> {
ide_host::ops::vcs::vcs_revision_files(&state.host, window.label(), repo, revision).await
}
#[tauri::command]
#[specta::specta]
pub async fn vcs_commit_files(
+117 -20
Переглянути файл
@@ -42,6 +42,7 @@ export const commands = {
isGit: boolean,
settings: Settings_Serialize,
workspace?: Workspace_Serialize | null,
unity?: UnityProjectInfo | null,
} | null>("project_current"),
closeProject: () => __TAURI_INVOKE<void>("close_project"),
languages: () => __TAURI_INVOKE<LanguageInfo_Serialize[]>("languages"),
@@ -324,6 +325,7 @@ export const commands = {
/** Quits through every window's unsaved-changes check, then starts again. */
appRestart: () => __TAURI_INVOKE<void>("app_restart"),
indexStatus: () => typedError<IndexStatus, IdeError>(__TAURI_INVOKE("index_status")),
indexFileExtensions: () => typedError<ExtensionCount[], IdeError>(__TAURI_INVOKE("index_file_extensions")),
/** Spring Web mapping sources for the request-path index of Search Everywhere. */
springRouteSources: () => typedError<RouteSource[], IdeError>(__TAURI_INVOKE("spring_route_sources")),
findFiles: (query: string, limit: number) => typedError<FileMatch[], IdeError>(__TAURI_INVOKE("find_files", { query, limit })),
@@ -474,7 +476,15 @@ export const commands = {
* editor text. Cancellable with `cancel_request(request)`.
*/
vcsBlockHistory: (request: RequestId, path: string, text: string | null, lines: [number, number]) => typedError<BlockHistory, IdeError>(__TAURI_INVOKE("vcs_block_history", { request, path, text, lines })),
vcsLog: (repo: string | null, query: LogQuery) => typedError<Commit[], IdeError>(__TAURI_INVOKE("vcs_log", { repo, query })),
vcsLog: (repo: string | null, query: LogQuery) => typedError<Commit_Serialize[], IdeError>(__TAURI_INVOKE("vcs_log", { repo, query })),
vcsLogRefs: (repo: string | null) => typedError<{ [key in string]: string }, IdeError>(__TAURI_INVOKE("vcs_log_refs", { repo })),
vcsLogUsers: (repo: string | null) => typedError<string[], IdeError>(__TAURI_INVOKE("vcs_log_users", { repo })),
vcsOpenExternalLog: (path: string) => typedError<IpcPath, IdeError>(__TAURI_INVOKE("vcs_open_external_log", { path })),
vcsLogDetails: (repo: string | null, revision: string) => typedError<LogDetails, IdeError>(__TAURI_INVOKE("vcs_log_details", { repo, revision })),
vcsLogDetailsBatch: (repo: string | null, revisions: string[], request: RequestId) => typedError<LogDetails[], IdeError>(__TAURI_INVOKE("vcs_log_details_batch", { repo, revisions, request })),
vcsLogIndex: (repo: string | null, request: number | null) => typedError<LogIndexProgress, IdeError>(__TAURI_INVOKE("vcs_log_index", { repo, request })),
vcsRevisionChildren: (repo: string | null, revision: string, directory: string) => typedError<string[], IdeError>(__TAURI_INVOKE("vcs_revision_children", { repo, revision, directory })),
vcsRevisionFiles: (repo: string | null, revision: string) => typedError<string[], IdeError>(__TAURI_INVOKE("vcs_revision_files", { repo, revision })),
vcsCommitFiles: (repo: string | null, commit: string) => typedError<ChangedFile[], IdeError>(__TAURI_INVOKE("vcs_commit_files", { repo, commit })),
/** Combined changes of several commits, `commits` oldest first. */
vcsCommitsChanges: (repo: string | null, commits: string[]) => typedError<RevisionChange[], IdeError>(__TAURI_INVOKE("vcs_commits_changes", { repo, commits })),
@@ -2115,24 +2125,7 @@ export type CommandForm = {
formAnswers: FormAnswer[],
};
export type Commit = {
id: string,
shortId: string,
parents: string[],
author: string,
email: string,
timeMs: number | null,
summary: string,
message: string,
refs: string[],
/** Committer time (Log › View Options › Commit Timestamp). */
commitTimeMs?: number | null,
/**
* Per parent, under a user or text filter: the link passes commits the filter hides
* (`parents` then name the nearest shown ancestors). Empty when no parent is rewritten.
*/
dashed?: boolean[],
};
export type Commit = Commit_Serialize | Commit_Deserialize;
/** Commit Options (IDEA's commit options popup). */
export type CommitOptions = {
@@ -2173,6 +2166,64 @@ export type CommitSettings = {
wrapAtMargin?: boolean,
};
export type Commit_Deserialize = {
id: string,
shortId: string,
parents: string[],
/** Connections in the filtered graph; never use these as revision/diff parents. */
graphParents?: string[] | null,
graphDashed?: boolean[],
/** Repository-relative filename at this revision in rename-following history. */
historyPath?: string | null,
logPosition?: number | null,
logTotal?: number | null,
graphBoundaryParents?: string[],
/** Reachability from HEAD, computed independently of the visible filters. */
onCurrentBranch?: boolean | null,
author: string,
email: string,
committer?: string,
committerEmail?: string,
timeMs: number | null,
summary: string,
message: string,
messageTruncated?: boolean,
refs: string[],
/** Committer time (Log › View Options › Commit Timestamp). */
commitTimeMs?: number | null,
/** Legacy alias of `graph_dashed`, indexed by displayed parents. */
dashed?: boolean[],
};
export type Commit_Serialize = {
id: string,
shortId: string,
parents: string[],
/** Connections in the filtered graph; never use these as revision/diff parents. */
graphParents?: string[] | null,
graphDashed?: boolean[],
/** Repository-relative filename at this revision in rename-following history. */
historyPath?: string | null,
logPosition?: number | null,
logTotal?: number | null,
graphBoundaryParents?: string[],
/** Reachability from HEAD, computed independently of the visible filters. */
onCurrentBranch?: boolean | null,
author: string,
email: string,
committer: string,
committerEmail: string,
timeMs: number | null,
summary: string,
message: string,
messageTruncated: boolean,
refs: string[],
/** Committer time (Log › View Options › Commit Timestamp). */
commitTimeMs: number | null,
/** Legacy alias of `graph_dashed`, indexed by displayed parents. */
dashed?: boolean[],
};
export type CompareResult = {
repositories: RepositoryComparison[],
skippedPaths: IpcPath[],
@@ -3363,6 +3414,12 @@ export type ExpressionAt = {
hasError: boolean,
};
/** How many indexed files share an extension (lower case, without the dot). */
export type ExtensionCount = {
extension: string,
files: number,
};
/** A formatter that runs outside the language servers, with its own settings group. */
export type ExternalFormatter = "prettier" | "oxfmt";
@@ -4856,6 +4913,22 @@ export type Location = {
uri?: string | null,
};
export type LogDetails = {
message: string,
containingBranches: string[],
/** Git's verification code: G/U good, B bad, E error, N unsigned, X/Y expired, R revoked. */
signature: string,
signer: string,
key: string,
fingerprint: string,
};
export type LogIndexProgress = {
indexed: number,
total: number,
running: boolean,
};
export type LogLevel = "debug" | "info" | "warn" | "error";
export type LogLocation = {
@@ -4869,11 +4942,19 @@ export type LogOrder =
/** `--topo-order`: lines of history are not intermixed. */
"topo" |
/** `--date-order`: commit time, but never a parent before its children. */
"date";
"date" | "standard";
export type LogQuery = {
speedSearch?: string | null,
searchFields?: string[],
/** Jump directly to an indexed window containing this commit (50 rows of context). */
seek?: string | null,
retainUntil?: string | null,
branch: string | null,
path: IpcPath | null,
paths?: IpcPath[],
/** File history follows renames; structure filters retain fixed paths. */
follow?: boolean,
author: string | null,
text: string | null,
skip: number,
@@ -4883,6 +4964,8 @@ export type LogQuery = {
* not the left). Takes precedence over `branch`.
*/
range?: string | null,
/** Additional ranges unioned with each other and with selected branches. */
ranges?: string[],
/** `text` is a regular expression (Log filter `.*`). */
textRegex?: boolean,
/** `text` matches case-sensitively (Log filter `Cc`). */
@@ -4891,6 +4974,7 @@ export type LogQuery = {
branches?: string[],
/** More author needles next to `author`; a commit matches any of them (Log User filter). */
authors?: string[],
authorsExact?: boolean,
order?: LogOrder,
/** Follow only the first parent of merges (`--first-parent`). */
firstParent?: boolean,
@@ -4903,6 +4987,10 @@ export type LogQuery = {
*/
sinceMs?: number | null,
untilMs?: number | null,
request?: RequestId | null,
summaryOnly?: boolean,
/** Inclusive refresh boundary. Clients join only verified linear prefixes. */
stopAt?: string | null,
};
export type LspRefreshKind = "inlayHints" | "semanticTokens" | "codeLens";
@@ -5646,6 +5734,7 @@ export type ProjectInfo_Deserialize = {
isGit: boolean,
settings: Settings_Deserialize,
workspace?: Workspace_Deserialize | null,
unity?: UnityProjectInfo | null,
};
export type ProjectInfo_Serialize = {
@@ -5655,6 +5744,7 @@ export type ProjectInfo_Serialize = {
isGit: boolean,
settings: Settings_Serialize,
workspace?: Workspace_Serialize | null,
unity?: UnityProjectInfo | null,
};
export type ProjectRoots = {
@@ -7163,6 +7253,13 @@ export type UndoOutcome = {
conflicts: IpcPath[],
};
export type UnityProjectInfo = {
editorVersion: string | null,
/** File names relative to the Unity root, in stable order. */
solutions: string[],
projects: string[],
};
export type UpdateCheck = {
/** False when no update endpoint is configured (no request was made). */
enabled: boolean,
+1
Переглянути файл
@@ -432,6 +432,7 @@ export const GUTTER_ICON_GROUPS = [
{ id: "bookmarks", gutterClass: "cm-openidea-bookmarks" },
{ id: "inheritors", gutterClass: "cm-openidea-gutter-lineMarkers" },
{ id: "supers", gutterClass: "cm-openidea-gutter-lineMarkers" },
{ id: "colors", gutterClass: "cm-openidea-gutter-colors" },
] as const;
export interface PrefsOptions {
+4 -3
Переглянути файл
@@ -104,9 +104,10 @@ export const openideaTheme = EditorView.theme({
"&.cm-openidea-methodSeparators .cm-openidea-methodSeparator": {
boxShadow: "inset 0 1px 0 var(--border-method-separator, var(--border))",
},
"&.cm-openidea-hideGutter-run .cm-openidea-gutter-run, &.cm-openidea-hideGutter-bookmarks .cm-openidea-bookmarks": {
display: "none !important",
},
"&.cm-openidea-hideGutter-run .cm-openidea-gutter-run, &.cm-openidea-hideGutter-bookmarks .cm-openidea-bookmarks, &.cm-openidea-hideGutter-colors .cm-openidea-gutter-colors":
{
display: "none !important",
},
// Inheritance markers share one gutter: each group hides its own icons.
"&.cm-openidea-hideGutter-inheritors :is(.cm-openidea-lineMarker-implemented, .cm-openidea-lineMarker-overridden), &.cm-openidea-hideGutter-supers :is(.cm-openidea-lineMarker-implementing, .cm-openidea-lineMarker-overriding)":
{ display: "none" },
+22 -2
Переглянути файл
@@ -24,6 +24,7 @@ import {
notifications,
resolveFileEditor,
useContributions,
useStandaloneEditor,
type EditorCloseSession,
type EditorInput,
type OpenOptions,
@@ -230,6 +231,7 @@ export class EditorController implements SlotHost {
private closeSession: EditorCloseSession | null = null;
private closeCommitted = false;
private projectGeneration = 0;
private replacingProject = false;
private admissionGeneration = 0;
private openSequence = 0;
private selectionRequests = new Map<string, number>();
@@ -255,7 +257,14 @@ export class EditorController implements SlotHost {
_provideOpenEditorPaths(() => openFilePaths(useTabs.getState()));
let prevTabs = useTabs.getState();
this.disposers.push(
useTabs.subscribe((s) => {
useTabs.subscribe((s, previous) => {
const open = openKeys(s);
const closed = new Map<string, EditorInput>();
for (const pane of Object.values(previous.panes))
for (const tab of pane.tabs) if (!open.has(tab.input.key)) closed.set(tab.input.key, tab.input);
if (!this.replacingProject)
for (const input of closed.values())
useContributions.getState().editorKinds.get(input.kind)?.onClose?.(input);
const prev = prevTabs;
prevTabs = s;
if (
@@ -265,6 +274,11 @@ export class EditorController implements SlotHost {
++this.activationGeneration;
this.stampActive(s);
this.onTabsChanged(prev, s);
const kinds = useContributions.getState().editorKinds;
const standalone = Object.values(s.panes)
.flatMap((pane) => pane.tabs)
.find((tab) => kinds.get(tab.input.kind)?.standalone);
useStandaloneEditor.setState({ title: standalone ? tabTitle(standalone.input, kinds) : null });
}),
);
tabOptions.activateOnClose = editorPrefs().tabs.activateOnClose as typeof tabOptions.activateOnClose;
@@ -299,7 +313,12 @@ export class EditorController implements SlotHost {
const documents = customDocuments(useTabs.getState(), useContributions.getState().editorKinds);
// The guard decided already. Disposal must never prompt or autosave
// custom documents after the backend has replaced their project.
useTabs.setState(initialTabsState(), true);
this.replacingProject = true;
try {
useTabs.setState(initialTabsState(), true);
} finally {
this.replacingProject = false;
}
this.closeSession = null;
this.closeCommitted = false;
this.preparedDocuments.clear();
@@ -367,6 +386,7 @@ export class EditorController implements SlotHost {
this.selectionRequests.clear();
this.manager.stop();
useTabs.setState(initialTabsState(), true);
useStandaloneEditor.setState({ title: null });
void this.releaseDocuments(documents.values()).catch((e) => this.documentError(e));
}
+37
Переглянути файл
@@ -0,0 +1,37 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { registerEditorKind } from "@/workbench/contributions";
import { EditorController, useTabs } from "./controller";
import { createMemoryBackend } from "./backend";
import { initialTabsState } from "./model/tabs";
let controller: EditorController | null = null;
afterEach(() => {
controller?.stop();
controller = null;
useTabs.setState(initialTabsState(), true);
});
describe("custom editor close lifecycle", () => {
it("notifies once when the last split showing an input closes", async () => {
const close = vi.fn();
const dispose = registerEditorKind({
kind: "close-probe",
title: () => "Probe",
component: () => null,
onClose: close,
});
controller = new EditorController(createMemoryBackend({}));
controller.start();
const input = { kind: "close-probe", key: "close-probe:1" };
try {
await controller.openInput(input);
controller.split(useTabs.getState().activePane, "row");
const panes = Object.values(useTabs.getState().panes);
expect(panes).toHaveLength(2);
await controller.closeTab(panes[0]!.id, panes[0]!.tabs[0]!.id);
expect(close).not.toHaveBeenCalled();
await controller.closeInput(input.key);
expect(close).toHaveBeenCalledExactlyOnceWith(input);
} finally {
dispose();
}
});
});
+40 -10
Переглянути файл
@@ -39,7 +39,14 @@ import { setContext } from "@/platform/context";
import { showFindResults, type FindResultsSource } from "@/workbench/contributions";
import { relativePath, useProject } from "@/platform/project";
import { tx } from "@/platform/i18n";
import { bindingsFor, hasPrimaryModifier, normalizeBinding, registerKeyClaim, shortcutLabel } from "@/platform/keymap";
import {
bindingsFor,
formatBinding,
hasPrimaryModifier,
normalizeBinding,
registerKeyClaim,
shortcutLabel,
} from "@/platform/keymap";
/**
* The last search (IDEA's find-in-file model): a newly opened bar starts from it and ⌘G
@@ -516,7 +523,12 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo
: [{ label: kind === "find" ? "No recent searches" : "No recent replacements", disabled: true }];
};
const filterItems: MenuItem[] = [
{ label: "Search In Selection", shortcut: "⌥E", checked: scoped || undefined, run: () => toggleScope(target) },
{
label: "Search In Selection",
shortcut: formatBinding("Alt+E"),
checked: scoped || undefined,
run: () => toggleScope(target),
},
{ kind: "separator" },
{ kind: "header", label: "Search Scope" },
...SEARCH_CONTEXTS.map((c) => ({
@@ -595,7 +607,7 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo
id: "case",
icon: "case",
title: "Match Case",
shortcut: "⌥C",
shortcut: formatBinding("Alt+C"),
pressed: opts.caseSensitive,
onToggle: () => toggle("caseSensitive"),
},
@@ -603,7 +615,7 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo
id: "word",
icon: "word",
title: "Words",
shortcut: "⌥W",
shortcut: formatBinding("Alt+W"),
pressed: opts.wholeWord,
onToggle: () => toggle("wholeWord"),
},
@@ -611,7 +623,7 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo
id: "regex",
icon: "regex",
title: "Regex",
shortcut: "⌥X",
shortcut: formatBinding("Alt+X"),
pressed: opts.regexp,
onToggle: () => toggle("regexp"),
},
@@ -625,11 +637,17 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo
<IconButton
icon="arrow-up"
title="Previous Occurrence"
shortcut="⇧↵"
shortcut={formatBinding("Shift+Enter")}
size="small"
onClick={() => run(findPrevious)}
/>
<IconButton icon="arrow-down" title="Next Occurrence" shortcut="↵" size="small" onClick={() => run(findNext)} />
<IconButton
icon="arrow-down"
title="Next Occurrence"
shortcut={formatBinding("Enter")}
size="small"
onClick={() => run(findNext)}
/>
<IconButton
ref={filterRef}
icon="filter"
@@ -665,15 +683,27 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo
/>
</div>
<div className={styles.replaceButtons}>
<Button size="small" title="Replace (⌥P)" onClick={doReplace} disabled={!canReplace}>
<Button
size="small"
title={tx`Replace (${formatBinding("Alt+P")})`}
onClick={doReplace}
disabled={!canReplace}
>
<T>Replace</T>
</Button>
<Button size="small" title="Replace All (⌥A)" onClick={doReplaceAll} disabled={!canReplace}>
<Button
size="small"
title={tx`Replace All (${formatBinding("Alt+A")})`}
onClick={doReplaceAll}
disabled={!canReplace}
>
<T>Replace All</T>
</Button>
<Button
size="small"
title={count?.excluded ? "Include (⌥L)" : "Exclude (⌥L)"}
title={
count?.excluded ? tx`Include (${formatBinding("Alt+L")})` : tx`Exclude (${formatBinding("Alt+L")})`
}
onClick={() => run(excludeCurrent)}
disabled={!canReplace || (!count?.total && !count?.excluded)}
>
+33 -1
Переглянути файл
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { Text } from "@codemirror/state";
import { fragmentOffset, linkReference, looksLikePath, textReference } from "./links";
import { fragmentOffset, linkReference, looksLikePath, resolvePath, textReference } from "./links";
const at = (src: string, marker = "|") => {
const offset = src.indexOf(marker);
@@ -28,6 +28,20 @@ describe("text references", () => {
expect(textReference(text, offset)).toMatchObject({ kind: "path", value: "img/logo.svg" });
});
it("finds fragment-only link targets", () => {
for (const source of ["[artist::order](#Artist-or|der)", '<a href="#Artist-or|der">order</a>']) {
const { text, offset } = at(source);
expect(textReference(text, offset)).toMatchObject({ kind: "path", value: "#Artist-order" });
}
});
it("does not treat arbitrary fragment strings as links", () => {
for (const source of ['const color = "#ff|f"', '<a id="Artist-or|der">', "url(#ic|on)"]) {
const { text, offset } = at(source);
expect(textReference(text, offset)).toBeNull();
}
});
it("ignores prose and identifiers", () => {
expect(looksLikePath("hello world.txt")).toBe(false);
expect(looksLikePath("utf-8")).toBe(false);
@@ -41,6 +55,18 @@ describe("text references", () => {
});
describe("links and fragments", () => {
it("resolves local fragments without probing the filesystem", async () => {
const ref = { kind: "path" as const, from: 5, to: 20, value: "#Artist%2Dorder" };
expect(await resolvePath(ref, "/p/notes.md")).toEqual({
kind: "file",
from: 5,
to: 20,
path: "/p/notes.md",
fragment: "Artist-order",
});
expect(await resolvePath({ ...ref, value: "#bad%" }, "/p/notes.md")).toBeNull();
});
it("picks the server link around the offset", () => {
const text = Text.of(['<a href="b.html#top">']);
const range = { start: { line: 0, col: 9 }, end: { line: 0, col: 19 } };
@@ -55,6 +81,12 @@ describe("links and fragments", () => {
const html = '<p>\n<div class="x" id="main">';
expect(fragmentOffset(html, "/i.html", "main")).toBe(html.indexOf("id="));
expect(fragmentOffset("# Intro\n\n## Getting Started!\n", "/r.md", "getting-started")).toBe(9);
for (const path of ["/r.md", "/r.markdown", "/r.mdx"]) {
for (const attr of ["id", "name"]) {
const source = `[artist::order](#Artist-order)\n\n<a ${attr}="Artist-order"></a>`;
expect(fragmentOffset(source, path, "Artist-order")).toBe(source.indexOf(`${attr}=`));
}
}
expect(fragmentOffset("x", "/i.html", "nope")).toBeNull();
});
});
+16 -5
Переглянути файл
@@ -87,14 +87,19 @@ export function textReference(text: Text, offset: number): Reference | null {
return { kind: "url", from: line.from + m.index, to: line.from + m.index + m[0].length, url: m[0] };
}
const strings = [
...[...line.text.matchAll(QUOTED_RE)].map((m) => ({ value: m[1] ?? m[2] ?? m[3] ?? "", from: m.index + 1 })),
...[...line.text.matchAll(QUOTED_RE)].map((m) => ({
value: m[1] ?? m[2] ?? m[3] ?? "",
from: m.index + 1,
fragment: /\bhref\s*=\s*$/i.test(line.text.slice(0, m.index)),
})),
...[...line.text.matchAll(BARE_RE)].map((m) => {
const value = m[1] ?? m[2] ?? "";
return { value, from: m.index + m[0].indexOf(value) };
return { value, from: m.index + m[0].indexOf(value), fragment: m[1] !== undefined };
}),
];
for (const { value, from } of strings) {
if (col < from || col > from + value.length || !looksLikePath(value)) continue;
for (const { value, from, fragment } of strings) {
if (col < from || col > from + value.length || (!looksLikePath(value) && !(fragment && /^#[^\s]+$/.test(value))))
continue;
return { kind: "path", from: line.from + from, to: line.from + from + value.length, value };
}
return null;
@@ -113,6 +118,13 @@ async function isFile(path: string): Promise<boolean> {
/** Resolves a `path` reference (in the backend, like IDEA's file references); null when nothing exists there. */
export async function resolvePath(ref: Reference, from: string): Promise<Reference | null> {
if (ref.kind !== "path") return ref;
if (ref.value.startsWith("#")) {
try {
return { kind: "file", from: ref.from, to: ref.to, path: from, fragment: decodeURIComponent(ref.value.slice(1)) };
} catch {
return null;
}
}
if (!isTauri()) return null;
const path = await call(commands.fsResolveReference(from, ref.value)).catch(() => null);
if (!path) return null;
@@ -142,7 +154,6 @@ export function fragmentOffset(text: string, path: string, fragment: string): nu
if (h && slug(h[1]!) === fragment.toLowerCase()) return offset;
offset += l.length + 1;
}
return null;
}
const m = new RegExp(`\\b(?:id|name)\\s*=\\s*["']?${esc}(?=["'\\s>])`).exec(text);
return m ? m.index : null;
+17 -1
Переглянути файл
@@ -50,7 +50,15 @@ import { showHint, showPendingHint } from "./hint";
import { outsideProjectReason } from "./outsideProject";
import { caretAnchor, openPopup, type ListPopupItem } from "./popupStore";
import { readManyFileLines, targetLabel } from "./files";
import { documentLinks, followReference, knownLinks, linkReference, referenceAt, textReference } from "./links";
import {
documentLinks,
followReference,
fragmentOffset,
knownLinks,
linkReference,
referenceAt,
textReference,
} from "./links";
import { featureBackoff } from "./availability";
import { requestHover, showPhpConstructDocumentation } from "./hover";
import { declarationSummary, renderCode } from "./markdown";
@@ -277,6 +285,14 @@ async function followReferenceAt(view: EditorView, doc: EditorDocContext, offset
const ref = await referenceAt(view, doc, offset);
if (!ref) return false;
try {
if (ref.kind === "file" && ref.path === doc.path && ref.fragment) {
const target = fragmentOffset(view.state.doc.toString(), doc.path, ref.fragment);
if (target !== null) {
view.dispatch({ selection: EditorSelection.cursor(target), effects: EditorView.scrollIntoView(target) });
view.focus();
return true;
}
}
await followReference(ref);
} catch (e) {
showHint(view, e instanceof Error ? e.message : String(e), { tone: "error" });
+15 -5
Переглянути файл
@@ -82,15 +82,12 @@ const local = (over: Partial<Extract<Locals, { status: "local" }>["symbol"]> = {
});
const views: EditorView[] = [];
function editor(doc: string, language = "typescript", anchor = 0) {
function editor(doc: string, language = "typescript", anchor = 0, path = "/p/a.ts") {
const view = new EditorView({
state: EditorState.create({
doc,
selection: { anchor },
extensions: [
lspDoc.of({ doc: 7, path: "/p/a.ts", language, uiMode: null, readOnly: false }),
navigationExtension(),
],
extensions: [lspDoc.of({ doc: 7, path, language, uiMode: null, readOnly: false }), navigationExtension()],
}),
parent: document.body,
});
@@ -670,3 +667,16 @@ describe("modifier-hover navigation recovery", () => {
expect(view.dom.querySelector(".cm-lsp-link")?.textContent).toBe("bar");
});
});
describe("same-document fragment navigation", () => {
it.each(["definition", "declaration"] as const)(
"follows Markdown HTML anchors through %s without a server",
async (kind) => {
const source = '[artist::order](#Artist-order)\n\n<a id="Artist-order"></a>';
const view = editor(source, "markdown", source.indexOf("#Artist"), "/p/notes.md");
await gotoTargets(view, kind);
expect(view.state.selection.main.head).toBe(source.indexOf("id="));
expect(openFile).not.toHaveBeenCalled();
},
);
});
+35
Переглянути файл
@@ -0,0 +1,35 @@
/* Editor gutter color swatches. */
.gutter :global(.cm-gutterElement) {
display: flex;
align-items: center;
justify-content: center;
}
.swatch {
width: 12px;
height: 12px;
box-sizing: border-box;
border: 1px solid var(--border-strong);
border-radius: var(--radius-small);
overflow: hidden;
}
.swatch > span {
display: block;
width: 100%;
height: 100%;
}
.editable {
cursor: pointer;
}
.editable:hover {
border-color: var(--fg-muted);
}
/* The native color input only anchors the system picker. */
.picker {
position: fixed;
width: 1px;
height: 1px;
padding: 0;
border: 0;
opacity: 0;
pointer-events: none;
}
+70
Переглянути файл
@@ -0,0 +1,70 @@
import { describe, expect, it } from "vitest";
import { findColors, formatColor, fromHex6, parseComputed, toHex6, type ColorMatch } from "./colors";
const NAMES = new Set(["red", "rebeccapurple", "white"]);
const isName = (w: string) => NAMES.has(w.toLowerCase());
const texts = (line: string, language: string) => findColors(line, language, isName).map((c) => c.text);
describe("findColors", () => {
it("finds every format in style sheets", () => {
expect(texts(" background-color: #1b766c;", "css")).toEqual(["#1b766c"]);
expect(texts(" border: 1px solid #FFF8;", "scss")).toEqual(["#FFF8"]);
expect(texts(" color: rgba(0, 0, 0, .5); fill: hsl(210deg 40% 50% / 0.3);", "css")).toEqual([
"rgba(0, 0, 0, .5)",
"hsl(210deg 40% 50% / 0.3)",
]);
expect(texts(" color: red; outline: 2px solid RebeccaPurple;", "less")).toEqual(["red", "RebeccaPurple"]);
expect(findColors("a { color: #abc }", "css", isName)[0]).toMatchObject({ from: 11, to: 15, format: "hex" });
});
it("skips names that are no property value, keywords and non-colors", () => {
expect(texts(".red, #main { white-space: nowrap; color: inherit }", "css")).toEqual([]);
expect(texts("@media screen { }", "css")).toEqual([]);
expect(texts(" color: $white; background: var(--off-white) off-white;", "scss")).toEqual([]);
expect(texts(" color: #12345;", "css")).toEqual([]);
});
it("takes only quoted hex values in code, and no names", () => {
expect(texts(`const accent = "#1b766c"; // see #123 and #add`, "typescript")).toEqual(["#1b766c"]);
expect(texts("color = 'rgb(255, 0, 0)' # red", "python")).toEqual(["rgb(255, 0, 0)"]);
expect(texts('<div style="color: #fff">', "html")).toEqual(["#fff"]);
});
it("leaves prose alone", () => {
expect(texts("Fixed in #123, color `#fff`", "markdown")).toEqual([]);
});
});
describe("formatColor", () => {
const match = (text: string, format: ColorMatch["format"]): ColorMatch => ({
from: 0,
to: text.length,
text,
format,
});
it("keeps hex case, length and alpha", () => {
expect(formatColor([255, 0, 0, 1], match("#abc", "hex"))).toBe("#f00");
expect(formatColor([18, 52, 86, 1], match("#ABC", "hex"))).toBe("#123456");
expect(formatColor([18, 52, 86, 1], match("#1B766C", "hex"))).toBe("#123456".toUpperCase());
expect(formatColor([18, 52, 86, 0.5], match("#1b766c80", "hex"))).toBe("#12345680");
expect(formatColor([18, 52, 86, 1], match("red", "name"))).toBe("#123456");
});
it("keeps a function's name and separators", () => {
expect(formatColor([1, 2, 3, 1], match("rgb(0, 0, 0)", "rgb"))).toBe("rgb(1, 2, 3)");
expect(formatColor([1, 2, 3, 0.5], match("rgba(0, 0, 0, .5)", "rgb"))).toBe("rgba(1, 2, 3, 0.5)");
expect(formatColor([1, 2, 3, 1], match("rgb(0 0 0 / 50%)", "rgb"))).toBe("rgb(1 2 3 / 1)");
expect(formatColor([255, 0, 0, 1], match("hsl(0, 0%, 0%)", "hsl"))).toBe("hsl(0, 100%, 50%)");
});
});
describe("conversions", () => {
it("round-trips the color input's hex and reads computed colors", () => {
expect(toHex6([27, 118, 108, 1])).toBe("#1b766c");
expect(fromHex6("#1b766c", 0.5)).toEqual([27, 118, 108, 0.5]);
expect(parseComputed("rgb(27, 118, 108)")).toEqual([27, 118, 108, 1]);
expect(parseComputed("rgba(0, 0, 0, 0.25)")).toEqual([0, 0, 0, 0.25]);
expect(parseComputed("color(display-p3 1 0 0)")).toBeNull();
});
});
+137
Переглянути файл
@@ -0,0 +1,137 @@
/**
* Color literals of a line for the gutter's color preview: `#rgb` / `#rrggbb` (with alpha),
* `rgb()` / `rgba()` / `hsl()` / `hsla()`, and CSS named colors in style sheets. Pure; the
* names are checked by the caller (the browser knows them).
*/
export type ColorFormat = "hex" | "rgb" | "hsl" | "name";
export interface ColorMatch {
/** UTF-16 offsets in the line. */
from: number;
to: number;
text: string;
format: ColorFormat;
}
/** Red, green, blue 0–255 and alpha 0–1. */
export type Rgba = [number, number, number, number];
/** Style sheet languages: named colors and unquoted hex values are colors there. */
const STYLE_SHEETS = new Set(["css", "scss", "sass", "less", "stylus", "postcss"]);
/** Markup that embeds style sheets (`<style>`, `style="…"`): unquoted hex values too. */
const MARKUP = new Set(["html", "vue", "svelte", "astro", "xml", "xhtml"]);
/** Prose: `#123` is an issue, `#fab` a heading or a tag. */
const PROSE = new Set(["markdown", "plaintext", "text", "restructuredtext", "asciidoc", "git-commit"]);
const HEX = String.raw`#(?:[0-9a-fA-F]{8}|[0-9a-fA-F]{6}|[0-9a-fA-F]{3,4})(?![\w-])`;
const NUMBER = String.raw`[-+]?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?`;
const FUNCTION = String.raw`\b(?:rgba?|hsla?)\(\s*${NUMBER}(?:deg|%)?(?:\s*[,\s]\s*${NUMBER}%?){2}(?:\s*[,/]\s*${NUMBER}%?)?\s*\)`;
// No lookbehind (WebKit before 16.4 can't parse it): a name's preceding character is checked in code.
const COLOR_RE = new RegExp(`${FUNCTION}|${HEX}|[a-zA-Z]{3,20}(?![\\w(-])`, "g");
/** Before a name, these make it part of a selector, variable or longer word (`.red`, `$white`, `off-white`). */
const NAME_PREFIX = /[\w.#$@-]/;
/** Global keywords and words that are valid colors but say nothing about one. */
const NOT_COLORS = new Set(["inherit", "initial", "unset", "revert", "currentcolor", "transparent"]);
/**
* The colors on `line` of a document in `language`. Outside style sheets and markup, only quoted hex
* values (`"#1b766c"`) and color functions count: `#add` may be a comment, `#123` an issue.
*/
export function findColors(line: string, language: string, isColorName: (word: string) => boolean): ColorMatch[] {
if (PROSE.has(language)) return [];
const sheet = STYLE_SHEETS.has(language);
const looseHex = sheet || MARKUP.has(language);
const out: ColorMatch[] = [];
for (const m of line.matchAll(COLOR_RE)) {
const text = m[0];
const from = m.index;
const format: ColorFormat = text.startsWith("#")
? "hex"
: text.includes("(")
? /^r/i.test(text)
? "rgb"
: "hsl"
: "name";
if (format === "name") {
// A property value (`color: red`), not a property, selector or at-rule.
if (
!sheet ||
(from > 0 && NAME_PREFIX.test(line[from - 1]!)) ||
NOT_COLORS.has(text.toLowerCase()) ||
!/:\s*(?:\S+\s+)*$/.test(line.slice(0, from))
)
continue;
if (!isColorName(text)) continue;
} else if (format === "hex" && !looseHex && !/["'`]$/.test(line.slice(0, from))) continue;
out.push({ from, to: from + text.length, text, format });
}
return out;
}
const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));
const hex2 = (v: number) =>
Math.round(clamp(v, 0, 255))
.toString(16)
.padStart(2, "0");
const round = (v: number, digits = 2) => String(Number(v.toFixed(digits)));
/** `#rrggbb` of `rgba`, as `<input type=color>` takes it. */
export function toHex6([r, g, b]: Rgba): string {
return `#${hex2(r)}${hex2(g)}${hex2(b)}`;
}
/** `#rrggbb` → its components with `alpha`. */
export function fromHex6(hex: string, alpha: number): Rgba | null {
const m = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(hex);
return m ? [Number.parseInt(m[1]!, 16), Number.parseInt(m[2]!, 16), Number.parseInt(m[3]!, 16), alpha] : null;
}
/** Components of the browser's computed color (`rgb(1, 2, 3)` / `rgba(1, 2, 3, 0.5)`), null for other spaces. */
export function parseComputed(color: string): Rgba | null {
const m = /^rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)(?:\s*[,/]\s*([\d.]+%?))?\s*\)$/.exec(color.trim());
if (!m) return null;
const a = m[4] === undefined ? 1 : m[4].endsWith("%") ? Number.parseFloat(m[4]) / 100 : Number(m[4]);
return [Number(m[1]), Number(m[2]), Number(m[3]), a];
}
function toHsl([r, g, b]: Rgba): [number, number, number] {
const [R, G, B] = [r / 255, g / 255, b / 255];
const max = Math.max(R, G, B);
const min = Math.min(R, G, B);
const l = (max + min) / 2;
const d = max - min;
if (d === 0) return [0, 0, l * 100];
const s = d / (1 - Math.abs(2 * l - 1));
const h = max === R ? ((G - B) / d) % 6 : max === G ? (B - R) / d + 2 : (R - G) / d + 4;
return [(h * 60 + 360) % 360, s * 100, l * 100];
}
/**
* `rgba` written in the original's format: hex keeps its case and whether it had alpha, a function
* keeps its name and separators; a named color becomes hex.
*/
export function formatColor(rgba: Rgba, original: ColorMatch): string {
const alpha = rgba[3];
const hasAlpha = alpha < 1;
if (original.format === "hex" || original.format === "name") {
const short = original.text.length === 4 || original.text.length === 5;
const hadAlpha = original.format === "hex" && (original.text.length === 5 || original.text.length === 9);
let hex = toHex6(rgba) + (hadAlpha || hasAlpha ? hex2(alpha * 255) : "");
// `#abc` stays short when the new color has a short form.
if (short && /^#(?:([0-9a-f])\1)+$/.test(hex)) hex = `#${hex.slice(1).replace(/(.)\1/g, "$1")}`;
return /[A-F]/.test(original.text) ? hex.toUpperCase() : hex;
}
const name = /^\w+/.exec(original.text)![0];
const commas = original.text.includes(",");
// The original's fourth component is its alpha.
const withAlpha = hasAlpha || (original.text.match(new RegExp(NUMBER, "g"))?.length ?? 0) > 3;
const parts =
original.format === "rgb"
? rgba.slice(0, 3).map((v) => String(Math.round(clamp(v, 0, 255))))
: toHsl(rgba).map((v, i) => (i === 0 ? round(v, 0) : `${round(v, 1)}%`));
const a = round(alpha);
if (commas) return `${name}(${parts.join(", ")}${withAlpha ? `, ${a}` : ""})`;
return `${name}(${parts.join(" ")}${withAlpha ? ` / ${a}` : ""})`;
}
+130
Переглянути файл
@@ -0,0 +1,130 @@
/**
* Color preview gutter: a swatch on each line with a color literal (the first one), as IDEA's
* color gutter icons. Clicking it in an editable file opens the system color picker; the picked
* color replaces the literal in its own format (alpha kept, the picker has none).
*/
import type { Extension } from "@codemirror/state";
import { GutterMarker, gutter, type EditorView } from "@codemirror/view";
import type { EditorDocContext } from "@/editor/api";
import { findColors, formatColor, fromHex6, parseComputed, toHex6, type ColorMatch, type Rgba } from "./colors";
import styles from "./ColorPreview.module.css";
/** Longer lines (minified style sheets) are not scanned. */
const MAX_LINE = 2000;
const names = new Map<string, boolean>();
function isColorName(word: string): boolean {
let known = names.get(word);
if (known === undefined) {
known = typeof CSS !== "undefined" && CSS.supports("color", word);
names.set(word, known);
}
return known;
}
let probe: HTMLElement | null = null;
/** The literal's components, as the browser parses it. */
function rgbaOf(text: string): Rgba | null {
if (!probe?.isConnected) {
probe = document.createElement("span");
probe.hidden = true;
document.body.append(probe);
}
probe.style.color = "";
probe.style.color = text;
return probe.style.color ? parseComputed(getComputedStyle(probe).color) : null;
}
class Swatch extends GutterMarker {
constructor(
readonly color: ColorMatch,
readonly editable: boolean,
) {
super();
}
override eq(other: GutterMarker): boolean {
return (
other instanceof Swatch &&
other.color.text === this.color.text &&
other.color.from === this.color.from &&
other.editable === this.editable
);
}
override toDOM() {
const el = document.createElement("span");
el.className = this.editable ? `${styles.swatch} ${styles.editable}` : `${styles.swatch}`;
el.title = this.color.text;
const fill = document.createElement("span");
fill.style.background = this.color.text;
el.append(fill);
return el;
}
}
function lineColor(view: EditorView, pos: number, language: string): ColorMatch | null {
const line = view.state.doc.lineAt(pos);
if (line.length > MAX_LINE) return null;
return findColors(line.text, language, isColorName)[0] ?? null;
}
let picker: HTMLInputElement | null = null;
/** Opens the system color picker for `color` at `from`; each pick replaces the literal. */
function pickColor(view: EditorView, from: number, color: ColorMatch, at: { x: number; y: number }) {
const rgba = rgbaOf(color.text);
if (!rgba) return;
picker?.remove();
const input = document.createElement("input");
picker = input;
input.type = "color";
input.className = `${styles.picker}`;
input.style.left = `${at.x}px`;
input.style.top = `${at.y}px`;
input.value = toHex6(rgba);
document.body.append(input);
let current = color.text;
const apply = () => {
const next = fromHex6(input.value, rgba[3]);
// The literal changed meanwhile: leave it alone.
if (!next || view.state.sliceDoc(from, from + current.length) !== current) return;
const text = formatColor(next, color);
if (text === current) return;
view.dispatch({ changes: { from, to: from + current.length, insert: text }, userEvent: "input.color" });
current = text;
};
input.addEventListener("input", apply);
input.addEventListener("change", () => {
apply();
input.remove();
});
try {
input.showPicker();
} catch {
input.click();
}
}
export function colorPreviewGutter(ctx: EditorDocContext): Extension {
return gutter({
class: `${styles.gutter} cm-openidea-gutter-colors`,
lineMarker: (view, block) => {
const color = lineColor(view, block.from, ctx.language);
return color ? new Swatch(color, !view.state.readOnly) : null;
},
lineMarkerChange: (update) => update.docChanged || update.startState.readOnly !== update.state.readOnly,
domEventHandlers: {
mousedown: (view, block, event) => {
const e = event as MouseEvent;
const swatch = e.target instanceof Element ? e.target.closest(`.${styles.swatch}`) : null;
if (e.button !== 0 || !swatch || view.state.readOnly) return false;
const line = view.state.doc.lineAt(block.from);
const color = lineColor(view, block.from, ctx.language);
if (!color) return false;
e.preventDefault();
const rect = swatch.getBoundingClientRect();
pickColor(view, line.from + color.from, color, { x: rect.left, y: rect.bottom + 2 });
return true;
},
},
});
}
+7
Переглянути файл
@@ -0,0 +1,7 @@
/** Color swatches in the editor gutter for color literals (Settings › Editor › General › Gutter Icons). */
import { registerEditorContribution } from "@/editor/api";
import { colorPreviewGutter } from "./gutter";
export function activate(): () => void {
return registerEditorContribution({ id: "colorPreview.gutter", order: 59, extensions: colorPreviewGutter });
}
+12 -1
Переглянути файл
@@ -54,7 +54,7 @@ const { isJavaDebuggable, javaAttachConfig, javaLaunchConfig } = await import(".
const app: RunConfig = {
id: "application:a.Main",
name: "Main",
kind: "spring-boot",
kind: "application",
command: "java",
args: ["-Xmx1g", "-cp", "${classpath}", "a.Main", "--port", "8081 x"],
cwd: "api",
@@ -93,6 +93,17 @@ describe("Java debugging (java-debug through jdtls)", () => {
});
});
it("debugs Spring Boot with coloured console output, as Run does", async () => {
const boot = { ...app, kind: "spring-boot" };
expect(JSON.parse((await javaLaunchConfig(boot, "/p")).extraJson!).vmArgs).toBe(
"-Dspring.output.ansi.enabled=always -Xmx1g",
);
const own = { ...boot, args: ["-Dspring.output.ansi.enabled=never", ...app.args] };
expect(JSON.parse((await javaLaunchConfig(own, "/p")).extraJson!).vmArgs).toBe(
"-Dspring.output.ansi.enabled=never -Xmx1g",
);
});
it("passes the configuration's VM options to java-debug's vmArgs, before the main class", async () => {
const args = [
"-Ddemo.flag=on",
+3 -2
Переглянути файл
@@ -7,6 +7,7 @@
import { executeAction } from "@/platform/actions";
import { call, commands, IpcError, nextRequestId, type LaunchConfig, type RunConfig } from "@/platform/ipc";
import {
consoleVmArgs,
formatCompileErrors,
isJvmApplication,
joinJavaArgs,
@@ -117,7 +118,7 @@ export async function javaLaunchConfig(
classPaths,
modulePaths: info.modulePaths,
javaExec: resolved.command,
vmArguments: parsed.vmArgs,
vmArguments: [...consoleVmArgs(rc), ...parsed.vmArgs],
programArgs: parsed.programArgs,
}),
};
@@ -139,7 +140,7 @@ export async function javaLaunchConfig(
classPaths,
modulePaths: info.modulePaths,
javaExec: resolved.command === "java" ? undefined : resolved.command,
vmArgs: joinJavaArgs(parsed.vmArgs),
vmArgs: joinJavaArgs([...consoleVmArgs(rc), ...parsed.vmArgs]),
args: joinJavaArgs(parsed.programArgs),
// java-debug spawns the JVM itself: it must shorten a classpath too long for the OS the same way Run does.
shortenCommandLine: info.shortenCommandLine ?? "none",
+36 -4
Переглянути файл
@@ -4,6 +4,7 @@ import { useVirtualizer } from "@tanstack/react-virtual";
import { copySelectionOnKeyDown } from "@/ui/selectableText";
import { EmptyState, IconButton, showContextMenu, T, type MenuItem } from "@/ui";
import { tx } from "@/platform/i18n";
import { useWorkflowSettings } from "@/platform/workflowSettings";
import { spanStyle } from "@/ui/ansi";
import ansi from "@/ui/ansi.module.css";
import { appendConsole, clearConsole, evaluate, isLive, useDebug, type DebugSession } from "../state";
@@ -23,7 +24,14 @@ export function DebugServiceConsole({ sessionId }: { sessionId: number }) {
export function DebugConsole({ session, interactive = true }: { session: DebugSession; interactive?: boolean }) {
const lines = useDebug((s) => s.console[session.id]);
const scroller = useRef<HTMLDivElement>(null);
// Scroll to End: follows new output; scrolling up turns it off, back to the end turns it on.
const [follow, setFollow] = useState(true);
const stick = useRef(true);
stick.current = follow;
// Settings › Console › Use soft wraps is the default; the toggle overrides it for this console.
const defaultWrap = useWorkflowSettings((s) => s.console.softWrap);
const [wrapOverride, setWrapOverride] = useState<boolean | null>(null);
const softWrap = wrapOverride ?? defaultWrap;
const programmatic = useRef(false);
const [input, setInput] = useState("");
const history = useRef<string[]>(readHistory("console"));
@@ -39,14 +47,21 @@ export function DebugConsole({ session, interactive = true }: { session: DebugSe
getItemKey: (i) => lines?.[i]?.id ?? i,
});
// Wrapping changes every row's height; the end is pinned again below.
useLayoutEffect(() => virtualizer.measure?.(), [softWrap, virtualizer]);
useLayoutEffect(() => {
const el = scroller.current;
if (!el || !stick.current || !lines?.length) return;
programmatic.current = true;
virtualizer.scrollToIndex(lines.length - 1, { align: "end" });
el.scrollTop = el.scrollHeight;
requestAnimationFrame(() => (programmatic.current = false));
}, [lines, virtualizer]);
// Rows measured after this frame grow the content: pin the end once more.
requestAnimationFrame(() => {
if (stick.current) el.scrollTop = el.scrollHeight;
requestAnimationFrame(() => (programmatic.current = false));
});
}, [lines, virtualizer, follow, softWrap]);
const submit = async () => {
const e = input.trim();
@@ -101,11 +116,12 @@ export function DebugConsole({ session, interactive = true }: { session: DebugSe
<div className={styles.console}>
<div
ref={scroller}
className={clsx(styles.consoleOutput, ansi.palette)}
className={clsx(styles.consoleOutput, ansi.palette, !softWrap && styles.noWrap)}
onScroll={(e) => {
if (programmatic.current) return;
const el = e.currentTarget;
stick.current = el.scrollHeight - el.scrollTop - el.clientHeight < 24;
const atEnd = el.scrollHeight - el.scrollTop - el.clientHeight < 24;
if (atEnd !== stick.current) setFollow(atEnd);
}}
onContextMenu={(e) => {
e.preventDefault();
@@ -170,6 +186,22 @@ export function DebugConsole({ session, interactive = true }: { session: DebugSe
{completion.popup}
</>
)}
<IconButton
icon="arrow-down"
title="Scroll to End"
size="small"
iconSize={12}
pressed={follow}
onClick={() => setFollow((v) => !v)}
/>
<IconButton
icon="soft-wrap"
title="Soft-Wrap"
size="small"
iconSize={12}
pressed={softWrap}
onClick={() => setWrapOverride(!softWrap)}
/>
<IconButton
icon="trash"
title="Clear Console"
+6
Переглянути файл
@@ -251,6 +251,12 @@
cursor: text;
}
/* Soft-Wrap off: long lines scroll horizontally. */
.noWrap {
white-space: pre;
word-break: normal;
}
.out {
position: absolute;
top: 0;
+2
Переглянути файл
@@ -24,6 +24,7 @@ import { activate as runAnything } from "./run-anything";
import { activate as macros } from "./macros";
import { activate as debuggerFeature } from "./debugger";
import { activate as coverage } from "./coverage";
import { activate as colorPreview } from "./color-preview";
import { activate as profiler } from "./profiler";
import { activate as buildTools } from "./build-tools";
import { activate as build } from "./build";
@@ -70,6 +71,7 @@ const features: Array<[string, Activate]> = [
["macros", macros],
["debugger", debuggerFeature],
["coverage", coverage],
["color-preview", colorPreview],
["profiler", profiler],
["build-tools", buildTools],
["build", build],
+17 -2
Переглянути файл
@@ -6,14 +6,22 @@ import type { SortKey } from "./model";
/** The title's "Project ▾" pane switcher (IDEA: Project / Project Files / Open Files / …). */
export function useProjectTitleMenu(): { label: string; items: MenuItem[] } {
const mode = useProjectTree((s) => s.mode);
const unity = useProjectTree((s) => s.unity);
return {
label: VIEW_MODES.find(([id]) => id === mode)?.[1] ?? "Project",
items: VIEW_MODES.map(([id, label]) => ({ id, label, checked: id === mode, run: () => setViewMode(id) })),
items: VIEW_MODES.filter(([id]) => id !== "unity" || unity).map(([id, label]) => ({
id,
label,
checked: id === mode,
run: () => setViewMode(id),
})),
};
}
/** The on / off view options. */
export type ToggleOption = { [K in keyof ViewOptions]: ViewOptions[K] extends boolean ? K : never }[keyof ViewOptions];
export type ToggleOption = {
[K in keyof ViewOptions]-?: ViewOptions[K] extends boolean ? K : never;
}[keyof ViewOptions];
export const OPTION_LABELS: Array<[ToggleOption, string]> = [
["showHidden", "Show Hidden Files"],
@@ -54,8 +62,15 @@ export const SORT_LABELS: Array<[SortKey, string]> = [
/** View options in the header's "⋮" menu (IDEA: Project › Options › Appearance / Behavior). */
export function useProjectHeaderMenu(): MenuItem[] {
const options = useProjectTree((s) => s.options);
const unity = useProjectTree((s) => s.mode === "unity");
return [
{ kind: "header", label: "Appearance" },
...(unity
? [
option("showUnityMeta", "Show Meta Files", options),
option("showUnityGenerated", "Show Generated Files", options),
]
: []),
...OPTION_LABELS.slice(0, 5).map(([key, label]) => option(key, label, options)),
{ kind: "separator" },
...SORT_LABELS.map(([sortBy, label]): MenuItem => ({
+9
Переглянути файл
@@ -6,6 +6,15 @@
flex-direction: column;
}
.unityNotice {
flex: none;
padding: 8px 12px;
color: var(--fg-muted);
font-size: 12px;
line-height: 1.5;
border-bottom: 1px solid var(--border);
}
.content {
flex: 1;
min-width: 0;
+41
Переглянути файл
@@ -95,6 +95,47 @@ function setup() {
}
describe("ProjectView", () => {
it("toggles Unity metadata and generated files independently in the rendered tree", async () => {
fs = new MemoryFs(
{
"/w/acme/Assets/Player.cs": "code",
"/w/acme/Assets/Player.cs.meta": "metadata",
"/w/acme/Library/cache": "cache",
"/w/acme/Game.sln": "",
},
ROOT,
);
setProjectFsForTests(fs, ROOT);
initProjectTree(ROOT, "Game", null, { editorVersion: "6000.0.62f1", projects: [], solutions: [] });
const { rows } = setup();
act(() => useProjectTree.setState({ expanded: new Set([ROOT, `${ROOT}/Assets`]) }));
await waitFor(() => expect(rows()).toContain("Player.cs"));
expect(rows()).not.toContain("Player.cs.meta");
expect(rows()).not.toContain("Library");
act(() => setViewOption("showUnityMeta", true));
await waitFor(() => expect(rows()).toContain("Player.cs.meta"));
expect(rows()).not.toContain("Game.sln");
act(() => setViewOption("showUnityGenerated", true));
await waitFor(() => expect(rows()).toContain("Game.sln"));
expect(rows()).toContain("Library");
act(() => setViewOption("showUnityMeta", false));
expect(rows()).not.toContain("Player.cs.meta");
expect(rows()).toContain("Library");
});
it("shows Unity version and generation guidance, then updates when project files arrive", async () => {
initProjectTree(ROOT, "Game", null, { editorVersion: "6000.0.62f1", projects: [], solutions: [] });
const { row } = setup();
expect(screen.getByText(/C# project files are missing/)).toHaveAttribute("role", "status");
await waitFor(() => expect(row("Game")).toHaveTextContent("Unity 6000.0.62f1"));
act(() => {
useProjectTree.setState({
unity: { editorVersion: "6000.0.62f1", projects: ["Assembly-CSharp.csproj"], solutions: ["Game.sln"] },
});
});
expect(screen.queryByText(/C# project files are missing/)).not.toBeInTheDocument();
});
it("shows the root with its path and loads children lazily", async () => {
const { rows, row, tree } = setup();
await waitFor(() => expect(rows()).toEqual(["acme/w/acme", "build", "src", "README.md"]));
+7 -1
Переглянути файл
@@ -426,6 +426,7 @@ export function ProjectView() {
const info = useMemo(() => visibleInfo(model, expanded), [model, expanded]);
const mode = useProjectTree((s) => s.mode);
const unity = useProjectTree((s) => s.unity);
const outlines = useProjectTree((s) => s.outlines);
const showMembers = options.showMembers;
@@ -755,7 +756,7 @@ export function ProjectView() {
editing={editing}
cut={cutPaths.has(node.path)}
dropTarget={dropTarget === node.key}
detail={node.root && !node.icon ? tildify(node.path, home) : (node.detail ?? null)}
detail={node.detail ?? (node.root && !node.icon ? tildify(node.path, home) : null)}
onEditDone={focusTree}
onClick={onRowClick}
onDoubleClick={onRowDoubleClick}
@@ -781,6 +782,11 @@ export function ProjectView() {
onFocus={(e) => setContext("projectViewFocus", (e.target as HTMLElement).getAttribute("role") === "tree")}
onBlur={() => setContext("projectViewFocus", false)}
>
{mode === "unity" && unity && !unity.projects.length && (
<div className={styles.unityNotice} role="status">
{tx`C# project files are missing. In Unity, select an external script editor in Preferences > External Tools, then regenerate project files.`}
</div>
)}
{!model.roots.length && (
<div className={styles.empty}>
{txTemplate(`Nothing to show in ${VIEW_MODES.find(([id]) => id === mode)?.[1] ?? "this view"}`)}
+13 -2
Переглянути файл
@@ -1,6 +1,7 @@
/** Actions of the project view (Find Action, keymap, other features via `executeAction`). */
import { activeEditor } from "@/editor/api";
import { getAction, registerActions, type Action } from "@/platform/actions";
import { getContext } from "@/platform/context";
import { dirname, useProject } from "@/platform/project";
import { showContextMenu, type MenuItem } from "@/ui";
import { maybeEditorService, menuGroupItems, toolWindowService } from "@/workbench/contributions";
@@ -74,6 +75,16 @@ function nodesFrom(arg: unknown): ProjectNode[] {
});
}
/**
* The target of an action invoked without one: the Project view's selection while it has focus,
* otherwise the active editor's file (a shortcut pressed in the editor acts on the edited file).
*/
function contextTarget(arg: unknown): unknown {
if (arg !== undefined && arg !== null) return arg;
if (getContext().projectViewFocus) return arg;
return maybeEditorService()?.activePath() ?? arg;
}
function folderFrom(arg: unknown): string | null {
if (typeof arg === "string") return useProjectTree.getState().listings.has(arg) ? arg : parentOf(arg);
return folderOf(leadNode());
@@ -379,7 +390,7 @@ export function registerProjectActions(): () => void {
icon: "external-link",
when: OPEN,
keywords: ["show in explorer", "open in finder"],
run: ({ arg }) => revealInFinder(nodesFrom(arg)),
run: ({ arg }) => revealInFinder(nodesFrom(contextTarget(arg))),
},
{
id: "project.openInTerminal",
@@ -388,7 +399,7 @@ export function registerProjectActions(): () => void {
icon: "terminal",
when: OPEN,
run: ({ arg }) => {
const dir = folderFrom(arg);
const dir = folderFrom(contextTarget(arg));
if (dir) delegate("terminal.openAt", dir);
},
},
+46 -3
Переглянути файл
@@ -1,6 +1,6 @@
/** Project view: the "project" tool window, its file operations and actions. */
import { onEditorEvent, openEditorPaths } from "@/editor/api";
import { onIdeEvent } from "@/platform/ipc";
import { commands, isTauri, onIdeEvent } from "@/platform/ipc";
import { useBuildModel } from "@/platform/buildModel";
import { validateProjectStructure, type RootFolder } from "@/platform/languageSettings";
import { useProject } from "@/platform/project";
@@ -33,22 +33,60 @@ import {
reloadLoadedDirs,
setChangedFiles,
setOpenFiles,
setViewMode,
useProjectTree,
} from "./store";
export function activate(): () => void {
loadHomeDir();
let unityTimer: ReturnType<typeof setTimeout> | undefined;
let unityGeneration = 0;
const sync = () => {
const p = useProject.getState().project;
const s = useProjectTree.getState();
if ((p?.root ?? null) !== s.root || p?.workspace?.projects !== (s.members ?? undefined))
initProjectTree(p?.root ?? null, p?.name ?? "", p?.workspace?.projects ?? null);
else if (p && p.name !== s.name) useProjectTree.setState({ name: p.name });
initProjectTree(p?.root ?? null, p?.name ?? "", p?.workspace?.projects ?? null, p?.unity ?? null);
else if (p) {
useProjectTree.setState({ name: p.name, unity: p.unity ?? null });
if (p.unity && !s.unity && s.mode === "project") setViewMode("unity");
if (!p.unity && s.mode === "unity") setViewMode("project");
}
};
sync();
const unsubProject = useProject.subscribe((s, prev) => {
if (s.project?.root !== prev.project?.root) {
unityGeneration++;
clearTimeout(unityTimer);
}
if (s.project !== prev.project) sync();
});
// Unity regenerates these files while the IDE stays open. Refresh only metadata,
// retaining the current settings and ignoring replies from a previous project.
const unsubUnity = onIdeEvent("fsChanged", (e) => {
const project = useProject.getState().project;
if (!project || !isTauri()) return;
const relevant = [...e.created, ...e.modified, ...e.removed].some((p) => {
if (!p.startsWith(project.root + "/")) return false;
const rel = p.slice(project.root.length + 1);
return (
/^(Assets|Packages|ProjectSettings)(\/ProjectVersion\.txt)?$/.test(rel) ||
/^[^/]+\.(csproj|sln|slnx)$/i.test(rel)
);
});
if (!relevant) return;
const generation = ++unityGeneration;
clearTimeout(unityTimer);
unityTimer = setTimeout(async () => {
try {
const fresh = await commands.projectCurrent();
const current = useProject.getState().project;
if (generation !== unityGeneration || current?.root !== project.root || fresh?.root !== project.root) return;
useProject.setState({ project: { ...current, unity: fresh.unity } });
} catch {
// A project may have closed while the metadata request was in flight.
}
}, 150);
});
// Excluded folders / exclude globs change which entries are `ignored`.
const unsubExcludes = useProject.subscribe((s, prev) => {
const ex = (x: typeof s.settings) =>
@@ -132,6 +170,11 @@ export function activate(): () => void {
});
const disposers = [
() => {
clearTimeout(unityTimer);
unityGeneration++;
unsubUnity();
},
() => clearTimeout(openTimer),
unsubEditor,
unsubDecorations,
+22
Переглянути файл
@@ -8,6 +8,10 @@ import { isIgnoredName } from "@/platform/ignoredNames";
import { ancestorsWithin, isInside, isSameOrInside, nameOf, parentOf, relativeTo } from "./paths";
export interface TreeOptions {
/** Applied only by the Unity pane, never persisted as a user preference. */
unityRoot?: string;
showUnityMeta: boolean;
showUnityGenerated: boolean;
/** Show ignored names (`files.ignoredNames`: `.git`, `.DS_Store`, …). Dotfiles are always shown. */
showHidden: boolean;
/** Show entries matched by .gitignore / exclude settings (dimmed). */
@@ -22,6 +26,8 @@ export interface TreeOptions {
export type SortKey = "name" | "type" | "modified";
export const DEFAULT_TREE_OPTIONS: TreeOptions = {
showUnityMeta: false,
showUnityGenerated: false,
showHidden: false,
showExcluded: true,
compact: true,
@@ -69,7 +75,23 @@ export interface TreeModel {
export type Listings = ReadonlyMap<string, readonly FileEntry[]>;
export function unityPathVisible(path: string, opts: TreeOptions): boolean {
if (opts.unityRoot && path.startsWith(opts.unityRoot + "/")) {
const relative = path.slice(opts.unityRoot.length + 1);
// The full Project / Project Files panes retain access to generated files.
if (!opts.showUnityGenerated) {
if (/^(Library|Temp|Obj|obj|Logs|Build|Builds|UserSettings|\.vs|\.idea|\.vscode)(\/|$)/.test(relative))
return false;
if (!relative.includes("/") && /\.(csproj|sln|slnx|suo|user|pidb|booproj|unityproj)$/i.test(relative))
return false;
}
if (!opts.showUnityMeta && /\.meta$/i.test(relative)) return false;
}
return true;
}
export function isVisible(entry: FileEntry, opts: TreeOptions): boolean {
if (!unityPathVisible(entry.path, opts)) return false;
// Ignored names are also excluded on the backend; only "Show Hidden" brings them back.
if (isIgnoredName(entry.name)) return opts.showHidden;
if (!opts.showExcluded && entry.ignored) return false;
+45
Переглянути файл
@@ -8,6 +8,7 @@ import {
refreshOsClipboard,
selectionAfterDelete,
transfer,
topLevelPaths,
} from "./operations";
import { IpcError } from "@/platform/ipc";
import { closeFileRefactorDialog, pendingFileRefactorDialog } from "./FileRefactorDialogs";
@@ -50,6 +51,50 @@ describe("selectionAfterDelete", () => {
});
});
describe("Unity asset selections", () => {
beforeEach(async () => {
fs = new MemoryFs(
{
"/p/Assets/Player.cs": "code",
"/p/Assets/Player.cs.meta": "metadata",
"/p/Assets/Player copy.cs.meta": "orphan",
},
"/p",
);
setProjectFsForTests(fs, "/p");
initProjectTree("/p", "Game", null, { editorVersion: "6000.0.1f1", projects: [], solutions: [] });
provideNotificationService({ notify });
notify.mockClear();
await loadDir("/p/Assets");
});
afterEach(() => {
setProjectFsForTests(null);
initProjectTree(null);
});
it("treats an asset and its selected metadata as one operation", () => {
expect(topLevelPaths([node("/p/Assets/Player.cs"), node("/p/Assets/Player.cs.meta")])).toEqual([
"/p/Assets/Player.cs",
]);
expect(
topLevelPaths([
node("/p/Assets/Group", true),
node("/p/Assets/Group.meta"),
node("/p/Assets/Group/Inner.cs.meta"),
]),
).toEqual(["/p/Assets/Group"]);
expect(topLevelPaths([node("/p/Assets/Player.cs.meta")])).toEqual(["/p/Assets/Player.cs.meta"]);
});
it("skips orphan metadata names when choosing a duplicate asset name", async () => {
const copy = vi.spyOn(fs, "copy");
await transfer(["/p/Assets/Player.cs", "/p/Assets/Player.cs.meta"], "/p/Assets", "copy");
expect(copy).toHaveBeenCalledTimes(1);
expect(copy).toHaveBeenCalledWith("/p/Assets/Player.cs", "/p/Assets/Player copy 2.cs");
});
});
// Local OS paths and remote project paths may be identical strings.
describe("OS file imports", () => {
beforeEach(async () => {
+19 -2
Переглянути файл
@@ -84,10 +84,24 @@ export function leadNode(): ProjectNode | null {
/** Selected paths without entries nested in other selected folders. */
export function topLevelPaths(nodes: ProjectNode[] = selectedNodes()): string[] {
const paths = nodes.map((n) => n.path);
const paths = assetPaths(nodes.map((n) => n.path));
return paths.filter((p) => !paths.some((q) => q !== p && isInside(p, q)));
}
/** A visible sidecar is already included by the backend asset operation. */
function assetPaths(paths: string[]): string[] {
const { root, unity } = get();
if (!root || !unity) return paths;
return paths.filter(
(p) => !(isInside(p, joinPath(root, "Assets")) && p.endsWith(".meta") && paths.includes(p.slice(0, -5))),
);
}
function isUnityAssetFolder(path: string): boolean {
const { root, unity } = get();
return !!(root && unity && isSameOrInside(path, joinPath(root, "Assets")));
}
/** Folder that receives new / pasted items: the selected folder or the selected file's parent. */
export function targetFolder(node: ProjectNode | null = leadNode()): string | null {
if (!node && get().lead?.startsWith(MEMBER_PREFIX)) return null;
@@ -667,13 +681,15 @@ export async function transfer(
name?: string,
source: "project" | "local" = "project",
): Promise<string | boolean> {
paths = assetPaths(paths);
if (mode === "move") return moveInto(paths, target);
const { root } = get();
if (!root) return false;
const fs = projectFs(root);
await loadDir(target);
const taken = new Set(siblingsOf(target).map((n) => (caseInsensitive ? n.toLowerCase() : n)));
const isTaken = (n: string) => taken.has(caseInsensitive ? n.toLowerCase() : n);
const hasName = (n: string) => taken.has(caseInsensitive ? n.toLowerCase() : n);
const isTaken = (n: string) => hasName(n) || (isUnityAssetFolder(target) && hasName(`${n}.meta`));
const touched = new Set<string>([target]);
const errors: string[] = [];
let first: string | null = null;
@@ -726,6 +742,7 @@ export async function transfer(
* the options last used in the Move dialog). Refuses to overwrite.
*/
async function moveInto(paths: string[], target: string): Promise<boolean> {
paths = assetPaths(paths);
await loadDir(target);
const taken = new Set(siblingsOf(target).map((n) => (caseInsensitive ? n.toLowerCase() : n)));
const errors: string[] = [];
+18
Переглянути файл
@@ -14,6 +14,24 @@ afterEach(() => {
useContextMenuStore.setState({ menu: null });
});
describe("Open in Terminal", () => {
it("opens the edited file's folder unless the Project view has focus", async () => {
const opened: unknown[] = [];
disposers.push(
registerProjectActions(),
registerActions([{ id: "terminal.openAt", title: "Open Terminal At", run: ({ arg }) => void opened.push(arg) }]),
() => setContext("projectOpen", false),
() => setContext("projectViewFocus", false),
);
setContext("projectOpen", true);
provideEditorService({ activePath: () => "/p/src/a.ts" } as unknown as EditorService);
await executeAction("project.openInTerminal");
expect(opened).toEqual(["/p/src"]);
await executeAction("project.openInTerminal", "/p/docs/readme.md");
expect(opened.at(-1)).toBe("/p/docs");
});
});
describe("Select In (⌥F1)", () => {
it("lists the project view, contributed targets, Finder and the terminal", () => {
disposers.push(
+41 -12
Переглянути файл
@@ -4,6 +4,7 @@
* Kept outside React so actions (keyboard, Find Action, context menu) share it.
*/
import { create } from "zustand";
import type { UnityProjectInfo } from "@/bindings";
import { call } from "@/platform/ipc";
import { commands, type FileEntry, type OutlineItem } from "@/bindings";
import { withDocument } from "@/editor/lsp/files";
@@ -25,6 +26,7 @@ import {
mergeListing,
planRefresh,
visibleEntries,
unityPathVisible,
type Placeholder,
type ProjectNode,
type TreeModel,
@@ -67,9 +69,10 @@ function storedOptions(): ViewOptions {
}
/** IDEA's Project view panes ("Project ▾" in the tool window header). */
export type ViewMode = "project" | "projectFiles" | "openFiles" | "changedFiles" | "scratches";
export type ViewMode = "unity" | "project" | "projectFiles" | "openFiles" | "changedFiles" | "scratches";
export const VIEW_MODES: ReadonlyArray<[ViewMode, string]> = [
["unity", "Unity"],
["project", "Project"],
["projectFiles", "Project Files"],
["openFiles", "Open Files"],
@@ -94,6 +97,7 @@ export interface Clipboard {
}
interface ProjectTreeState {
unity: UnityProjectInfo | null;
root: string | null;
name: string;
members: readonly string[] | null;
@@ -140,6 +144,7 @@ function writeJson(key: string, value: unknown) {
}
export const useProjectTree = create<ProjectTreeState>(() => ({
unity: null,
root: null,
name: "",
members: null,
@@ -170,6 +175,7 @@ const set = (patch: Partial<ProjectTreeState>) => useProjectTree.setState(patch)
// Derived model (memoised on its inputs so React and actions share one instance)
let memo: {
unity: UnityProjectInfo | null;
root: string | null;
name: string;
members: readonly string[] | null;
@@ -187,10 +193,15 @@ const EMPTY_MODEL: TreeModel = { roots: [], children: new Map(), byKey: new Map(
const filesOf = (s: ProjectTreeState) =>
s.mode === "openFiles" ? s.openFiles : s.mode === "changedFiles" ? s.changedFiles : null;
function treeOptions(s: ProjectTreeState): TreeOptions {
return s.mode === "unity" && s.unity && s.root ? { ...s.options, compact: false, unityRoot: s.root } : s.options;
}
export function selectModel(s: ProjectTreeState): TreeModel {
const files = filesOf(s);
if (
memo &&
memo.unity === s.unity &&
memo.root === s.root &&
memo.name === s.name &&
memo.members === s.members &&
@@ -205,6 +216,7 @@ export function selectModel(s: ProjectTreeState): TreeModel {
const placeholder: Placeholder | null =
s.editing?.kind === "new" ? { parent: s.editing.parent, kind: s.editing.nodeKind } : null;
const extras = useProjectViewRoots.getState().roots;
const options = treeOptions(s);
const contributed = projectViewRoots(extras);
const memberRoots = s.members?.map((path) => ({
path,
@@ -214,8 +226,8 @@ export function selectModel(s: ProjectTreeState): TreeModel {
}));
const project = () =>
memberRoots
? withExtraRoots(EMPTY_MODEL, memberRoots, s.listings, s.options, placeholder)
: buildModel({ path: s.root!, name: s.name }, s.listings, s.options, placeholder);
? withExtraRoots(EMPTY_MODEL, memberRoots, s.listings, options, placeholder)
: buildModel({ path: s.root!, name: s.name }, s.listings, options, placeholder);
let model = EMPTY_MODEL;
if (s.root) {
if (s.mode === "projectFiles") model = project();
@@ -233,13 +245,16 @@ export function selectModel(s: ProjectTreeState): TreeModel {
files,
s.options.foldersFirst,
);
else model = withExtraRoots(project(), contributed, s.listings, s.options, placeholder);
else model = withExtraRoots(project(), contributed, s.listings, options, placeholder);
if (s.unity && s.mode === "unity" && model.roots[0])
model.roots[0].detail = s.unity.editorVersion ? `Unity ${s.unity.editorVersion}` : "Unity";
const libraries = extraFolders(contributed).flatMap((r) =>
r.readOnly && r.path !== undefined && isSameOrInside(r.path, s.root!) ? [r.path] : [],
);
model = withReadOnlyFolders(model, libraries);
}
memo = {
unity: s.unity,
root: s.root,
name: s.name,
members: s.members,
@@ -264,19 +279,29 @@ const inflight = new Map<string, Promise<void>>();
let persistTimer: ReturnType<typeof setTimeout> | undefined;
/** Resets the view for a newly opened project, restoring its expansion state. */
export function initProjectTree(root: string | null, name = "", members: readonly string[] | null = null) {
export function initProjectTree(
root: string | null,
name = "",
members: readonly string[] | null = null,
unity: UnityProjectInfo | null = null,
) {
generation++;
inflight.clear();
outlineInflight.clear();
clearTimeout(persistTimer);
modeExpanded.clear();
autoExpanded.clear();
const previousMode = get().mode;
const mode =
unity && previousMode === "project" ? "unity" : !unity && previousMode === "unity" ? "project" : previousMode;
set({
unity,
mode,
root,
name,
members,
listings: new Map(),
expanded: initialExpanded(root, get().mode, members),
expanded: initialExpanded(root, mode, members),
selected: new Set(),
lead: null,
editing: null,
@@ -304,23 +329,25 @@ function initialExpanded(root: string | null, mode: ViewMode, members = get().me
// The tree as the user left it, like IDEA: a collapsed project root stays collapsed, and
// nodes outside it (content roots, contributed roots) stay open.
// Keys of nodes that no longer exist are inert. Only a first open expands the roots.
const persisted = mode === "project" ? readJson<string[]>(expandedKey(root)) : null;
const persisted = mode === "project" || mode === "unity" ? readJson<string[]>(expandedKey(root)) : null;
if (persisted) return new Set(persisted);
return new Set(members ?? [root]);
}
function persistExpanded() {
if (get().mode !== "project") return;
if (get().mode !== "project" && get().mode !== "unity") return;
clearTimeout(persistTimer);
persistTimer = setTimeout(() => {
const { root, expanded, mode } = get();
if (root && mode === "project") writeJson(expandedKey(root), [...expanded].slice(0, MAX_PERSISTED));
if (root && (mode === "project" || mode === "unity"))
writeJson(expandedKey(root), [...expanded].slice(0, MAX_PERSISTED));
}, 300);
}
/** Switches the pane ("Project ▾"), remembered across sessions. */
export function setViewMode(mode: ViewMode) {
const s = get();
if (mode === "unity" && !s.unity) return;
if (s.mode === mode) return;
modeExpanded.set(s.mode, s.expanded);
autoExpanded.clear();
@@ -409,8 +436,8 @@ export function loadDir(path: string, force = false): Promise<void> {
putListing(path, entries);
// Compact Middle Packages needs to look one level down a single-folder chain.
const s = get();
if (s.options.compact) {
const visible = visibleEntries(entries, s.options);
if (treeOptions(s).compact) {
const visible = visibleEntries(entries, treeOptions(s));
const only = visible.length === 1 ? visible[0]! : null;
if (only && isDirEntry(only) && !only.ignored && !s.listings.has(only.path)) void loadDir(only.path);
}
@@ -590,6 +617,8 @@ export function modeShows(path: string): boolean {
const { mode, root } = get();
if (!root) return false;
switch (mode) {
case "unity":
return unityPathVisible(path, treeOptions(get()));
case "project":
return true;
case "projectFiles":
@@ -655,7 +684,7 @@ export async function expandAll(from?: string, limit = 400) {
await loadDir(path);
if (gen !== generation) return;
const s = get();
for (const e of visibleEntries(s.listings.get(path) ?? [], s.options))
for (const e of visibleEntries(s.listings.get(path) ?? [], treeOptions(s)))
if (isDirEntry(e) && !e.ignored && e.kind !== "symlink") queue.push(keyLike(dir, e.path));
}
setExpanded(toExpand);
+78
Переглянути файл
@@ -0,0 +1,78 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import type { FileEntry } from "@/bindings";
import { DEFAULT_TREE_OPTIONS, visibleEntries } from "./model";
import { currentModel, initProjectTree, modeShows, setViewMode, useProjectTree } from "./store";
const unity = { editorVersion: "2022.3.62f1", solutions: [], projects: [] };
const entry = (path: string, dir = false): FileEntry => ({
path,
name: path.slice(path.lastIndexOf("/") + 1),
kind: dir ? "dir" : "file",
size: 1,
mtimeMs: null,
ignored: false,
excluded: false,
hidden: false,
});
const files = [
entry("/game/Assets", true),
entry("/game/Packages", true),
entry("/game/ProjectSettings", true),
entry("/game/Library", true),
entry("/game/Temp", true),
entry("/game/Assets.meta"),
entry("/game/Game.sln"),
entry("/game/Assembly-CSharp.csproj"),
entry("/game/README.md"),
];
beforeEach(() => {
localStorage.clear();
initProjectTree(null);
setViewMode("project");
});
afterEach(() => initProjectTree(null));
describe("Unity project view", () => {
it("opens in Unity mode and keeps the full project view available", () => {
initProjectTree("/game", "Game", null, unity);
useProjectTree.setState({ listings: new Map([["/game", files]]) });
expect(useProjectTree.getState().mode).toBe("unity");
const model = currentModel();
expect(model.roots[0]?.detail).toBe("Unity 2022.3.62f1");
expect(model.children.get("/game")?.map((n) => n.label)).toEqual([
"Assets",
"Packages",
"ProjectSettings",
"README.md",
]);
setViewMode("projectFiles");
expect(currentModel().children.get("/game")).toHaveLength(files.length);
});
it("does not leak Unity mode or metadata into the next ordinary project", () => {
initProjectTree("/game", "Game", null, unity);
initProjectTree("/app", "App");
expect(useProjectTree.getState()).toMatchObject({ mode: "project", unity: null });
setViewMode("unity");
expect(useProjectTree.getState().mode).toBe("project");
});
it("hides only root caches, keeps asset folders with matching names, and can reveal metadata", () => {
const options = { ...DEFAULT_TREE_OPTIONS, unityRoot: "/game" };
const entries = [entry("/game/Assets/Library", true), entry("/game/Assets/P.cs.meta"), entry("/other/P.cs.meta")];
expect(visibleEntries(entries, options).map((e) => e.path)).toEqual(["/game/Assets/Library", "/other/P.cs.meta"]);
expect(visibleEntries(entries, { ...options, showHidden: true })).toHaveLength(2);
expect(visibleEntries(entries, { ...options, showUnityMeta: true })).toHaveLength(3);
expect(visibleEntries(files, { ...options, showUnityGenerated: true }).map((e) => e.name)).toContain("Library");
expect(visibleEntries(files, { ...options, showUnityGenerated: true }).map((e) => e.name)).toContain("Game.sln");
expect(visibleEntries(files, DEFAULT_TREE_OPTIONS)).toHaveLength(files.length);
});
it("keeps navigation to unloaded scripts in Unity mode", () => {
initProjectTree("/game", "Game", null, unity);
expect(modeShows("/game/Assets/Scripts/Player.cs")).toBe(true);
expect(modeShows("/game/Library/Cached.cs")).toBe(false);
expect(modeShows("/game/Assets/Player.cs.meta")).toBe(false);
});
});
+75
Переглянути файл
@@ -0,0 +1,75 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import type { ProjectInfo } from "@/bindings";
import { emitLocalIdeEvent } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { activate } from "./index";
import { useProjectTree } from "./store";
const current = vi.hoisted(() => vi.fn());
vi.mock("@/platform/ipc", async (original) => {
const real = await original<typeof import("@/platform/ipc")>();
return {
...real,
isTauri: () => true,
commands: {
...real.commands,
projectCurrent: current,
projectRoots: async () => ({ status: "ok", data: { roots: [], detected: [] } }),
},
};
});
const project = (root = "/game"): ProjectInfo => ({
root,
name: "Game",
trusted: false,
isGit: false,
settings: {} as ProjectInfo["settings"],
unity: { editorVersion: "2022.3.62f1", projects: [], solutions: [] },
});
let dispose: () => void;
beforeEach(() => {
vi.useFakeTimers();
current.mockReset();
useProject.setState({ project: project() });
dispose = activate();
});
afterEach(() => {
dispose();
useProject.setState({ project: null });
vi.useRealTimers();
});
const changed = () =>
emitLocalIdeEvent({ type: "fsChanged", created: ["/game/Assembly-CSharp.csproj"], modified: [], removed: [] });
it("refreshes generated C# files through backend events without overwriting a project rename", async () => {
let resolve!: (value: unknown) => void;
current.mockReturnValue(
new Promise((r) => {
resolve = r;
}),
);
changed();
await vi.advanceTimersByTimeAsync(160);
expect(current).toHaveBeenCalledTimes(1);
useProject.setState({ project: { ...project(), name: "Renamed" } });
resolve({ ...project(), unity: { ...project().unity, projects: ["Assembly-CSharp.csproj"] } });
await vi.advanceTimersByTimeAsync(0);
expect(useProjectTree.getState().unity?.projects).toEqual(["Assembly-CSharp.csproj"]);
expect(useProject.getState().project?.name).toBe("Renamed");
});
it("discards a late reply after switching to another project", async () => {
let resolve!: (value: unknown) => void;
current.mockReturnValue(
new Promise((r) => {
resolve = r;
}),
);
changed();
await vi.advanceTimersByTimeAsync(160);
useProject.setState({ project: { ...project("/app"), unity: undefined } });
resolve(project());
await vi.advanceTimersByTimeAsync(0);
expect(useProjectTree.getState()).toMatchObject({ root: "/app", unity: null, mode: "project" });
});
+5 -5
Переглянути файл
@@ -2,7 +2,7 @@
import { type KeyboardEvent, type RefObject } from "react";
import clsx from "clsx";
import { IconButton, SearchField } from "@/ui";
import { hasPrimaryModifier } from "@/platform/keymap";
import { formatBinding, hasPrimaryModifier } from "@/platform/keymap";
import { tx } from "@/platform/i18n";
import type { FindOptions } from "./find";
import styles from "./Run.module.css";
@@ -97,7 +97,7 @@ export function ConsoleFindBar({
id: "case",
icon: "case",
title: "Match Case",
shortcut: "⌥C",
shortcut: formatBinding("Alt+C"),
pressed: options.caseSensitive,
onToggle: () => toggle("caseSensitive"),
},
@@ -105,7 +105,7 @@ export function ConsoleFindBar({
id: "word",
icon: "word",
title: "Words",
shortcut: "⌥W",
shortcut: formatBinding("Alt+W"),
pressed: options.wholeWord,
onToggle: () => toggle("wholeWord"),
},
@@ -113,7 +113,7 @@ export function ConsoleFindBar({
id: "regex",
icon: "regex",
title: "Regex",
shortcut: "⌥X",
shortcut: formatBinding("Alt+X"),
pressed: options.regex,
onToggle: () => toggle("regex"),
},
@@ -125,7 +125,7 @@ export function ConsoleFindBar({
<IconButton
icon="arrow-up"
title="Previous Occurrence"
shortcut="⇧↵"
shortcut={formatBinding("Shift+Enter")}
size="small"
disabled={count === 0}
onClick={onPrevious}
+4 -1
Переглянути файл
@@ -29,9 +29,11 @@ import {
scriptLanguage,
type ContextInput,
type Produced,
hasRelativeImports,
} from "./producers";
import { runWithExecutor } from "./executors";
import { goModulePath, loadGoModules } from "./goModules";
import { isPythonPackage, loadPythonPackages } from "./pythonPackages";
import { remoteDebugBlocked } from "./remote";
import { toolEnv } from "./runtimes";
import { adoptTemporary, loadConfigs, modifyTemporary, startRun, useRun } from "./store";
@@ -88,7 +90,8 @@ export async function produceResolved(input: ContextInput, dir = false): Promise
const configs = useRun.getState().configs;
if (dir || /\.go$/.test(input.path)) await loadGoModules(input.root, configs);
if (dir) return produceDirectory({ ...input, goModule: goModulePath });
const fresh = { ...input, configs, goModule: goModulePath };
if (/\.py$/.test(input.path) && hasRelativeImports(input.content)) await loadPythonPackages(input.path);
const fresh = { ...input, configs, goModule: goModulePath, pythonPackage: isPythonPackage };
const named = produceContext(fresh, OPTIMISTIC);
if (!named) return null;
// Project configurations (tests, cargo, gradle…) need no runtime lookup.
+22 -1
Переглянути файл
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vitest";
import type { GradleModel, RunConfig } from "@/platform/ipc";
import { applicationConfig } from "./application";
import { DELEGATED_DEBUG, delegatedGradleConfig, wrapperGradleVersion } from "./gradleRun";
import { DELEGATED_DEBUG, delegatedGradleConfig, withTestEvents, wrapperGradleVersion } from "./gradleRun";
import { jdwpLaunch } from "./javaDebug";
import { isJvmApplication } from "@/platform/javaLaunch";
@@ -122,3 +122,24 @@ describe("Build and run using: Gradle", () => {
expect(jdwpLaunch(debug)!.args.filter((a) => a === DELEGATED_DEBUG)).toHaveLength(1);
});
});
describe("Gradle test runs", () => {
const script = "/tmp/openidea-gradle-tests.gradle";
it("add the init script that reports each test", () => {
expect(
withTestEvents({ kind: "gradle", command: "./gradlew", args: ["test", "--tests", "*OrderTest"] }, script).args,
).toEqual(["--init-script", script, "test", "--tests", "*OrderTest"]);
expect(withTestEvents({ kind: "shell", command: "C:\\w\\gradlew.bat", args: ["test"] }, script).args).toEqual([
"--init-script",
script,
"test",
]);
});
it("leave other runs and an added script alone", () => {
const maven = { kind: "maven", command: "./mvnw", args: ["test"] };
expect(withTestEvents(maven, script)).toBe(maven);
const twice = withTestEvents({ kind: "gradle", command: "gradle", args: ["test"] }, script);
expect(withTestEvents(twice, script)).toBe(twice);
});
});
+46 -15
Переглянути файл
@@ -6,6 +6,7 @@
* the forked JVM (`-Dopenidea.run.debug`), not to the Gradle daemon.
*/
import RUN_SCRIPT from "./gradleRun.gradle?raw";
import TESTS_SCRIPT from "./gradleTests.gradle?raw";
import { useBuildModel } from "@/platform/buildModel";
import { call, commands, isTauri, type GradleModel, type RunConfig } from "@/platform/ipc";
import { findJavaModule, isJvmApplication, parseJavaArgs } from "@/platform/javaLaunch";
@@ -84,20 +85,47 @@ export function delegatedGradleConfig(config: RunConfig, module: string, ctx: De
};
}
/** Writes the init script where Gradle can read it; it never changes, so once per session. */
let scriptPath: Promise<string> | null = null;
function writeScript(): Promise<string> {
scriptPath ??= (async () => {
const { tempDir, join } = await import("@tauri-apps/api/path");
const path = await join(await tempDir(), "openidea-gradle-run.gradle");
await call(commands.fsDelete(path)).catch(() => {});
await call(commands.fsCreateFileBytes(path, Array.from(new TextEncoder().encode(RUN_SCRIPT))));
return path;
})().catch((e) => {
scriptPath = null;
throw e;
});
return scriptPath;
/** Writes an init script where Gradle can read it; it never changes, so once per session. */
const scriptPaths = new Map<string, Promise<string>>();
function writeScript(name: string, text: string): Promise<string> {
let written = scriptPaths.get(name);
if (!written) {
written = (async () => {
const { tempDir, join } = await import("@tauri-apps/api/path");
const path = await join(await tempDir(), name);
await call(commands.fsDelete(path)).catch(() => {});
await call(commands.fsCreateFileBytes(path, Array.from(new TextEncoder().encode(text))));
return path;
})().catch((e) => {
scriptPaths.delete(name);
throw e;
});
scriptPaths.set(name, written);
}
return written;
}
const isGradleCommand = (config: Pick<RunConfig, "kind" | "command">) =>
config.kind === "gradle" || /(^|[/\\])gradlew?(\.bat)?$/.test(config.command);
/** `config` with the init script (`script`) that reports each test as it runs, for a Gradle test run. */
export function withTestEvents<T extends Pick<RunConfig, "kind" | "command" | "args">>(config: T, script: string): T {
if (!isGradleCommand(config) || config.args.includes(script)) return config;
return { ...config, args: ["--init-script", script, ...config.args] };
}
/**
* A Gradle test run reporting each test as it runs (`gradleTests.gradle`): Gradle prints only
* failures, and its XML reports are complete only once a test task ends.
*/
export async function gradleTestLaunch<T extends RunConfig>(config: T): Promise<T> {
if (!isTauri() || !config.isTest || !isGradleCommand(config)) return config;
try {
return withTestEvents(config, await writeScript("openidea-gradle-tests.gradle", TESTS_SCRIPT));
} catch (e) {
console.warn("Gradle test init script not written", e);
return config;
}
}
/**
@@ -121,7 +149,10 @@ export async function gradleDelegation(config: RunConfig): Promise<RunConfig | n
configurationCache: false,
};
if (!delegatedGradleConfig(config, module, ctx)) return null;
const [script, configurationCache] = await Promise.all([writeScript(), supportsConfigurationCache(ctx)]);
const [script, configurationCache] = await Promise.all([
writeScript("openidea-gradle-run.gradle", RUN_SCRIPT),
supportsConfigurationCache(ctx),
]);
return delegatedGradleConfig(config, module, { ...ctx, script, configurationCache });
}
+44
Переглянути файл
@@ -0,0 +1,44 @@
// OpenIDEA: reports each test of Gradle's Test tasks as a TeamCity service message on the
// build's output, for the Run window's test tree: Gradle itself prints only failures (or a
// project's own format), and writes its XML reports when a task ends. Test tasks always run,
// so a rerun never ends UP-TO-DATE without results.
def tc = { String s ->
s == null ? '' : s.replace('|', '||').replace("'", "|'").replace('\n', '|n').replace('\r', '|r')
.replace('[', '|[').replace(']', '|]')
}
allprojects {
tasks.withType(Test).configureEach { Test task ->
task.outputs.upToDateWhen { false }
task.addTestListener(new TestListener() {
void beforeSuite(TestDescriptor suite) {}
void afterSuite(TestDescriptor suite, TestResult result) {}
void beforeTest(TestDescriptor test) {
println "##teamcity[testStarted name='${tc(test.name)}' className='${tc(test.className)}']"
}
void afterTest(TestDescriptor test, TestResult result) {
def id = "name='${tc(test.name)}' className='${tc(test.className)}'"
def type = result.resultType.toString()
if (type == 'FAILURE') {
def error = result.exception
def trace = new StringWriter()
error?.printStackTrace(new PrintWriter(trace))
println "##teamcity[testFailed ${id} message='${tc(error?.toString())}' details='${tc(trace.toString())}']"
} else if (type == 'SKIPPED') {
println "##teamcity[testIgnored ${id}]"
}
println "##teamcity[testFinished ${id} duration='${result.endTime - result.startTime}']"
}
})
task.addTestOutputListener(new TestOutputListener() {
void onOutput(TestDescriptor test, TestOutputEvent output) {
if (test.className == null) return
println "##teamcity[testStdOut name='${tc(test.name)}' className='${tc(test.className)}' out='${tc(output.message)}']"
}
})
}
}
+2
Переглянути файл
@@ -38,6 +38,7 @@ import { EditConfigsOverlay } from "./EditConfigsDialog";
import { openImport } from "./importConfigs";
import { registerGoActions } from "./goActions";
import { invalidateGoModules } from "./goModules";
import { invalidatePythonPackages } from "./pythonPackages";
import { RunWidget } from "./RunWidget";
import { runConfigsRunAnything } from "./runAnything";
import { cleanupRemovedProject, recordRun, runServiceProvider } from "./services";
@@ -574,6 +575,7 @@ export function activate(): () => void {
onIdeEvent("fsChanged", (e) => {
const paths = [...e.created, ...e.modified, ...e.removed];
if (paths.some((p) => /(?:^|\/)go\.(?:mod|work)$/.test(p))) invalidateGoModules();
if (paths.some((p) => p.endsWith("/__init__.py"))) invalidatePythonPackages();
if (paths.some((p) => CONFIG_FILES.test(p))) scheduleReload();
}),
onIdeEvent("runExited", (e) => {
+25
Переглянути файл
@@ -162,6 +162,31 @@ describe("single-file producers (scratches)", () => {
expect(produceContext(scratch("hi.py"), env({}))!.missing!.title).toBe("Cannot run 'hi.py'");
});
it("Python: a module with relative imports runs with -m from above its top package", () => {
const venv = [cfg({ id: "pytest", kind: "pytest", command: ".venv/bin/pytest" })];
const packages = new Set([`${ROOT}/src/tasks`, `${ROOT}/src/tasks/sub`]);
const at = (path: string, content: string) =>
run({ path, root: ROOT, configs: venv, content, pythonPackage: (d) => packages.has(d) });
const relative = "from .models import TaskList\n";
expect(at(`${ROOT}/src/tasks/cli.py`, relative)).toMatchObject({
command: `${ROOT}/.venv/bin/python`,
args: ["-m", "tasks.cli"],
cwd: "src",
});
expect(at(`${ROOT}/src/tasks/sub/__main__.py`, "from ..models import X\n")).toMatchObject({
args: ["-m", "tasks.sub"],
cwd: "src",
});
// A directory without `__init__.py` is still the module's package; a top-level one runs from the root.
expect(at(`${ROOT}/scripts/gen.py`, relative)).toMatchObject({ args: ["-m", "scripts.gen"], cwd: null });
// Without relative imports, the file runs as a script.
expect(at(`${ROOT}/src/tasks/cli.py`, "import argparse\n")).toMatchObject({
command: ".venv/bin/python",
args: ["src/tasks/cli.py"],
cwd: null,
});
});
it("shell scripts: the shell of the #! line, else by extension; extensionless files by #!", () => {
expect(run(scratch("a.sh", "#!/usr/bin/env bash\necho hi"))).toMatchObject({
command: "/bin/bash",
+43
Переглянути файл
@@ -55,6 +55,8 @@ export interface ContextInput {
content?: string;
/** Go: the module path of a module directory (`go.mod`), when known. */
goModule?: (dir: string) => string | null | undefined;
/** Python: whether a directory is a package (`__init__.py`), when known. */
pythonPackage?: (dir: string) => boolean | undefined;
/** 0-based caret line: the element at the caret wins over the file. */
line?: number;
/**
@@ -409,6 +411,31 @@ function fileConfig(
};
}
const PYTHON_RELATIVE_IMPORT = /^\s*from\s+\.+[\w.]*\s+import\b/m;
/** Whether Python source imports relatively (`from .models import X`): it only runs as a module. */
export function hasRelativeImports(content: string | undefined): boolean {
return !!content && PYTHON_RELATIVE_IMPORT.test(content);
}
/**
* A module with relative imports, run as `python -m package.module` from the directory above
* its top package (its own directory is a package for the import, `__init__.py` or not).
*/
function pythonModule(input: ContextInput): { name: string; dir: string } | null {
if (!hasRelativeImports(input.content)) return null;
let top = dirName(input.path);
for (let up = dirName(top); up && up !== top && input.pythonPackage?.(up); up = dirName(up)) top = up;
const dir = dirName(top);
if (!dir || dir === top) return null;
const parts = input.path
.slice(dir === "/" ? 1 : dir.length + 1)
.replace(/\.py$/, "")
.split("/");
if (parts.length > 1 && (parts.at(-1) === "__init__" || parts.at(-1) === "__main__")) parts.pop();
return { name: parts.join("."), dir };
}
/** Python: the interpreter from settings, the detected project interpreter, then `python3` on the PATH. */
function pythonCommand(input: ContextInput, env: ToolEnv, s: FileSite): { command: string; prefix: string[] } | null {
if (env.python) return { command: env.python, prefix: [] };
@@ -655,6 +682,22 @@ export function produceFile(input: ContextInput, env: ToolEnv): Produced | null
case "python": {
const py = pythonCommand(input, env, s);
if (!py) return { name: s.file, scope: "file", missing: missing("python", s.file, ["python3", "python"]) };
const module = pythonModule(input);
if (module) {
// It runs in another directory: a venv-relative interpreter is relative to the project root.
const command =
input.root && py.command.includes("/") && !py.command.startsWith("/")
? `${input.root}/${py.command}`
: py.command;
return {
name: s.file,
scope: "file",
config: {
...fileConfig(s, "python", command, [...py.prefix, "-m", module.name], "debugpy"),
cwd: module.dir === input.root ? null : relTo(module.dir, input.root),
},
};
}
return {
name: s.file,
scope: "file",
Loaded 100 of 191 files, more files were not shown because too many files have changed in this diff. Show more