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

...
Автор SHA1 Повідомлення Дата
l0ng-ai 7dd6a1e779 fix(keymap): make shortcut recording and conflicts easier to read 2026-11-22 21:29:05 +08:00
ntbang0901 aa849b9cf4 fix(vcs): keep each project's git executable with its repositories (#5214)
Settings › Version Control › Git › Path to Git executable can be set per project, but the value lived in one process-wide variable that each trusted window overwrote before running git. Two windows running git at once could start a command of one project with the other's executable, and a relative value then resolved inside the wrong repository.

Each project's repositories now carry its executable on the same per-thread scope that already carries their trust. Work that opens repositories of its own (agent worktrees and snapshots, gh pull requests, plugin repository access, Create Git Repository…) runs with the project's value. The process-wide value is only the global settings' one, used for git without a project (clone, init without a project).

Co-authored-by: ntbang0901 <[email protected]>
2026-11-22 20:56:38 +08:00
l0ng-ai 0cc8f90708 fix(vcs): keep long Git Log filters compact (#5201)
Long Git Log filter values now end in an ellipsis, with the full value available on hover. A tighter width in compact commit panes keeps the active filter and its clear button visible at more window sizes.
2026-11-22 20:47:43 +08:00
LU XIANGRUIтаwildcatDownstairs bc307fdea3 feat(lsp): lint CSS, SCSS and Less with Stylelint (#5208)
CSS, SCSS and Less files get Stylelint diagnostics from the Stylelint language server, installed on demand like the other tools. A project's Stylelint config is picked up as is, a Fix Stylelint Problems action applies the server's fixes, and the built-in CSS diagnostics step aside for rules Stylelint covers.

Closes #5156

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 20:44:18 +08:00
ntbang0901 407f1c5235 feat(debugger): toggle an exception breakpoint from a throw or catch (#5206)
Alt+Enter on a throw statement or a catch parameter offers to create, enable or disable a Java exception breakpoint for that exception type. The type is resolved by the new openidea.java.exceptionType command in the java-usages bundle (1.17.0), and intention providers can now be asynchronous.

Co-authored-by: ntbang0901 <[email protected]>
2026-11-22 20:43:54 +08:00
l0ng-ai ddf9cc3d70 fix(debugger): stabilize the inline variable editor (#5195)
Keep a debugger variable's icon, name and equals sign anchored when Set Value opens. The input fits the tree row, and an error uses a limited share of the value area so the field remains usable in a narrow pane.
2026-11-22 20:43:05 +08:00
l0ng-ai 6e4f536722 fix(search): keep Find in Files footer actions together (#5192)
Keep the shortcut hint beside Open in Find Window and keep Replace All beside the current selection action when the popup wraps. A separator and a smaller keyboard hint give the footer its own visual hierarchy. The popup handles its advertised shortcut when either search field has focus.
2026-11-22 20:42:54 +08:00
l0ng-ai d3be99543d fix(run): anchor console fold controls in the gutter (#5198)
Expanded output has a collapse control beside its row in the Run console gutter. It stays at the left edge while long output scrolls horizontally. A fold at the start of the buffer keeps its control after expansion, and activating a focused fold control leaves process input alone.
2026-11-22 20:34:31 +08:00
l0ng-ai f0cc99a4c7 fix(vcs): give commit subjects room beside compact refs (#5191)
Give Git Log commit subjects room beside long reference labels. Compact References View keeps labels within about a third of the available text column, with the full reference on hover. References in the log use the small UI font and the layout works on either side of the subject.
2026-11-22 20:34:26 +08:00
l0ng-ai 8db16dea32 fix(editor): keep same-name tabs distinguishable (#5187)
Same-name editor tabs show the distinguishing directory before the filename. In a narrow split, the directory gives up space first and the filename stays intact when it fits. The Hidden Tabs picker uses the same path label.
2026-11-22 20:34:21 +08:00
l0ng-ai 6a7297519c fix(settings): keep the current page visible in breadcrumbs (#5196)
Keep the current page name visible as the Settings pane narrows. Parent labels shorten first, and the breadcrumb tooltip shows the full path.
2026-11-22 20:33:01 +08:00
l0ng-ai 08362db3ca fix(run): keep the test summary together and clarify its status (#5186)
Keep elapsed time beside the test counts in the Run window at the same text size. The summary keeps its Running label when the first test has started and no results have arrived yet. A thin line below the summary shows the current state alongside the icon and counts.
2026-11-22 20:32:57 +08:00
l0ng-ai b7f3df0472 fix(debugger): keep values readable beside long type labels (#5185)
Keep debugger values readable beside long runtime types. The row reserves space for a value preview based on its length, so short values leave more room for names. A truncated type can still be read on hover, and the full type appears when the pane has room.
2026-11-22 20:32:52 +08:00
l0ng-ai c5824771c1 fix(editor): make workspace refactoring previews easier to scan (#5183)
Separate the filename from its directory in workspace refactoring previews. This gives same-named files distinct locations and frees space for rename targets and occurrence counts. Hovering a file or a rename target shows its full path.
2026-11-22 20:32:47 +08:00
l0ng-ai 40e5f9b7b3 fix(usages): distinguish files with the same name in the popup (#5181)
Add a muted directory caption beside each filename that appears in more than one file in Show Usages. Identical filenames, line numbers and snippets can otherwise make two results indistinguishable until selected. The popup uses the same directory labels as editor tabs, including a longer suffix when directory names repeat at different depths.
2026-11-22 20:32:41 +08:00
l0ng-ai 8bc82d08c6 fix(vcs): give outgoing commit messages a clear subject (#5180)
Give the selected commit's subject a stronger weight and separate it from the body in the Push dialog. The preview uses the editor's font settings for the message and compact text for the revision, author and date, matching the message hierarchy in Git Log.
2026-11-22 20:32:23 +08:00
l0ng-ai b0473f17b5 fix(run): keep the configuration header visible while scrolling (#5175)
Keep the configuration name and project-file checkbox visible above the scrolling options in Run/Debug Configurations. Long forms previously scrolled these controls out of view, so editing the name or changing where a configuration is saved meant returning to the top.
2026-11-22 20:31:59 +08:00
l0ng-ai 21264641ba fix(search): clarify Recent Locations file captions (#5170)
Recent Locations now shows the filename once, with a symbol breadcrumb or its parent directory beside it. Directory captions distinguish entries with the same filename, and hovering over a caption reveals the full project-relative path.
2026-11-22 20:31:00 +08:00
l0ng-ai 3ce4578600 fix(editor): separate quick fixes in the intentions popup (#5167)
Separate quick fixes from other actions in the Intentions popup with a divider. The divider is skipped during keyboard navigation and disappears when filtering leaves a single group. The popup keeps the chosen action selected when more results arrive from the language server.
2026-11-22 20:30:36 +08:00
112 змінених файлів з 2867 додано та 645 видалено

No files matched your search

+35 -16
Переглянути файл
@@ -63,6 +63,9 @@ pub type NewTaskApprovalsHook = Arc<dyn Fn() -> ide_core::settings::NewTaskAppro
/// attached projects the user trusts.
pub type WorkspaceRootsHook = Arc<dyn Fn() -> Vec<PathBuf> + Send + Sync>;
/// Returns the project's git executable (`None`: the default), which the tasks' git runs.
pub type GitExecutableHook = Arc<dyn Fn() -> Option<PathBuf> + Send + Sync>;
/// Entry changes are batched for this long before they are sent.
const FLUSH_DELAY: Duration = Duration::from_millis(40);
/// Updates that arrive this late after `session/load` returns are still replayed history.
@@ -185,6 +188,7 @@ struct Shared {
security: RwLock<Option<SecurityHook>>,
new_task_approvals: RwLock<Option<NewTaskApprovalsHook>>,
workspace_roots: RwLock<Option<WorkspaceRootsHook>>,
git_executable: RwLock<Option<GitExecutableHook>>,
known: Arc<Mutex<HashMap<String, Known>>>,
providers: RwLock<Vec<provider::ProviderSpec>>,
/// Last probe of each provider.
@@ -599,6 +603,7 @@ impl AgentManager {
security: RwLock::new(None),
new_task_approvals: RwLock::new(None),
workspace_roots: RwLock::new(None),
git_executable: RwLock::new(None),
known,
providers,
probes: Mutex::new(HashMap::new()),
@@ -671,6 +676,11 @@ impl AgentManager {
*self.shared.workspace_roots.write() = Some(hook);
}
/// Sets the callback that reads the project's git executable.
pub fn set_git_executable_hook(&self, hook: GitExecutableHook) {
*self.shared.git_executable.write() = Some(hook);
}
/// The agents (custom ones re-read), whether each is installed, and what they offered last time.
pub fn providers(&self) -> Vec<AgentProvider> {
let specs = provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets());
@@ -983,14 +993,15 @@ impl AgentManager {
}
let dir = self.shared.paths.worktrees_dir.clone();
let (t, b) = (title.clone(), req.base.clone());
let c = blocking(move || worktree::create(&root, &dir, &t, b.as_deref())).await?;
let c = vcs(&self.shared, move || worktree::create(&root, &dir, &t, b.as_deref())).await?;
(c.path, Some(c.branch), Some(c.base), Some(c.base_commit), BTreeMap::new())
}
Isolation::Local => {
let r = root.clone();
let (head, before) =
blocking(move || Ok((worktree::head_of(&r).ok(), worktree::snapshot(&r).unwrap_or_default())))
.await?;
let (head, before) = vcs(&self.shared, move || {
Ok((worktree::head_of(&r).ok(), worktree::snapshot(&r).unwrap_or_default()))
})
.await?;
let (base, commit) = head.unzip();
(root, None, base, commit, before)
}
@@ -1024,7 +1035,7 @@ impl AgentManager {
} else {
let name = format!("{id}.before");
let (dir, at, files) = (self.shared.paths.store_dir.join(&name), cwd.clone(), before.clone());
match blocking(move || worktree::save_before(&at, &files, &dir)).await {
match vcs(&self.shared, move || worktree::save_before(&at, &files, &dir)).await {
Ok(saved) => saved.then_some(name),
Err(e) => {
tracing::warn!("saving the changed files of agent task {id}: {e}");
@@ -1826,7 +1837,7 @@ impl AgentManager {
let _ = tokio::time::timeout(EXIT_WAIT, peer.exited()).await;
}
let worktrees = self.shared.paths.worktrees_dir.clone();
blocking(move || worktree::remove(&root, &worktrees, &cwd)).await?;
vcs(&self.shared, move || worktree::remove(&root, &worktrees, &cwd)).await?;
}
Ok(())
}
@@ -1836,7 +1847,7 @@ impl AgentManager {
let task = self.task(id)?;
let at = task.base();
let (before, touched) = task.attribution();
blocking(move || Ok(worktree::made_by_task(at.changes(&before)?, touched.as_deref()))).await
vcs(&self.shared, move || Ok(worktree::made_by_task(at.changes(&before)?, touched.as_deref()))).await
}
/// The task's uncommitted changes and, for a worktree task, the commits made since it
@@ -1845,7 +1856,7 @@ impl AgentManager {
let task = self.task(id)?;
let at = task.base();
let (before, touched) = task.attribution();
blocking(move || {
vcs(&self.shared, move || {
let mut grouped = at.grouped_changes(&before)?;
grouped.uncommitted = worktree::made_by_task(grouped.uncommitted, touched.as_deref());
Ok(grouped)
@@ -1858,7 +1869,7 @@ impl AgentManager {
pub async fn turn_changes(&self, id: &str) -> IdeResult<Vec<AgentChange>> {
let (cwd, turn, dir) = self.task(id)?.last_turn();
let Some(turn) = turn else { return Ok(Vec::new()) };
blocking(move || {
vcs(&self.shared, move || {
let changed = match &turn.changed {
Some(changed) => changed.clone(),
None => worktree::changed_in_turn(&cwd, &turn)?.1,
@@ -1875,10 +1886,10 @@ impl AgentManager {
if view == AgentChangesView::LastTurn {
let (cwd, turn, dir) = task.last_turn();
let Some(turn) = turn else { return Ok(None) };
return blocking(move || worktree::turn_text(&cwd, &path, &turn, &dir)).await;
return vcs(&self.shared, move || worktree::turn_text(&cwd, &path, &turn, &dir)).await;
}
let at = task.base();
blocking(move || {
vcs(&self.shared, move || {
let rev = match view {
AgentChangesView::Group => worktree::head_commit(at.cwd())?,
_ => at.rev()?,
@@ -1912,7 +1923,7 @@ impl AgentManager {
let s = task.state.lock();
(s.before.clone(), s.saved.as_ref().map(|name| self.shared.paths.store_dir.join(name)), s.touched.clone())
};
let (restamped, restored) = blocking(move || {
let (restamped, restored) = vcs(&self.shared, move || {
let (changes, rev) = match view {
AgentChangesView::Group => (at.grouped_changes(&before)?.uncommitted, worktree::head_commit(at.cwd())?),
AgentChangesView::SinceStart | AgentChangesView::LastTurn => (at.changes(&before)?, at.rev()?),
@@ -1968,7 +1979,7 @@ impl AgentManager {
let s = task.state.lock();
(s.before.clone(), s.saved.as_ref().map(|name| self.shared.paths.store_dir.join(name)))
};
let restamped = blocking(move || {
let restamped = vcs(&self.shared, move || {
let changed = match &turn.changed {
Some(changed) => changed.clone(),
None => worktree::changed_in_turn(&cwd, &turn)?.1,
@@ -2025,7 +2036,7 @@ impl AgentManager {
let Some(base) = base else {
return Err(IdeError::invalid("the task has no base revision to accept from"));
};
blocking(move || {
vcs(&self.shared, move || {
let wanted: Vec<AgentChange> = worktree::without_untouched(worktree::changes(&cwd, &base)?, &before)
.into_iter()
.filter(|c| rel_paths.as_ref().is_none_or(|p| p.contains(&c.rel_path)))
@@ -2280,7 +2291,7 @@ impl Task {
/// Records the checkout as a turn starts: what the turn's changes are compared with.
async fn checkout_before_turn(&self) {
let (cwd, previous, dir) = self.last_turn();
let turn = match blocking(move || worktree::start_turn(&cwd, &dir, previous.as_deref())).await {
let turn = match vcs(&self.shared, move || worktree::start_turn(&cwd, &dir, previous.as_deref())).await {
Ok(turn) => Some(Arc::new(turn)),
Err(e) => {
tracing::warn!("recording the checkout as a turn of agent task {} starts: {e}", self.id);
@@ -2297,7 +2308,9 @@ impl Task {
let (cwd, turn, _) = self.last_turn();
let Some(turn) = turn else { return };
let start = turn.clone();
let Ok((in_worktree, all)) = blocking(move || worktree::changed_in_turn(&cwd, &start)).await else { return };
let Ok((in_worktree, all)) = vcs(&self.shared, move || worktree::changed_in_turn(&cwd, &start)).await else {
return;
};
{
let mut s = self.state.lock();
if !in_worktree.is_empty()
@@ -4251,6 +4264,12 @@ async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + '
tokio::task::spawn_blocking(f).await.map_err(|e| IdeError::internal(e.to_string()))?
}
/// [`blocking`] for work that runs git: the repositories it opens run the project's git.
async fn vcs<T: Send + 'static>(shared: &Shared, f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
let git = shared.git_executable.read().as_ref().and_then(|hook| hook());
blocking(move || ide_vcs::with_git_executable(git.as_deref(), f)).await
}
#[cfg(test)]
mod replay;
#[cfg(test)]
+11 -2
Переглянути файл
@@ -25,7 +25,7 @@ pub mod rpc;
pub mod shell_env;
pub mod trust;
pub use project::{Project, apply_git_executable, history_retention};
pub use project::{Project, history_retention};
use ide_core::{CancellationToken, IdeError, IdeResult, RequestId, SharedSink};
use ide_language::{LanguageRegistry, Syntax};
@@ -34,7 +34,7 @@ use ide_terminal::TerminalManager;
use ide_workspace::SettingsStore;
use parking_lot::{Mutex, RwLock};
use std::collections::HashMap;
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use std::sync::{Arc, OnceLock};
/// Event sink for one window (by label).
@@ -207,6 +207,7 @@ impl Host {
};
host.apply_proxy();
host.apply_added_jdks();
host.apply_git_executable();
// Before any project starts jdtls; the deleting itself can take a while.
let unused =
ide_sdk::jdtls_workspaces::take_unused(&host.local_data_dir, ide_sdk::jdtls_workspaces::UNUSED_FOR);
@@ -598,6 +599,14 @@ impl Host {
let homes = self.global_settings.effective().languages.java.added_jdks;
ide_sdk::java::set_added_jdks(homes.into_iter().map(PathBuf::from));
}
/// Global Settings › Version Control › Git › Path to Git executable, for git started outside
/// a project's repositories (clone, init, agents, gh, plugins). A project's own value stays
/// with its repositories ([`Project::repos`]).
pub fn apply_git_executable(&self) {
let exe = self.global_settings.read_effective(|s| s.vcs.git.executable.trim().to_owned());
ide_vcs::set_default_git_executable((!exe.is_empty()).then(|| Path::new(&exe)));
}
}
#[cfg(test)]
+17
Переглянути файл
@@ -1176,6 +1176,22 @@ pub async fn lsp_prepare_rename(host: &Host, window: &str, doc: DocId, pos: Pos)
host.project(window)?.lsp.prepare_rename(doc, pos).await
}
/// The Throwable class the caret at `pos` names, for the exception breakpoint intention.
#[command(trust = trusted)]
pub async fn lsp_exception_class_at(
host: &Host,
window: &str,
request: RequestId,
doc: DocId,
pos: Pos,
) -> IdeResult<Option<ExceptionClassRef>> {
let project = host.project(window)?;
let cancel = host.begin_request(request);
let result = project.lsp.exception_class_at(doc, pos, cancel).await;
host.end_request(request);
result
}
/// The class at `pos` and the members Pull Members Up / Push Members Down can move.
#[command(trust = trusted)]
pub async fn lsp_hierarchy_members(
@@ -2786,6 +2802,7 @@ ide_command::domain!(
lsp_completion,
lsp_document_highlights,
lsp_document_links,
lsp_exception_class_at,
lsp_execute_code_action,
lsp_execute_command,
lsp_extract_interface,
+3
Переглянути файл
@@ -391,6 +391,9 @@ pub fn set_settings(
if key == "languages" || key == "languages.java" || key.starts_with("languages.java.addedJdks") {
host.apply_added_jdks();
}
if key == "vcs" || key == "vcs.git" || key == "vcs.git.executable" {
host.apply_git_executable();
}
if is_proxy {
host.apply_proxy();
}
+1 -7
Переглянути файл
@@ -1,4 +1,4 @@
use crate::{Host, apply_git_executable};
use crate::Host;
use ide_command::command;
use ide_core::IdeResult;
use ide_vcs::FileStatus;
@@ -9,9 +9,6 @@ pub async fn vcs_status(host: &Host, window: &str) -> IdeResult<Vec<FileStatus>>
let project = host.project(window)?;
host.blocking(move || {
let settings = project.settings.effective();
if project.is_trusted() {
apply_git_executable(&settings);
}
let repos = project.repos();
if repos.is_empty() {
return Err(ide_core::IdeError::unavailable("project is not a git repository"));
@@ -32,9 +29,6 @@ pub async fn vcs_status_paths(host: &Host, window: &str, paths: Vec<std::path::P
let project = host.project(window)?;
host.blocking(move || {
let settings = project.settings.effective();
if project.is_trusted() {
apply_git_executable(&settings);
}
let repos = project.repos();
if repos.is_empty() {
return Err(ide_core::IdeError::unavailable("project is not a git repository"));
+7 -16
Переглянути файл
@@ -10,8 +10,6 @@ use serde::{Deserialize, Serialize};
use specta::Type;
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>>,
@@ -663,7 +661,6 @@ pub async fn vcs_add_to_ignore(
return Err(ide_core::IdeError::invalid("Ignore selection is outside the project"));
}
}
apply_git_executable(&project.settings.effective());
let result = project.with_disk_sync(|| ide_vcs::add_to_ignore(&paths, destination));
// Exclude may live outside a worktree's watched directory. Refresh filters and UI explicitly.
project.watcher.reload_ignore_rules();
@@ -1056,7 +1053,6 @@ pub async fn vcs_clone(
depth: Option<u32>,
on_output: Channel<String>,
) -> IdeResult<()> {
apply_git_executable(&host.global_settings.effective());
let cancel = host.begin_request(request);
let result = tokio::task::spawn_blocking(move || {
ide_vcs::clone(&url, &dest, depth, &cancel, &|line| {
@@ -1069,11 +1065,12 @@ pub async fn vcs_clone(
result
}
/// `git init` in `dir` (File › New Project… "Create Git repository").
/// `git init` in `dir` (VCS › Create Git Repository…): with the git of the window's project when
/// it is trusted, the default one in a window without a project.
#[command(trust = always)]
pub async fn vcs_init(host: &Host, dir: PathBuf) -> IdeResult<()> {
apply_git_executable(&host.global_settings.effective());
blocking(move || ide_vcs::init(&dir)).await
pub async fn vcs_init(host: &Host, window: &str, dir: PathBuf) -> IdeResult<()> {
let git = host.project(window).ok().and_then(|p| p.git_executable());
blocking(move || ide_vcs::with_git_executable(git.as_deref(), || ide_vcs::init(&dir))).await
}
/// Settings › Git › Test: runs `git --version` on `path`, or on the auto-detected
@@ -1349,14 +1346,8 @@ pub async fn vcs_compare_paths(
) -> IdeResult<CompareResult> {
let project = host.project(window)?;
let cancel = host.begin_request(request);
let result = blocking(move || {
let settings = project.settings.effective();
if project.is_trusted() {
apply_git_executable(&settings);
}
project.repos().compare_paths(&paths, &revision, repositories.as_deref(), &cancel)
})
.await;
let result =
blocking(move || project.repos().compare_paths(&paths, &revision, repositories.as_deref(), &cancel)).await;
host.end_request(request);
result
}
+15 -2
Переглянути файл
@@ -136,6 +136,10 @@ pub trait PluginWorkspace: Send + Sync {
fn apply_edits(&self, path: &Path, version: u64, edits: &[TextEdit], background: bool) -> Result<u64, HostError>;
/// Code from the project may run (git hooks and config on fetch).
fn trusted(&self, root: &Path) -> bool;
/// The git executable of the project at `root` (see [`crate::Project::git_executable`]).
fn git_executable(&self, _root: &Path) -> Option<PathBuf> {
None
}
/// Root of the project open in `window`.
fn project_of(&self, window: &str) -> Option<PathBuf>;
/// Windows showing the open project at `root`, the most recently focused first.
@@ -1457,6 +1461,7 @@ pub(super) fn commit_draft(
};
// Both callers have checked that the window's project is trusted.
r.set_execution_allowed(true);
r.set_git_executable(workspace.git_executable(&repo.root.0).as_deref());
let backend = &r as &dyn ide_vcs::Backend;
let pending = backend
.pending_changes(&repo.options, budget, &|path| Ok(workspace.vcs_encoding(path)))
@@ -3724,6 +3729,10 @@ impl PluginWorkspace for HostWorkspace {
HostWorkspace::project_covering(self, root).is_some_and(|p| p.is_trusted())
}
fn git_executable(&self, root: &Path) -> Option<PathBuf> {
HostWorkspace::project_covering(self, root)?.git_executable()
}
fn project_of(&self, window: &str) -> Option<PathBuf> {
self.0.upgrade()?.project(window).ok().map(|p| p.root.clone())
}
@@ -4728,8 +4737,12 @@ impl PluginApi {
/// no upstream. The other reads use [`Self::read_repo`] and never execute.
fn repo(&self, root: &Path) -> Result<Option<ide_vcs::Repo>, HostError> {
let repo = ide_vcs::Repo::discover(root).map_err(failed)?;
if let Some(repo) = &repo {
repo.set_execution_allowed(self.shared.workspace().is_some_and(|w| w.trusted(root)));
if let Some(repo) = &repo
&& let Some(workspace) = self.shared.workspace()
&& workspace.trusted(root)
{
repo.set_execution_allowed(true);
repo.set_git_executable(workspace.git_executable(root).as_deref());
}
Ok(repo)
}
+18 -10
Переглянути файл
@@ -696,6 +696,10 @@ impl Host {
roots
}));
}
{
let weak = Arc::downgrade(&project);
project.agents.set_git_executable_hook(Arc::new(move || weak.upgrade()?.git_executable()));
}
self.insert_project(window, project.clone());
for (key, text, dirty) in &carried {
let _ = project.documents.restore_untitled_buffer(key, text, *dirty);
@@ -1073,11 +1077,24 @@ impl Project {
);
}
/// Settings › Version Control › Git › Path to Git executable, this project's value (its own
/// layer over the global one); `None` when it is empty or the project is not trusted.
/// Every git started for the project runs it: the project's repositories carry it, and work
/// that opens repositories of its own (agent worktrees, gh, plugins) passes it to
/// [`ide_vcs::with_git_executable`].
pub fn git_executable(&self) -> Option<PathBuf> {
let git = self.settings.read_effective(|s| s.vcs.git.executable.trim().to_owned());
(self.is_trusted() && !git.is_empty()).then(|| PathBuf::from(git))
}
/// The project's git repositories.
pub fn repos(&self) -> Repos {
let repos = self.repos.read().clone();
let trusted = self.is_trusted();
let git = self.git_executable();
for repo in repos.all() {
repo.set_execution_allowed(self.is_trusted());
repo.set_execution_allowed(trusted);
repo.set_git_executable(git.as_deref());
}
repos
}
@@ -1161,9 +1178,6 @@ impl Project {
fn run_in<T>(&self, repo: &Repo, f: impl FnOnce(&Repo) -> IdeResult<T>) -> IdeResult<T> {
let settings = self.settings.effective();
if self.is_trusted() {
apply_git_executable(&settings);
}
repo.set_ignored_names(settings.ignored_names());
repo.set_cli_status(settings.vcs.git.cli_status);
f(repo)
@@ -2179,12 +2193,6 @@ fn notify_transfer(sink: &SharedSink, what: &str, path: &Path, result: IdeResult
});
}
/// Settings › Version Control › Git › Path to Git executable (empty = auto-detect).
pub fn apply_git_executable(settings: &ide_core::settings::Settings) {
let exe = settings.vcs.git.executable.trim();
ide_vcs::set_git_executable((!exe.is_empty()).then(|| Path::new(exe)));
}
#[cfg(test)]
mod maven_linkage_tests {
#[test]
-1
Переглянути файл
@@ -352,7 +352,6 @@ async fn restricted_git_views_ignore_project_executables_and_mutations_cannot_ru
project.with_repo(|repo| repo.commit("trusted", false, false)).unwrap();
assert!(root.join("git-executable.marker").exists());
assert!(root.join("git-hook.marker").exists());
ide_vcs::set_git_executable(None);
host.shutdown().await;
}
+125 -7
Переглянути файл
@@ -1,15 +1,14 @@
//! The configured Git binary is process-wide, so it has its own test binary.
//! Which git executable each window's repositories run. Its own test binary: the default
//! executable (global settings) is process-wide.
#![cfg(unix)]
use ide_core::NullSink;
use ide_host::{Host, HostConfig, ops};
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
use std::sync::Arc;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn restricted_status_does_not_select_the_project_git_for_other_windows() {
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let host = Arc::new(Host::new(HostConfig {
fn host(base: &Path) -> Arc<Host> {
Arc::new(Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("data"),
@@ -19,7 +18,126 @@ async fn restricted_status_does_not_select_the_project_git_for_other_windows() {
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
}));
}))
}
/// A repository with `tools/git`: it appends a line to `marker`, waits while `gate` exists,
/// then runs the real git.
fn repo_with_wrapper(root: &Path, marker: &Path, gate: &Path) {
std::fs::create_dir_all(root.join(".openidea")).unwrap();
std::fs::create_dir_all(root.join("tools")).unwrap();
let real = ide_vcs::detected_git_executable().expect("git is installed");
let wrapper = root.join("tools/git");
let script = format!(
"#!/bin/sh\necho run >> '{}'\ni=0\nwhile [ -e '{}' ] && [ $i -lt 400 ]; do sleep 0.05; i=$((i+1)); done\nexec '{}' \"$@\"\n",
marker.display(),
gate.display(),
real.display()
);
std::fs::write(&wrapper, script).unwrap();
std::fs::set_permissions(&wrapper, std::fs::Permissions::from_mode(0o755)).unwrap();
let init = std::process::Command::new(&real).arg("init").arg("-q").arg(root).output().unwrap();
assert!(init.status.success(), "{}", String::from_utf8_lossy(&init.stderr));
}
fn runs(marker: &Path) -> usize {
std::fs::read_to_string(marker).map_or(0, |s| s.lines().count())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_project_git_executable_stays_with_its_project_while_another_window_runs_git() {
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let host = host(&base);
let (a, c) = (base.join("a"), base.join("c"));
let (a_marker, c_marker, gate) = (base.join("a.marker"), base.join("c.marker"), base.join("gate"));
repo_with_wrapper(&a, &a_marker, &gate);
repo_with_wrapper(&c, &c_marker, &gate);
// Relative: resolved against the repository that runs it, so C has a `tools/git` of its own.
std::fs::write(a.join(".openidea/settings.toml"), "[vcs.git]\nexecutable = \"tools/git\"\n").unwrap();
let project_a = host.open_project("a", &a).unwrap();
host.open_project("c", &c).unwrap();
for root in [&a, &c] {
host.set_project_trust(root, true, false).await.unwrap();
}
// Project A runs two git commands in one go, as `compare_paths` does; window C runs its own
// git between them.
std::fs::write(&gate, "").unwrap();
let two_commands = tokio::task::spawn_blocking(move || {
project_a.with_repo(|repo| {
repo.remotes()?;
repo.remotes()
})
});
for _ in 0..200 {
if runs(&a_marker) > 0 {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
}
assert_eq!(runs(&a_marker), 1, "control: project A's first command runs A's git");
ops::vcs::vcs_status(&host, "c").await.unwrap();
ops::vcs::vcs_remotes(&host, "c", None).await.unwrap();
std::fs::remove_file(&gate).unwrap();
two_commands.await.unwrap().unwrap();
assert_eq!(runs(&a_marker), 2, "project A's second command lost A's git once window C ran git");
assert_eq!(runs(&c_marker), 0, "project C has no git setting but ran A's relative tools/git");
host.shutdown().await;
}
/// An agent task opens repositories of its own (the project's, then its worktree): their git is
/// the project's too.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn an_agent_task_worktree_runs_the_project_git() {
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let host = host(&base);
let root = base.join("a");
let marker = base.join("a.marker");
repo_with_wrapper(&root, &marker, &base.join("no-gate"));
let real = ide_vcs::detected_git_executable().unwrap();
let commit = std::process::Command::new(&real)
.arg("-C")
.arg(&root)
.args(["-c", "user.name=t", "-c", "[email protected]", "-c", "commit.gpgsign=false"])
.args(["commit", "-q", "--allow-empty", "-m", "init"])
.output()
.unwrap();
assert!(commit.status.success(), "{}", String::from_utf8_lossy(&commit.stderr));
let wrapper = root.join("tools/git");
std::fs::write(root.join(".openidea/settings.toml"), format!("[vcs.git]\nexecutable = {wrapper:?}\n")).unwrap();
host.open_project("a", &root).unwrap();
host.set_project_trust(&root, true, false).await.unwrap();
let task = ops::agent::agent_create(
&host,
"a",
ide_agent::NewAgentTask {
prompt: ide_agent::AgentPrompt { text: "Say hi".into(), ..Default::default() },
provider: "codex".into(),
isolation: ide_agent::Isolation::Worktree,
idle: true,
..Default::default()
},
)
.await
.unwrap();
assert!(task.cwd.0.join(".git").exists(), "the task has its worktree");
let created = runs(&marker);
assert!(created > 0, "creating the task's worktree ran another git than the project's");
ops::agent::agent_delete(&host, "a", task.id, true).await.unwrap();
assert!(runs(&marker) > created, "removing the task's worktree ran another git than the project's");
host.shutdown().await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn restricted_status_does_not_select_the_project_git_for_other_windows() {
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let host = host(&base);
let root = base.join("malicious");
std::fs::create_dir_all(root.join(".openidea")).unwrap();
let marker = base.join("git.marker");
+1 -1
Переглянути файл
@@ -249,7 +249,7 @@ async fn restricted_vcs_commands_run_no_program_of_the_repository() {
call!("vcs_revision_files", "external", vcs::vcs_revision_files(host, w, log(), external.head.clone())),
call!("vcs_commit_files", "external", vcs::vcs_commit_files(host, w, log(), external.head.clone())),
// Last: it rewrites nothing of an existing repository, but it does touch it.
call!("vcs_init", "", vcs::vcs_init(host, project.root.clone())),
call!("vcs_init", "", vcs::vcs_init(host, w, project.root.clone())),
];
// The sweep covers every `vcs_*` command declared `trust = always`: a newly allowed one fails
+27
Переглянути файл
@@ -837,6 +837,33 @@ mod tests {
}
}
#[test]
fn stylelint_serves_style_sheets_only_below_its_config() {
let reg = reg();
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
for dir in ["apps/web/src", "apps/admin/src", "apps/api"] {
std::fs::create_dir_all(root.join(dir)).unwrap();
}
std::fs::write(root.join("apps/web/stylelint.config.mjs"), "export default {};").unwrap();
std::fs::write(root.join("apps/admin/package.json"), r#"{"stylelint": {"extends": []}}"#).unwrap();
std::fs::write(root.join("apps/api/package.json"), r#"{"name": "api"}"#).unwrap();
for lang in ["css", "scss", "less"] {
let cfg = reg.get(&LanguageId::new(lang)).unwrap();
let stylelint = cfg.language_servers.iter().find(|s| s.name == "stylelint").unwrap();
assert_eq!(stylelint.command, "stylelint-language-server", "{lang}");
assert!(stylelint.require_root_marker && !stylelint.fallback, "{lang}");
assert_eq!(stylelint.features, ["code-action", "diagnostics"], "{lang}");
// The server lints only the languages in `validate` (CSS alone by default).
let validate = stylelint.settings.as_ref().unwrap().get("validate").unwrap();
assert_eq!(validate, &serde_json::json!(["css", "scss", "less"]), "{lang}");
let served = |file: &str| crate::marked_root(Some(root), &root.join(file), &stylelint.root_markers);
assert_eq!(served("apps/web/src/app.css"), Some(root.join("apps/web")), "{lang}");
assert_eq!(served("apps/admin/src/app.css"), Some(root.join("apps/admin")), "{lang}");
assert_eq!(served("apps/api/app.css"), None, "{lang}: package.json without stylelint");
}
}
#[test]
fn laravel_lsp_serves_php_files_only_below_artisan() {
let reg = reg();
+1
Переглянути файл
@@ -21,6 +21,7 @@ const GENERATED_SOURCES: &str = "openidea.java.generatedSources";
pub(crate) mod configuration;
pub(crate) mod exception_breakpoints;
mod exception_type;
mod extract_interface;
mod formatter;
mod generated;
+38
Переглянути файл
@@ -0,0 +1,38 @@
//! The exception class at a caret, for the exception breakpoint intention, through the
//! app-owned JDT extension (`java/java-usages`).
use super::COMMAND_TIMEOUT;
use crate::LspManager;
use crate::types::ExceptionClassRef;
use ide_core::{CancellationToken, DocId, IdeError, IdeResult, Pos};
use serde_json::json;
const EXCEPTION_TYPE: &str = "openidea.java.exceptionType";
impl LspManager {
/// The Throwable class the caret at `pos` names; `None` when there is none, or when no
/// server of the document has the command.
pub async fn exception_class_at(
&self,
doc: DocId,
pos: Pos,
cancel: CancellationToken,
) -> IdeResult<Option<ExceptionClassRef>> {
let snap = self.snapshot(doc)?;
let mut targets = self.ready_targets(&snap.servers, |c| c.commands().iter().any(|c| c == EXCEPTION_TYPE)).await;
if targets.is_empty() {
return Ok(None);
}
let t = targets.swap_remove(0);
let at = snap.position(&t, pos);
let params = json!({
"command": EXCEPTION_TYPE,
"arguments": [snap.uri, at.line, at.character],
});
let found: Option<ExceptionClassRef> =
self.call(&t, "workspace/executeCommand", params, Some(&cancel), COMMAND_TIMEOUT).await?;
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
Ok(found)
}
}
+10
Переглянути файл
@@ -467,6 +467,16 @@ pub struct HierarchyMember {
pub abstractable: bool,
}
/// The exception class a caret names: a reference to it, its declaration, or a throw of it.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct ExceptionClassRef {
/// The binary name (`app.Outer$Failure`), as exception breakpoints take it.
pub qualified_name: String,
/// The simple name (`Failure`).
pub display_name: String,
}
/// The class at a position and what can move: pull-up destinations, or the subclasses
/// members are pushed into.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
+30
Переглянути файл
@@ -3770,6 +3770,36 @@ async fn exception_breakpoints_send_the_whole_list_and_decode_states() {
);
}
#[tokio::test(flavor = "multi_thread")]
async fn exception_class_at_asks_the_extension_and_is_none_without_it() {
let mut caps = incremental_caps();
caps["executeCommandProvider"] = json!({"commands": ["openidea.java.exceptionType"]});
let h = harness_for("java", "java", &[("jdtls", caps)], &[]);
let (doc, path) = h.open("Main.java", "class Main {\n void f() { throw new Failure(); }\n}");
h.wait_status("jdtls", ServerStatus::Ready).await;
let s = h.launcher.state("jdtls");
s.respond("workspace/executeCommand", json!({"qualifiedName": "app.Main$Failure", "displayName": "Failure"}));
let found = h.mgr.exception_class_at(doc, Pos::new(1, 23), Default::default()).await.unwrap();
assert_eq!(
found,
Some(ide_lsp::types::ExceptionClassRef {
qualified_name: "app.Main$Failure".into(),
display_name: "Failure".into()
})
);
let asked = s.requested("workspace/executeCommand");
assert_eq!(asked[0]["command"], "openidea.java.exceptionType");
assert_eq!(asked[0]["arguments"], json!([uri_of(&path), 1, 23]));
s.respond("workspace/executeCommand", json!(null));
assert_eq!(h.mgr.exception_class_at(doc, Pos::new(0, 1), Default::default()).await.unwrap(), None);
let plain = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
let (doc, _) = plain.open("Main.java", "class Main {}");
plain.wait_status("jdtls", ServerStatus::Ready).await;
assert_eq!(plain.mgr.exception_class_at(doc, Pos::new(0, 7), Default::default()).await.unwrap(), None);
assert!(plain.launcher.state("jdtls").requested("workspace/executeCommand").is_empty());
}
#[tokio::test(flavor = "multi_thread")]
async fn debug_server_port_maps_to_module() {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
+1 -1
Переглянути файл
@@ -1629,7 +1629,7 @@ pub fn usages_bundle(data_dir: &Path) -> Option<PathBuf> {
install_bundle(
data_dir,
"java-usages",
"1.16.0",
"1.17.0",
include_bytes!("../../../java/java-usages/openidea-java-usages.jar"),
)
}
+11
Переглянути файл
@@ -224,6 +224,17 @@ pub static TOOLS: &[ToolSpec] = &[
homepage: "https://github.com/hrsh7th/vscode-langservers-extracted",
needs: NODE,
},
ToolSpec {
name: "stylelint",
display: "Stylelint Language Server",
kind: LanguageServer,
commands: &["stylelint-language-server"],
method: Method::Npm { packages: &["@stylelint/language-server"] },
fallback: None,
version: V,
homepage: "https://github.com/stylelint/vscode-stylelint",
needs: NODE,
},
ToolSpec {
name: "rust-analyzer",
display: "rust-analyzer",
+14 -10
Переглянути файл
@@ -13,15 +13,15 @@ use std::time::{Duration, Instant};
/// to exit on `SIGTERM` before `SIGKILL`: git removes its `index.lock` on `SIGTERM`.
const KILL_GRACE: Duration = Duration::from_millis(20);
/// Explicit git executable from Settings › Version Control › Git (`None` = auto-detect).
static CONFIGURED: std::sync::RwLock<Option<PathBuf>> = std::sync::RwLock::new(None);
/// Git executable of the user's global settings (`None` = auto-detect). Never a project's: a
/// project's repositories carry their own ([`crate::Repo::set_git_executable`]).
static DEFAULT: std::sync::RwLock<Option<PathBuf>> = std::sync::RwLock::new(None);
/// Sets (or clears, with `None` / an empty path) the git executable to use.
pub fn set_git_executable(path: Option<&Path>) {
/// Sets (or clears, with `None` / an empty path) the git executable of repositories that have
/// none of their own, from the global settings only.
pub fn set_default_git_executable(path: Option<&Path>) {
let path = path.filter(|p| !p.as_os_str().is_empty()).map(Path::to_path_buf);
if *CONFIGURED.read().unwrap_or_else(|e| e.into_inner()) != path {
*CONFIGURED.write().unwrap_or_else(|e| e.into_inner()) = path;
}
*DEFAULT.write().unwrap_or_else(|e| e.into_inner()) = path;
}
/// Environment that routes credential prompts (`ssh` passphrases and host keys,
@@ -102,16 +102,20 @@ pub fn detected_git_executable() -> Option<PathBuf> {
detected_git().map(Path::to_path_buf)
}
/// The executable of the repository this thread works in, else the default, else the detected one.
pub(crate) fn git_binary() -> IdeResult<PathBuf> {
if let Some(configured) = CONFIGURED.read().unwrap_or_else(|e| e.into_inner()).clone() {
return Ok(configured);
if let Some(own) = crate::scoped_git_executable() {
return Ok(own.to_path_buf());
}
if let Some(default) = DEFAULT.read().unwrap_or_else(|e| e.into_inner()).clone() {
return Ok(default);
}
detected_git()
.map(Path::to_path_buf)
.ok_or_else(|| IdeError::unavailable("git executable not found; install git and make sure it is on PATH"))
}
/// `git --version` of `executable` (or the configured / detected one), e.g. `git version 2.44.0`.
/// `git --version` of `executable` (or the default / detected one), e.g. `git version 2.44.0`.
pub fn git_version(executable: Option<&Path>) -> IdeResult<String> {
let exe = match executable.filter(|p| !p.as_os_str().is_empty()) {
Some(p) => p.to_path_buf(),
+1 -2
Переглянути файл
@@ -129,8 +129,7 @@ impl Repos {
continue;
}
let repo = self.at_root(&root.0).expect("scope comes from registry");
let _scope =
crate::ExecutionScope::enter(repo.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = repo.execution_scope();
let mut missing_revision = false;
let mut compare = || -> IdeResult<(String, Vec<WorkingTreeChange>)> {
// Worktree comparisons must not run repository-defined clean/process filters
+153 -102
Переглянути файл
@@ -700,7 +700,7 @@ mod write;
pub use backend::Backend;
pub use cli::{
GitCommandObserver, detected_git_executable, filter_overrides_from, git_version, restrict, set_askpass_env,
set_git_command_observer, set_git_executable,
set_default_git_executable, set_git_command_observer,
};
pub use diff::build_partial_patch;
pub use external_diff::{ExternalDiffSide, launch_external_diff};
@@ -774,7 +774,7 @@ mod clone_tests {
/// Creates an empty repository in `dir` (`git init`).
pub fn init(dir: &Path) -> IdeResult<()> {
// `git init` runs nothing a repository config names, so the configured git runs as it is.
let _scope = ExecutionScope::enter(true);
let _scope = ExecutionScope::enter_with(true, opening_git_executable());
cli::run(dir, &["init", "-q"], None).map(|_| ())
}
@@ -788,6 +788,7 @@ pub fn diff_hunks(old_text: &str, new_text: &str) -> Vec<LineHunk> {
/// on-disk state, so it never needs to be reopened after external changes.
pub struct Repo {
execution_allowed: std::sync::atomic::AtomicBool,
git_executable: std::sync::RwLock<Option<std::sync::Arc<Path>>>,
root: PathBuf,
git_dir: PathBuf,
inner: std::sync::Mutex<repo::Cache>,
@@ -806,18 +807,18 @@ impl Repo {
}
/// The worktree root.
pub fn root(&self) -> &Path {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
&self.root
}
/// git's own folders for this worktree: its git dir and the common one (they differ for a
/// linked worktree, whose `.git` file points into the main repository).
pub fn metadata_dirs(&self) -> IdeResult<[PathBuf; 2]> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
Ok([self.git_dir.clone(), repo::absolute(self.gix()?.common_dir())?])
}
/// Untracked files with one of these names (or under such a folder) are not reported.
pub fn set_ignored_names(&self, names: IgnoredNames) {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
*self.ignored.write().unwrap_or_else(|p| p.into_inner()) = names;
}
/// Read the working-tree status with `git status` rather than in process: for file systems
@@ -828,13 +829,13 @@ impl Repo {
/// Staged (HEAD↔index) and unstaged (index↔worktree, incl. untracked) changes,
/// sorted by path. Conflicted files report `unstaged: Conflicted` and no staged kind.
pub fn status(&self) -> IdeResult<Vec<FileStatus>> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
status::status(self)
}
/// Status of `paths` only (absolute; those outside the repository are ignored), for the
/// dirty-scope refresh after a watcher batch. An empty list is the full status.
pub fn status_paths(&self, paths: &[PathBuf]) -> IdeResult<Vec<FileStatus>> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
// Restricted Mode starts no program of the repository, and the scoped read is `git status`
// with a pathspec: answer with the full gitoxide status instead.
if !self.execution_allowed.load(std::sync::atomic::Ordering::Acquire) {
@@ -850,18 +851,18 @@ impl Repo {
status::status_paths(self, &rel)
}
pub fn branch_info(&self) -> IdeResult<BranchInfo> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
refs::branch_info(self)
}
/// Current branch (short name; `None` when detached) and HEAD commit, without
/// upstream tracking (cheap enough to call for every repository on each refresh).
pub fn head(&self) -> IdeResult<(Option<String>, Option<String>)> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
refs::head(&self.gix()?)
}
/// Merge / rebase / cherry-pick… in progress (cheap: no ref walking).
pub fn operation(&self) -> IdeResult<Option<String>> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
Ok(refs::operation(&self.gix()?))
}
/// Content of `path` at `rev` (default HEAD); `None` if absent there.
@@ -873,13 +874,13 @@ impl Repo {
encoding: impl Into<TextEncoding>,
) -> IdeResult<Option<String>> {
let encoding = encoding.into();
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
Ok(self.blob_of(path, rev.unwrap_or("HEAD"))?.map(|b| text_encoding::decode(&b, encoding).into_owned()))
}
/// The file's git mode at `rev` as printed by git (`100644`, `100755`, `120000`…),
/// `None` when absent there. `rev` follows `file_at`'s rules, `WT` reads the worktree.
pub fn file_mode_at(&self, path: &Path, rev: Option<&str>) -> IdeResult<Option<String>> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
if rev == Some("WT") {
return repo::worktree_mode(self.root(), &self.rel_path(path)?);
}
@@ -889,7 +890,7 @@ impl Repo {
}
/// Raw revision bytes, for encoding detection when the working file is absent.
pub fn file_bytes_at(&self, path: &Path, rev: Option<&str>) -> IdeResult<Option<Vec<u8>>> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
self.blob_of(path, rev.unwrap_or("HEAD"))
}
/// Stage selected decoded hunks, retaining the index encoding, BOM and line endings.
@@ -901,7 +902,7 @@ impl Repo {
encoding: impl Into<TextEncoding>,
) -> IdeResult<()> {
let encoding = encoding.into();
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
write::stage_hunks(self, path, current, selected, encoding)
}
/// Hunks of `current_text` against HEAD (or the index when `against_index`).
@@ -918,7 +919,7 @@ impl Repo {
encoding: impl Into<TextEncoding>,
) -> IdeResult<Vec<LineHunk>> {
let encoding = encoding.into();
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
let Ok(rel) = self.rel_path(path) else { return Ok(Vec::new()) };
if rel.is_empty() || rel == ".git" || rel.starts_with(".git/") {
return Ok(Vec::new());
@@ -948,13 +949,13 @@ impl Repo {
encoding: impl Into<TextEncoding>,
) -> IdeResult<Vec<BlameLine>> {
let encoding = encoding.into();
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
write::blame(self, path, current_text, revision, encoding)
}
/// Adds `commit` to the list `blame.ignoreRevsFile` names, so annotate skips it; with none
/// configured, to `.git-blame-ignore-revs` at the worktree root, which the local config then names.
pub fn ignore_blame_revision(&self, commit: &str) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
write::ignore_blame_revision(self, commit)
}
/// History for Selection: commits that changed `lines` (0-based, inclusive, of the
@@ -968,7 +969,7 @@ impl Repo {
cancel: &CancellationToken,
) -> IdeResult<BlockHistory> {
let encoding = encoding.into();
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
block_history::block_history(self, path, current_text, lines, encoding, cancel)
}
/// Commits newest-first in topological order (children before parents).
@@ -979,11 +980,11 @@ impl Repo {
/// `skip`/`limit` paginate over the filtered result; `limit == 0` means no limit.
/// `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));
let _scope = self.execution_scope();
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));
let _scope = self.execution_scope();
history::log(self, query, cancel)
}
/// Enables the disposable, content-addressed log cache outside the worktree.
@@ -1000,7 +1001,7 @@ impl Repo {
.collect())
}
pub fn log_users(&self) -> IdeResult<Vec<String>> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
let out = cli::run(self.root(), &["log", "--all", "--format=%an <%ae>"], None)?;
Ok(out
.stdout_str()
@@ -1026,7 +1027,7 @@ impl Repo {
cancel: &CancellationToken,
) -> IdeResult<Vec<LogDetails>> {
let allowed = self.execution_allowed.load(std::sync::atomic::Ordering::Acquire);
let _scope = crate::ExecutionScope::enter(allowed);
let _scope = self.execution_scope();
let repo = self.gix()?;
let shallow: std::collections::HashSet<gix::ObjectId> =
repo.shallow_commits().map_err(repo::gx)?.map(|ids| ids.iter().copied().collect()).unwrap_or_default();
@@ -1099,7 +1100,7 @@ impl Repo {
/// Lists one immutable revision directory. Directory names end in `/`.
pub fn revision_children(&self, revision: &str, directory: &str) -> IdeResult<Vec<String>> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
let repo = self.gix()?;
let id = repo::resolve(&repo, revision)?.to_string();
let directory = self.rel_path(std::path::Path::new(directory))?;
@@ -1122,7 +1123,7 @@ impl Repo {
}
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 _scope = self.execution_scope();
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)?;
@@ -1135,23 +1136,23 @@ impl Repo {
}
/// Files changed by `commit` relative to its first parent (renames detected).
pub fn commit_files(&self, commit: &str) -> IdeResult<Vec<ChangedFile>> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
history::commit_files(self, commit)
}
/// Combined changes of several commits (oldest first): per file, before the first commit
/// that touched it ↔ after the last one (IDEA's multi-commit Git Log selection).
pub fn commits_changes(&self, commits: &[String]) -> IdeResult<Vec<RevisionChange>> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
history::commits_changes(self, commits)
}
/// Local and remote branches; the current branch first, then most recent first.
pub fn branches(&self) -> IdeResult<Vec<Branch>> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
refs::branches(self)
}
/// Stash entries, newest (`stash@{0}`) first.
pub fn stashes(&self) -> IdeResult<Vec<Stash>> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
refs::stashes(self)
}
/// Working tree against a revision, optionally restricted to a file. Bounded and cancellable.
@@ -1162,7 +1163,7 @@ impl Repo {
max_bytes: usize,
cancel: &CancellationToken,
) -> IdeResult<String> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
let rev = against.unwrap_or("HEAD");
if rev.is_empty() || rev.starts_with('-') || rev.contains('\0') {
return Err(ide_core::IdeError::invalid("invalid revision"));
@@ -1184,13 +1185,13 @@ impl Repo {
/// against /dev/null) or HEAD↔index (`staged == true`). Empty when unchanged.
pub fn diff_text(&self, path: &Path, staged: bool, encoding: impl Into<TextEncoding>) -> IdeResult<String> {
let encoding = encoding.into();
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
write::diff_text(self, path, staged, encoding)
}
/// `git config --get <key>` (all scopes); `None` when unset.
pub fn config_get(&self, key: &str) -> IdeResult<Option<String>> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
let out = cli::run_raw(&self.root, &["config", "--get", key], None)?;
Ok((out.code == Some(0)).then(|| out.stdout_str().trim().to_string()))
}
@@ -1198,7 +1199,7 @@ impl Repo {
/// Sets `user.name` and `user.email` for commits: in this repository's config, or in the
/// user's global one (`global`).
pub fn set_user_identity(&self, name: &str, email: &str, global: bool) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
let scope = if global { "--global" } else { "--local" };
for (key, value) in [("user.name", name.trim()), ("user.email", email.trim())] {
if value.is_empty() {
@@ -1211,11 +1212,11 @@ impl Repo {
// ---- writes (git CLI) ----
pub fn stage(&self, paths: &[PathBuf]) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
write::stage(self, paths)
}
pub fn unstage(&self, paths: &[PathBuf]) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
write::unstage(self, paths)
}
/// Applies a unified-diff patch to the index (partial staging of hunks/lines).
@@ -1225,20 +1226,20 @@ impl Repo {
patch: &str,
encoding: &dyn Fn(&Path) -> IdeResult<E>,
) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
write::stage_patch(self, patch, &|path| encoding(path).map(Into::into))
}
/// Discards unstaged changes: tracked paths are restored from the index (staged
/// changes are kept), untracked files and directories are deleted. A submodule goes back
/// to the commit the index records, with its tracked files restored.
pub fn discard(&self, paths: &[PathBuf]) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
write::discard(self, paths)
}
/// Commits the index; returns the new HEAD commit id. An empty message with
/// `amend` keeps the previous message.
pub fn commit(&self, message: &str, amend: bool, sign_off: bool) -> IdeResult<String> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
let options = CommitOptions { amend, sign_off, author: None, run_hooks: true, ..Default::default() };
write::commit(self, message, &options, &|_| Ok(encoding_rs::UTF_8.into()))
}
@@ -1249,7 +1250,7 @@ impl Repo {
options: &CommitOptions,
encoding: &dyn Fn(&Path) -> IdeResult<E>,
) -> IdeResult<String> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
write::commit(self, message, options, &|path| encoding(path).map(Into::into))
}
/// What [`Repo::commit_with`] would commit with `options`, file by file, without
@@ -1260,14 +1261,14 @@ impl Repo {
max_bytes: usize,
encoding: &dyn Fn(&Path) -> IdeResult<E>,
) -> IdeResult<Vec<PendingChange>> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
write::pending_changes(self, options, max_bytes, &|path| encoding(path).map(Into::into))
}
/// Switches to `branch`. With `create`, creates it at HEAD. Without, a remote branch
/// (`origin/x`) gets a local tracking branch and any other revision is checked out
/// detached.
pub fn checkout(&self, branch: &str, create: bool) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
write::checkout(self, branch, create)
}
/// [`Repo::checkout`] as IDEA does it: local changes in the way are reported (or
@@ -1275,7 +1276,7 @@ impl Repo {
/// is behind fast-forwards that branch, while one that is ahead is reported (or
/// rebased / reset per `options.diverged`).
pub fn checkout_with(&self, branch: &str, create: bool, options: &CheckoutOptions) -> IdeResult<CheckoutOutcome> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
write::checkout_with(self, branch, create, options)
}
/// Creates branch `name` at `start` (default HEAD), optionally switching to it. A
@@ -1292,62 +1293,62 @@ impl Repo {
checkout: bool,
overwrite: bool,
) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
write::create_branch(self, name, start, checkout, overwrite)
}
/// Undo Commit: resets the current branch to the parent of `commit` (which must be
/// HEAD and not a merge) keeping its changes staged; undoing the initial commit
/// leaves an unborn branch. Returns the undone commit's message.
pub fn undo_commit(&self, commit: &str) -> IdeResult<String> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
write::undo_commit(self, commit)
}
/// Deletes a local branch (`git branch -d`, `-D` when `force`).
/// Edit Commit Message without touching the index or the working tree; returns HEAD
/// before and after.
pub fn reword(&self, commit: &str, message: &str) -> IdeResult<HeadChange> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
write::reword(self, commit, message).map(|(before, after)| HeadChange { before, after })
}
/// Undoes a history rewrite: HEAD goes from `after` back to `before`, local changes kept.
pub fn restore_head(&self, before: &str, after: &str) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
write::restore_head(self, before, after)
}
pub fn delete_branch(&self, branch: &str, force: bool) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
write::delete_branch(self, branch, force)
}
/// Deletes a local branch as IDEA does: without asking, force-deleting one that is not
/// fully merged (reported as `unmerged`), and returning what [`Repo::restore_branch`]
/// needs to undo it.
pub fn delete_branch_restorable(&self, branch: &str) -> IdeResult<DeletedBranch> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
write::delete_branch_restorable(self, branch)
}
/// Recreates a deleted branch at its old tip, with its upstream.
pub fn restore_branch(&self, deleted: &DeletedBranch) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
write::restore_branch(self, deleted)
}
/// Renames a local branch (`git branch -m`); its upstream configuration moves with it,
/// unless `unset_upstream` drops the tracking instead.
pub fn rename_branch(&self, from: &str, to: &str, unset_upstream: bool) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
write::rename_branch(self, from, to, unset_upstream)
}
/// Merges `branch` into HEAD; local changes are stashed and restored around it. On
/// conflicts an error is returned and the repository is left mid-merge
/// (`branch_info().operation == Some("merge")`).
pub fn merge(&self, branch: &str) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
write::merge(self, branch)
}
/// Rebases the current branch onto `onto`; local changes are stashed and restored.
pub fn rebase(&self, onto: &str) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
write::rebase(self, onto)
}
/// `paths` (absolute) stashes only those files; empty stashes the whole working tree.
@@ -1359,23 +1360,23 @@ impl Repo {
keep_index: bool,
paths: &[PathBuf],
) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
write::stash_push(self, message, include_untracked, keep_index, paths)
}
/// `reinstate_index`: also restore what was staged when the stash was made.
pub fn stash_apply(&self, index: u32, pop: bool, reinstate_index: bool) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
write::stash_apply(self, index, pop, reinstate_index)
}
/// Creates and checks out `branch` at the commit the stash was made on, applies the
/// stash there (index included) and drops it.
pub fn stash_branch(&self, index: u32, branch: &str) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
write::stash_branch(self, index, branch)
}
/// Removes `stash@{index}` without applying it.
pub fn stash_drop(&self, index: u32) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
write::stash_drop(self, index)
}
/// Deletes a branch on a remote (`git push <remote> --delete <branch>`); `branch` is the
@@ -1386,19 +1387,19 @@ impl Repo {
cancel: &CancellationToken,
on_output: &dyn Fn(String),
) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
write::delete_remote_branch(self, branch, cancel, on_output)
}
/// Network operations stream progress lines through `on_output`.
/// Fetches all remotes (pruning deleted branches).
pub fn fetch(&self, cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
cli::run_streaming(&self.root, &["fetch", "--progress", "--all", "--prune"], cancel, on_output)
}
/// Update Project: pulls the upstream by merge or rebase. Local changes are stashed
/// and restored; the merge mode fast-forwards when possible whatever `pull.ff` says.
pub fn pull(&self, rebase: bool, cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
let mode: &[&str] = if rebase { &["--rebase"] } else { &["--no-rebase", "--ff"] };
let mut args = vec!["pull", "--progress"];
args.extend_from_slice(mode);
@@ -1435,13 +1436,13 @@ impl Repo {
cancel: &CancellationToken,
on_output: &dyn Fn(String),
) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
write::push(self, options, cancel, on_output)
}
/// Whether the repository has an executable hook `name` (e.g. `pre-push`), wherever
/// `core.hooksPath` puts it: the Push dialog then offers to skip it.
pub fn has_hook(&self, name: &str) -> IdeResult<bool> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
write::has_hook(self, name)
}
/// Pushes a local branch, or its history up to `revision`, to its upstream (Git Log
@@ -1454,7 +1455,7 @@ impl Repo {
cancel: &CancellationToken,
on_output: &dyn Fn(String),
) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
write::push_branch(
self,
branch,
@@ -1473,13 +1474,13 @@ impl Repo {
cancel: &CancellationToken,
on_output: &dyn Fn(String),
) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
write::push_branch(self, branch, options, cancel, on_output)
}
/// Update Project › Reset to the Remote Branch: the current branch is moved to its
/// freshly fetched tracked branch; local commits are dropped, local changes kept.
pub fn reset_to_upstream(&self, cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
write::reset_to_upstream(self, cancel, on_output)
}
/// Branches › Update Selected: fetches each remote once and fast-forwards every
@@ -1490,7 +1491,7 @@ impl Repo {
cancel: &CancellationToken,
on_output: &dyn Fn(String),
) -> IdeResult<Vec<BranchUpdate>> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
write::update_branches(self, branches, cancel, on_output)
}
// ---- in-progress operations, history rewriting, tags ----
@@ -1498,21 +1499,21 @@ impl Repo {
/// Continues the merge / rebase / cherry-pick / revert in progress; fails while
/// conflicts are unresolved.
pub fn continue_operation(&self, cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
ops::continue_op(self, false, cancel, on_output)
}
/// Stage and Retry: stages the changes of tracked files, then continues.
pub fn stage_and_continue(&self, cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
ops::continue_op(self, true, cancel, on_output)
}
pub fn abort_operation(&self, cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
ops::abort_op(self, cancel, on_output)
}
/// Skips the current commit of a rebase / cherry-pick / revert.
pub fn skip_operation(&self, cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
ops::skip_op(self, cancel, on_output)
}
/// Cherry-picks `commits` in order (oldest first). Stops mid-way on conflicts.
@@ -1532,12 +1533,12 @@ impl Repo {
cancel: &CancellationToken,
on_output: &dyn Fn(String),
) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
ops::cherry_pick(self, commits, record_origin, cancel, on_output)
}
/// Reverts `commits` in order (newest first) with git's default messages.
pub fn revert(&self, commits: &[String], cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
ops::revert(self, commits, cancel, on_output)
}
/// Interactive rebase of `base..HEAD` (`None`: from the root) following `entries`,
@@ -1550,7 +1551,7 @@ impl Repo {
cancel: &CancellationToken,
on_output: &dyn Fn(String),
) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
ops::interactive_rebase(self, base, entries, cancel, on_output)
}
/// Moves the current branch to `commit` (`git reset --<mode>`).
@@ -1561,22 +1562,22 @@ impl Repo {
cancel: &CancellationToken,
on_output: &dyn Fn(String),
) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
ops::reset(self, commit, mode, cancel, on_output)
}
/// Creates tag `name` on `commit` (annotated when `message` is given).
pub fn create_tag(&self, name: &str, commit: &str, message: Option<&str>, force: bool) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
ops::create_tag(self, name, commit, message, force)
}
/// Deletes a local tag, returning what [`Repo::restore_tag`] needs to undo it.
pub fn delete_tag(&self, name: &str) -> IdeResult<DeletedTag> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
ops::delete_tag(self, name)
}
/// Recreates a deleted tag (annotated ones with their message).
pub fn restore_tag(&self, deleted: &DeletedTag) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
ops::restore_tag(self, deleted)
}
/// Pushes one tag to `remote` (Push Tag › Push to …).
@@ -1587,7 +1588,7 @@ impl Repo {
cancel: &CancellationToken,
on_output: &dyn Fn(String),
) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
ops::push_tag(self, tag, remote, false, cancel, on_output)
}
/// Deletes a tag on `remote` (Delete on Remote, after deleting it locally).
@@ -1598,33 +1599,33 @@ impl Repo {
cancel: &CancellationToken,
on_output: &dyn Fn(String),
) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
ops::push_tag(self, tag, remote, true, cancel, on_output)
}
pub fn tags(&self) -> IdeResult<Vec<String>> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
ops::tags(self)
}
/// Files that differ between revisions `from` and `to`.
pub fn diff_revisions(&self, from: &str, to: &str) -> IdeResult<Vec<ChangedFile>> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
ops::diff_revisions(self, from, to)
}
/// Added and deleted lines between `from` and `to`. `paths` limits the diff to those
/// repository-relative paths (both names of a rename); empty diffs every file.
pub fn diff_numstat(&self, from: &str, to: &str, paths: &[String]) -> IdeResult<Vec<FileLineStats>> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
ops::diff_numstat(self, from, to, paths)
}
/// Tracked files whose working-tree content differs from `rev`.
pub fn diff_with_worktree(&self, rev: &str) -> IdeResult<Vec<ChangedFile>> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
ops::diff_with_worktree(self, rev)
}
/// `(repo-relative path, added lines, deleted lines)` of the tracked files whose
/// working-tree content differs from `rev`.
pub fn numstat_with_worktree(&self, rev: &str) -> IdeResult<Vec<(String, u32, u32)>> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
ops::numstat_with_worktree(self, rev)
}
@@ -1632,45 +1633,45 @@ impl Repo {
/// Patch of the local changes of `paths` against HEAD (untracked files included).
pub fn create_patch(&self, paths: &[PathBuf], reverse: bool) -> IdeResult<String> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
let rel = self.rel_paths(paths)?;
Ok(patch::working_patch(self, &rel, reverse, true)?.0)
}
/// Patch of the changes made by `commits` (oldest first).
pub fn create_commits_patch(&self, commits: &[String], reverse: bool) -> IdeResult<String> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
patch::commits_patch(self, commits, reverse)
}
pub fn patch_preview(&self, patch: &str) -> IdeResult<Vec<PatchFile>> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
patch::preview(self, patch)
}
/// Applies a patch to the working tree, 3-way merging when it does not apply cleanly.
pub fn apply_patch(&self, patch: &str) -> IdeResult<ApplyOutcome> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
patch::apply(self, patch)
}
/// Saves the changes of `paths` under `shelf_dir` and reverts them.
pub fn shelve(&self, shelf_dir: &Path, name: &str, paths: &[PathBuf]) -> IdeResult<ShelvedChangeList> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
let rel = self.rel_paths(paths)?;
shelf::shelve(self, shelf_dir, name, &rel)
}
pub fn unshelve(&self, shelf_dir: &Path, id: &str, remove: bool) -> IdeResult<ApplyOutcome> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
shelf::unshelve(self, shelf_dir, id, remove)
}
/// Who is on each side of the conflicts of the operation in progress.
pub fn merge_sides(&self) -> IdeResult<MergeSides> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
ops::merge_sides(self)
}
/// The versions of a conflicted file with the user's work as `ours`, as IDEA's merge
/// dialog shows them (sides swapped during a rebase).
pub fn merge_versions(&self, path: &Path, encoding: impl Into<TextEncoding>) -> IdeResult<MergeVersions> {
let encoding = encoding.into();
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
let (base, ours, theirs) = self.conflict_versions(path, encoding)?;
let sides = self.merge_sides()?;
let (ours, theirs) = if sides.reversed { (theirs, ours) } else { (ours, theirs) };
@@ -1687,7 +1688,7 @@ impl Repo {
encoding: impl Into<TextEncoding>,
) -> IdeResult<(Option<String>, Option<String>, Option<String>)> {
let encoding = encoding.into();
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
let rel = self.rel_path(path)?;
let repo = self.gix()?;
let stage = |n: u8| -> IdeResult<Option<String>> {
@@ -1697,33 +1698,83 @@ impl Repo {
}
}
/// What git started on this thread may do, and which executable it is.
#[derive(Clone)]
struct Grant {
allowed: bool,
git: Option<std::sync::Arc<Path>>,
}
// `None`: nobody has decided yet. Git started now is restricted, and the first scope entered
// decides. The flag governs the git CLI only: gitoxide follows the repository's own flag.
thread_local! { static EXECUTION_ALLOWED: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) }; }
struct ExecutionScope(Option<bool>);
// decides. The grant governs the git CLI only: gitoxide follows the repository's own flag.
thread_local! { static EXECUTION: std::cell::RefCell<Option<Grant>> = const { std::cell::RefCell::new(None) }; }
struct ExecutionScope(Option<Grant>);
impl ExecutionScope {
/// The outermost scope decides; a scope inside it can only restrict.
fn enter(allowed: bool) -> Self {
Self(
EXECUTION_ALLOWED
.with(|current| current.replace(Some(current.get().map_or(allowed, |outer| outer && allowed)))),
)
Self::enter_with(allowed, None)
}
/// The outermost scope decides; a scope inside it can only restrict.
fn enter_with(allowed: bool, git: Option<std::sync::Arc<Path>>) -> Self {
EXECUTION.with(|current| {
let mut current = current.borrow_mut();
let grant = match current.as_ref() {
Some(outer) => Grant { allowed: outer.allowed && allowed, git: outer.git.clone() },
None => Grant { allowed, git },
};
Self(current.replace(grant))
})
}
}
impl Drop for ExecutionScope {
fn drop(&mut self) {
EXECUTION_ALLOWED.with(|current| current.set(self.0));
EXECUTION.with(|current| *current.borrow_mut() = self.0.take());
}
}
pub(crate) fn execution_allowed() -> bool {
EXECUTION_ALLOWED.with(|current| current.get().unwrap_or(false))
EXECUTION.with(|current| current.borrow().as_ref().is_some_and(|grant| grant.allowed))
}
/// The git executable of the repository whose scope this thread is in, when it may execute.
pub(crate) fn scoped_git_executable() -> Option<std::sync::Arc<Path>> {
EXECUTION
.with(|current| current.borrow().as_ref().filter(|grant| grant.allowed).and_then(|grant| grant.git.clone()))
}
thread_local! { static OPENING_GIT: std::cell::RefCell<Option<std::sync::Arc<Path>>> = const { std::cell::RefCell::new(None) }; }
/// Runs `f` with `git` (a project's Path to Git executable; `None` for the default) as the git
/// executable of every [`Repo`] opened in it on this thread, and of [`init`]: for work on behalf
/// of a project that opens its own repositories. It grants no execution.
pub fn with_git_executable<T>(git: Option<&Path>, f: impl FnOnce() -> T) -> T {
struct Restore(Option<std::sync::Arc<Path>>);
impl Drop for Restore {
fn drop(&mut self) {
OPENING_GIT.with(|opening| *opening.borrow_mut() = self.0.take());
}
}
let git = git.filter(|p| !p.as_os_str().is_empty()).map(std::sync::Arc::from);
let _restore = Restore(OPENING_GIT.with(|opening| opening.replace(git)));
f()
}
pub(crate) fn opening_git_executable() -> Option<std::sync::Arc<Path>> {
OPENING_GIT.with(|opening| opening.borrow().clone())
}
impl Repo {
/// Whether git may run what the repository's config names (hooks, filters, the fsmonitor,
/// signature verifiers, a promisor) and use the configured git executable. A repository
/// starts without it: only a caller that knows the project is trusted grants it.
pub fn set_execution_allowed(&self, allowed: bool) {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
self.execution_allowed.store(allowed, std::sync::atomic::Ordering::Release);
}
/// The git executable from this repository's project settings (`None` or empty: the default,
/// see [`set_default_git_executable`]). A relative path resolves against the worktree root.
/// Used only while execution is allowed.
pub fn set_git_executable(&self, path: Option<&Path>) {
let path = path.filter(|p| !p.as_os_str().is_empty()).map(std::sync::Arc::from);
*self.git_executable.write().unwrap_or_else(|p| p.into_inner()) = path;
}
fn execution_scope(&self) -> ExecutionScope {
let git = self.git_executable.read().unwrap_or_else(|p| p.into_inner()).clone();
ExecutionScope::enter_with(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire), git)
}
}
+8 -8
Переглянути файл
@@ -210,7 +210,7 @@ pub(crate) fn parse_worktrees(text: &str) -> Vec<Worktree> {
impl Repo {
/// Merges `branches` into the current branch (Git › Merge…).
pub fn merge_with(&self, branches: &[String], options: &MergeOptions) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
let args = merge_args(branches, options)?;
let args: Vec<&str> = args.iter().map(String::as_str).collect();
crate::preserve::around(self, "Local changes saved before merge", || run(self.root(), &args, None).map(|_| ()))
@@ -218,7 +218,7 @@ impl Repo {
/// Rebases the current branch onto `upstream` (or `upstream..HEAD` onto `options.onto`).
pub fn rebase_with(&self, upstream: &str, options: &RebaseOptions) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
let args = rebase_args(upstream, options)?;
let args: Vec<&str> = args.iter().map(String::as_str).collect();
crate::preserve::around(self, "Local changes saved before rebase", || run(self.root(), &args, None).map(|_| ()))
@@ -234,7 +234,7 @@ impl Repo {
cancel: &CancellationToken,
on_output: &dyn Fn(String),
) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
let args = pull_args(remote, branches, rebase, options)?;
let args: Vec<&str> = args.iter().map(String::as_str).collect();
crate::preserve::around(self, "Local changes saved before update", || {
@@ -244,7 +244,7 @@ impl Repo {
/// Manage Remotes: adds, removes or edits a remote.
pub fn edit_remote(&self, edit: &RemoteEdit) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
match edit {
RemoteEdit::Add { name, url } => {
let (name, url) = (arg(name, "remote name")?, arg(url, "URL")?);
@@ -268,7 +268,7 @@ impl Repo {
/// Working trees of the repository, the main one first.
pub fn worktrees(&self) -> IdeResult<Vec<Worktree>> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
let out = run(self.root(), &["worktree", "list", "--porcelain"], None)?;
Ok(parse_worktrees(&out.stdout_str()))
}
@@ -276,7 +276,7 @@ impl Repo {
/// Git › New Worktree…: checks out `commitish` at `path`, on a new branch `new_branch`
/// when given (otherwise `commitish` must be a branch not checked out elsewhere).
pub fn add_worktree(&self, path: &Path, commitish: &str, new_branch: Option<&str>) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
let path = path.to_string_lossy().into_owned();
let commitish = arg(commitish, "revision")?;
let mut args: Vec<String> = vec!["worktree".into(), "add".into()];
@@ -294,7 +294,7 @@ impl Repo {
/// Move Worktree…: moves a linked worktree's folder to exactly `to`. An empty folder there
/// is replaced (Git would move the worktree inside it); any other existing `to` is refused.
pub fn move_worktree(&self, path: &Path, to: &Path) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
if std::fs::symlink_metadata(to).is_ok() {
let empty_dir = to.is_dir() && std::fs::read_dir(to).is_ok_and(|mut d| d.next().is_none());
if !empty_dir {
@@ -307,7 +307,7 @@ impl Repo {
}
pub fn remove_worktree(&self, path: &Path, force: bool) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
let path = path.to_string_lossy().into_owned();
let mut args = vec!["worktree", "remove"];
if force {
+5 -5
Переглянути файл
@@ -43,14 +43,14 @@ pub(crate) fn parse_remotes(text: &str) -> Vec<Remote> {
impl Repo {
/// Configured remotes with their fetch URLs.
pub fn remotes(&self) -> IdeResult<Vec<Remote>> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
let out = cli::run(self.root(), &["remote", "-v"], None)?;
Ok(parse_remotes(&out.stdout_str()))
}
/// Whether `rev` names a commit present in the object database.
pub fn has_commit(&self, rev: &str) -> bool {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
check_rev(rev).is_ok()
&& cli::run_raw(self.root(), &["cat-file", "-e", &format!("{rev}^{{commit}}")], None)
.is_ok_and(|o| o.code == Some(0))
@@ -65,7 +65,7 @@ impl Repo {
cancel: &CancellationToken,
on_output: &dyn Fn(String),
) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
check_rev(remote)?;
for r in refspecs {
check_rev(r)?;
@@ -77,7 +77,7 @@ impl Repo {
/// The best common ancestor of two revisions, if any.
pub fn merge_base(&self, a: &str, b: &str) -> IdeResult<Option<String>> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
check_rev(a)?;
check_rev(b)?;
let out = cli::run_raw(self.root(), &["merge-base", a, b], None)?;
@@ -86,7 +86,7 @@ impl Repo {
/// Files changed between two revisions (renames detected).
pub fn diff_files(&self, from: &str, to: &str) -> IdeResult<Vec<ChangedFile>> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
check_rev(from)?;
check_rev(to)?;
let out = cli::run(
+4 -3
Переглянути файл
@@ -72,6 +72,7 @@ pub(crate) fn discover(path: &Path) -> IdeResult<Option<Repo>> {
let cache = Cache { stamp: stamp(&files), files, repo: ts, pack_stamp: pack_stamp(&pack_dir), pack_dir };
Ok(Some(Repo {
execution_allowed: std::sync::atomic::AtomicBool::new(false),
git_executable: std::sync::RwLock::new(crate::opening_git_executable()),
root,
git_dir,
inner: std::sync::Mutex::new(cache),
@@ -102,7 +103,7 @@ impl Repo {
/// A thread-local gitoxide handle; reopened when configuration or packed refs change.
/// gitoxide's packed-ref snapshot only reloads for a newer mtime, which a replacement may preserve.
pub(crate) fn gix(&self) -> IdeResult<gix::Repository> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
if !self.execution_allowed.load(std::sync::atomic::Ordering::Acquire) {
return gix::open_opts(&self.git_dir, gix::open::Options::default().filter_config_section(|_| false))
.map_err(gx);
@@ -128,7 +129,7 @@ impl Repo {
/// Repository-relative path with `/` separators. Accepts absolute paths inside the
/// worktree or paths already relative to it.
pub(crate) fn rel_path(&self, path: &Path) -> IdeResult<String> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
Ok(self.index_spelling(self.given_rel_path(path)?))
}
@@ -217,7 +218,7 @@ impl Repo {
/// Absolute path for a repository-relative path.
pub(crate) fn abs_path(&self, rel: &str) -> PathBuf {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
let mut p = self.root.clone();
for part in rel.split('/').filter(|s| !s.is_empty()) {
p.push(part);
+2 -2
Переглянути файл
@@ -200,7 +200,7 @@ pub(crate) fn unshelve(r: &Repo, shelf: &Path, id: &str, remove: bool) -> IdeRes
}
pub fn unshelve_path(r: &Repo, shelf: &Path, id: &str, remove: bool, path: Option<&str>) -> IdeResult<ApplyOutcome> {
let _scope = crate::ExecutionScope::enter(r.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = r.execution_scope();
let patch = selected_patch(shelf, id, path)?;
let outcome = crate::patch::apply(r, &patch)?;
if remove && outcome.conflicts.is_empty() {
@@ -292,7 +292,7 @@ pub fn delete_path(shelf: &Path, id: &str, path: Option<&str>) -> IdeResult<()>
/// Reconstruct each side in a throwaway index; neither HEAD nor the working files are used.
pub fn diff_files(r: &Repo, shelf: &Path, id: &str) -> IdeResult<Vec<ShelfDiffFile>> {
let _scope = crate::ExecutionScope::enter(r.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = r.execution_scope();
let patch = patch_of(shelf, id)?;
let mut out = Vec::new();
for (section, file) in sections(&patch) {
+2 -2
Переглянути файл
@@ -17,7 +17,7 @@ const UNCOMMITTED_AUTHOR: &str = "Not Committed Yet";
impl Repo {
pub(crate) fn rel_paths(&self, paths: &[PathBuf]) -> IdeResult<Vec<String>> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
paths
.iter()
.map(|p| {
@@ -28,7 +28,7 @@ impl Repo {
}
pub(crate) fn has_head(&self) -> IdeResult<bool> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let _scope = self.execution_scope();
let repo = self.gix()?;
Ok(!repo.head().map_err(gx)?.is_unborn())
}
+5
Переглянути файл
@@ -355,6 +355,11 @@ impl SettingsStore {
self.effective.read().clone()
}
/// Reads part of the effective settings without copying all of them.
pub fn read_effective<T>(&self, read: impl FnOnce(&Settings) -> T) -> T {
read(&self.effective.read())
}
/// Settings defined in `scope`'s file alone (without merging the other layer).
pub fn layer(&self, scope: SettingsScope) -> Settings {
let mut merged = defaults_json();
+4 -4
Переглянути файл
@@ -34,7 +34,7 @@ For a recognized file, support comes in layers:
A language can list more than one server:
- **Alternatives** (shown as `a → b` in the table below): only the first one that is installed runs. Python, for example, uses basedpyright, and falls back to pyright, ty or pyrefly only when basedpyright is missing. In **Settings › Languages & Frameworks › Language Servers** you can pick one of them or set the choice to **Automatic** (the first one available).
- **Additions** (shown as `+ b`): run next to the main server, usually only in projects that use them. Ruff joins basedpyright in projects with a Ruff configuration; oxlint joins vtsls in projects with an oxlint configuration; Biome joins the JavaScript, TypeScript, JSON, CSS and GraphQL servers in projects with a Biome configuration or installation; the Angular, Laravel and Tailwind CSS servers join in Angular, Laravel and Tailwind CSS projects.
- **Additions** (shown as `+ b`): run next to the main server, usually only in projects that use them. Ruff joins basedpyright in projects with a Ruff configuration; oxlint joins vtsls in projects with an oxlint configuration; Stylelint joins the CSS, SCSS and Less server in projects with a Stylelint configuration (`.stylelintrc*`, `stylelint.config.*` or `stylelint` in `package.json`), running the project's own `stylelint` (**Fix Stylelint Problems** in the editor's context menu applies its fixes); Biome joins the JavaScript, TypeScript, JSON, CSS and GraphQL servers in projects with a Biome configuration or installation; the Angular, Laravel and Tailwind CSS servers join in Angular, Laravel and Tailwind CSS projects.
## Installing language servers and debuggers
@@ -103,7 +103,7 @@ The table lists every built-in language definition. Server and debugger names in
| C++ | `cpp` | `.cpp`, `.cc`, `.cxx`, `.c++`, `.hpp`, … | Yes | Yes | **clangd** | lldb-dap |
| Clojure | `clojure` | `.clj`, `.cljs`, `.cljc`, `.cljd`, `.edn`, … | Yes | — | **clojure-lsp** | — |
| CMake | `cmake` | `.cmake` | Yes | Yes | **neocmakelsp** → cmake-language-server | — |
| CSS | `css` | `.css`, `.pcss`, `.postcss` | Yes | Yes | **vscode-css-language-server** + **biome** | — |
| CSS | `css` | `.css`, `.pcss`, `.postcss` | Yes | Yes | **vscode-css-language-server** + **biome** + **stylelint** | — |
| D | `d` | `.d`, `.di` | Yes | — | serve-d | — |
| Dart | `dart` | `.dart` | Yes | Yes | dart | dart |
| Diff | `diff` | `.diff`, `.patch`, `.rej` | Yes | — | — | — |
@@ -137,7 +137,7 @@ The table lists every built-in language definition. Server and debugger names in
| Julia | `julia` | `.jl` | Yes | — | julia-languageserver | — |
| Kotlin | `kotlin` | `.kt`, `.kts` | Yes | Yes | **kotlin-lsp** → **kotlin-language-server** → **kmp-lsp** | **kotlin-debug-adapter** |
| LaTeX | `latex` | `.tex`, `.ltx`, `.sty`, `.cls`, `.dtx`, … | Yes | — | **texlab** | — |
| Less | `less` | `.less` | Yes | — | **vscode-css-language-server** | — |
| Less | `less` | `.less` | Yes | — | **vscode-css-language-server** + **stylelint** | — |
| Log | `log` | `.log` | Yes | — | — | — |
| Lua | `lua` | `.lua`, `.luau`, `.rockspec` | Yes | Yes | **lua-language-server** | — |
| Makefile | `makefile` | `.mk`, `.mak`, `.make` | Yes | Yes | — | — |
@@ -161,7 +161,7 @@ The table lists every built-in language definition. Server and debugger names in
| Rust | `rust` | `.rs` | Yes | Yes | **rust-analyzer** | **codelldb** |
| Sass | `sass` | `.sass` | Yes | — | — | — |
| Scala | `scala` | `.scala`, `.sc`, `.sbt`, `.mill` | Yes | Yes | metals | — |
| SCSS | `scss` | `.scss` | Yes | — | **vscode-css-language-server** | — |
| SCSS | `scss` | `.scss` | Yes | — | **vscode-css-language-server** + **stylelint** | — |
| Shell Script | `shellscript` | `.sh`, `.bash`, `.zsh`, `.ksh`, `.ash`, … | Yes | Yes | **bash-language-server** | **bash-debug** |
| Slint | `slint` | `.slint` | Yes | — | **slint-lsp** | — |
| SQL | `sql` | `.sql`, `.ddl`, `.dml`, `.psql`, `.pgsql`, … | Yes | — | **sqls** | — |
+4 -4
Переглянути файл
@@ -32,7 +32,7 @@ OpenIDEA 用一个小的定义文件 `languages/<id>.toml` 描述每种语言:
一种语言可以配置多个服务器:
- **备选**(下表中写作 `a → b`):只运行第一个已安装的。例如 Python 默认用 basedpyright,只有它缺失时才退回 pyright、ty 或 pyrefly。在 **设置 › 语言和框架 › 语言服务器** 中可以指定其中一个,或选 **自动**(使用第一个可用的)。
- **附加**(写作 `+ b`):和主服务器同时运行,通常只在用到它的项目中启用。带 Ruff 配置的项目里 Ruff 与 basedpyright 一起运行;带 oxlint 配置的项目里 oxlint 与 vtsls 一起运行;带 Biome 配置或安装了 Biome 的项目里 Biome 与 JavaScript、TypeScript、JSON、CSS 和 GraphQL 的服务器一起运行;Angular、Laravel 和 Tailwind CSS 项目里分别加上 Angular、Laravel 和 Tailwind CSS 的服务器。
- **附加**(写作 `+ b`):和主服务器同时运行,通常只在用到它的项目中启用。带 Ruff 配置的项目里 Ruff 与 basedpyright 一起运行;带 oxlint 配置的项目里 oxlint 与 vtsls 一起运行;带 Stylelint 配置(`.stylelintrc*`、`stylelint.config.*` 或 `package.json` 中的 `stylelint`)的项目里 Stylelint 与 CSS、SCSS、Less 的服务器一起运行,使用项目自己的 `stylelint`(编辑器右键菜单中的 **修复 Stylelint 问题** 应用它的修复);带 Biome 配置或安装了 Biome 的项目里 Biome 与 JavaScript、TypeScript、JSON、CSS 和 GraphQL 的服务器一起运行;Angular、Laravel 和 Tailwind CSS 项目里分别加上 Angular、Laravel 和 Tailwind CSS 的服务器。
## 安装语言服务器和调试器
@@ -98,7 +98,7 @@ IDE 安装工具从不需要 `sudo`。工具装在本地数据目录下 IDE 自
| C++ | `cpp` | `.cpp`, `.cc`, `.cxx`, `.c++`, `.hpp`, … | 是 | 是 | **clangd** | lldb-dap |
| Clojure | `clojure` | `.clj`, `.cljs`, `.cljc`, `.cljd`, `.edn`, … | 是 | — | **clojure-lsp** | — |
| CMake | `cmake` | `.cmake` | 是 | 是 | **neocmakelsp** → cmake-language-server | — |
| CSS | `css` | `.css`, `.pcss`, `.postcss` | 是 | 是 | **vscode-css-language-server** + **biome** | — |
| CSS | `css` | `.css`, `.pcss`, `.postcss` | 是 | 是 | **vscode-css-language-server** + **biome** + **stylelint** | — |
| D | `d` | `.d`, `.di` | 是 | — | serve-d | — |
| Dart | `dart` | `.dart` | 是 | 是 | dart | dart |
| Diff | `diff` | `.diff`, `.patch`, `.rej` | 是 | — | — | — |
@@ -132,7 +132,7 @@ IDE 安装工具从不需要 `sudo`。工具装在本地数据目录下 IDE 自
| Julia | `julia` | `.jl` | 是 | — | julia-languageserver | — |
| Kotlin | `kotlin` | `.kt`, `.kts` | 是 | 是 | **kotlin-lsp** → **kotlin-language-server** → **kmp-lsp** | **kotlin-debug-adapter** |
| LaTeX | `latex` | `.tex`, `.ltx`, `.sty`, `.cls`, `.dtx`, … | 是 | — | **texlab** | — |
| Less | `less` | `.less` | 是 | — | **vscode-css-language-server** | — |
| Less | `less` | `.less` | 是 | — | **vscode-css-language-server** + **stylelint** | — |
| Log | `log` | `.log` | 是 | — | — | — |
| Lua | `lua` | `.lua`, `.luau`, `.rockspec` | 是 | 是 | **lua-language-server** | — |
| Makefile | `makefile` | `.mk`, `.mak`, `.make` | 是 | 是 | — | — |
@@ -156,7 +156,7 @@ IDE 安装工具从不需要 `sudo`。工具装在本地数据目录下 IDE 自
| Rust | `rust` | `.rs` | 是 | 是 | **rust-analyzer** | **codelldb** |
| Sass | `sass` | `.sass` | 是 | — | — | — |
| Scala | `scala` | `.scala`, `.sc`, `.sbt`, `.mill` | 是 | 是 | metals | — |
| SCSS | `scss` | `.scss` | 是 | — | **vscode-css-language-server** | — |
| SCSS | `scss` | `.scss` | 是 | — | **vscode-css-language-server** + **stylelint** | — |
| Shell Script | `shellscript` | `.sh`, `.bash`, `.zsh`, `.ksh`, `.ash`, … | 是 | 是 | **bash-language-server** | **bash-debug** |
| Slint | `slint` | `.slint` | 是 | — | **slint-lsp** | — |
| SQL | `sql` | `.sql`, `.ddl`, `.dml`, `.psql`, `.pgsql`, … | 是 | — | **sqls** | — |
+52
Переглянути файл
@@ -715,6 +715,58 @@ test("rename keeps the typed name, uses the editor font and shows long preview n
await expect.poll(() => ipcCalls(page, "apply_workspace_edit")).toHaveLength(1);
});
test("intentions separate quick fixes from other actions and navigate across the divider", async ({
workbench: page,
}) => {
const editor = await openSample(page);
const fix = "Correct the Order type";
const refactor = "Extract the order value";
await page.evaluate(
({ file, edit, fix, refactor }) => {
const action = (title: string, kind: string, newText: string) => ({
title,
kind,
isPreferred: false,
disabledReason: null,
edit: { files: [{ kind: "edit", path: file, edits: [{ range: edit, new_text: newText }] }] },
command: null,
data: null,
server: 1,
});
window.__ipc.handlers.lsp_code_actions = () => [
action(refactor, "refactor.extract", "ExtractedOrder"),
action(fix, "quickfix", "CorrectOrder"),
];
window.__ipc.handlers.lsp_execute_code_action = () => [];
},
{ file: FILE, edit: range(20, 19, 24), fix, refactor },
);
await caretAt(editor, page, "val order: Order", "Order ");
await page.keyboard.press("Alt+Enter");
const popup = page.getByRole("dialog", { name: "Intentions", exact: true });
const list = popup.getByRole("listbox", { name: "Intentions" });
const divider = list.locator("[class*=listDivider]");
const preview = popup.locator('[aria-label="Preview"] pre');
await expect(list.getByRole("option", { name: fix })).toBeVisible();
await page.keyboard.type("order");
await expect(list.getByRole("option")).toHaveText([fix, refactor]);
await expect(divider).toHaveCount(1);
await expect(list.getByRole("option", { name: fix })).toHaveAttribute("aria-selected", "true");
await expect(preview).toContainText("CorrectOrder");
await list.press("ArrowDown");
await expect(list.getByRole("option", { name: refactor })).toHaveAttribute("aria-selected", "true");
await expect(preview).toContainText("ExtractedOrder");
for (const _character of "order") await list.press("Backspace");
await page.keyboard.type("extract");
await expect(list.getByRole("option")).toHaveText([refactor]);
await expect(divider).toHaveCount(0);
await list.press("Enter");
await expect(popup).toBeHidden();
await expect.poll(() => ipcCalls(page, "lsp_execute_code_action")).toHaveLength(1);
});
test("intention previews fit narrow windows and wrap long code lines", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1600, height: 900 });
const editor = await openSample(page);
+151 -34
Переглянути файл
@@ -4,61 +4,178 @@ const amountName = "regionalSettlementAmountFromExternalProcessorBeforeRounding"
const routingName = "settlementRoutingReferenceForCrossBorderReconciliation";
const routingText = "APR-2026 / eu-west / batch-701 / settlement complete";
const routingValue = "'" + routingText + "'";
const invalidValueMessage = "The settlement amount must be a valid decimal expression.";
test("keeps values and their full-value action readable in a narrow debugger", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1220, height: 760 });
test.describe("a paused session with editable values", () => {
test.beforeEach(async ({ workbench: page }) => {
await page.setViewportSize({ width: 1220, height: 760 });
await stubDesktop(page);
await page.evaluate(
async ({ amountName, routingName, routingValue, invalidValueMessage }) => {
const debugModule = "/src/features/debugger/state.ts";
const layoutModule = "/src/workbench/toolwindows/store.ts";
const servicesModule = "/src/workbench/contributions.ts";
const { adoptSession } = await import(/* @vite-ignore */ debugModule);
const { moveToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ layoutModule);
const { toolWindowService } = await import(/* @vite-ignore */ servicesModule);
const h = window.__ipc.handlers;
let amountValue = "47.74";
const amount = () => ({
name: amountName,
value: amountValue,
typeName: "float",
variablesReference: 0,
evaluateName: amountName,
});
h.debug_scopes = () => [{ name: "Locals", variablesReference: 100, expensive: false }];
h.debug_variables = () => [
amount(),
{ name: routingName, value: routingValue, typeName: "str", variablesReference: 0, evaluateName: routingName },
];
h.debug_set_variable = ({ value }) => {
if (value === "invalid") throw { kind: "invalid", message: invalidValueMessage, detail: null };
amountValue = String(value);
return amount();
};
adoptSession(91, {
name: "Checkout",
adapter: "debugpy",
status: "paused",
selectedFrame: 11,
frames: [{ id: 11, name: "checkout", path: null, line: 0, column: 0, presentationHint: null }],
});
moveToolWindow("debug", "right");
setToolWindowSize("right", 390);
toolWindowService().show("debug", true);
},
{ amountName, routingName, routingValue, invalidValueMessage },
);
const debug = page.getByRole("region", { name: "Debug", exact: true });
await debug.getByRole("tab", { name: "Threads & Variables", exact: true }).click();
});
test("keeps values and their full-value action readable in a narrow debugger", async ({ workbench: page }) => {
const debug = page.getByRole("region", { name: "Debug", exact: true });
const amount = debug.getByText("47.74", { exact: true });
await expect
.poll(() => amount.evaluate((el) => el.clientWidth > 0 && el.scrollWidth <= el.clientWidth + 1))
.toBe(true);
const routing = debug.getByRole("treeitem").filter({ hasText: routingName });
const show = routing.getByTitle("Show", { exact: true });
await expect(show).toBeInViewport({ ratio: 1 });
await show.click();
const dialog = page.getByRole("dialog", { name: `Value of ${routingName}` });
await expect(dialog.getByText(routingText, { exact: true })).toBeVisible();
await page.keyboard.press("Escape");
await expect(dialog).toBeHidden();
await page.setViewportSize({ width: 1640, height: 760 });
await page.evaluate(async () => {
const layoutModule = "/src/workbench/toolwindows/store.ts";
const { moveToolWindow } = await import(/* @vite-ignore */ layoutModule);
moveToolWindow("debug", "bottom");
});
await expect(show).toBeHidden();
await expect
.poll(() =>
routing.getByText(routingValue, { exact: true }).evaluate((el) => el.scrollWidth <= el.clientWidth + 1),
)
.toBe(true);
});
test("keeps the variable label and input in place when editing a value", async ({ workbench: page }) => {
const debug = page.getByRole("region", { name: "Debug", exact: true });
const row = debug.getByRole("treeitem").filter({ hasText: amountName });
const name = row.getByText(amountName, { exact: true });
await row.click();
const nameBefore = (await name.boundingBox())!;
const equal = row.getByText("=", { exact: true });
const equalBefore = (await equal.boundingBox())!;
const color = await name.evaluate((el) => getComputedStyle(el).color);
await page.keyboard.press("F2");
const input = row.getByRole("textbox", { name: `New value of ${amountName}` });
await expect(input).toBeFocused();
await expect(input).toHaveValue("47.74");
await expect(name).toHaveCSS("color", color);
expect((await name.boundingBox())!.x).toBeCloseTo(nameBefore.x, 0);
expect((await equal.boundingBox())!.x).toBeCloseTo(equalBefore.x, 0);
await expect(row.locator("svg")).toHaveCount(1);
await input.fill("invalid");
await input.press("Enter");
await expect(input).toHaveAttribute("aria-invalid", "true");
await expect(input).toHaveAttribute("title", invalidValueMessage);
await expect(input).toBeInViewport({ ratio: 1 });
expect((await input.boundingBox())!.width).toBeGreaterThan(60);
expect((await equal.boundingBox())!.x).toBeCloseTo(equalBefore.x, 0);
await input.press("Escape");
await expect(input).toBeHidden();
await expect(row).toContainText("47.74");
await page.keyboard.press("F2");
await expect(input).toHaveValue("47.74");
await input.fill("48.25");
await input.press("Enter");
await expect(input).toBeHidden();
await expect(row).toContainText("48.25");
});
});
test("keeps a decimal value legible beside a long runtime type", async ({ workbench: page }) => {
const name = "dailySettlementTotal";
const type = "ExactSettlementAmountForCrossBorderReconciliation";
const value = "12486245.8067";
const countName = "pendingInvoices";
await page.setViewportSize({ width: 1100, height: 720 });
await stubDesktop(page);
await page.evaluate(
async ({ amountName, routingName, routingValue }) => {
async ({ name, type, value, countName }) => {
const debugModule = "/src/features/debugger/state.ts";
const layoutModule = "/src/workbench/toolwindows/store.ts";
const servicesModule = "/src/workbench/contributions.ts";
const serviceModule = "/src/workbench/contributions.ts";
const { adoptSession } = await import(/* @vite-ignore */ debugModule);
const { moveToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ layoutModule);
const { toolWindowService } = await import(/* @vite-ignore */ servicesModule);
const h = window.__ipc.handlers;
h.debug_scopes = () => [{ name: "Locals", variablesReference: 100, expensive: false }];
h.debug_variables = () => [
{ name: amountName, value: "47.74", typeName: "float", variablesReference: 0, evaluateName: amountName },
{ name: routingName, value: routingValue, typeName: "str", variablesReference: 0, evaluateName: routingName },
const { toolWindowService } = await import(/* @vite-ignore */ serviceModule);
window.__ipc.handlers.debug_scopes = () => [{ name: "Locals", variablesReference: 100, expensive: false }];
window.__ipc.handlers.debug_variables = () => [
{ name, value, typeName: type, variablesReference: 0, evaluateName: name },
{ name: countName, value: "327", typeName: "int", variablesReference: 0, evaluateName: countName },
];
adoptSession(91, {
name: "Checkout",
adoptSession(92, {
name: "Settlement",
adapter: "debugpy",
status: "paused",
selectedFrame: 11,
frames: [{ id: 11, name: "checkout", path: null, line: 0, column: 0, presentationHint: null }],
frames: [{ id: 11, name: "settle", path: null, line: 0, column: 0, presentationHint: null }],
});
moveToolWindow("debug", "right");
setToolWindowSize("right", 390);
setToolWindowSize("right", 280);
toolWindowService().show("debug", true);
},
{ amountName, routingName, routingValue },
{ name, type, value, countName },
);
const debug = page.getByRole("region", { name: "Debug", exact: true });
await debug.getByRole("tab", { name: "Threads & Variables", exact: true }).click();
const amount = debug.getByText("47.74", { exact: true });
await expect
.poll(() => amount.evaluate((el) => el.clientWidth > 0 && el.scrollWidth <= el.clientWidth + 1))
.toBe(true);
const routing = debug.getByRole("treeitem").filter({ hasText: routingName });
const show = routing.getByTitle("Show", { exact: true });
await expect(show).toBeInViewport({ ratio: 1 });
await show.click();
const dialog = page.getByRole("dialog", { name: `Value of ${routingName}` });
await expect(dialog.getByText(routingText, { exact: true })).toBeVisible();
await page.keyboard.press("Escape");
await expect(dialog).toBeHidden();
const variable = debug.getByRole("treeitem").filter({ hasText: name });
const amount = variable.getByText(value, { exact: true });
const annotation = variable.getByTitle(`{${type}}`, { exact: true });
await expect(amount).toBeVisible();
await expect.poll(() => amount.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await expect(variable.getByTitle("Show", { exact: true })).toBeHidden();
await expect(annotation).toBeVisible();
await page.setViewportSize({ width: 1640, height: 760 });
const shortValueName = debug.getByText(countName, { exact: true });
await expect.poll(() => shortValueName.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await page.setViewportSize({ width: 1440, height: 760 });
await page.evaluate(async () => {
const layoutModule = "/src/workbench/toolwindows/store.ts";
const { moveToolWindow } = await import(/* @vite-ignore */ layoutModule);
const { moveToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ layoutModule);
moveToolWindow("debug", "bottom");
setToolWindowSize("bottom", 310);
});
await expect(show).toBeHidden();
await expect
.poll(() => routing.getByText(routingValue, { exact: true }).evaluate((el) => el.scrollWidth <= el.clientWidth + 1))
.toBe(true);
await expect.poll(() => annotation.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
});
+46
Переглянути файл
@@ -69,3 +69,49 @@ test("the bottom single row keeps a long selected tab visible alongside the hidd
await pane.getByRole("tab", { name: shortFile, exact: true }).press("End");
await expectCloseToFit(tab);
});
test("same-name tabs keep the filename beside a shortened directory", async ({ workbench: page }) => {
const filename = "AllocationRule.ts";
const first = "qa";
const second = "backoffice-reconciliation";
await openSplit(page, [`${first}/${filename}`, `${second}/${filename}`], "top");
await page.setViewportSize({ width: 900, height: 760 });
const pane = page.locator("section[data-pane-id]").filter({
has: page.getByRole("tab").filter({ hasText: second }),
});
const selected = pane.getByRole("tab").filter({ hasText: second });
await expect(selected).toHaveText(`${second}/${filename}`);
await expectCloseToFit(selected);
const directory = selected.getByText(`${second}/`, { exact: true });
const name = selected.getByText(filename, { exact: true });
await expect.poll(() => directory.evaluate((el) => el.clientWidth > 0 && el.scrollWidth > el.clientWidth)).toBe(true);
await expect
.poll(() =>
name.evaluate((el) => {
const text = document.createRange();
text.selectNodeContents(el);
return el.getBoundingClientRect().width >= text.getBoundingClientRect().width;
}),
)
.toBe(true);
await pane.getByRole("button", { name: "Show Hidden Tabs" }).click();
const picker = page.getByRole("grid", { name: "Hidden Editor Tabs" });
await expect(picker.getByRole("gridcell").filter({ hasText: `${first}/${filename}` })).toBeVisible();
await page.keyboard.press("Enter");
const firstTab = pane.getByRole("tab").filter({ hasText: first });
await expectCloseToFit(firstTab);
await expect
.poll(() =>
firstTab.getByText(`${first}/`, { exact: true }).evaluate((el) => {
const text = document.createRange();
text.selectNodeContents(el);
return Math.abs(el.clientWidth - text.getBoundingClientRect().width);
}),
)
.toBeLessThanOrEqual(1);
await firstTab.locator("..").getByRole("button", { name: "Close Tab", exact: true }).click();
await expect(page.getByRole("tab", { name: filename, exact: true })).toHaveAttribute("aria-selected", "true");
});
+2 -2
Переглянути файл
@@ -117,7 +117,7 @@ test("fits a wide graph and saved columns without horizontal scrolling", async (
expect(await list.evaluate((element) => element.scrollLeft)).toBe(0);
});
test("keeps ref names visible when a long commit subject competes for space", async ({ workbench: page }) => {
test("keeps expanded ref names visible when a long commit subject competes for space", async ({ workbench: page }) => {
const branch = "origin/feature/workspace-settings";
const tag = "v2.1";
const summary = "Keep workspace settings and commit references visible ".repeat(4).trim();
@@ -127,7 +127,7 @@ test("keeps ref names visible when a long commit subject competes for space", as
const options = "/src/features/vcs/logOptions.ts";
const { useGitLog } = await import(/* @vite-ignore */ log);
const { useLogOptions } = await import(/* @vite-ignore */ options);
useLogOptions.setState({ tagNames: true });
useLogOptions.setState({ tagNames: true, compactRefs: false });
const [first, ...rest] = useGitLog.getState().commits;
useGitLog.setState({ commits: [{ ...first, summary, refs: [branch, `tag: ${tag}`] }, ...rest] });
},
+95
Переглянути файл
@@ -112,6 +112,57 @@ test("Git Log separates commit message typography from compact metadata", async
await expect(author).toHaveCSS("font-size", "12px");
});
test("compact Git Log refs give the subject room on either side", async ({ workbench: page }) => {
await page.setViewportSize({ width: 630, height: 720 });
const refSubject = "Reconcile shipping credits";
const longReference = "release-quarterly-settlement-and-backoffice-invoice-reconciliation";
await page.evaluate(
async ({ refSubject, longReference }) => {
const optionsModule = "/src/features/vcs/logOptions.ts";
const logModule = "/src/features/vcs/logStore.ts";
const { setLogOptions } = await import(/* @vite-ignore */ optionsModule);
const { useGitLog } = await import(/* @vite-ignore */ logModule);
setLogOptions({ showBranches: false, showDetails: false });
const [first, ...rest] = useGitLog.getState().commits;
useGitLog.setState({
commits: [{ ...first, summary: refSubject, message: refSubject, refs: [longReference] }, ...rest],
});
},
{ refSubject, longReference },
);
const row = page.getByRole("listbox", { name: "Commits" }).getByRole("option").filter({ hasText: refSubject });
const subject = row.getByText(refSubject, { exact: true });
const ref = row.getByTitle(longReference, { exact: true });
const expectLayout = async () => {
await expect
.poll(() =>
subject.evaluate((el) => {
const text = document.createRange();
text.selectNodeContents(el);
return el.getBoundingClientRect().width + 0.02 >= text.getBoundingClientRect().width;
}),
)
.toBe(true);
await expect
.poll(() =>
ref.evaluate((el) => {
const refs = el.parentElement!;
return refs.clientWidth / refs.parentElement!.clientWidth;
}),
)
.toBeLessThanOrEqual(0.34);
await expect(ref).toHaveCSS("font-size", "12px");
await expect(subject).toHaveCSS("font-size", "13px");
};
await expectLayout();
await expect.poll(async () => (await subject.boundingBox())!.x < (await ref.boundingBox())!.x).toBe(true);
await page.getByRole("toolbar", { name: "Log filters" }).getByRole("button", { name: "View Options" }).click();
await page.getByRole("menuitemcheckbox", { name: "References on the Left" }).click();
await expectLayout();
await expect.poll(async () => (await subject.boundingBox())!.x > (await ref.boundingBox())!.x).toBe(true);
});
test("a second click on a Git Log toolbar button closes its popup", async ({ workbench: page }) => {
const toolbar = page.getByRole("toolbar", { name: "Log filters" });
const branchPopup = page.getByRole("dialog", { name: "Filter by Branch" });
@@ -174,6 +225,50 @@ test("Git Log keeps filters and actions inside the commit pane at the minimum wi
await expect(page.getByRole("menuitem", { name: "Paths" })).toBeVisible();
});
test("long Git Log filter values shorten inside their buttons", async ({ workbench: page }) => {
const branchName = "feature/quarterly-settlement-and-backoffice-invoice-reconciliation";
await page.setViewportSize({ width: 1120, height: 720 });
await page.evaluate(async (branch) => {
const logModule = "/src/features/vcs/logStore.ts";
const optionsModule = "/src/features/vcs/logOptions.ts";
const { setLogBranches } = await import(/* @vite-ignore */ logModule);
const { setLogOptions } = await import(/* @vite-ignore */ optionsModule);
setLogOptions({ showBranches: false, showDetails: false });
setLogBranches([branch]);
}, branchName);
const toolbar = page.getByRole("toolbar", { name: "Log filters" });
const branch = toolbar.getByRole("button", { name: `Branch: ${branchName}`, exact: true });
const value = branch.getByText(branchName, { exact: true });
const clear = toolbar.getByRole("button", { name: "Clear Branch filter", exact: true });
for (const width of [1120, 620]) {
await page.setViewportSize({ width, height: 720 });
await expect(branch).toBeVisible();
await expect(value).toHaveCSS("text-overflow", "ellipsis");
expect(
await value.evaluate((label) => {
const bounds = label.getBoundingClientRect();
const button = label.closest("button")!.getBoundingClientRect();
return label.scrollWidth > label.clientWidth && bounds.width > 0 && bounds.right <= button.right;
}),
).toBe(true);
await expect(branch).toHaveAttribute("title", branchName);
await clear.click({ trial: true });
}
await page.setViewportSize({ width: 400, height: 560 });
// The overflow is measured after the resize: open the menu once the filter has moved into it.
await expect(branch).toBeHidden();
await toolbar.getByRole("button", { name: "More Filters" }).click();
await expect(page.getByRole("menuitem", { name: `Branch: ${branchName}`, exact: true })).toBeVisible();
await page.keyboard.press("Escape");
await page.setViewportSize({ width: 620, height: 720 });
await clear.click();
await expect(toolbar.getByRole("button", { name: "Branch", exact: true })).toBeVisible();
await expect(clear).toBeHidden();
});
test("Git Log puts affected changes on the changed-files toolbar and groups preview options", async ({
workbench: page,
}) => {
+23 -1
Переглянути файл
@@ -176,7 +176,29 @@ test("Push keeps commit subjects and changed files readable in a narrow window",
await expect(input).toHaveValue("main");
await expect(dialog.getByRole("button", { name: "Push", exact: true })).toBeInViewport();
const details = dialog.getByRole("region", { name: "Commit details" });
await expect(details).toContainText("Keep the new totals consistent with receipts.");
await page.evaluate(async () => {
const project = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ project);
const { settings } = useProject.getState();
useProject.setState({
settings: {
...settings,
editor: { ...settings?.editor, fontFamily: "Consolas", fontSize: 18, fontWeight: 400, boldFontWeight: 700 },
},
});
});
const messageSubject = details.getByText(OUTGOING, { exact: true });
const messageBody = details.getByText("Keep the new totals consistent with receipts.", { exact: true });
await expect(messageSubject).toHaveCSS("font-weight", "700");
await expect(messageBody).toHaveCSS("font-weight", "400");
await expect(messageSubject).toHaveCSS("font-size", "18px");
await expect(messageBody).toHaveCSS("font-size", "18px");
await expect(messageBody).toHaveCSS("font-family", /Consolas/);
const metadata = details.getByText(/Sam Rivera <sam@example\.com>/);
await expect(metadata).toHaveCSS("font-size", "12px");
await metadata.scrollIntoViewIfNeeded();
await expect(metadata).toBeInViewport();
expect(await details.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await expect
.poll(async () => {
const [tree, message] = await Promise.all([files.boundingBox(), details.boundingBox()]);
+39
Переглянути файл
@@ -93,3 +93,42 @@ test("Recent Locations keeps all snippet lines visible when the editor font grow
await expect(row.getByText("changed", { exact: true })).toBeInViewport({ ratio: 1 });
await expect(filter).toBeFocused();
});
test("Recent Locations shows each file name once with its parent directory", async ({ workbench: page }) => {
await stubDesktop(page);
await page.evaluate(async () => {
const tracking = "/src/features/search/common/tracking.ts";
const { useTracking } = await import(/* @vite-ignore */ tracking);
const now = Date.now();
useTracking.setState({
locations: [
["README.md", "# Shop API"],
["packages/billing/Routes.ts", "registerBillingRoutes();"],
["packages/checkout/Routes.ts", "registerCheckoutRoutes();"],
].map(([path, snippet], index) => ({
path: `/dev/acme-api/${path}`,
line: 0,
col: 0,
changed: false,
time: now - index * 60000,
snippet: [snippet],
snippetStart: 0,
})),
});
});
await openRecent(page, "recentLocations");
const dialog = page.getByRole("dialog", { name: "Recent Locations", exact: true });
const rows = dialog.getByRole("option");
await expect(rows).toHaveCount(3);
await expect(rows.filter({ hasText: "# Shop API" }).getByText("README.md", { exact: true })).toHaveCount(1);
const billing = rows.filter({ hasText: "registerBillingRoutes();" });
const checkout = rows.filter({ hasText: "registerCheckoutRoutes();" });
await expect(billing.getByText("packages/billing", { exact: true })).toBeVisible();
await expect(checkout.getByText("packages/checkout", { exact: true })).toBeVisible();
await expect(checkout.getByTitle("packages/checkout/Routes.ts", { exact: true })).toBeVisible();
await dialog.getByRole("textbox", { name: "Filter recent locations" }).fill("packages/checkout");
await expect(rows).toHaveCount(1);
await expect(rows.first()).toContainText("registerCheckoutRoutes();");
});
+63
Переглянути файл
@@ -0,0 +1,63 @@
import { expect, test } from "./fixtures";
test("the workspace refactoring preview separates filenames from directories and keeps outcomes readable", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 420, height: 620 });
await page.evaluate(async () => {
const popupPath = "/src/editor/lsp/popupStore.ts";
const editPath = "/src/editor/lsp/workspaceEdit.ts";
const { openPopup } = await import(/* @vite-ignore */ popupPath);
const { summarizeWorkspaceEdit } = await import(/* @vite-ignore */ editPath);
const root = "/dev/acme-api";
const edit = {
range: { start: { line: 0, col: 0 }, end: { line: 0, col: 9 } },
new_text: "postInvoice",
};
openPopup({
kind: "preview",
title: "Rename 'saveOrder' to 'postInvoice'",
summary: summarizeWorkspaceEdit({
files: [
{ kind: "edit", path: `${root}/README.md`, edits: [edit] },
{ kind: "edit", path: `${root}/packages/billing/src/Routes.ts`, edits: [edit, edit] },
{ kind: "edit", path: `${root}/packages/checkout/src/Routes.ts`, edits: [edit] },
{
kind: "rename",
from: `${root}/packages/checkout/src/Invoice.ts`,
to: `${root}/packages/checkout/src/InvoiceReconciliationForInternationalOrders.ts`,
},
],
}),
renameThemeClasses: "",
confirmLabel: "Do Refactor",
onConfirm: () => {
document.body.dataset.refactorConfirmed = "true";
},
});
});
const dialog = page.getByRole("dialog", { name: "Rename 'saveOrder' to 'postInvoice'" });
const rows = dialog.getByRole("list", { name: "Changes" }).getByRole("listitem");
await expect(rows).toHaveCount(4);
await expect(dialog.getByText("4 occurrences in 4 files")).toBeVisible();
const root = rows.filter({ hasText: "README.md" });
await expect(root.getByText("README.md", { exact: true })).toHaveCount(1);
const billing = rows.filter({ hasText: "2 occurrences" });
await expect(billing.getByText("Routes.ts", { exact: true })).toBeVisible();
await expect(billing.getByText("packages/billing/src", { exact: true })).toBeVisible();
await expect(billing.getByTitle("packages/billing/src/Routes.ts", { exact: true })).toBeVisible();
const checkout = rows.filter({ hasText: "packages/checkout/src" }).filter({ hasText: "Routes.ts" });
await expect(checkout.getByText("packages/checkout/src", { exact: true })).toBeVisible();
const rename = rows.filter({ hasText: "Invoice.ts" });
const target = rename.getByText("→ InvoiceReconciliationForInternationalOrders.ts", { exact: true });
await expect(target).toBeVisible();
await expect(target).toHaveAttribute("title", "packages/checkout/src/InvoiceReconciliationForInternationalOrders.ts");
expect((await target.boundingBox())!.width).toBeGreaterThan(35);
await expect(dialog.getByRole("button", { name: "Do Refactor", exact: true })).toBeInViewport();
await dialog.getByRole("button", { name: "Do Refactor", exact: true }).click();
await expect(dialog).toBeHidden();
await expect(page.locator("body")).toHaveAttribute("data-refactor-confirmed", "true");
});
+125
Переглянути файл
@@ -76,6 +76,73 @@ test("⌃R runs the selected configuration and shows its output and exit", async
expect(started).toMatchObject({ config: { id: "npm:dev", command: "npm", args: ["run", "dev"] } });
});
test("expanded console folds stay reachable at the start of their rows", async ({ workbench: page }) => {
const heading = "Reconciling orders for the overnight settlement and inventory reporting pipeline";
await stubRun(
page,
[
{
kind: "stdout",
text: [
"TRACE Reused inventory connection",
"TRACE Loaded warehouse configuration",
heading,
"TRACE Checked warehouse audit result",
"TRACE Updated inventory snapshot",
"Processed 24 orders",
"",
].join("\n"),
},
],
null,
);
await page.evaluate(async () => {
const projectModule = "/src/platform/project.ts";
const layoutModule = "/src/workbench/toolwindows/store.ts";
const { useProject } = await import(/* @vite-ignore */ projectModule);
const { moveToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ layoutModule);
const { settings } = useProject.getState();
useProject.setState({
settings: { ...settings, console: { ...settings?.console, foldPatterns: ["TRACE "] } },
});
moveToolWindow("run", "right");
setToolWindowSize("right", 320);
});
await page.keyboard.press("Control+r");
const log = page.getByRole("region", { name: "Run", exact: true }).getByRole("log");
const expand = log.getByTitle("Expand folded lines", { exact: true });
const collapse = log.getByRole("button", { name: "Collapse folded lines", exact: true });
await expect(expand).toHaveCount(2);
await expand.first().click();
await expect(log.getByText("TRACE Reused inventory connection", { exact: true })).toBeVisible();
await expect(collapse).toHaveCount(1);
await collapse.press("Space");
await expect(expand).toHaveCount(2);
await expand.first().press("Enter");
await expect(collapse).toBeFocused();
await expand.last().click();
await expect(collapse).toHaveCount(2);
for (const scrollLeft of [0, 120]) {
await log.evaluate((element, x) => (element.scrollLeft = x), scrollLeft);
expect(await log.evaluate((element) => element.scrollLeft)).toBe(scrollLeft);
for (const control of await collapse.all()) {
const aligned = await control.evaluate((button) => {
const log = button.closest('[role="log"]')!.getBoundingClientRect();
const row = button.closest("[data-index]")!.getBoundingClientRect();
const box = button.getBoundingClientRect();
return Math.abs(box.left - log.left) <= 1 && box.top >= row.top && box.bottom <= row.bottom + 1;
});
expect(aligned).toBe(true);
}
}
await collapse.first().click();
await collapse.first().click();
await expect(expand).toHaveCount(2);
expect(await ipcCalls(page, "run_stdin")).toEqual([]);
});
test("⌘F2 stops a running process", async ({ workbench: page }) => {
await stubRun(page, [{ kind: "stdout", text: "Watching for changes…\n" }], null);
await page.keyboard.press("Control+r");
@@ -323,6 +390,64 @@ test("test results keep counts, actions and selected output visible as the pane
await expect(output).toContainText(message);
});
test("test results keep elapsed time beside the counts", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1060, height: 740 });
const lines = [
"test_tax (test_ledger.CheckoutTests.test_tax) ... ok",
"test_refund (test_ledger.CheckoutTests.test_refund) ... FAIL",
"test_callback (test_ledger.CheckoutTests.test_callback) ... skipped 'Requires a callback'",
"Ran 3 tests in 0.170s",
"FAILED (failures=1, skipped=1)",
];
await stubRun(page, [{ kind: "stderr", text: lines.join("\n") + "\n" }], 1, {
id: "django:checkout-tests",
name: "Checkout tests",
kind: "django-test",
command: "python",
args: ["manage.py", "test", "-v", "2"],
isTest: true,
});
await page.keyboard.press("Control+r");
const run = page.getByRole("region", { name: "Run", exact: true });
const summary = run.getByRole("status").filter({ hasText: "1 failing" });
const ignored = summary.getByText("1 ignored", { exact: true });
const elapsed = summary.getByText("170 ms", { exact: true });
await expect(elapsed).toBeVisible();
for (const width of [1060, 540]) {
await page.setViewportSize({ width, height: 740 });
await expect
.poll(async () => {
const [count, duration] = await Promise.all([ignored.boundingBox(), elapsed.boundingBox()]);
return count && duration && Math.abs(count.y - duration.y) <= 1 ? duration.x - count.x - count.width : Infinity;
})
.toBeLessThanOrEqual(12);
}
await expect(summary).toHaveCSS("border-bottom-width", "2px");
});
test("test results retain a running label after the first test starts", async ({ workbench: page }) => {
const name = "TestCheckoutTotals";
await stubRun(
page,
[{ kind: "stdout", text: JSON.stringify({ Package: "example.com/checkout", Action: "run", Test: name }) + "\n" }],
null,
{
id: "go:checkout-tests",
name: "Checkout tests",
kind: "go",
command: "go",
args: ["test", "-json"],
isTest: true,
},
);
await page.keyboard.press("Control+r");
const run = page.getByRole("region", { name: "Run", exact: true });
await expect(run.getByRole("treeitem", { name: new RegExp(name) })).toBeVisible();
const summary = run.getByRole("status").filter({ hasText: "Running…" });
await expect(summary).toBeVisible();
await expect(summary).toHaveCSS("border-bottom-width", "2px");
});
test("test results group failure navigation and let users hide row durations", async ({ workbench: page }) => {
await page.setViewportSize({ width: 540, height: 740 });
const first = "TestCheckoutTotalsWithTaxRoundingAndPendingRefunds";
+8 -2
Переглянути файл
@@ -2,7 +2,7 @@ import type { Locator, Page } from "@playwright/test";
import { expect, test } from "./fixtures";
for (const height of [990, 700, 560]) {
test(`run configurations dialog keeps its toolbar and scrolls only inside the panes at ${height}px`, async ({
test(`run configurations dialog keeps its toolbar and name visible while scrolling at ${height}px`, async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 900, height });
@@ -62,9 +62,13 @@ async function resize(page: Page, dialog: Locator, dy: number) {
async function checkScrolling(page: Page, dialog: Locator) {
const body = dialog.locator("[data-dialog-body]");
const list = dialog.getByRole("tree", { name: "Run configurations", exact: true });
const form = dialog.locator('[class*="_editForm_"]');
const form = dialog.locator('[class*="_formSettings_"]');
const nameField = dialog.getByRole("textbox", { name: "Name", exact: true });
await list.evaluate((el) => (el.scrollTop = 0));
await form.evaluate((el) => (el.scrollTop = 0));
// Measure once the dialog's opening animation has settled.
await dialog.evaluate((el) => Promise.all(el.getAnimations().map((animation) => animation.finished)));
const nameTop = (await nameField.boundingBox())!.y;
await list.hover();
await page.mouse.wheel(0, 200);
await expect.poll(() => list.evaluate((el) => el.scrollTop)).toBeGreaterThan(0);
@@ -74,6 +78,8 @@ async function checkScrolling(page: Page, dialog: Locator) {
await page.mouse.wheel(0, 200);
await expect.poll(() => form.evaluate((el) => el.scrollTop)).toBeGreaterThan(0);
expect(await list.evaluate((el) => el.scrollTop)).toBe(listTop);
expect((await nameField.boundingBox())!.y).toBeCloseTo(nameTop, 0);
await expect(dialog.getByRole("checkbox", { name: /Store as project file/ })).toBeInViewport({ ratio: 1 });
const overflow = await body.evaluate((el) => ({
scroll: el.scrollHeight,
client: el.clientHeight,
+3 -3
Переглянути файл
@@ -112,7 +112,7 @@ test("resizing the configuration dialog grows its panes and keeps the footer vis
await expect(dialog.getByRole("tree", { name: "Run configurations", exact: true })).toBeVisible();
await expect.poll(async () => (await content.boundingBox())!.height).toBeLessThan(initial);
await expect
.poll(() => dialog.locator("[class*='editForm_']").evaluate((el) => el.scrollHeight - el.clientHeight))
.poll(() => dialog.locator("[class*='_formSettings_']").evaluate((el) => el.scrollHeight - el.clientHeight))
.toBeGreaterThan(0);
});
@@ -144,7 +144,7 @@ test("Java, npm and Python forms fit narrow and zoomed content panes", async ({
for (const width of [1024, 640, 520]) {
await page.setViewportSize({ width, height: 820 });
await expect
.poll(() => dialog.locator("[class*='editForm_']").evaluate((el) => el.scrollWidth - el.clientWidth), {
.poll(() => dialog.locator("[class*='_formSettings_']").evaluate((el) => el.scrollWidth - el.clientWidth), {
message: `${kind}, ${width}px, ${zoom * 100}%`,
})
.toBeLessThanOrEqual(1);
@@ -204,7 +204,7 @@ for (const locale of ["en", "zh"]) {
)
.toMatchObject({ overflow: expect.any(Number), footerFits: true, footerVisible: true });
await expect
.poll(() => dialog.locator("[class*='editForm_']").evaluate((el) => el.scrollWidth - el.clientWidth))
.poll(() => dialog.locator("[class*='_formSettings_']").evaluate((el) => el.scrollWidth - el.clientWidth))
.toBeLessThanOrEqual(1);
const tasks = dialog.getByRole("list");
await tasks.scrollIntoViewIfNeeded();
+44 -1
Переглянути файл
@@ -3,7 +3,7 @@
* header on screen: titles stay on one line and every header control lies inside the popup.
*/
import type { Page } from "@playwright/test";
import { expect, stubDesktop, test } from "./fixtures";
import { expect, openFromTree, stubDesktop, test } from "./fixtures";
const LONG_RESULT_PATH = "config/RegionalOrderReconciliationEndpointsForSandboxEnvironments.txt";
@@ -118,6 +118,49 @@ test.describe("search popups at the minimum window width", () => {
await dialog.getByRole("button", { name: /Browse/ }).click({ trial: true });
});
test("Replace in Files keeps its footer actions together as the window narrows", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1120, height: 750 });
await openFromTree(page, "settings.gradle.kts");
await stubFindMatches(page);
await run(page, "find.replaceInPath");
const dialog = page.getByRole("dialog", { name: "Replace in Files" });
const search = dialog.getByRole("textbox", { name: "Text to find" });
await search.fill("http://localhost:8080");
await expect(dialog.locator("header [aria-live]")).toContainText("13 matches in 12 files");
await search.press("Shift+ArrowDown");
await search.press("Shift+ArrowDown");
const footer = dialog.locator("footer");
const open = footer.getByRole("button", { name: "Open in Find Window", exact: true });
const shortcut = footer.getByText(/^(Ctrl\+Enter|⌘↵)$/);
const replaceAll = footer.getByRole("button", { name: "Replace All", exact: true });
const replaceSelected = footer.getByRole("button", { name: "Replace 3 Occurrences", exact: true });
await expect(replaceSelected).toBeEnabled();
for (const [width, height] of [
[400, 500],
[1120, 750],
] as const) {
await page.setViewportSize({ width, height });
const [key, find, all, selected] = await Promise.all([
shortcut.boundingBox(),
open.boundingBox(),
replaceAll.boundingBox(),
replaceSelected.boundingBox(),
]);
if (!key || !find || !all || !selected) throw new Error("Expected all footer actions to be visible");
expect(Math.abs(key.y + key.height / 2 - find.y - find.height / 2)).toBeLessThanOrEqual(1);
expect(Math.abs(all.y - selected.y)).toBeLessThanOrEqual(1);
await expectControlsFit(page);
await expect(footer).toBeInViewport({ ratio: 1 });
await expect(shortcut).toHaveCSS("font-size", "12px");
await open.click({ trial: true });
await replaceSelected.click({ trial: true });
}
await search.press("Meta+Enter");
await expect(dialog).toBeHidden();
await expect(page.getByRole("region", { name: "Find", exact: true })).toContainText("http://localhost:8080");
});
for (const id of [
"navigate.searchEverywhere",
"navigate.searchText",
+33
Переглянути файл
@@ -1,5 +1,38 @@
import { expect, test } from "./fixtures";
test("keeps the current settings page name readable when the path is wider than the pane", async ({
workbench: page,
}) => {
await page.keyboard.press("Meta+,");
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
const search = settings.getByRole("textbox", { name: "Search settings" });
await search.fill("Maven");
const path = settings.getByLabel("Breadcrumb", { exact: true });
const parent = path.getByText("Build, Execution, Deployment", { exact: true });
const current = path.getByText("Maven", { exact: true });
await expect(current).toBeVisible();
await search.clear();
for (const width of [400, 560, 1120]) {
await page.setViewportSize({ width, height: 720 });
await expect
.poll(() =>
current.evaluate((label) => {
const box = label.getBoundingClientRect();
const trail = label.closest("[aria-label=Breadcrumb]")!.getBoundingClientRect();
return label.clientWidth >= label.scrollWidth && box.width > 0 && box.right <= trail.right + 1;
}),
)
.toBe(true);
}
await expect(parent).toBeInViewport({ ratio: 1 });
expect(await parent.evaluate((label) => label.scrollWidth <= label.clientWidth)).toBe(true);
await settings.getByRole("button", { name: "Back", exact: true }).click();
await expect(current).toBeHidden();
await settings.getByRole("button", { name: "Forward", exact: true }).click();
await expect(current).toBeVisible();
});
test("dirty settings keep scope labels and navigation inside the page header", async ({ workbench: page }) => {
await page.keyboard.press("Meta+,");
await expect(page.getByRole("dialog", { name: "Settings", exact: true })).toBeVisible();
+44
Переглянути файл
@@ -0,0 +1,44 @@
import { expect, test } from "./fixtures";
test("shortcut assignment fits the first stroke and conflict names in a narrow window", async ({ workbench: page }) => {
await page.setViewportSize({ width: 336, height: 540 });
await page.keyboard.press("Meta+,");
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
await settings.getByRole("treeitem", { name: "Keymap", exact: true }).click();
await settings.getByRole("textbox", { name: "Search actions" }).fill("Find Action");
const action = settings.getByRole("treeitem", { name: /Find Action/ });
await action.click();
await settings.getByRole("button", { name: "Add Keyboard Shortcut", exact: true }).click();
const dialog = page.getByRole("dialog", { name: "Keyboard Shortcut: Find Action…", exact: true });
const first = dialog.getByRole("textbox", { name: "First stroke" });
const body = dialog.locator("[data-dialog-body]");
const titleBar = dialog.locator("[data-dialog-titlebar]");
await expect(first).toBeFocused();
await expect(titleBar).toHaveText("Keyboard Shortcut");
await expect(body.getByText("Find Action…", { exact: true })).toBeVisible();
const firstBounds = (await first.boundingBox())!;
const bodyBounds = (await body.boundingBox())!;
expect(firstBounds.width).toBeGreaterThan(bodyBounds.width - 32);
const conflicts = dialog.getByRole("list", { name: "Conflicts:" });
await expect(conflicts).toHaveCount(0);
await first.press("Meta+Alt+L");
await expect(conflicts).toBeVisible();
await expect(conflicts.getByRole("listitem").filter({ hasText: "Reformat Code" }).first()).toBeVisible();
expect(await conflicts.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
expect(
await conflicts
.getByRole("listitem")
.evaluateAll((rows) => rows.every((row) => row.scrollHeight <= row.clientHeight)),
).toBe(true);
expect(await body.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
const ok = dialog.getByRole("button", { name: "OK", exact: true });
await ok.click();
const confirmation = page.getByRole("dialog", { name: "Warning", exact: true });
await expect(confirmation.getByRole("list").getByText("Reformat Code", { exact: true })).toHaveCount(2);
await confirmation.getByRole("button", { name: "Leave", exact: true }).click();
await expect(dialog).toBeHidden();
await expect(action.locator("kbd").filter({ hasText: "⌥⌘L" })).toHaveCount(1);
});
+45
Переглянути файл
@@ -0,0 +1,45 @@
import { expect, test } from "./fixtures";
test("Show Usages distinguishes same-named files without losing the line or snippet", async ({ workbench: page }) => {
await page.setViewportSize({ width: 480, height: 620 });
await page.evaluate(async () => {
const usages = "/src/features/code-insight/usages.ts";
const { useUsagesPopup } = await import(/* @vite-ignore */ usages);
const symbol = "submitOrder";
useUsagesPopup.setState({
open: true,
anchor: { x: 30, y: 90 },
symbol,
groups: (
[
["/dev/acme-api/packages/billing/src/Routes.ts", "return submitOrder(invoice);"],
["/dev/acme-api/packages/checkout/src/Routes.ts", "return submitOrder(cart);"],
["/dev/acme-api/src/Worker.ts", "await submitOrder(job);"],
] as const
).map(([path, text]) => {
const col = text.indexOf(symbol);
return { path, usages: [{ path, line: 6, col, endCol: col + symbol.length, text }] };
}),
});
});
const popup = page.getByRole("dialog", { name: "Usages", exact: true });
const rows = popup.getByRole("option");
const billing = rows.filter({ hasText: "invoice" });
const checkout = rows.filter({ hasText: "cart" });
await expect(rows).toHaveCount(3);
for (const [row, directory] of [
[billing, "billing"],
[checkout, "checkout"],
] as const) {
await expect(row.getByText("Routes.ts", { exact: true })).toBeVisible();
const caption = row.getByText(directory, { exact: true });
await expect(caption).toBeVisible();
expect(await caption.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await expect(row.getByText("7", { exact: true })).toBeVisible();
await expect(row.locator("mark")).toHaveText("submitOrder");
}
await expect(checkout.getByTitle("/dev/acme-api/packages/checkout/src/Routes.ts", { exact: true })).toBeVisible();
await expect(rows.filter({ hasText: "Worker.ts" }).getByText("src", { exact: true })).toHaveCount(0);
});
+2 -1
Переглянути файл
@@ -22,6 +22,7 @@ something to show.
| `tailwind-app/` | Node 22+, pnpm/npm, Tailwind CSS 4, React | `pnpm dev` | — | — | `flex` conflicting with `block` in `src/App.tsx` |
| `zig-app/` | Zig 0.17 | `zig build run` | `zig build test` | — | — |
| `biome-app/` | Node 22+, `@biomejs/biome` (`npm install`) | `npm start` | — | — | `let` never reassigned, `==` and a duplicate CSS `color` (Biome) |
| `stylelint-app/` | Node 22+, `stylelint` (`npm install`) | — | — | — | long hex colour, unknown property, empty block, duplicate selector (Stylelint) |
| `polyglot/` | Go, TS, Python, C, shell, SQL, TOML/YAML/JSON, proto, Terraform | `make` | `make test` | — | unused variable in `native/hash.c` |
The fixtures are standalone: `rust-app` declares its own `[workspace]` and
@@ -44,7 +45,7 @@ git init -q && git add -A && git commit -qm "initial" # for the VCS checks
```
Then open the folder with **File › Open…** (`⌘⇧⌥O`) or from the Welcome screen.
For `ts-app` / `playwright-app` / `mocha-app` / `polyglot/web` run `pnpm install` first (`npm install` for `biome-app`); for `python-app` create a
For `ts-app` / `playwright-app` / `mocha-app` / `polyglot/web` run `pnpm install` first (`npm install` for `biome-app` and `stylelint-app`); for `python-app` create a
venv (`python3 -m venv .venv && .venv/bin/pip install -e '.[dev]'`); for
`php-app` run `composer install` (debugging it needs Xdebug in the PHP on `PATH`).
+17
Переглянути файл
@@ -0,0 +1,17 @@
{
"name": "openidea-fixture-stylelint",
"version": "0.1.0",
"private": true,
"description": "OpenIDEA QA fixture: Stylelint diagnostics and fixes for CSS, SCSS and Less",
"type": "module",
"scripts": {
"lint": "stylelint \"src/**/*.{css,scss,less}\"",
"fix": "stylelint \"src/**/*.{css,scss,less}\" --fix"
},
"devDependencies": {
"postcss-less": "6.0.0",
"stylelint": "18.1.0",
"stylelint-config-standard": "41.1.0",
"stylelint-config-standard-scss": "18.0.0"
}
}
+7
Переглянути файл
@@ -0,0 +1,7 @@
/* Intentional Stylelint problems: a long hex colour (color-hex-length, fixable)
and a misspelt property (property-no-unknown). */
.card {
color: #ffffff;
colour: red;
padding: 4px 8px;
}
+10
Переглянути файл
@@ -0,0 +1,10 @@
@gutter: 16px;
// Intentional Stylelint problem: the same selector twice (no-duplicate-selectors).
.layout {
margin: @gutter;
}
.layout {
padding: @gutter;
}
+9
Переглянути файл
@@ -0,0 +1,9 @@
$accent: #336699;
// Intentional Stylelint problem: an empty block (block-no-empty).
.button {
color: $accent;
&:hover {
}
}
+8
Переглянути файл
@@ -0,0 +1,8 @@
/** @type {import("stylelint").Config} */
export default {
extends: ["stylelint-config-standard"],
overrides: [
{ files: ["**/*.scss"], extends: ["stylelint-config-standard-scss"] },
{ files: ["**/*.less"], customSyntax: "postcss-less" },
],
};
+1 -1
Переглянути файл
@@ -2,7 +2,7 @@ Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: OpenIDEA Java usages
Bundle-SymbolicName: ai.openidea.usages;singleton:=true
Bundle-Version: 1.16.0
Bundle-Version: 1.17.0
Bundle-RequiredExecutionEnvironment: JavaSE-21
Require-Bundle: org.eclipse.jdt.ls.core,org.eclipse.jdt.core,
org.eclipse.jdt.core.manipulation,org.eclipse.core.runtime,
+20 -1
Переглянути файл
@@ -88,7 +88,7 @@ is not a claim of full IntelliJ feature parity.
## Rebuild and delivery
The checked-in jar is embedded by ide-sdk `include_bytes!`, installed as
`java-usages-1.16.0.jar`, and added alongside existing initialization bundles.
`java-usages-1.17.0.jar`, and added alongside existing initialization bundles.
Users need no compiler, Maven or Python. Manifest/install version must change
when replacing the bundle because OSGi caches bundles.
@@ -139,6 +139,9 @@ reproducible SHA-256 is `c29e5455c02c245523b2e7a5861e00ae670cefc66cda33ec19fdce2
Version 1.16.0 adds `openidea.java.generatedSources`, which puts Maven plugin output such as
protobuf and gRPC stubs on the project classpath; its reproducible SHA-256 is
`a5feda1cae11bdea1044fb311404840b048601af037f65685973721f1eefff8b`.
Version 1.17.0 adds `openidea.java.exceptionType`, the exception class at a caret for the exception
breakpoint intention; its reproducible SHA-256 is
`d1c596b37dcb6bd402ad48b214fd2a7651dbd4472eeea49e2ce992ea2f1363e9`.
```sh
export PATH=/path/to/jdk25/bin:$PATH
@@ -169,6 +172,7 @@ python3 java/java-usages/tests/read-write.py /path/to/jdtls /path/to/lombok.jar
OPENIDEA_USAGES_INDEX_STRESS=1 python3 java/java-usages/tests/read-write.py /path/to/jdtls /path/to/lombok.jar > /tmp/read-write-indexed.json
python3 java/java-usages/tests/hierarchy.py /path/to/jdtls
python3 java/java-usages/tests/implementations.py /path/to/jdtls
python3 java/java-usages/tests/exception-type.py /path/to/jdtls
```
The harnesses select the JDT LS configuration for the current platform. The first
@@ -185,6 +189,21 @@ listing, moving, declaring abstract, pulling up to an interface, conflicts repor
before any change, and a class without supertypes. Each edit is applied to a copy of
the fixture and compiled with javac.
`exception-type.py` puts the caret on throws, catches (multi-catch too), qualified names, a
thrown variable or call, a nested, local, unresolved or non-Throwable class, an import and a
class declaration, and compares each answer with IntelliJ's.
## Exception class at a caret
`openidea.java.exceptionType(uri, line, column)` answers `{qualifiedName, displayName}` (the
binary name, `app.Outer$Failure`, and the simple name) or `null`, as IntelliJ's
`ControlExceptionBreakpointJVMSupport` decides: from the token right of the caret, else the one
left of it, the nearest enclosing reference, class or throw statement. A reference gives the class
it resolves to (a constructor's class; a variable, a method or a package gives nothing, and so does
a call with a qualifier, which UAST sees as a reference to its method), a class gives itself only on
its name, a throw statement the class of what it throws. The class must be a `Throwable` with a
qualified name: not unresolved, local, anonymous or a type variable.
## Class-hierarchy refactorings
`openidea.java.hierarchy.members(uri, line, column, kind)` describes the class at the
Бінарний файл не відображається.
+3
Переглянути файл
@@ -30,5 +30,8 @@
<command id="openidea.java.hierarchy.members"/>
<command id="openidea.java.hierarchy.refactor"/>
</delegateCommandHandler>
<delegateCommandHandler class="ai.openidea.breakpoints.ExceptionTypeCommand">
<command id="openidea.java.exceptionType"/>
</delegateCommandHandler>
</extension>
</plugin>
+113
Переглянути файл
@@ -0,0 +1,113 @@
package ai.openidea.breakpoints;
import ai.openidea.Documents;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.core.ITypeRoot;
import org.eclipse.jdt.core.dom.*;
import org.eclipse.jdt.core.manipulation.CoreASTProvider;
import org.eclipse.jdt.ls.core.internal.IDelegateCommandHandler;
import org.eclipse.jdt.ls.core.internal.JDTUtils;
import org.eclipse.jdt.ls.core.internal.handlers.JsonRpcHelpers;
/**
* The exception class a caret names, for the Create / Enable / Disable exception breakpoint intention.
*
* <p>{@code openidea.java.exceptionType(uri, line, column)} answers {@code {qualifiedName, displayName}}
* ({@code qualifiedName} is the binary name, {@code app.Outer$Failure}) or {@code null}. It follows
* IntelliJ's {@code ControlExceptionBreakpointJVMSupport}: from the token right of the caret, else the
* one left of it, the nearest enclosing reference, class or throw statement decides. A reference gives
* the class it resolves to (a constructor's class; a variable, a method or a package gives nothing), a
* class gives itself only on its name, and a throw statement the class of the thrown expression. The
* class must be a {@link Throwable} with a qualified name: not unresolved, local, anonymous or a type
* variable.
*/
public final class ExceptionTypeCommand implements IDelegateCommandHandler {
@Override
public Object executeCommand(String command, List<Object> arguments, IProgressMonitor monitor) throws Exception {
Documents.awaitChanges(monitor);
String uri = (String) arguments.get(0);
int line = ((Number) arguments.get(1)).intValue();
int column = ((Number) arguments.get(2)).intValue();
ITypeRoot root = JDTUtils.resolveTypeRoot(uri);
if (root == null || !root.exists()) return null;
CompilationUnit ast = CoreASTProvider.getInstance().getAST(root, CoreASTProvider.WAIT_YES, monitor);
if (ast == null) return null;
int offset = JsonRpcHelpers.toOffset(root, line, column);
if (offset < 0) return null;
ITypeBinding found = classAt(ast, offset);
if (found == null && offset > 0) found = classAt(ast, offset - 1);
return found == null ? null : describe(found);
}
/** The exception class for the token holding the character at {@code offset}. */
static ITypeBinding classAt(CompilationUnit ast, int offset) {
if (offset >= ast.getStartPosition() + ast.getLength()) return null;
ASTNode leaf = new NodeFinder(ast, offset, 1).getCoveringNode();
ITypeBinding type = classReference(leaf);
return isException(type) ? type : null;
}
private static ITypeBinding classReference(ASTNode leaf) {
for (ASTNode n = leaf; n != null; n = n.getParent()) {
if (n instanceof AbstractTypeDeclaration declaration) {
return leaf == declaration.getName() ? declaration.resolveBinding() : null;
}
if (n instanceof AnonymousClassDeclaration) return null;
if (n instanceof ThrowStatement thrown) return thrown.getExpression().resolveTypeBinding();
if (isReference(n)) return referencedClass(n);
}
return null;
}
/**
* What UAST converts to a reference expression: a name that is not a declaration or a label, a
* field access, a call or instance creation with a qualifier, a method or constructor reference.
*/
private static boolean isReference(ASTNode n) {
if (n instanceof SimpleName name) {
if (name.isDeclaration()) return false;
StructuralPropertyDescriptor at = name.getLocationInParent();
return at != LabeledStatement.LABEL_PROPERTY && at != BreakStatement.LABEL_PROPERTY
&& at != ContinueStatement.LABEL_PROPERTY && at != MemberValuePair.NAME_PROPERTY;
}
return n instanceof QualifiedName || n instanceof FieldAccess || n instanceof SuperFieldAccess
|| n instanceof SuperMethodInvocation || n instanceof MethodReference || n instanceof MemberRef
|| n instanceof MethodRef || (n instanceof MethodInvocation call && call.getExpression() != null)
|| (n instanceof ClassInstanceCreation creation && creation.getExpression() != null);
}
private static ITypeBinding referencedClass(ASTNode reference) {
IBinding binding = switch (reference) {
case Name name -> name.resolveBinding();
case ClassInstanceCreation creation -> creation.resolveConstructorBinding();
case MethodReference method -> method.resolveMethodBinding();
case MethodInvocation call -> call.resolveMethodBinding();
case SuperMethodInvocation call -> call.resolveMethodBinding();
default -> null;
};
if (binding instanceof ITypeBinding type) return type;
if (binding instanceof IMethodBinding method && method.isConstructor()) return method.getDeclaringClass();
return null;
}
private static boolean isException(ITypeBinding type) {
if (type == null || type.isRecovered() || !type.isClass() || type.isLocal() || type.isAnonymous()) return false;
for (ITypeBinding t = type.getErasure(); t != null; t = t.getSuperclass()) {
if ("java.lang.Throwable".equals(t.getQualifiedName())) return true;
}
return false;
}
private static Map<String, String> describe(ITypeBinding type) {
ITypeBinding erased = type.getErasure();
String binary = erased.getBinaryName();
if (binary == null) return null;
Map<String, String> out = new LinkedHashMap<>();
out.put("qualifiedName", binary);
out.put("displayName", erased.getName());
return out;
}
}
+242
Переглянути файл
@@ -0,0 +1,242 @@
"""The exception class at a caret, against a real JDT LS. Arguments: jdtls home, optional bundle jar.
Each case puts the caret at an offset inside a unique piece of text and compares the answer of
`openidea.java.exceptionType` with IntelliJ's ControlExceptionBreakpointJVMSupport: the class a
reference resolves to (a constructor's class), a class declaration's name, or the type a throw
statement throws, when that class is a Throwable with a qualified name.
"""
import json
import pathlib
import platform
import queue
import subprocess
import sys
import tempfile
import threading
import time
home = pathlib.Path(sys.argv[1]).resolve()
bundle = pathlib.Path(sys.argv[2]).resolve() if len(sys.argv) > 2 else pathlib.Path(__file__).resolve().parents[1] / 'openidea-java-usages.jar'
work = pathlib.Path(tempfile.mkdtemp(prefix='openidea-exception-type-'))
config = work / 'config'
config.mkdir()
system, machine = platform.system(), platform.machine().lower()
config_name = {'Windows': 'config_win', 'Darwin': 'config_mac'}.get(system, 'config_linux')
config_names = ([config_name + '_arm'] if machine in ('arm64', 'aarch64') else []) + [config_name]
config_source = next(home / name / 'config.ini' for name in config_names if (home / name / 'config.ini').is_file())
(config / 'config.ini').write_bytes(config_source.read_bytes())
project = work / 'project'
(project / 'src/app/errors').mkdir(parents=True)
(project / '.project').write_text('<projectDescription><name>app</name><buildSpec><buildCommand><name>org.eclipse.jdt.core.javabuilder</name></buildCommand></buildSpec><natures><nature>org.eclipse.jdt.core.javanature</nature></natures></projectDescription>')
(project / '.classpath').write_text('<classpath><classpathentry kind="src" path="src"/><classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/><classpathentry kind="output" path="bin"/></classpath>')
sources = {
'errors/OrderException.java': '''package app.errors;
public class OrderException extends Exception {
public OrderException(String message) {
super(message);
}
}
''',
'Main.java': '''package app;
import app.errors.OrderException;
import java.io.IOException;
public class Main {
static class Failure extends RuntimeException {
}
static class NotAnException {
}
void place(Exception given, String msg) throws Exception {
try {
throw new OrderException("order " + msg);
} catch (OrderException | IllegalArgumentException e) {
throw given;
}
}
void qualified() {
throw new java.lang.IllegalStateException("qualified");
}
void nested() {
throw new Failure();
}
void missing() {
throw new Missing();
}
Object plain() {
return new NotAnException();
}
static Exception build(String why) {
return new IOException(why);
}
void call() throws Exception {
throw build("call");
}
void qualifiedCall() throws Exception {
throw Main.build("qualifiedCall");
}
<T extends Exception> void typeVariable(T t) throws T {
throw t;
}
void local() {
class Local extends RuntimeException {
}
throw new Local();
}
}
''',
}
for name, text in sources.items():
(project / 'src/app' / name).write_text(text)
uri = lambda name: (project / 'src/app' / name).as_uri()
log = (work / 'stderr.log').open('w')
proc = subprocess.Popen(['java', '-Declipse.application=org.eclipse.jdt.ls.core.id1', '-Dosgi.bundles.defaultStartLevel=4', '-Declipse.product=org.eclipse.jdt.ls.core.product', '-Xmx1G', '--add-modules=ALL-SYSTEM', '--add-opens', 'java.base/java.util=ALL-UNNAMED', '--add-opens', 'java.base/java.lang=ALL-UNNAMED', '-jar', str(next((home / 'plugins').glob('org.eclipse.equinox.launcher_*.jar'))), '-configuration', str(config), '-data', str(work / 'metadata')], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=log)
messages = queue.Queue()
lock = threading.Lock()
def send(message):
data = json.dumps(message).encode()
with lock:
proc.stdin.write(f'Content-Length: {len(data)}\r\n\r\n'.encode() + data)
proc.stdin.flush()
def read():
while True:
headers = {}
while True:
line = proc.stdout.readline()
if not line:
return
if line == b'\r\n':
break
k, v = line.decode().split(':', 1)
headers[k.lower()] = v.strip()
message = json.loads(proc.stdout.read(int(headers['content-length'])))
if 'method' in message and 'id' in message:
send({'jsonrpc': '2.0', 'id': message['id'], 'result': [] if message['method'] == 'workspace/configuration' else None})
else:
messages.put(message)
threading.Thread(target=read, daemon=True).start()
seq = 0
def request(method, params):
global seq
seq += 1
send({'jsonrpc': '2.0', 'id': seq, 'method': method, 'params': params})
deadline = time.monotonic() + 180
while time.monotonic() < deadline:
msg = messages.get(timeout=max(1, deadline - time.monotonic()))
if msg.get('id') == seq:
if 'error' in msg:
raise RuntimeError(msg['error'])
return msg.get('result')
raise TimeoutError(method)
def exception_type(file, needle, at=0):
"""The answer with the caret `at` characters into the only line holding `needle`."""
lines = sources[file].splitlines()
found = [i for i, t in enumerate(lines) if needle in t]
assert len(found) == 1, (needle, found)
line = found[0]
column = lines[line].index(needle) + at
return request('workspace/executeCommand', {'command': 'openidea.java.exceptionType', 'arguments': [uri(file), line, column]})
ORDER = {'qualifiedName': 'app.errors.OrderException', 'displayName': 'OrderException'}
EXCEPTION = {'qualifiedName': 'java.lang.Exception', 'displayName': 'Exception'}
CASES = [
# throw new X(…): on the class, on `throw`, on `new`, inside a literal argument; a variable is not a class.
('throw new OrderException', 'OrderException', 10, ORDER),
('throw new OrderException', 'throw', 0, ORDER),
('throw new OrderException', 'new', 1, ORDER),
('throw new OrderException', '"order "', 2, ORDER),
('throw new OrderException', 'msg', 1, None),
# Multi-catch: each alternative; the caret right after a name takes the name to its left.
('catch (OrderException', 'OrderException', 3, ORDER),
('catch (OrderException', 'IllegalArgumentException', 0, {'qualifiedName': 'java.lang.IllegalArgumentException', 'displayName': 'IllegalArgumentException'}),
('catch (OrderException', 'OrderException', len('OrderException'), ORDER),
('catch (OrderException', 'catch', 1, None),
('catch (OrderException', '|', 0, None),
('catch (OrderException', ' e)', 1, None),
# A thrown variable: its declared type on `throw`, nothing on the variable.
('throw given', 'throw', 2, EXCEPTION),
('throw given', 'given', 2, None),
# A qualified name: the class, not its packages.
('java.lang.IllegalStateException', 'IllegalStateException', 4, {'qualifiedName': 'java.lang.IllegalStateException', 'displayName': 'IllegalStateException'}),
('java.lang.IllegalStateException', 'java', 1, None),
('java.lang.IllegalStateException', 'lang', 1, None),
# A nested class: its binary name, its simple name; also on its declaration and its superclass.
('throw new Failure', 'Failure', 2, {'qualifiedName': 'app.Main$Failure', 'displayName': 'Failure'}),
('static class Failure', 'Failure', 0, {'qualifiedName': 'app.Main$Failure', 'displayName': 'Failure'}),
('static class Failure', 'RuntimeException', 3, {'qualifiedName': 'java.lang.RuntimeException', 'displayName': 'RuntimeException'}),
('static class Failure', 'static', 1, None),
# A type that does not resolve, and a class that is not a Throwable.
('throw new Missing', 'Missing', 2, None),
('throw new Missing', 'throw', 1, None),
('static class NotAnException', 'NotAnException', 2, None),
('return new NotAnException', 'NotAnException', 2, None),
# A call: its return type on `throw`; the method name is not a class.
('throw build', 'throw', 0, EXCEPTION),
('throw build', 'build', 1, None),
('throw build', '"call"', 1, EXCEPTION),
# A qualified call is a reference to its method (UAST): nothing inside it, the qualifier's class aside.
('throw Main.build', '"qualifiedCall"', 1, None),
('throw Main.build', 'throw', 0, EXCEPTION),
# A type variable and a local class have no qualified name.
('throw t;', 'throw', 0, None),
('throw new Local', 'Local', 1, None),
# An import names the class too.
('import app.errors.OrderException', 'OrderException', 1, ORDER),
# Outside a throw, a reference or a class name: nothing.
('void nested()', 'nested', 1, None),
('public class Main', 'Main', 1, None),
]
try:
init = request('initialize', {'processId': None, 'rootUri': project.as_uri(), 'workspaceFolders': [{'uri': project.as_uri(), 'name': 'app'}], 'capabilities': {}, 'initializationOptions': {'bundles': [str(bundle)], 'settings': {'java': {'import': {'gradle': {'enabled': False}, 'maven': {'enabled': False}}}}}})
commands = init['capabilities']['executeCommandProvider']['commands']
assert 'openidea.java.exceptionType' in commands, commands
send({'jsonrpc': '2.0', 'method': 'initialized', 'params': {}})
for name, text in sources.items():
send({'jsonrpc': '2.0', 'method': 'textDocument/didOpen', 'params': {'textDocument': {'uri': uri(name), 'languageId': 'java', 'version': 1, 'text': text}}})
request('java/buildWorkspace', True)
failed = []
for line_needle, needle, at, expected in CASES:
lines = sources['Main.java'].splitlines()
line = next(i for i, t in enumerate(lines) if line_needle in t)
column = lines[line].index(needle, lines[line].index(line_needle) if needle in line_needle else 0) + at
got = request('workspace/executeCommand', {'command': 'openidea.java.exceptionType', 'arguments': [uri('Main.java'), line, column]})
status = 'OK' if got == expected else 'FAIL'
if got != expected:
failed.append((line_needle, needle, at))
print(f'{status} {line_needle!r} at {needle!r}+{at}: {got}')
# A class declared in another file, read through the position in that file.
got = exception_type('errors/OrderException.java', 'class OrderException', 6)
print(('OK' if got == ORDER else 'FAIL'), 'declaration in its own file:', got)
if got != ORDER:
failed.append('declaration in its own file')
assert not failed, failed
print('exception-type: all cases passed')
finally:
proc.terminate()
proc.wait(timeout=20)
print('Evidence:', work, file=sys.stderr)
+17
Переглянути файл
@@ -25,6 +25,23 @@ require-root-marker = true
features = ["code-action", "diagnostics"]
install-hint = "npm i -D @biomejs/biome"
# Stylelint: only below a project's Stylelint configuration; the server runs the project's own
# stylelint. Diagnostics, quick fixes and fix-all (Code Cleanup, Actions on Save) only: the
# server's formatting applies the same fixes, and Reformat Code stays the formatter's.
[[language-servers]]
name = "stylelint"
command = "stylelint-language-server"
args = ["--stdio"]
root-markers = [".stylelintrc", ".stylelintrc.json", ".stylelintrc.yaml", ".stylelintrc.yml", ".stylelintrc.js", ".stylelintrc.cjs", ".stylelintrc.mjs", ".stylelintrc.ts", ".stylelintrc.cts", ".stylelintrc.mts", "stylelint.config.js", "stylelint.config.cjs", "stylelint.config.mjs", "stylelint.config.ts", "stylelint.config.cts", "stylelint.config.mts", "package.json#stylelint"]
require-root-marker = true
features = ["code-action", "diagnostics"]
install-hint = "npm i -g @stylelint/language-server"
# Read as section `stylelint`: the languages it lints (its default is CSS only).
[language-servers.settings]
validate = ["css", "scss", "less"]
snippet = ["css", "scss", "less"]
# Tailwind CSS: class completion, hover and diagnostics, only in a project that uses Tailwind
# (`tailwind.config.*` or `tailwindcss` in package.json). After the language's own servers,
# which answer hover first.
+17
Переглянути файл
@@ -13,3 +13,20 @@ command = "vscode-css-language-server"
args = ["--stdio"]
initialization-options = { provideFormatter = true, css = {}, scss = {}, less = {} }
install-hint = "npm i -g vscode-langservers-extracted"
# Stylelint: only below a project's Stylelint configuration; the server runs the project's own
# stylelint. Diagnostics, quick fixes and fix-all (Code Cleanup, Actions on Save) only: the
# server's formatting applies the same fixes, and Reformat Code stays the formatter's.
[[language-servers]]
name = "stylelint"
command = "stylelint-language-server"
args = ["--stdio"]
root-markers = [".stylelintrc", ".stylelintrc.json", ".stylelintrc.yaml", ".stylelintrc.yml", ".stylelintrc.js", ".stylelintrc.cjs", ".stylelintrc.mjs", ".stylelintrc.ts", ".stylelintrc.cts", ".stylelintrc.mts", "stylelint.config.js", "stylelint.config.cjs", "stylelint.config.mjs", "stylelint.config.ts", "stylelint.config.cts", "stylelint.config.mts", "package.json#stylelint"]
require-root-marker = true
features = ["code-action", "diagnostics"]
install-hint = "npm i -g @stylelint/language-server"
# Read as section `stylelint`: the languages it lints (its default is CSS only).
[language-servers.settings]
validate = ["css", "scss", "less"]
snippet = ["css", "scss", "less"]
+17
Переглянути файл
@@ -13,3 +13,20 @@ command = "vscode-css-language-server"
args = ["--stdio"]
initialization-options = { provideFormatter = true, css = {}, scss = {}, less = {} }
install-hint = "npm i -g vscode-langservers-extracted"
# Stylelint: only below a project's Stylelint configuration; the server runs the project's own
# stylelint. Diagnostics, quick fixes and fix-all (Code Cleanup, Actions on Save) only: the
# server's formatting applies the same fixes, and Reformat Code stays the formatter's.
[[language-servers]]
name = "stylelint"
command = "stylelint-language-server"
args = ["--stdio"]
root-markers = [".stylelintrc", ".stylelintrc.json", ".stylelintrc.yaml", ".stylelintrc.yml", ".stylelintrc.js", ".stylelintrc.cjs", ".stylelintrc.mjs", ".stylelintrc.ts", ".stylelintrc.cts", ".stylelintrc.mts", "stylelint.config.js", "stylelint.config.cjs", "stylelint.config.mjs", "stylelint.config.ts", "stylelint.config.cts", "stylelint.config.mts", "package.json#stylelint"]
require-root-marker = true
features = ["code-action", "diagnostics"]
install-hint = "npm i -g @stylelint/language-server"
# Read as section `stylelint`: the languages it lints (its default is CSS only).
[language-servers.settings]
validate = ["css", "scss", "less"]
snippet = ["css", "scss", "less"]
+1
Переглянути файл
@@ -313,6 +313,7 @@ pub async fn settings_import(window: Window, state: State<'_, AppState>, path: P
crate::commands::ssh::apply_ssh_settings(&state);
state.host.mcp.apply(&state.host);
state.host.apply_proxy();
state.host.apply_git_executable();
state.updates.wake.notify_one();
state.sink.emit(ide_core::IdeEvent::SettingsChanged { key: String::new() });
let settings = ide_host::ops::project::settings_get(&state.host, window.label());
+10 -3
Переглянути файл
@@ -133,11 +133,14 @@ pub async fn gh_pr_create(
on_output: Channel<String>,
) -> IdeResult<String> {
let root = root(&window, &state, repo)?;
let git = state.project(window.label())?.git_executable();
let cancel = state.begin_request(request);
let dir = root.clone();
let result = blocking(move || {
ide_github::create(&dir, &pr, &cancel, &|line| {
let _ = on_output.send(line);
ide_vcs::with_git_executable(git.as_deref(), || {
ide_github::create(&dir, &pr, &cancel, &|line| {
let _ = on_output.send(line);
})
})
})
.await;
@@ -207,10 +210,14 @@ pub async fn gh_pr_prepare_diff(
on_output: Channel<String>,
) -> IdeResult<PrDiffRevisions> {
let root = root(&window, &state, repo)?;
let git = state.project(window.label())?.git_executable();
let cancel = state.begin_request(request);
let result = blocking(move || {
ide_github::prepare_diff(&root, number, &head_oid, &base_oid, &base_ref, &name_with_owner, &cancel, &|line| {
let output = |line: String| {
let _ = on_output.send(line);
};
ide_vcs::with_git_executable(git.as_deref(), || {
ide_github::prepare_diff(&root, number, &head_oid, &base_oid, &base_ref, &name_with_owner, &cancel, &output)
})
})
.await;
+1
Переглянути файл
@@ -349,6 +349,7 @@ lsp_code_lens trusted project_host bin
lsp_completion trusted project_host bindings async
lsp_document_highlights trusted project_host bindings async
lsp_document_links trusted project_host bindings async
lsp_exception_class_at trusted project_host bindings async
lsp_execute_code_action trusted project_host bindings async
lsp_execute_command trusted project_host bindings async
lsp_extract_interface trusted project_host bindings async
+19 -1
Переглянути файл
@@ -846,6 +846,13 @@ export const commands = {
lspDocumentHighlights: (doc: DocId, pos: Pos) => typedError<Highlight[], IdeError>(__TAURI_INVOKE("lsp_document_highlights", { doc, pos })),
/** Links in a document (`href`s, Markdown links, `#include`s…) from its language servers. */
lspDocumentLinks: (doc: DocId) => typedError<DocumentLink[], IdeError>(__TAURI_INVOKE("lsp_document_links", { doc })),
/** The Throwable class the caret at `pos` names, for the exception breakpoint intention. */
lspExceptionClassAt: (request: RequestId, doc: DocId, pos: Pos) => typedError<{
/** The binary name (`app.Outer$Failure`), as exception breakpoints take it. */
qualifiedName: string,
/** The simple name (`Failure`). */
displayName: string,
} | null, IdeError>(__TAURI_INVOKE("lsp_exception_class_at", { request, doc, pos })),
lspExecuteCodeAction: (request: RequestId, doc: DocId, action: CodeAction, answers: FormAnswer[]) => typedError<IpcPath[], IdeError>(__TAURI_INVOKE("lsp_execute_code_action", { request, doc, action, answers })),
/**
* Runs a server command (`workspace/executeCommand`), e.g. a completion item's
@@ -1880,7 +1887,10 @@ export const commands = {
/** Whether the repository has the executable Git hook `name` (Push dialog › Run Git hooks). */
vcsHasHook: (repo: string | null, name: string) => typedError<boolean, IdeError>(__TAURI_INVOKE("vcs_has_hook", { repo, name })),
vcsIgnoreBlameRevision: (path: string, commit: string) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_ignore_blame_revision", { path, commit })),
/** `git init` in `dir` (File › New Project… "Create Git repository"). */
/**
* `git init` in `dir` (VCS › Create Git Repository…): with the git of the window's project when
* it is trusted, the default one in a window without a project.
*/
vcsInit: (dir: string) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_init", { dir })),
/** Gutter change markers for a file, computed against its current (unsaved) text. */
vcsLineHunks: (path: string) => typedError<LineHunk[], IdeError>(__TAURI_INVOKE("vcs_line_hunks", { path })),
@@ -6180,6 +6190,14 @@ export type ExceptionClassBreakpoint = {
classExclusionFilters: string[],
};
/** The exception class a caret names: a reference to it, its declaration, or a throw of it. */
export type ExceptionClassRef = {
/** The binary name (`app.Outer$Failure`), as exception breakpoints take it. */
qualifiedName: string,
/** The simple name (`Failure`). */
displayName: string,
};
/** What a session's exception class breakpoints can do. */
export type ExceptionClassSupport = {
/** Whose class names the session takes: `java`. */
+26
Переглянути файл
@@ -40,6 +40,7 @@ import { rootOfPath } from "@/platform/projectRoots";
import { isVirtualUri } from "@/platform/virtualDocs";
import { cornerInset } from "@/editor/core/cm/cornerInset";
export { iconAreaSource, mapLineStart, type IconAreaSource } from "@/editor/core/cm/iconArea";
export { disambiguateTitles } from "@/editor/core/model/tabTitles";
export {
invalidateNavigationProviders,
navigationEpoch,
@@ -572,6 +573,31 @@ export function contributedIntentions(view: EditorView): ContributedIntention[]
});
}
/**
* Providers of context actions that need an answer from the language server first. ⌥↵ waits for
* them along with the server's code actions; the light bulb does too. `signal` aborts when the
* answer is no longer wanted (the caret moved on).
*/
export const asyncIntentionProviders =
Facet.define<(view: EditorView, signal: AbortSignal) => Promise<ContributedIntention[]>>();
export async function contributedIntentionsAsync(
view: EditorView,
signal: AbortSignal,
): Promise<ContributedIntention[]> {
const found = await Promise.all(
view.state.facet(asyncIntentionProviders).map((p) =>
Promise.resolve()
.then(() => p(view, signal))
.catch((e: unknown) => {
if (!signal.aborted) console.error("intention provider failed", e);
return [];
}),
),
);
return found.flat();
}
// --- navigation history ------------------------------------------------------
/** One entry of the Back/Forward (⌘[ / ⌘]) history. 0-based line, UTF-16 col. */
+6
Переглянути файл
@@ -26,6 +26,12 @@ describe("disambiguateTitles", () => {
expect(m.get("/r/a/d/f.ts")).toBe("d");
});
it("distinguishes directory names that occur at different depths", () => {
const paths = ["/r/prod/shared/f.ts", "/r/shared/prod/f.ts", "/r/test/shared/f.ts"];
const labels = disambiguateTitles(paths);
expect(paths.map((path) => labels.get(path))).toEqual(["prod/shared", "shared/prod", "test"]);
});
it("ignores duplicates of the same path", () => {
expect(disambiguateTitles(["/p/a/x.ts", "/p/a/x.ts"]).size).toBe(0);
});
+19 -20
Переглянути файл
@@ -1,6 +1,6 @@
/**
* IDEA-style editor tab titles for files that share a name: the nearest parent
* directory that tells them apart is shown after the name (`lib.rs — ide-lsp`
* Directory hints for files that share a name: a distinguishing parent
* directory is shown after the name (`lib.rs — ide-lsp`
* for `crates/ide-lsp/src/lib.rs` next to `crates/ide-vcs/src/lib.rs`).
*/
@@ -27,25 +27,24 @@ export function disambiguateTitles(paths: readonly string[], titleOf = baseName)
for (const group of groups.values()) {
if (group.length < 2) continue;
const dirs = group.map(parents);
const nameCounts = new Map<string, number>();
const suffixCounts = new Map<string, number>();
const suffixes = dirs.map((names) => {
for (const name of new Set(names)) {
nameCounts.set(name, (nameCounts.get(name) ?? 0) + 1);
}
let suffix = "";
return names.map((name) => {
suffix = suffix ? `${name}/${suffix}` : name;
suffixCounts.set(suffix, (suffixCounts.get(suffix) ?? 0) + 1);
return suffix;
});
});
group.forEach((path, i) => {
const own = dirs[i]!;
let hint: string | null = null;
for (let depth = 0; depth < own.length; depth++) {
const seg = own[depth]!;
if (dirs.every((other, j) => j === i || other[depth] !== seg)) {
hint = seg;
break;
}
}
if (hint === null) {
// No single directory is unique: the shortest distinguishing parent path.
const suffix = (d: string[], k: number) => d.slice(0, k).reverse().join("/");
for (let k = 2; k <= own.length && hint === null; k++) {
const mine = suffix(own, k);
if (dirs.every((other, j) => j === i || suffix(other, k) !== mine)) hint = mine;
}
}
out.set(path, hint ?? (own.length ? own.slice().reverse().join("/") : "/"));
const name = dirs[i]!.find((segment) => nameCounts.get(segment) === 1);
const paths = suffixes[i]!;
const hint = name ?? paths.find((suffix, depth) => depth > 0 && suffixCounts.get(suffix) === 1);
out.set(path, hint ?? paths.at(-1) ?? "/");
});
}
return out;
+22
Переглянути файл
@@ -150,6 +150,28 @@
.deprecated {
text-decoration-line: line-through;
}
.tabPath {
--tab-directory-min: min(5ch, 25%);
display: flex;
}
.tabDirectory > span,
.tabFilename {
overflow: hidden;
text-overflow: ellipsis;
}
.tabDirectory {
flex: 0 1000 max-content;
/* Leave space for a short prefix without stretching one that already fits. */
width: var(--tab-directory-min);
color: var(--fg-subtle);
}
.tabDirectory > span {
display: block;
}
.tabFilename {
flex: none;
max-width: calc(100% - var(--tab-directory-min));
}
.dupe {
color: var(--fg-faint);
margin-left: 4px;
+10 -2
Переглянути файл
@@ -219,15 +219,23 @@ function PaneView({ paneId }: { paneId: string }) {
const pin = t.pinned ? <Icon name="pin" size={11} className={styles.pin} label="Pinned" /> : null;
const file = t.input.kind === "file" && t.input.path ? files.get(t.input.path) : undefined;
const title = markModified && dirty[i] ? `*${name}` : name;
const prefix = t.input.kind === "file" && dupe ? (dupe.endsWith("/") ? dupe : `${dupe}/`) : null;
return {
id: t.id,
label: (
label: prefix ? (
<span className={styles.tabPath}>
<span className={styles.tabDirectory}>
<span>{prefix}</span>
</span>
<span className={clsx(styles.tabFilename, file?.deprecated && styles.deprecated)}>{title}</span>
</span>
) : (
<>
{file?.deprecated ? <span className={styles.deprecated}>{title}</span> : title}
{dupe && <span className={styles.dupe}>{dupe}</span>}
</>
),
text: dupe ? `${name} — ${dupe}` : name,
text: prefix ? `${prefix}${name}` : dupe ? `${name} — ${dupe}` : name,
icon: showFileIcon
? t.input.kind === "file" && t.input.path
? (tabIcons[i] ?? file?.icon)
+27 -18
Переглянути файл
@@ -532,20 +532,6 @@
.renamePreview .previewList {
overflow: visible;
}
.renamePreview .previewName {
min-width: 0;
max-width: 55%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.renamePreview .previewOp {
flex: 0 1 auto;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.renamePreview .previewWarning {
overflow-wrap: anywhere;
}
@@ -571,23 +557,46 @@
padding: 0 14px;
font-size: var(--fs-ui);
}
.previewName {
color: var(--fg-emphasis);
.previewFile {
flex: 1 1 auto;
display: flex;
align-items: baseline;
gap: var(--space-2);
min-width: 0;
}
.previewPath {
.previewName,
.previewDirectory,
.previewOp {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.previewName {
flex: none;
max-inline-size: 100%;
color: var(--fg-emphasis);
}
.previewFile:has(.previewDirectory) .previewName {
max-inline-size: 70%;
}
.previewDirectory {
color: var(--fg-subtle);
font-size: var(--fs-small);
direction: rtl;
}
.previewOp,
.previewCount {
flex: none;
font-size: var(--fs-small);
color: var(--fg-muted);
}
.previewOp {
max-inline-size: 55%;
}
.previewCount {
flex: none;
font-variant-numeric: tabular-nums;
}
.previewWarning {
flex: none;
+26 -1
Переглянути файл
@@ -15,7 +15,7 @@ vi.mock("@/workbench/contributions", async (orig) => {
});
const { LspPopups, DocumentationWindow } = await import("./Popups");
const { closePopup, openPopup, useLspPopup } = await import("./popupStore");
const { closePopup, openPopup, updatePopup, useLspPopup } = await import("./popupStore");
const { useDocWindow, hoverDoc, pushHistory, stepHistory, hoverCandidates } = await import("./docs");
const { mountHoverDoc } = await import("./DocView");
const { hoverSource } = await import("./hover");
@@ -139,6 +139,31 @@ describe("list popup", () => {
expect(onClose).toHaveBeenCalledOnce();
});
it("keeps the chosen intention when a quick-fix section arrives ahead of it", () => {
const local = ["Extract variable", "Inline value"].map((label) => ({
id: label,
label,
section: { id: "intentions" },
run: vi.fn(),
}));
openPopup({ kind: "list", title: "Intentions", anchor: { x: 0, y: 0 }, items: local, busy: true });
render(<LspPopups />);
fireEvent.keyDown(screen.getByRole("listbox"), { key: "ArrowDown" });
expect(screen.getByRole("option", { name: "Inline value", selected: true })).toBeVisible();
const runFix = vi.fn();
act(() =>
updatePopup("list", {
busy: false,
items: [{ id: "fix", label: "Correct type", section: { id: "quick-fixes" }, run: runFix }, ...local],
}),
);
expect(screen.getByRole("option", { name: "Inline value", selected: true })).toBeVisible();
fireEvent.keyDown(screen.getByRole("listbox"), { key: "Enter" });
expect(local[1]!.run).toHaveBeenCalledOnce();
expect(runFix).not.toHaveBeenCalled();
});
it("focuses the rows, not the header's pin button, when it opens", () => {
openPopup({
kind: "list",
+37 -29
Переглянути файл
@@ -22,7 +22,7 @@ import {
selectableText,
T,
} from "@/ui";
import { basename, relativePath, useProject } from "@/platform/project";
import { basename, relativeDir, relativePath, useProject } from "@/platform/project";
import {
closePopup,
updatePopup,
@@ -112,14 +112,10 @@ function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
const [query, setQuery] = useState("");
const rows = useMemo(() => listPopupRows(popup.items, query), [popup.items, query]);
const firstEnabled = rows.findIndex((row) => row.kind === "action" && !row.item.disabled);
const [active, setActive] = useState(firstEnabled);
const clamped = Math.min(active, rows.length - 1);
const [activeId, setActiveId] = useState<string | null>(null);
const selected = rows.findIndex((row) => row.kind === "action" && row.item.id === activeId);
const activeIndex =
rows[clamped]?.kind === "action"
? clamped
: firstEnabled >= 0
? firstEnabled
: firstSelectable(rows, isListSection);
selected >= 0 ? selected : firstEnabled >= 0 ? firstEnabled : firstSelectable(rows, isListSection);
const activeRow = rows[activeIndex];
const activeItem = activeRow?.kind === "action" ? activeRow.item : undefined;
const showIcons = !popup.compact || popup.items.some((item) => item.icon || item.symbol);
@@ -183,11 +179,11 @@ function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
if (item) activate(item);
} else if (e.key === "Backspace" && query) {
setQuery(query.slice(0, -1));
setActive(-1);
setActiveId(null);
e.preventDefault();
} else if (e.key.length === 1 && !(e.key === " " && !query)) {
setQuery(query + e.key);
setActive(-1);
setActiveId(null);
e.preventDefault();
}
};
@@ -297,7 +293,10 @@ function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
row.kind === "section" && row.label ? <T>{row.label}</T> : <span className={styles.listDivider} />
}
activeIndex={activeIndex}
onActiveChange={setActive}
onActiveChange={(index) => {
const row = rows[index];
setActiveId(row?.kind === "action" ? row.item.id : null);
}}
hoverSelects
autoFocus
aria-label={popup.title}
@@ -762,25 +761,34 @@ function PreviewDialog({ popup }: { popup: Extract<LspPopup, { kind: "preview" }
</ul>
) : (
<ul data-testid="refactor-preview" className={styles.previewList} aria-label={tx("Changes")}>
{summary.entries.map((e) => (
<li key={e.path} className={styles.previewRow}>
<Icon name={fileIconName(basename(e.path), e.path)} size={14} className={styles.itemIcon} />
<span className={styles.previewName} title={relativePath(root, e.path)}>
{basename(e.path)}
</span>
<span className={styles.previewPath} title={relativePath(root, e.path)}>
{relativePath(root, e.path)}
</span>
<span className={styles.spacer} />
{e.operation === "rename" && e.to && <span className={styles.previewOp}>→ {basename(e.to)}</span>}
{e.operation && e.operation !== "rename" && <span className={styles.previewOp}>{e.operation}</span>}
{e.edits > 0 && (
<span className={styles.previewCount}>
{e.edits} {e.edits === 1 ? "occurrence" : "occurrences"}
{summary.entries.map((e) => {
const name = basename(e.path);
const directory = relativeDir(root, e.path);
return (
<li key={e.path} className={styles.previewRow}>
<Icon name={fileIconName(name, e.path)} size={14} className={styles.itemIcon} />
<span className={styles.previewFile} title={relativePath(root, e.path)}>
<span className={styles.previewName}>{name}</span>
{directory && (
<span className={styles.previewDirectory}>
<bdi>{directory}</bdi>
</span>
)}
</span>
)}
</li>
))}
{e.operation === "rename" && e.to && (
<span className={styles.previewOp} title={relativePath(root, e.to)}>
→ {basename(e.to)}
</span>
)}
{e.operation && e.operation !== "rename" && <span className={styles.previewOp}>{e.operation}</span>}
{e.edits > 0 && (
<span className={styles.previewCount}>
{e.edits} {e.edits === 1 ? "occurrence" : "occurrences"}
</span>
)}
</li>
);
})}
</ul>
)}
</Dialog>
+10
Переглянути файл
@@ -104,6 +104,13 @@ const fixEslintProblems = (v: EditorView) =>
none: "No ESLint problems to fix",
label: "Fix ESLint Problems",
});
/** WebStorm's Fix Stylelint Problems: vscode-stylelint's fix-all for the whole file. */
const fixStylelintProblems = (v: EditorView) =>
runKindAction(v, "source.fixAll.stylelint", {
whole: true,
none: "No Stylelint problems to fix",
label: "Fix Stylelint Problems",
});
/**
* typescript-language-server's organize imports only sorts and merges them; removing the unused
* ones is its own action, so Optimize Imports runs that first in these languages.
@@ -295,6 +302,9 @@ export function registerLspActions(): () => void {
editorAction("code.fixEslintProblems", "Fix ESLint Problems", "Code", fixEslintProblems, {
keywords: ["eslint", "lint", "fix all"],
}),
editorAction("code.fixStylelintProblems", "Fix Stylelint Problems", "Code", fixStylelintProblems, {
keywords: ["stylelint", "lint", "css", "fix all"],
}),
editorAction("code.optimizeImports", "Optimize Imports", "Code", optimizeImports, {
keywords: ["organize imports"],
}),
+53
Переглянути файл
@@ -54,6 +54,7 @@ const {
withInspectionControls,
} = await import("./intentions");
const { useLspPopup, closePopup } = await import("./popupStore");
const { asyncIntentionProviders } = await import("@/editor/api");
const { setFileDiagnostics, toLintDiagnostics } = await import("./diagnostics");
const { lspDoc } = await import("./lsp");
@@ -195,6 +196,58 @@ describe("⌥↵ popup timing", () => {
});
});
describe("context actions a feature finds through the language server", () => {
const editor = (...providers: Parameters<typeof asyncIntentionProviders.of>[0][]) => {
const view = new EditorView({
state: EditorState.create({
doc: "f(1);\n",
extensions: [
lspDoc.of({ doc: 1, path: "/p/A.java", language: "java", uiMode: null, readOnly: false }),
...providers.map((p) => asyncIntentionProviders.of(p)),
],
}),
});
views.push(view);
return view;
};
const labels = () => (useLspPopup.getState().popup as { items: { label: string }[] }).items.map((i) => i.label);
const intention = (label: string) => ({ id: label, label, run: () => {} });
it("waits for them and lists them with the server's actions", async () => {
let answer!: (v: ReturnType<typeof intention>[]) => void;
const view = editor(() => new Promise((r) => (answer = r)));
lspCodeActions.mockResolvedValue({ status: "ok", data: [{ ...resolved, edit: null }] });
const shown = showIntentions(view);
await Promise.resolve();
answer([intention("Create exception breakpoint on Failure")]);
await shown;
expect(labels()).toEqual(
expect.arrayContaining(["Create exception breakpoint on Failure", "Introduce local variable"]),
);
});
it("lists them alone when the server has nothing", async () => {
const view = editor(async () => [intention("Disable exception breakpoint on Failure")]);
lspCodeActions.mockResolvedValue({ status: "ok", data: [] });
await showIntentions(view);
expect(labels()).toEqual(["Disable exception breakpoint on Failure"]);
});
it("keeps the other rows when one provider fails", async () => {
const error = vi.spyOn(console, "error").mockImplementation(() => {});
const view = editor(
async () => {
throw new Error("boom");
},
async () => [intention("Enable exception breakpoint on Failure")],
);
lspCodeActions.mockResolvedValue({ status: "ok", data: [] });
await showIntentions(view);
expect(labels()).toEqual(["Enable exception breakpoint on Failure"]);
error.mockRestore();
});
});
describe("inspection controls in ⌥↵ (issue #42)", () => {
const editorAt = (path: string) => {
const view = new EditorView({
+28 -7
Переглянути файл
@@ -11,6 +11,7 @@ import { diff } from "@codemirror/merge";
import { commands, isCancelled, type CodeAction, type Diagnostic } from "@/platform/ipc";
import {
contributedIntentions,
contributedIntentionsAsync,
contributedQuickFixes,
intentionProviders,
intentionsChanged,
@@ -60,11 +61,18 @@ export function quickFixIcon(view: EditorView): "bulb" | "bulb-fix" {
const isFixItem = (item: ListPopupItem) => item.quickFix ?? item.icon === "bulb-fix";
/** Local and language-server fixes share icons and the same stable ordering. */
/** Local and language-server fixes share icons and are grouped separately from other actions. */
export function listedIntentions(view: EditorView, items: ListPopupItem[]): ListPopupItem[] {
const rank = (item: ListPopupItem) => (item.disabled ? 4 : 0) + (isFixItem(item) ? 0 : 2) + (item.emphasis ? 0 : 1);
return items
.map((item) => (isFixItem(item) ? { ...item, quickFix: true, icon: quickFixIcon(view) } : item))
.map((item) => {
const fix = isFixItem(item);
return {
...item,
...(fix && { quickFix: true, icon: quickFixIcon(view) }),
section: item.section ?? { id: item.disabled ? "unavailable" : fix ? "quick-fixes" : "intentions" },
};
})
.sort((a, b) => rank(a) - rank(b));
}
@@ -497,6 +505,7 @@ export function withInspectionControls(view: EditorView, items: ListPopupItem[])
...inspections.map((inspection) => ({
id: `inspection:${inspection.id}`,
label: tx`Inspection '${txPart(inspection.name)}' options`,
section: { id: "inspection-options" },
icon: "settings",
run: () => editInspectionSettings(inspection.id),
submenu: intentionControls(inspection),
@@ -566,13 +575,18 @@ export async function showIntentions(view: EditorView) {
display(itemsFor([]), true);
}, INTENTIONS_POPUP_DELAY_MS);
const asked = new AbortController();
try {
let failure: unknown = null;
// Like IDEA, only applicable intentions are listed (servers also report disabled refactorings).
const actions = await fetchIntentions(view).catch((e: unknown) => {
failure = e;
return null;
});
const [actions, found] = await Promise.all([
fetchIntentions(view).catch((e: unknown) => {
failure = e;
return null;
}),
contributedIntentionsAsync(view, asked.signal),
]);
local.push(...found);
clearTimeout(timer);
const items = actions ? itemsFor(actions) : withInspectionControls(view, listedIntentions(view, local));
if (!items.length) {
@@ -591,6 +605,8 @@ export async function showIntentions(view: EditorView) {
clearTimeout(timer);
if (ours()) closePopup();
reportLspError(view, e, true);
} finally {
asked.abort();
}
}
@@ -696,6 +712,7 @@ const bulbField = StateField.define<Bulb | null>({
const bulbPlugin = ViewPlugin.fromClass(
class {
private lookup = debounce(() => void this.run(), 500);
private asked: AbortController | null = null;
constructor(private view: EditorView) {
this.lookup();
}
@@ -724,7 +741,9 @@ const bulbPlugin = ViewPlugin.fromClass(
const typoFix = spellingIntentions(this.view).length > 0;
const selection = state.selection.main;
const ownFix = contributedQuickFixes(this.view, selection.from, selection.to).length > 0;
const local = typoFix || ownFix || contributedIntentions(this.view).length > 0;
this.asked?.abort();
const asked = (this.asked = new AbortController());
const found = contributedIntentionsAsync(this.view, asked.signal);
const backoff = codeActionBackoff.active(doc.doc);
let actions: CodeAction[] = [];
if (!backoff) {
@@ -734,6 +753,7 @@ const bulbPlugin = ViewPlugin.fromClass(
if (isUnavailable(e)) codeActionBackoff.mark(doc.doc);
}
}
const local = typoFix || ownFix || contributedIntentions(this.view).length > 0 || (await found).length > 0;
if (this.view.state.doc !== state.doc || !this.view.state.selection.eq(state.selection) || !this.view.hasFocus)
return;
const line = state.doc.lineAt(state.selection.main.head).number;
@@ -751,6 +771,7 @@ const bulbPlugin = ViewPlugin.fromClass(
}
destroy() {
this.lookup.cancel();
this.asked?.abort();
}
},
);
+7 -1
Переглянути файл
@@ -94,10 +94,16 @@
flex: none;
color: var(--fg-muted);
}
.fileName {
.fileName,
.directory {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
}
.directory {
flex: 0 2 auto;
color: var(--fg-subtle);
}
.line {
overflow: hidden;
text-align: right;
+12 -5
Переглянути файл
@@ -8,7 +8,7 @@ import { create } from "zustand";
import clsx from "clsx";
import { EditorState, StateEffect, StateField } from "@codemirror/state";
import { Decoration, EditorView } from "@codemirror/view";
import { codePreviewExtensions } from "@/editor/api";
import { codePreviewExtensions, disambiguateTitles } from "@/editor/api";
import { basename } from "@/platform/project";
import { shortcutLabel } from "@/platform/keymap";
import { Icon, IconButton, List, Popup, Select, Spinner, fileIconName, listNavigate } from "@/ui";
@@ -86,6 +86,14 @@ function UsagesPopupInner() {
const preview = useUsagesPopupPreview((s) => s.preview);
const rowHeight = useRowHeight(ROW);
const all = useMemo<Usage[]>(() => groups.flatMap((g) => g.usages), [groups]);
const directories = useMemo(
() =>
disambiguateTitles(
groups.map((g) => g.path),
basename,
),
[groups],
);
const [filter, setFilter] = useState("");
const accessOptions = useUsageAccessOptions();
const items = useMemo(
@@ -233,11 +241,10 @@ function UsagesPopupInner() {
}
renderItem={(u) => (
<div className={styles.row} data-testid="usage-row" data-path={u.path} data-line={u.line}>
<span className={styles.file}>
<span className={styles.file} title={u.path}>
<Icon name={fileIconName(basename(u.path), u.path)} size={16} className={styles.icon} />
<span className={styles.fileName} title={u.path}>
{basename(u.path)}
</span>
<span className={styles.fileName}>{basename(u.path)}</span>
{directories.has(u.path) && <span className={styles.directory}>{directories.get(u.path)}</span>}
</span>
<span className={styles.line}>{u.line + 1}</span>
<UsagePreview usage={u} />
+12 -6
Переглянути файл
@@ -21,7 +21,7 @@ import { UsagesPopup } from "./UsagesPopup";
import { findUsages, rerunActiveUsages, resetUsages, showUsageResults, showUsagesPopup } from "./usages";
import { HierarchyTabs, HierarchyView } from "./HierarchyView";
import { resetHierarchy, showHierarchy } from "./hierarchy";
import { eslintCovers, installServerEvents } from "./servers";
import { installServerEvents, linterCovers } from "./servers";
import { ServerStatus } from "./ServerStatus";
import { reportProblems } from "./problemsReport";
import { installWorkspaceEditUndo } from "./workspaceUndo";
@@ -60,15 +60,21 @@ export function activate(): () => void {
reportProblems(),
installProblemDecorations(),
installServerEvents(),
// WebStorm's editor popup offers Fix ESLint Problems wherever ESLint lints the file.
// WebStorm's editor popup offers Fix ESLint / Stylelint Problems wherever that linter lints the file.
registerMenuGroup({
id: "codeInsight.eslint",
menus: ["editor"],
order: 40,
items: (_menu, { paths }) =>
paths.length === 1 && eslintCovers(paths[0]!, getContext().editorLangId as string | null)
? [{ kind: "action", action: "code.fixEslintProblems" }]
: [],
items: (_menu, { paths }) => {
if (paths.length !== 1) return [];
const language = getContext().editorLangId as string | null;
return [
["eslint", "code.fixEslintProblems"],
["stylelint", "code.fixStylelintProblems"],
]
.filter(([server]) => linterCovers(server!, paths[0]!, language))
.map(([, action]) => ({ kind: "action" as const, action: action! }));
},
}),
installWorkspaceEditUndo(),
registerToolWindow({
+20 -9
Переглянути файл
@@ -23,7 +23,7 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
const { emitLocalIdeEvent } = await import("@/platform/ipc");
const { useProject } = await import("@/platform/project");
const { provideNotificationService } = await import("@/workbench/contributions");
const { BUSY_SHOW_DELAY_MS, eslintCovers, installServerEvents, restartServer, serversSummary, useServers } =
const { BUSY_SHOW_DELAY_MS, installServerEvents, linterCovers, restartServer, serversSummary, useServers } =
await import("./servers");
describe("server status", () => {
@@ -177,7 +177,7 @@ describe("serversSummary", () => {
});
});
describe("ESLint coverage", () => {
describe("linter coverage", () => {
afterEach(() => useServers.setState({ servers: new Map() }));
it("covers files of its languages below its configuration while it runs", () => {
@@ -188,14 +188,25 @@ describe("ESLint coverage", () => {
]),
});
eslint("ready", "/p/web");
expect(eslintCovers("/p/web/src/a.ts", "typescript")).toBe(true);
expect(eslintCovers("/p/web/src/a.ts", "rust")).toBe(false);
expect(eslintCovers("/p/api/a.ts", "typescript")).toBe(false);
expect(eslintCovers("/p/webapp/a.ts", "typescript")).toBe(false);
expect(eslintCovers("/p/web/src/a.ts", null)).toBe(false);
expect(linterCovers("eslint", "/p/web/src/a.ts", "typescript")).toBe(true);
expect(linterCovers("eslint", "/p/web/src/a.ts", "rust")).toBe(false);
expect(linterCovers("eslint", "/p/api/a.ts", "typescript")).toBe(false);
expect(linterCovers("eslint", "/p/webapp/a.ts", "typescript")).toBe(false);
expect(linterCovers("eslint", "/p/web/src/a.ts", null)).toBe(false);
eslint("starting", "/p/web");
expect(eslintCovers("/p/web/src/a.ts", "typescript")).toBe(false);
expect(linterCovers("eslint", "/p/web/src/a.ts", "typescript")).toBe(false);
eslint("ready", "C:\\p\\web");
expect(eslintCovers("C:\\p\\web\\a.js", "javascript")).toBe(true);
expect(linterCovers("eslint", "C:\\p\\web\\a.js", "javascript")).toBe(true);
});
it("tells Stylelint apart from ESLint", () => {
useServers.setState({
servers: new Map([
[2, { id: 2, name: "stylelint", status: "ready", message: null, languages: ["css", "scss"], root: "/p/web" }],
]),
});
expect(linterCovers("stylelint", "/p/web/src/app.scss", "scss")).toBe(true);
expect(linterCovers("eslint", "/p/web/src/app.scss", "scss")).toBe(false);
expect(linterCovers("stylelint", "/p/web/src/app.less", "less")).toBe(false);
});
});
+3 -3
Переглянути файл
@@ -215,13 +215,13 @@ export function serversSummary(
const RUNNING: ReadonlySet<ServerStatus> = new Set(["ready", "busy"]);
/** Whether a running ESLint server covers `path` (a `language` file below its configuration). */
export function eslintCovers(path: string, language: string | null | undefined): boolean {
/** Whether a running `server` (ESLint, Stylelint) covers `path`: a `language` file below its configuration. */
export function linterCovers(server: string, path: string, language: string | null | undefined): boolean {
if (!language) return false;
const norm = (p: string) => p.replace(/\\/g, "/").replace(/\/+$/, "");
const file = norm(path);
for (const s of useServers.getState().servers.values()) {
if (s.name !== "eslint" || !RUNNING.has(s.status) || !s.languages.includes(language)) continue;
if (s.name !== server || !RUNNING.has(s.status) || !s.languages.includes(language)) continue;
const root = s.root ? norm(s.root) : null;
if (!root || file.startsWith(`${root}/`)) return true;
}
+117
Переглянути файл
@@ -0,0 +1,117 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import type { ExceptionClassRef } from "@/bindings";
const lspExceptionClassAt = vi.fn();
const cancelRequest = vi.fn(async () => ({ status: "ok" as const, data: null }));
vi.mock("@/platform/ipc", async (orig) => {
const actual = await orig<typeof import("@/platform/ipc")>();
return { ...actual, isTauri: () => true, commands: { ...actual.commands, lspExceptionClassAt, cancelRequest } };
});
const { contributedIntentionsAsync } = await import("@/editor/api");
const { exceptionBreakpointIntention } = await import("../editor/exceptionBreakpointIntention");
const {
addExceptionClass,
loadExceptionClasses,
removeAllExceptionClasses,
updateExceptionClass,
useExceptionClasses,
} = await import("../breakpoints/exceptionClasses");
const FAILURE: ExceptionClassRef = { qualifiedName: "app.Main$Failure", displayName: "Failure" };
const text = "class Main {\n void f() { throw new Failure(); }\n}\n";
const views: EditorView[] = [];
const editor = (language = "java", caret = text.indexOf("Failure")) => {
const ctx = { doc: 7, path: "/p/Main.java", language, uiMode: null, readOnly: false };
const view = new EditorView({
state: EditorState.create({
doc: text,
selection: { anchor: caret },
extensions: exceptionBreakpointIntention(ctx),
}),
});
views.push(view);
return view;
};
const offered = (view: EditorView) => contributedIntentionsAsync(view, new AbortController().signal);
const answer = (data: ExceptionClassRef | null) => lspExceptionClassAt.mockResolvedValue({ status: "ok", data });
beforeEach(() => {
localStorage.clear();
loadExceptionClasses("/p");
removeAllExceptionClasses();
});
afterEach(() => {
views.splice(0).forEach((v) => v.destroy());
vi.clearAllMocks();
});
describe("Create / Enable / Disable exception breakpoint (IDEA's intention)", () => {
it("asks the language server about the caret, in UTF-16 line and column", async () => {
answer(FAILURE);
await offered(editor());
expect(lspExceptionClassAt).toHaveBeenCalledWith(expect.any(Number), 7, { line: 1, col: 23 });
});
it("creates a breakpoint on caught and uncaught throws of the class", async () => {
answer(FAILURE);
const [action] = await offered(editor());
expect(action).toMatchObject({ label: "Create exception breakpoint on Failure", icon: "breakpoint-exception" });
await action!.run();
expect(useExceptionClasses.getState().list).toEqual([
expect.objectContaining({ className: "app.Main$Failure", caught: true, uncaught: true, enabled: true }),
]);
});
it("disables an enabled breakpoint on the class and enables a disabled one, never removing it", async () => {
answer(FAILURE);
const bp = addExceptionClass("app.Main$Failure");
const view = editor();
const [disable] = await offered(view);
expect(disable!.label).toBe("Disable exception breakpoint on Failure");
await disable!.run();
expect(useExceptionClasses.getState().list).toEqual([expect.objectContaining({ id: bp.id, enabled: false })]);
const [enable] = await offered(view);
expect(enable!.label).toBe("Enable exception breakpoint on Failure");
await enable!.run();
expect(useExceptionClasses.getState().list).toEqual([expect.objectContaining({ id: bp.id, enabled: true })]);
});
it("acts on the first breakpoint of the class, as IDEA does", async () => {
answer(FAILURE);
const first = addExceptionClass("app.Main$Failure");
updateExceptionClass(first.id, { enabled: false });
const second = addExceptionClass("app.Main$Failure");
const [action] = await offered(editor());
expect(action!.label).toBe("Enable exception breakpoint on Failure");
await action!.run();
expect(useExceptionClasses.getState().list.map((b) => [b.id, b.enabled])).toEqual([
[first.id, true],
[second.id, true],
]);
});
it("offers nothing where the caret names no exception class", async () => {
answer(null);
expect(await offered(editor())).toEqual([]);
});
it("is not offered outside Java", async () => {
answer(FAILURE);
expect(await offered(editor("kotlin"))).toEqual([]);
expect(lspExceptionClassAt).not.toHaveBeenCalled();
});
it("cancels the request when the answer is no longer wanted", async () => {
lspExceptionClassAt.mockImplementation(() => new Promise(() => {}));
const asked = new AbortController();
const pending = contributedIntentionsAsync(editor(), asked.signal);
await vi.waitFor(() => expect(lspExceptionClassAt).toHaveBeenCalled());
asked.abort();
expect(await pending).toEqual([]);
expect(cancelRequest).toHaveBeenCalledWith(lspExceptionClassAt.mock.calls[0]![0]);
});
});
+66
Переглянути файл
@@ -0,0 +1,66 @@
/**
* IDEA's Create / Enable / Disable exception breakpoint intention (ControlExceptionBreakpointIntentionAction)
* on a reference to a Java exception class, its declaration or a throw of it. The language server
* names the class; the breakpoint is one of the Java Exception Breakpoints, never removed here.
*/
import type { Extension } from "@codemirror/state";
import type { EditorView } from "@codemirror/view";
import { asyncIntentionProviders, whenSynced, type ContributedIntention, type EditorDocContext } from "@/editor/api";
import { call, commands, nextRequestId, type ExceptionClassRef } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { addExceptionClass, updateExceptionClass, useExceptionClasses } from "../breakpoints/exceptionClasses";
const firstNamed = (qualifiedName: string) =>
useExceptionClasses.getState().list.find((b) => b.className.trim() === qualifiedName);
/** IDEA decides between creating and switching when it offers the action, and applies that on run. */
function controlExceptionClass(qualifiedName: string, enable: boolean) {
const existing = firstNamed(qualifiedName);
if (existing) updateExceptionClass(existing.id, { enabled: enable });
else if (enable) addExceptionClass(qualifiedName);
}
function intentionFor(found: ExceptionClassRef): ContributedIntention {
const name = found.displayName;
const existing = firstNamed(found.qualifiedName);
const enable = !existing?.enabled;
return {
id: "debugger.controlExceptionBreakpoint",
label: !existing
? tx`Create exception breakpoint on ${name}`
: existing.enabled
? tx`Disable exception breakpoint on ${name}`
: tx`Enable exception breakpoint on ${name}`,
icon: "breakpoint-exception",
run: () => controlExceptionClass(found.qualifiedName, enable),
};
}
async function exceptionClassAt(ctx: EditorDocContext, view: EditorView, signal: AbortSignal) {
await whenSynced(view);
if (signal.aborted) return null;
const head = view.state.selection.main.head;
const line = view.state.doc.lineAt(head);
const request = nextRequestId();
const abandoned = new Promise<null>((resolve) =>
signal.addEventListener(
"abort",
() => {
void commands.cancelRequest(request).catch(() => undefined);
resolve(null);
},
{ once: true },
),
);
const asked = call(commands.lspExceptionClassAt(request, ctx.doc, { line: line.number - 1, col: head - line.from }));
// No Java server, an untrusted project, a cancelled request: no intention.
return Promise.race([asked.catch(() => null), abandoned]);
}
export function exceptionBreakpointIntention(ctx: EditorDocContext): Extension {
if (ctx.language !== "java") return [];
return asyncIntentionProviders.of(async (view, signal) => {
const found = await exceptionClassAt(ctx, view, signal);
return found && !signal.aborted ? [intentionFor(found)] : [];
});
}
+2
Переглянути файл
@@ -32,6 +32,7 @@ import { breakpointGutter } from "./editor/breakpointGutter";
import { executionPoint } from "./editor/execution";
import { runToCursorInlay } from "./editor/runToCursor";
import { installSmartStepPicking, smartStepTargets } from "./editor/smartStep";
import { exceptionBreakpointIntention } from "./editor/exceptionBreakpointIntention";
import { hotSwapMenuItems, onHotCodeReplace } from "./hotswap";
import { installFlutterHotReloadOnSave } from "./flutterReload";
import {
@@ -156,6 +157,7 @@ export function activate(): () => void {
selectionValueTooltip(),
quickEvaluateMouse(),
smartStepTargets(ctx),
exceptionBreakpointIntention(ctx),
],
}),
installSmartStepPicking(),
+18 -8
Переглянути файл
@@ -55,7 +55,8 @@
display: flex;
align-items: center;
gap: var(--space-1);
min-width: min(8ch, 45%);
/* Cap the automatic flex minimum at the space needed for a short preview. */
width: min(14ch, 50%);
flex: 1 1 0;
}
@@ -135,9 +136,8 @@
}
.type {
min-width: 0;
max-width: 25%;
flex: 0 1 auto;
min-width: min(3ch, 10%);
flex: 0 4 auto;
overflow: hidden;
text-overflow: ellipsis;
color: var(--fg-subtle);
@@ -159,11 +159,17 @@
font-size: var(--fs-ui);
}
.editRow,
.editRow > .valueGroup {
height: 100%;
}
.editInput {
flex: 1;
min-width: min(80px, 40%);
height: 18px;
padding: 0 4px;
box-sizing: border-box;
flex: 1 1 0;
min-width: 0;
height: calc(100% - var(--space-1));
padding: 0 var(--space-1);
font: inherit;
font-family: var(--font-mono);
color: var(--fg-strong);
@@ -176,6 +182,10 @@
border-color: var(--danger);
}
.editError {
max-width: 33%;
}
/* Changed since the previous stop. */
.name.changed {
color: var(--debug-changed, var(--link));
+58 -48
Переглянути файл
@@ -467,6 +467,7 @@ export function VariablesView({
editing?.key === n.key ? (
<VarEditRow
node={n}
changed={isChanged(n)}
value={editing.value}
error={editing.error}
onChange={(value) => setEditing({ ...editing, value, error: null })}
@@ -558,6 +559,7 @@ function ValueDialog({
function VarEditRow({
node,
changed,
value,
error,
onChange,
@@ -565,6 +567,7 @@ function VarEditRow({
onCancel,
}: {
node: VarNode;
changed: boolean;
value: string;
error: string | null;
onChange: (v: string) => void;
@@ -575,37 +578,36 @@ function VarEditRow({
// the global "Escape → focus editor" binding (`!popupOpen`) from firing.
useEffect(() => acquirePopup(), []);
return (
<span className={styles.row}>
<span className={styles.name} title={node.name}>
{node.name}
<span className={clsx(styles.row, styles.editRow)} title={node.name}>
<VarPrefix node={node} changed={changed} />
<span className={styles.valueGroup}>
<input
className={clsx(styles.editInput, error && styles.editInvalid)}
value={value}
autoFocus
spellCheck={false}
autoComplete="off"
aria-label={`New value of ${node.name}`}
aria-invalid={!!error || undefined}
title={error ?? undefined}
onFocus={(e) => e.currentTarget.select()}
onChange={(e) => onChange(e.target.value)}
onClick={(e) => e.stopPropagation()}
onDoubleClick={(e) => e.stopPropagation()}
onBlur={onCancel}
onKeyDown={(e) => {
e.stopPropagation();
if (e.key === "Enter") {
e.preventDefault();
onCommit();
} else if (e.key === "Escape") {
e.preventDefault();
onCancel();
}
}}
/>
{error && <span className={clsx(styles.error, styles.editError)}>{oneLine(error)}</span>}
</span>
<span className={styles.eq}>=</span>
<input
className={clsx(styles.editInput, error && styles.editInvalid)}
value={value}
autoFocus
spellCheck={false}
autoComplete="off"
aria-label={`New value of ${node.name}`}
aria-invalid={!!error || undefined}
title={error ?? undefined}
onFocus={(e) => e.currentTarget.select()}
onChange={(e) => onChange(e.target.value)}
onClick={(e) => e.stopPropagation()}
onDoubleClick={(e) => e.stopPropagation()}
onBlur={onCancel}
onKeyDown={(e) => {
e.stopPropagation();
if (e.key === "Enter") {
e.preventDefault();
onCommit();
} else if (e.key === "Escape") {
e.preventDefault();
onCancel();
}
}}
/>
{error && <span className={styles.error}>{error}</span>}
</span>
);
}
@@ -616,6 +618,31 @@ function nodeIcon(node: VarNode): string {
return node.depth0 ? "variable" : "field";
}
function VarPrefix({ node, changed, showName = true }: { node: VarNode; changed: boolean; showName?: boolean }) {
const evaluation = node.kind === "eval";
return (
<>
<Icon name={nodeIcon(node)} size={16} className={styles.nodeIcon} />
{showName && (
<>
<span
className={clsx(
styles.name,
evaluation && styles.evalName,
node.kind === "var" && styles.varName,
changed && styles.changed,
)}
title={evaluation ? node.name : undefined}
>
{evaluation ? oneLine(node.name) : node.name}
</span>
<span className={styles.eq}>=</span>
</>
)}
</>
);
}
function VarRow({
node,
changed,
@@ -655,26 +682,9 @@ function VarRow({
);
const kind = node.error ? null : classifyValue(node.value, node.typeName);
const shown = shownValue(node.value, node.typeName);
const evaluation = node.kind === "eval";
return (
<span className={styles.row} title={node.name}>
<Icon name={nodeIcon(node)} size={16} className={styles.nodeIcon} />
{!shown.entry && (
<>
<span
className={clsx(
styles.name,
evaluation && styles.evalName,
node.kind === "var" && styles.varName,
changed && styles.changed,
)}
title={evaluation ? node.name : undefined}
>
{evaluation ? oneLine(node.name) : node.name}
</span>
<span className={styles.eq}>=</span>
</>
)}
<VarPrefix node={node} changed={changed} showName={!shown.entry} />
{node.error ? (
<span className={styles.error}>{oneLine(node.error)}</span>
) : (
+2 -2
Переглянути файл
@@ -507,7 +507,7 @@ export function ConfigForm({ config, all, type, errors, template, onChange, modi
{config.kind === "tomcat" ? (
<TomcatSettings config={config} onChange={onChange} />
) : (
<>
<div className={styles.formSettings}>
{!noProcess && (
<Field
label="Run on"
@@ -860,7 +860,7 @@ export function ConfigForm({ config, all, type, errors, template, onChange, modi
}}
/>
)}
</>
</div>
)}
</div>
);
+15 -6
Переглянути файл
@@ -143,7 +143,10 @@ export function foldRows(
const fold: Fold = { start: i, count: j - i, id: lines[i]!.id, expanded: expanded.has(lines[i]!.id) };
const prev = rows[rows.length - 1];
if (prev?.kind === "line") prev.fold = fold;
else if (!fold.expanded) rows.push({ kind: "fold", fold });
else if (fold.expanded) {
rows.push({ kind: "line", index: i, fold });
i++;
} else rows.push({ kind: "fold", fold });
if (fold.expanded) for (; i < j; i++) rows.push({ kind: "line", index: i });
i = j;
continue;
@@ -230,7 +233,7 @@ export function ConsoleView({
// Pending input continues the open line (a prompt), or starts a row of its own.
const lastRow = folded[folded.length - 1];
const inputInline =
!!input && !!model.openLine && lastRow?.kind === "line" && !lastRow.fold && lines[lastRow.index] === model.openLine;
!!input && !!model.openLine && lastRow?.kind === "line" && lines[lastRow.index] === model.openLine;
const inputRow = !!input && !inputInline;
const [widest] = useState(() => new WidestColumns());
// eslint-disable-next-line react-hooks/exhaustive-deps -- `version` marks in-place appends to `lines`
@@ -255,7 +258,7 @@ export function ConsoleView({
getItemKey: (i) => {
const r = rows[i];
if (!r) return "input";
return r.kind === "fold" ? `f${r.fold.id}` : (lines[r.index]?.id ?? i);
return r.kind === "fold" ? r.fold.id : (lines[r.index]?.id ?? i);
},
});
@@ -486,7 +489,7 @@ export function ConsoleView({
return;
}
if (copySelectionOnKeyDown(e, selectedOutput)) return;
if (!input) return;
if (!input || e.target instanceof HTMLButtonElement) return;
if (e.key === "d" && e.ctrlKey && !e.metaKey && !e.altKey) {
e.preventDefault();
input.onEof();
@@ -523,19 +526,24 @@ export function ConsoleView({
const foldButton = (fold: Fold, attached: boolean) =>
fold.expanded ? (
<button
key={fold.id}
type="button"
className={styles.foldToggle}
style={{ height: rowHeight }}
title={tx("Collapse folded lines")}
aria-label={tx("Collapse folded lines")}
aria-expanded={true}
onClick={() => toggleFold(fold.id)}
>
<Icon name="chevron-up" size={10} />
<Icon name="chevron-down" size={10} />
</button>
) : (
<button
key={fold.id}
type="button"
className={styles.fold}
title={tx("Expand folded lines")}
aria-expanded={false}
onClick={() => toggleFold(fold.id)}
>
{`${attached ? " " : ""}${fold.count === 1 ? tx`<${fold.count} internal line>` : tx`<${fold.count} internal lines>`}`}
@@ -651,6 +659,7 @@ export function ConsoleView({
className={clsx(styles.line, styles[line.kind])}
style={{ ...rowStyle(item.start), color, background: ruled?.line?.bg }}
>
{row.fold?.expanded && foldButton(row.fold, false)}
<Line
line={line}
marks={marksByLine.get(row.index)}
@@ -658,7 +667,7 @@ export function ConsoleView({
length={line.text.length}
cwd={cwd}
/>
{row.fold && foldButton(row.fold, true)}
{row.fold && !row.fold.expanded && foldButton(row.fold, true)}
{inputInline && item.index === rows.length - 1 && pendingInput}
{"\n"}
</div>
+51 -22
Переглянути файл
@@ -212,7 +212,7 @@
top: 0;
left: 0;
min-width: 100%;
padding: 0 12px;
padding: 0 var(--space-3);
line-height: inherit;
white-space: pre;
tab-size: 4;
@@ -258,12 +258,12 @@
.testStatusBar {
flex: none;
display: flex;
flex-wrap: wrap;
align-items: center;
min-height: 28px;
border-bottom: 1px solid var(--border);
}
.testToolbar {
flex-wrap: wrap;
gap: var(--space-1);
padding: var(--space-0-5) var(--space-1);
}
@@ -275,27 +275,36 @@
border-inline-end: 1px solid var(--border);
}
.testStatusBar {
gap: var(--space-0-5) var(--space-2);
gap: var(--space-2);
padding: var(--space-0-5) var(--space-2);
border-block-end-width: var(--space-0-5);
font-size: var(--fs-ui);
color: var(--fg-secondary);
}
.testStatusBar[data-outcome="passed"] {
border-block-end-color: var(--success);
}
.testStatusBar[data-outcome="skipped"] {
border-block-end-color: var(--warning);
}
.testStatusBar[data-running] {
border-block-end-color: var(--accent);
}
.testStatusBar[data-outcome="failed"] {
border-block-end-color: var(--danger);
}
.testCounts {
flex: 1 1 auto;
display: flex;
flex-wrap: wrap;
gap: var(--space-0-5) var(--space-2);
min-width: 0;
white-space: nowrap;
}
.testStatus,
.testTotalDuration {
.testStatus {
flex: none;
}
.testTotalDuration {
margin-left: auto;
color: var(--fg-subtle);
font-size: var(--fs-small);
font-variant-numeric: tabular-nums;
}
.testTree {
@@ -665,22 +674,39 @@
gap: var(--space-2);
}
.configFields {
flex: 1;
min-height: 0;
display: grid;
grid-template-columns: fit-content(40%) minmax(0, 1fr);
grid-template-rows: [notice] auto [header] auto [options] minmax(0, 1fr);
column-gap: var(--space-3);
row-gap: var(--space-2);
align-content: start;
min-width: 0;
}
.configFields > * {
.configFields > *,
.formSettings > * {
grid-column: 1 / -1;
min-width: 0;
}
.configFields:not(.configFieldsTomcat) > .field,
.configFields > .notice {
grid-row: notice;
}
.configFields:not(.configFieldsTomcat) > .notice,
.configFields:not(.configFieldsTomcat) > .formHeader {
margin-bottom: var(--space-2);
}
.configFields:not(.configFieldsTomcat) > .formHeader,
.configFields:not(.configFieldsTomcat) > .formHeader > .field {
.configFields:not(.configFieldsTomcat) > .formHeader > .field,
.formSettings > .field {
grid-template-columns: subgrid;
}
.formSettings {
display: grid;
grid-row: options;
grid-template-columns: subgrid;
row-gap: var(--space-2);
align-content: start;
overflow: auto;
}
.formHeader > .field {
grid-column: 1 / -1;
}
@@ -688,8 +714,6 @@
overflow: hidden;
}
.configFieldsTomcat {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
gap: var(--space-2);
@@ -793,6 +817,7 @@
}
.formHeader {
display: grid;
grid-row: header;
grid-template-columns: minmax(0, 1fr);
align-items: center;
gap: var(--space-4);
@@ -1118,15 +1143,19 @@
color: var(--fg);
}
.foldToggle {
display: inline-flex;
align-items: center;
margin-left: 6px;
padding: 0 2px;
position: sticky;
inset-inline-start: 0;
z-index: 1;
display: inline-grid;
place-items: center;
width: var(--space-3);
margin-inline-start: calc(-1 * var(--space-3));
padding: 0;
border: none;
border-radius: 3px;
background: none;
border-radius: var(--radius-small);
background: var(--bg-app);
color: var(--fg-faint);
vertical-align: middle;
vertical-align: top;
cursor: pointer;
}
.foldToggle:hover {
+10 -13
Переглянути файл
@@ -112,27 +112,24 @@ export function TestStatusBar({
running: boolean;
}) {
const counts = useMemo(() => results.counts(), [results, version]); // eslint-disable-line react-hooks/exhaustive-deps
const status = running
? "running"
: counts.failed
? "failed"
: counts.passed
? "passed"
: counts.skipped
? "skipped"
: null;
const outcome = counts.failed ? "failed" : counts.passed ? "passed" : counts.skipped ? "skipped" : null;
const duration = results.summary.durationMs;
return (
<div className={styles.testStatusBar} role="status">
<StatusIcon status={status} />
<div
className={styles.testStatusBar}
role="status"
data-running={running || undefined}
data-outcome={outcome ?? undefined}
>
<StatusIcon status={running ? "running" : outcome} />
<span className={styles.testCounts}>
{counts.failed > 0 && <span className={styles.failed}>{tx`${counts.failed} failing`}</span>}
{counts.passed > 0 && <span>{tx`${counts.passed} passed`}</span>}
{counts.skipped > 0 && <span className={styles.skipped}>{tx`${counts.skipped} ignored`}</span>}
{counts.total === 0 && <span className={styles.skipped}>{running ? tx("Running…") : tx("No tests")}</span>}
{!outcome && <span className={styles.skipped}>{running ? tx("Running…") : tx("No tests")}</span>}
{duration !== undefined && <span className={styles.testTotalDuration}>{formatDuration(duration)}</span>}
</span>
{duration !== undefined && <span className={styles.testTotalDuration}>{formatDuration(duration)}</span>}
</div>
);
}
+26 -4
Переглянути файл
@@ -234,14 +234,31 @@
gap: var(--space-2);
min-height: 46px;
padding: 8px 20px;
border-top: 1px solid var(--border-popup);
background: var(--bg-frame, var(--bg-app));
}
.footer > button,
.footer > label {
.footerOptions,
.footerGroup {
display: flex;
flex: none;
white-space: nowrap;
max-width: 100%;
align-items: center;
gap: var(--space-2);
}
.footerOptions {
flex-wrap: wrap;
margin-inline-end: auto;
}
.footerGroup > button {
flex-shrink: 1;
min-width: 0;
height: auto;
min-height: var(--h-button);
padding-block: var(--space-1);
white-space: normal;
overflow-wrap: anywhere;
}
.hint {
flex: 1 1 0;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
@@ -249,6 +266,9 @@
color: var(--fg-faint);
font-size: var(--fs-small);
}
.footer > .hint {
flex: 1 1 0;
}
.rowDone {
opacity: 0.55;
}
@@ -286,6 +306,8 @@
.okHint {
flex: none;
color: var(--fg-faint);
font-family: var(--font-keys);
font-size: var(--fs-small);
white-space: nowrap;
}
+43 -25
Переглянути файл
@@ -13,7 +13,7 @@ import { openEditorPaths, useEditorRegistry } from "@/editor/api";
import { executeAction } from "@/platform/actions";
import { setContext } from "@/platform/context";
import { t, useTxTemplate, tx, txPart } from "@/platform/i18n";
import { formatBinding, hostBinding, shortcutLabel } from "@/platform/keymap";
import { formatBinding, hostBinding, registerKeyClaim, shortcutLabel } from "@/platform/keymap";
import { call, commands, isTauri, onIdeEvent } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { useProjectModules } from "@/platform/projectRoots";
@@ -193,7 +193,19 @@ function FindInFilesDialog() {
// Hidden popup actions (⌘G, F4, ⌥↓ …) win over the editor's bindings while this is set.
useEffect(() => {
setContext("findPopupOpen", true);
return () => setContext("findPopupOpen", false);
const release = registerKeyClaim(
(e) =>
e.key === "Enter" &&
(e.ctrlKey || e.metaKey) &&
!e.altKey &&
!e.shiftKey &&
e.target instanceof HTMLElement &&
e.target.matches("[data-find-field] :is(input, textarea)"),
);
return () => {
release();
setContext("findPopupOpen", false);
};
}, []);
useEffect(() => {
@@ -491,8 +503,7 @@ function FindInFilesDialog() {
const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
const target = e.target as HTMLElement;
const inField =
(target.tagName === "INPUT" || target.tagName === "TEXTAREA") && target.closest("[data-find-field]");
const inField = target.matches("[data-find-field] :is(input, textarea)");
if (e.key === "Backspace" && e.altKey && e.shiftKey && !e.metaKey && !e.ctrlKey) {
e.preventDefault();
clearOptions();
@@ -911,30 +922,37 @@ function FindInFilesDialog() {
)}
</div>
<footer className={styles.footer}>
<Checkbox
checked={s.newTab}
onChange={setFindPopupNewTab}
label={<Mnemonic text={tx("Open results in new tab")} char="B" />}
/>
{s.replace && <Checkbox checked={previewMode} onChange={setPreviewMode} label="Preview" />}
<div className={styles.footerOptions}>
<Checkbox
checked={s.newTab}
onChange={setFindPopupNewTab}
label={<Mnemonic text={tx("Open results in new tab")} char="B" />}
/>
{s.replace && <Checkbox checked={previewMode} onChange={setPreviewMode} label="Preview" />}
</div>
{navigationHint && <span className={styles.hint}>{navigationHint}</span>}
<span className={styles.spacer} />
{s.replace && progress && (
<span className={styles.hint} aria-live="polite">
{tx`Replacing… ${progress.done}/${progress.total} files`}
</span>
{s.replace && (progress || running) && (
<div className={styles.footerGroup}>
{progress && (
<span className={styles.hint} aria-live="polite">
{tx`Replacing… ${progress.done}/${progress.total} files`}
</span>
)}
{running && (
<Button onClick={() => running.cancel()}>
<T>Stop</T>
</Button>
)}
</div>
)}
{s.replace && running && (
<Button onClick={() => running.cancel()}>
<T>Stop</T>
<div className={styles.footerGroup}>
<kbd className={styles.okHint}>{formatBinding(hostBinding("Meta+Enter"))}</kbd>
<Button disabled={!query?.pattern} onClick={pin}>
<T>Open in Find Window</T>
</Button>
)}
<span className={styles.okHint}>{formatBinding(hostBinding("Meta+Enter"))}</span>
<Button disabled={!query?.pattern} onClick={pin}>
<T>Open in Find Window</T>
</Button>
</div>
{s.replace && (
<>
<div className={styles.footerGroup}>
<Button
title={formatBinding("Shift+Alt+Enter")}
disabled={stale || !rows.length || busy || state.status === "searching"}
@@ -945,7 +963,7 @@ function FindInFilesDialog() {
<Button variant="primary" disabled={stale || !selected || busy} onClick={() => void replaceSelected()}>
{pendingSelected > 1 ? txt(`Replace ${pendingSelected} Occurrences`) : <T>Replace</T>}
</Button>
</>
</div>
)}
</footer>
</div>
+33 -26
Переглянути файл
@@ -15,6 +15,7 @@ import { call, commands, type OutlineItem } from "@/platform/ipc";
import { monoFontFamily } from "@/platform/fonts";
import { shortcutLabel } from "@/platform/keymap";
import { useProject } from "@/platform/project";
import { isVirtualUri, virtualContainer } from "@/platform/virtualDocs";
import {
Checkbox,
Dialog,
@@ -40,7 +41,7 @@ import {
type ToolWindowContribution,
} from "@/workbench/contributions";
import { highlightTokens, languageForPath, type CodeToken } from "@/editor/lsp/markdown";
import { basename, openInListOrder, openLocation } from "../common/open";
import { basename, openInListOrder, openLocation, relDir } from "../common/open";
import { outlinePathAt } from "../structure/outline";
import { fromNavigationHistory, isDismissed, mergeLocations, type RecentLocation } from "../common/locations";
import { dismissLocation, useTracking } from "../common/tracking";
@@ -688,33 +689,39 @@ function RecentLocationsDialog() {
rowHeight={rowHeight}
aria-label="Recent locations"
empty={<span>{changedOnly ? tx("No changed locations") : tx("No recent locations")}</span>}
renderItem={(l) => (
<div className={styles.location}>
<div className={styles.locationHeader}>
<Icon name={fileIconName(basename(l.rel), l.rel)} size={14} className={styles.icon} />
<HighlightedText
className={clsx(styles.name, styles.locationName)}
text={basename(l.rel)}
indices={l.nameIndices}
tone="strong"
renderItem={(l) => {
const name = basename(l.rel);
const breadcrumb = breadcrumbOf(outlines.get(l.path), l);
const directory = isVirtualUri(l.path) ? virtualContainer(l.path) : relDir(l.rel);
const context = breadcrumb && breadcrumb !== name ? breadcrumb : directory;
return (
<div className={styles.location}>
<div className={styles.locationHeader} title={l.rel}>
<Icon name={fileIconName(name, l.rel)} size={14} className={styles.icon} />
<HighlightedText
className={clsx(styles.name, styles.locationName)}
text={name}
indices={l.nameIndices}
tone="strong"
/>
{context && <span className={styles.dir}>{context}</span>}
{l.changed && (
<span className={styles.changed}>
<T>changed</T>
</span>
)}
<span className={styles.time}>{locationTime(l.time, now)}</span>
</div>
<SnippetCode
path={l.path}
lines={dedent(l.snippet)}
first={l.snippetStart}
caret={l.line}
style={snippetStyle}
/>
<span className={styles.dir}>{breadcrumbOf(outlines.get(l.path), l) || l.rel}</span>
{l.changed && (
<span className={styles.changed}>
<T>changed</T>
</span>
)}
<span className={styles.time}>{locationTime(l.time, now)}</span>
</div>
<SnippetCode
path={l.path}
lines={dedent(l.snippet)}
first={l.snippetStart}
caret={l.line}
style={snippetStyle}
/>
</div>
)}
);
}}
/>
</div>
</Dialog>
+14 -5
Переглянути файл
@@ -101,19 +101,28 @@
color: var(--fg-strong);
font-weight: 600;
}
.crumb:last-child {
.parentCrumbs {
display: flex;
min-width: 0;
}
.crumb > span {
overflow: hidden;
text-overflow: ellipsis;
}
.crumb {
display: inline-flex;
align-items: center;
min-width: 0;
}
.crumbLabel {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
}
.currentCrumb {
flex: none;
max-width: 100%;
}
.crumbSep {
margin: 0 4px;
flex: none;
margin-inline: var(--space-1);
color: var(--fg-subtle);
}
.reset {
+16 -8
Переглянути файл
@@ -165,21 +165,29 @@ function PageHost({
const [headerSlot, setHeaderSlot] = useState<HTMLElement | null>(null);
if (!node) return <EmptyState title="Nothing found" icon="search" />;
const Body = page?.component;
const parents = crumbs.slice(0, -1);
return (
<PageContext.Provider value={ctx}>
<SettingsFormContext.Provider value={form}>
<SettingsPageFocusContext.Provider value={pageFocus}>
<SettingsHeaderSlotContext.Provider value={headerSlot}>
<div className={styles.pageHeader}>
<div className={styles.crumbs} aria-label={tx("Breadcrumb")}>
{crumbs.map((c, i) => (
<span key={i} className={styles.crumb}>
{i > 0 && <Icon name="chevron-right" size={12} className={styles.crumbSep} />}
<span>
<T>{c}</T>
</span>
<div className={styles.crumbs} aria-label={tx("Breadcrumb")} title={crumbs.map((c) => tx(c)).join(" › ")}>
{parents.length > 0 && (
<span className={styles.parentCrumbs}>
{parents.map((c, i) => (
<span key={i} className={styles.crumb}>
<span className={styles.crumbLabel}>
<T>{c}</T>
</span>
<Icon name="chevron-right" size={12} className={styles.crumbSep} />
</span>
))}
</span>
))}
)}
<span className={clsx(styles.crumbLabel, styles.currentCrumb)} aria-current="page">
<T>{node.title}</T>
</span>
</div>
<div ref={setHeaderSlot} className={styles.headerSlot} />
{dirty && (
+56 -24
Переглянути файл
@@ -30,9 +30,6 @@
.presetSelect {
flex: 1;
}
.spacer {
flex: 1;
}
.modifiedNote {
color: var(--fg-subtle);
font-size: var(--fs-small);
@@ -195,53 +192,88 @@
.recordLabel {
color: var(--fg);
}
.shortcutBody {
display: flex;
flex-direction: column;
gap: var(--space-2);
padding: var(--space-2) var(--space-3) 0;
font-size: var(--fs-ui);
overflow-wrap: anywhere;
}
.actionSummary {
display: grid;
gap: var(--space-0-5);
}
.actionName {
color: var(--fg-strong);
font-weight: 600;
}
.shortcutField {
flex: 0 0 auto;
background: var(--bg-field);
}
.shortcutField > span {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.secondStroke {
display: flex;
align-items: center;
gap: var(--space-2);
}
.secondStroke > label {
max-width: 55%;
}
.secondStroke .shortcutField {
flex: 1;
}
.recordHint {
color: var(--fg-subtle);
font-size: var(--fs-small);
}
.conflicts {
min-height: 72px;
padding: 6px 8px;
border-radius: var(--radius-small);
box-shadow: inset 0 0 0 1px var(--border);
}
.noConflicts {
color: var(--fg-subtle);
.shortcutStatus {
display: grid;
gap: var(--space-1);
}
.conflictTitle {
display: flex;
align-items: center;
gap: var(--space-1-5);
color: var(--fg-emphasis);
font-weight: 600;
}
.conflictIcon {
flex: none;
color: var(--warning);
--icon-color: currentColor;
}
.conflictList {
list-style: none;
margin: 6px 0 0;
padding: 0 0 0 20px;
max-height: 120px;
overflow: auto;
margin: 0;
padding: 0;
max-height: 132px;
overflow-y: auto;
}
.conflictList li {
display: flex;
min-width: 0;
align-items: center;
display: grid;
grid-template-columns: minmax(0, 1fr) fit-content(42%);
align-items: start;
gap: var(--space-2);
height: var(--h-row);
padding-block: var(--space-1);
}
.conflictAction {
color: var(--fg);
overflow-wrap: anywhere;
}
.conflictCategory {
.actionPath {
color: var(--fg-subtle);
font-size: var(--fs-small);
}
.conflictsLabel {
color: var(--fg);
padding-top: 4px;
.conflictBinding {
text-align: end;
white-space: normal;
overflow-wrap: anywhere;
}
.nameError {
color: var(--danger);
+46 -35
Переглянути файл
@@ -20,7 +20,7 @@ import { findConflicts, resolveBindings, type Conflict, type KeymapDraft } from
import { groupPath } from "./groups";
import { StrokeRecorder } from "./StrokeRecorder";
import styles from "./Keymap.module.css";
import { tx } from "@/platform/i18n";
import { useTx } from "@/platform/i18n";
import { usePlatform } from "@/platform/platformInfo";
export interface RecordShortcutDialogProps {
@@ -39,6 +39,8 @@ export function RecordShortcutDialog({ action, actions, draft, onCancel, onSubmi
const [second, setSecond] = useState("");
const [useSecond, setUseSecond] = useState(false);
const os = usePlatform((s) => s.os);
const tx = useTx();
const actionName = tx(action.title);
const rectangularSelection = action.id === "editor.createRectangularSelectionOnMouseDrag";
const allowsSecond = !isPageSwipe(first) && !parseDoubleModifier(first);
@@ -76,14 +78,23 @@ export function RecordShortcutDialog({ action, actions, draft, onCancel, onSubmi
<Dialog
open
onClose={onCancel}
title={mouse ? tx`Mouse Shortcut: ${action.title}` : tx`Keyboard Shortcut: ${action.title}`}
width={440}
title={mouse ? "Mouse Shortcut" : "Keyboard Shortcut"}
aria-label={mouse ? tx`Mouse Shortcut: ${actionName}` : tx`Keyboard Shortcut: ${actionName}`}
width={352}
buttons={[
{ label: "OK", role: "default", disabled: !binding || already, onClick: () => void ok() },
{ label: "Cancel", role: "cancel" },
]}
>
<div className={styles.recordBody}>
<div className={styles.shortcutBody}>
<div className={styles.actionSummary}>
<div className={styles.actionName}>{actionName}</div>
<div className={styles.actionPath}>
{groupPath(action)
.map((part) => tx(part))
.join(" › ")}
</div>
</div>
{mouse ? (
<MouseRecorder value={first} onChange={setFirst} sideButtons={!rectangularSelection} />
) : (
@@ -102,31 +113,23 @@ export function RecordShortcutDialog({ action, actions, draft, onCancel, onSubmi
<T>On Linux, middle-button rectangular selection conflicts with primary selection paste.</T>
</div>
)}
<div className={styles.conflictsLabel}>
<T>Conflicts:</T>
</div>
<div className={styles.conflicts} aria-live="polite">
<div className={styles.shortcutStatus} aria-live="polite">
{already && (
<span className={styles.noConflicts}>
<span className={styles.recordHint}>
<T>The action already has this shortcut</T>
</span>
)}
{!already && binding && conflicts.length === 0 && (
<span className={styles.noConflicts}>
<span className={styles.recordHint}>
<T>No conflicts</T>
</span>
)}
{!binding && (
<span className={styles.noConflicts}>
<T>Press a shortcut</T>
</span>
)}
{conflicts.length > 0 && (
<>
<div className={styles.conflictTitle}>
<Icon name="warning" size={14} className={styles.conflictIcon} />
<span>
<Kbd binding={binding} /> <T>is already assigned to:</T>
<Kbd binding={binding} className={styles.conflictBinding} /> <T>is already assigned to:</T>
</span>
</div>
<ConflictList conflicts={conflicts} />
@@ -139,21 +142,26 @@ export function RecordShortcutDialog({ action, actions, draft, onCancel, onSubmi
}
function ConflictList({ conflicts }: { conflicts: readonly Conflict[] }) {
const tx = useTx();
return (
<ul className={styles.conflictList}>
<ul className={styles.conflictList} aria-label={tx("Conflicts:")}>
{conflicts.map((c) => (
<li key={`${c.actionId}|${c.binding}`}>
<span className={styles.conflictAction}>{c.title}</span>
<span className={styles.conflictCategory}>
({groupPath({ id: c.actionId, category: c.category }).join(" | ")})
</span>
<span className={styles.spacer} />
{c.kind === "prefix" && (
<span className={styles.conflictCategory}>
<T>chord prefix</T>
<div className={styles.conflictAction}>
<div>{tx(c.title)}</div>
<span className={styles.actionPath}>
{groupPath({ id: c.actionId, category: c.category })
.map((part) => tx(part))
.join(" › ")}
{c.kind === "prefix" && (
<>
{" "}
· <T>chord prefix</T>
</>
)}
</span>
)}
<Kbd binding={c.binding} />
</div>
<Kbd binding={c.binding} className={styles.conflictBinding} />
</li>
))}
</ul>
@@ -171,23 +179,26 @@ interface KeyStrokesProps {
}
function KeyStrokes({ first, second, useSecond, allowsSecond, setFirst, setSecond, setUseSecond }: KeyStrokesProps) {
const tx = useTx();
return (
<>
<div className={styles.recordRow}>
<span className={styles.recordLabel}>
<T>First stroke:</T>
</span>
<StrokeRecorder autoFocus value={first} onChange={setFirst} aria-label="First stroke" />
</div>
<div className={styles.recordRow}>
<StrokeRecorder
autoFocus
className={styles.shortcutField}
value={first}
onChange={setFirst}
aria-label={tx("First stroke")}
/>
<div className={styles.secondStroke}>
<Checkbox checked={useSecond} onChange={setUseSecond} disabled={!allowsSecond} label="Second stroke:" />
<StrokeRecorder
className={styles.shortcutField}
value={second}
onChange={setSecond}
disabled={!useSecond}
allowDoubleModifier={false}
placeholder={useSecond ? "Press a shortcut" : ""}
aria-label="Second stroke"
aria-label={tx("Second stroke")}
/>
</div>
<div className={styles.recordHint}>
+43
Переглянути файл
@@ -0,0 +1,43 @@
import type { Commit } from "@/bindings";
import type { ReactNode } from "react";
import { fontWeightOf } from "@/platform/editorSettings";
import { resolveMonoFont } from "@/platform/fonts";
import { tx } from "@/platform/i18n";
import { useProject } from "@/platform/project";
import styles from "./GitLog.module.css";
export function CommitMessageContent({
commit,
message,
compact = false,
renderText = (text) => text,
revision = commit.shortId,
}: {
commit: Commit;
message: string;
compact?: boolean;
renderText?: (text: string) => ReactNode;
revision?: ReactNode;
}) {
const editor = useProject((s) => s.settings?.editor);
const { family, size } = resolveMonoFont(undefined, editor);
const [subject = "", ...bodyLines] = message.trimEnd().split("\n");
const body = compact ? "" : bodyLines.join("\n").replace(/^\n+/, "");
return (
<>
<div
className={styles.messageText}
style={{ fontFamily: family, fontSize: size, fontWeight: fontWeightOf(editor?.fontWeight, 400) }}
>
<div className={styles.subjectLine} style={{ fontWeight: fontWeightOf(editor?.boldFontWeight, 700) }}>
{renderText(subject)}
</div>
{body && <div className={styles.fullMessage}>{renderText(body)}</div>}
</div>
<div className={styles.meta}>
{revision} {commit.author} &lt;{commit.email}&gt;
{commit.timeMs ? " " + tx`on ${new Date(commit.timeMs).toLocaleString()}` : ""}
</div>
</>
);
}
+30 -2
Переглянути файл
@@ -162,15 +162,24 @@
white-space: nowrap;
max-width: 220px;
overflow: hidden;
text-overflow: ellipsis;
}
.filterValue {
min-width: 0;
max-width: 16ch;
overflow: hidden;
text-overflow: ellipsis;
color: var(--fg-strong);
}
@container git-log (max-width: 600px) {
.filterValue {
max-width: 10ch;
}
}
.filterChevron {
color: var(--fg-icon);
}
.filterClear {
flex: none;
height: 100%;
display: inline-flex;
align-items: center;
@@ -405,9 +414,12 @@
.subject {
flex: 0 1 auto;
min-width: var(--log-subject-min);
color: var(--fg);
}
.subjectText {
display: block;
overflow: hidden;
text-overflow: ellipsis;
color: var(--fg);
}
.headSubject {
font-weight: 600;
@@ -437,6 +449,22 @@
flex: none;
max-width: calc(100% - var(--log-subject-min) - var(--space-1-5));
}
.commitText > .refsCompact {
flex: 0 1 auto;
max-width: calc(100% / 3);
}
.commitText:has(> .refsCompact) > .subject {
/* Protect a short subject while leaving room for compact reference names. */
flex: 0 1000 max-content;
min-width: auto;
width: min(75%, 24ch);
}
.commitText > .refs .ref {
font-size: var(--fs-small);
}
.refsCompact .ref {
min-width: 11px;
}
.refsLeft {
margin-left: 0;
}
+2 -6
Переглянути файл
@@ -10,6 +10,7 @@ import { executeAction } from "@/platform/actions";
import { call, commands } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { Button, IconButton, Spinner, SplitGroup, SplitHandle, SplitPanel, T } from "@/ui";
import { CommitMessageContent } from "./CommitMessageContent";
import { ComparisonTree } from "./ComparisonTree";
import { buildFileTree } from "./fileTree";
import { flatFileNodes, toLogChanges, type LogChange } from "./logChanges";
@@ -151,14 +152,9 @@ export function PushChanges({
/** The selected commit's full message, revision, author and time. */
function PushCommitDetails({ commit }: { commit: Commit }) {
const date = commit.timeMs ? new Date(commit.timeMs).toLocaleString() : null;
return (
<section className={styles.pushCommitDetails} aria-label={tx("Commit details")}>
<div className={styles.pushCommitMessage}>{commit.message.trimEnd() || commit.summary}</div>
<div className={styles.fileDir}>
{commit.shortId} {commit.author} &lt;{commit.email}&gt;
{date ? " " + tx`on ${date}` : ""}
</div>
<CommitMessageContent commit={commit} message={commit.message.trimEnd() || commit.summary} />
</section>
);
}
+5 -3
Переглянути файл
@@ -1,5 +1,5 @@
import { describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen } from "@testing-library/react";
import { fireEvent, render, screen, within } from "@testing-library/react";
import type { Commit } from "@/bindings";
const { files, combined, executeAction } = vi.hoisted(() => ({
@@ -69,8 +69,10 @@ describe("Push dialog changes", () => {
const one = { ...older, message: "Add order service\n\nIntroduces the service.\n", timeMs: 1_700_000_000_000 };
render(<PushChanges repo="/r" commits={[one]} />);
const details = screen.getByRole("region", { name: "Commit details" });
expect(details.textContent).toContain("Add order service\n\nIntroduces the service.");
expect(details.textContent).toContain("aaaaaaa me <[email protected]> on ");
const message = within(details);
expect(message.getByText("Add order service", { exact: true })).toBeTruthy();
expect(message.getByText("Introduces the service.", { exact: true })).toBeTruthy();
expect(message.getByText(/^aaaaaaa me <me@example\.com> on /)).toBeTruthy();
expect(await screen.findByText("src/orders")).toBeTruthy();
expect(screen.getAllByRole("treeitem")).toHaveLength(2);
const grouping = screen.getByRole("button", { name: "Group by Directory" });
-8
Переглянути файл
@@ -363,9 +363,6 @@
.pushCommitDetails {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
gap: var(--space-1);
margin: var(--space-1) var(--space-3);
padding: var(--space-1) var(--space-2);
overflow: auto;
@@ -374,11 +371,6 @@
-webkit-user-select: text;
user-select: text;
}
.pushCommitMessage {
color: var(--fg-strong);
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.todoList {
margin: 8px 0 0;
padding-left: 18px;
Loaded 100 of 112 files, more files were not shown because too many files have changed in this diff. Show more