Compare commits

...
Author SHA1 Message Date
l0ng-aiandClaude Opus 5.5 0379d597be fix(database): rename databases and schemas from the tree
Rename… (db.rename, Shift+F6) did nothing on a database or schema node:
canRename accepted only tables, columns, views and PostgreSQL indexes, and
database nodes have no schema object.

Databases of a server that creates them (PostgreSQL, SQL Server) rename with
ALTER DATABASE after closing the IDE's sessions on them; the connected
database and read-only sources keep Rename disabled, as Drop does. Schemas
rename with ALTER SCHEMA on PostgreSQL and Snowflake. Both use the rename
dialog with its SQL preview and refresh the tree.

Fixes #5205

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-22 21:22:40 +08:00
lifeir f2b06bc376 feat(run): npm tool window with the project's package.json scripts (#5217)
A new npm tool window on the right lists the scripts of every package.json in the project (root, workspace members, detected module roots and any other package.json the index knows outside node_modules), grouped by package. Double-click runs a script; the context menu offers Run / Debug through the same path as the package.json gutter, reusing a matching run configuration or creating a temporary one. The window appears only while the project has scripts and refreshes when a package.json changes or indexing finishes. The editor context menu on a package.json script line also offers Run / Debug for that script.

Co-authored-by: lifeir <[email protected]>
2026-11-22 21:10:59 +08:00
l0ng-ai 08d719e03d fix(search): keep action names and shortcuts readable (#5203)
Search Everywhere reserves room for action names alongside shortcuts and categories. Shortcut text is smaller and semibold. Very long key sequences and categories can shorten with an ellipsis, and hovering shows their full text.
2026-11-22 21:07:00 +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 XIANGRUIandwildcatDownstairs 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
86 changed files with 2316 additions and 383 deletions

No files matched your search

+35 -16
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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;
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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** | — |
+114 -53
View File
@@ -4,63 +4,124 @@ 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 });
await stubDesktop(page);
await page.evaluate(
async ({ amountName, routingName, routingValue }) => {
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;
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 },
];
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 },
);
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();
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 debug = page.getByRole("region", { name: "Debug", exact: true });
await debug.getByRole("tab", { name: "Threads & Variables", exact: true }).click();
});
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");
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");
});
await expect(show).toBeHidden();
await expect
.poll(() => routing.getByText(routingValue, { exact: true }).evaluate((el) => el.scrollWidth <= el.clientWidth + 1))
.toBe(true);
});
test("keeps a decimal value legible beside a long runtime type", async ({ workbench: page }) => {
+44
View File
@@ -225,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,
}) => {
+44
View File
@@ -0,0 +1,44 @@
/** The npm tool window lists package.json scripts without run configurations and runs them. */
import type { Page } from "@playwright/test";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
const PKG = JSON.stringify({ name: "acme-api", scripts: { dev: "vite", build: "vite build" } });
/** The root package.json has scripts; there are no run configurations. */
async function stubNpm(page: Page) {
await stubDesktop(page);
await page.evaluate(async (pkg) => {
const h = window.__ipc.handlers;
h.fs_read_text = (args) => (String(args.path).endsWith("/package.json") ? pkg : "");
h.run_configs = () => [];
h.run_start = (args) => {
const config = args.config as { id: string; name: string };
return { id: 8, configId: config.id, name: config.name, pid: 4242, running: true, pty: false };
};
const npmModule = "/src/features/run/npmScripts.ts";
const { loadNpmScripts } = await import(/* @vite-ignore */ npmModule);
await loadNpmScripts();
}, PKG);
}
test("lists scripts without run configurations and runs one on double-click", async ({ workbench: page }) => {
await stubNpm(page);
await page.getByRole("button", { name: "npm", exact: true }).click();
const tree = page.getByRole("tree", { name: "npm scripts" });
await expect(tree).toBeVisible();
await expect(tree.getByRole("treeitem", { name: /^acme-api/ })).toBeVisible();
await expect(tree.getByRole("treeitem", { name: "dev" })).toBeVisible();
await expect(tree.getByRole("treeitem", { name: "build" })).toBeVisible();
await tree.getByRole("treeitem", { name: "dev" }).dblclick();
const [started] = await ipcCalls(page, "run_start");
expect(started).toMatchObject({ config: { args: ["run", "dev"], kind: "npm" } });
});
test("offers Run / Debug in a script's context menu", async ({ workbench: page }) => {
await stubNpm(page);
await page.getByRole("button", { name: "npm", exact: true }).click();
const tree = page.getByRole("tree", { name: "npm scripts" });
await tree.getByRole("treeitem", { name: "build" }).click({ button: "right" });
await expect(page.getByRole("menuitem", { name: /Run '.*run build'/ })).toBeVisible();
await expect(page.getByRole("menuitem", { name: /Debug '.*run build'/ })).toBeVisible();
});
+54
View File
@@ -1,6 +1,60 @@
import { doubleShift, expect, stubDesktop, test } from "./fixtures";
import type { Page } from "@playwright/test";
test("action names stay readable beside shortcuts and categories", async ({ workbench: page }) => {
const titles = ["Reconcile warehouse totals", "Reconcile settlement exports"];
const shortcuts = await page.evaluate(async (titles) => {
const actionsModule = "/src/platform/actions.ts";
const keymapModule = "/src/platform/keymap.ts";
const { registerActions, executeAction } = await import(/* @vite-ignore */ actionsModule);
const platformModule = "/src/platform/platformInfo.ts";
const { registerExtensionBindings, shortcutLabel } = await import(/* @vite-ignore */ keymapModule);
const { usePlatform } = await import(/* @vite-ignore */ platformModule);
usePlatform.setState({ os: "windows" });
const ids = ["review.reconcileWarehouse", "review.reconcileSettlement"];
const bindings = ["Ctrl+K Ctrl+R", "Ctrl+Alt+Shift+PageDown Ctrl+Alt+Shift+PageUp"];
registerActions(
titles.map((title, index) => ({
id: ids[index]!,
title,
category: "Warehouse reconciliation and settlement reports",
icon: "check",
run: () => document.body.setAttribute("data-review-action", title),
})),
);
ids.forEach((id, index) => registerExtensionBindings(id, [bindings[index]!]));
await executeAction("navigate.findAction");
return ids.map((id) => shortcutLabel(id) as string);
}, titles);
const dialog = page.locator('[role="dialog"]:has(#se-query)');
await dialog.getByRole("combobox", { name: "Search query" }).fill("Reconcile");
for (const width of [400, 1120]) {
await page.setViewportSize({ width, height: 630 });
for (const [index, title] of titles.entries()) {
const row = dialog.getByRole("option").filter({ hasText: title });
const keys = row.getByText(shortcuts[index]!, { exact: true });
await expect(keys).toBeAttached();
const geometry = await keys.evaluate((el) => {
const name = el.previousElementSibling!.getBoundingClientRect();
const main = el.parentElement!.getBoundingClientRect();
const key = el.getBoundingClientRect();
return { name: name.width, inside: key.left >= name.right && key.right <= main.right + 1 };
});
expect(geometry.name).toBeGreaterThanOrEqual(80);
expect(geometry.inside).toBe(true);
await expect(keys).toHaveCSS("font-size", "12px");
await expect(keys).toHaveCSS("font-weight", "600");
await expect(keys).toHaveAttribute("title", shortcuts[index]!);
if (index === 0) expect(await keys.evaluate((el) => el.scrollWidth <= el.clientWidth)).toBe(true);
}
}
await dialog.getByRole("option").filter({ hasText: titles[1]! }).click();
await expect(dialog).toBeHidden();
await expect(page.locator("body")).toHaveAttribute("data-review-action", titles[1]!);
});
async function searchFiles(page: Page) {
await stubDesktop(page);
await page.evaluate(() => {
+44 -1
View File
@@ -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",
+2 -1
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -0,0 +1,10 @@
@gutter: 16px;
// Intentional Stylelint problem: the same selector twice (no-duplicate-selectors).
.layout {
margin: @gutter;
}
.layout {
padding: @gutter;
}
+9
View File
@@ -0,0 +1,9 @@
$accent: #336699;
// Intentional Stylelint problem: an empty block (block-no-empty).
.button {
color: $accent;
&:hover {
}
}
@@ -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
View File
@@ -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
View File
@@ -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
Binary file not shown.
+3
View File
@@ -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>
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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`. */
+25
View File
@@ -573,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. */
+10
View File
@@ -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
View File
@@ -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({
+18 -5
View File
@@ -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,
@@ -574,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) {
@@ -599,6 +605,8 @@ export async function showIntentions(view: EditorView) {
clearTimeout(timer);
if (ours()) closePopup();
reportLspError(view, e, true);
} finally {
asked.abort();
}
}
@@ -704,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();
}
@@ -732,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) {
@@ -742,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;
@@ -759,6 +771,7 @@ const bulbPlugin = ViewPlugin.fromClass(
}
destroy() {
this.lookup.cancel();
this.asked?.abort();
}
},
);
+12 -6
View File
@@ -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
View File
@@ -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
View File
@@ -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;
}
+32 -7
View File
@@ -17,6 +17,7 @@ import {
createTableSql,
draftOf,
dropDatabaseSql,
renameDatabaseSql,
dropSql,
ident,
reference,
@@ -33,6 +34,7 @@ import {
connectedTargets,
createDatabase,
dropDatabase,
renameDatabase,
loadDetails,
openSourceDialog,
readableDdl,
@@ -103,20 +105,34 @@ function useRunner() {
// ---- Rename ------------------------------------------------------------------
function RenameDialog({ id, object }: { id: string; object: DbObjectRef | null }) {
/** Renames a data source, a schema object, or (with `database`) a database of the server. */
function RenameDialog({ id, object, database }: { id: string; object: DbObjectRef | null; database?: string }) {
const source = sourceById(id);
const initial = object ? objectName(object) : (source?.name ?? "");
const initial = database ?? (object ? objectName(object) : (source?.name ?? ""));
const [name, setName] = useState(initial);
const { busy, runAndClose } = useRunner();
const [renaming, setRenaming] = useState(false);
const driver = driverOf(id);
const changed = !!name.trim() && name.trim() !== initial;
const sql = object && changed ? renameSql(driver, object, name.trim()) : "";
const submit = () => {
const sql = !changed
? ""
: database !== undefined
? renameDatabaseSql(driver, database, name.trim())
: object
? renameSql(driver, object, name.trim())
: "";
const submit = async () => {
if (!changed) return closeDialog();
if (database !== undefined) {
setRenaming(true);
if (await renameDatabase(id, database, sql)) closeDialog();
else setRenaming(false);
return;
}
if (!object) return void renameSource(id, name).then(closeDialog);
void runAndClose(id, [sql]);
};
const what = object ? KIND_LABEL[object.kind] : "data source";
const what = database !== undefined ? "database" : object ? KIND_LABEL[object.kind] : "data source";
return (
<Dialog
open
@@ -125,7 +141,12 @@ function RenameDialog({ id, object }: { id: string; object: DbObjectRef | null }
width={480}
buttons={[
{ label: "Cancel", role: "cancel" },
{ label: "Refactor", role: "default", disabled: busy || !name.trim(), onClick: () => void submit() },
{
label: "Refactor",
role: "default",
disabled: busy || renaming || !name.trim(),
onClick: () => void submit(),
},
]}
>
<div className={styles.dialogBody}>
@@ -139,7 +160,7 @@ function RenameDialog({ id, object }: { id: string; object: DbObjectRef | null }
onFocus={(e) => e.currentTarget.select()}
onChange={(e) => setName(e.target.value)}
/>
{object && <SqlPreview sql={sql || `-- ${what} keeps its name`} />}
{(object || database !== undefined) && <SqlPreview sql={sql || `-- ${what} keeps its name`} />}
</div>
</Dialog>
);
@@ -895,6 +916,10 @@ export function ObjectDialogs() {
switch (dialog.kind) {
case "rename":
return <RenameDialog key={`${dialog.id}`} id={dialog.id} object={dialog.object} />;
case "renameDatabase":
return (
<RenameDialog key={`${dialog.id}:${dialog.database}`} id={dialog.id} object={null} database={dialog.database} />
);
case "drop":
return <DropDialog id={dialog.id} object={dialog.object} />;
case "truncate":
+13
View File
@@ -13,7 +13,9 @@ import {
dropSql,
ident,
reference,
canRename,
renameSql,
renameDatabaseSql,
scriptSql,
truncateSql,
quoteIdent,
@@ -114,6 +116,17 @@ describe("database object SQL", () => {
);
});
it("renames schemas and databases where the server can", () => {
const schema = { kind: "schema" as const, schema: "sales", name: "sales" };
expect(canRename("postgres", schema)).toBe(true);
expect(canRename("snowflake", schema)).toBe(true);
expect(canRename("mysql", schema)).toBe(false);
expect(canRename("sqlServer", schema)).toBe(false);
expect(renameSql("postgres", schema, "Old Sales")).toBe('alter schema sales rename to "Old Sales";');
expect(renameDatabaseSql("postgres", "shop", "store")).toBe("alter database shop rename to store;");
expect(renameDatabaseSql("sqlServer", "shop", "store")).toBe("alter database shop modify name = store;");
});
it("drops with IF EXISTS / CASCADE", () => {
const t = { kind: "table" as const, schema: "public", name: "users" };
expect(dropSql("postgres", t, { ifExists: true, cascade: true })).toBe(
+10 -1
View File
@@ -86,12 +86,15 @@ export const canRename = (driver: DbDriver, o: DbObjectRef) =>
(o.kind === "table" ||
o.kind === "column" ||
(o.kind === "view" && driver !== "sqlite") ||
(o.kind === "index" && driver === "postgres"));
(o.kind === "index" && driver === "postgres") ||
(o.kind === "schema" && (driver === "postgres" || driver === "snowflake")));
/** The statement renaming `o` to `to`. */
export function renameSql(driver: DbDriver, o: DbObjectRef, to: string): string {
const q = qualifiedName(driver, o.schema, o.name);
switch (o.kind) {
case "schema":
return `alter schema ${ident(driver, o.name)} rename to ${ident(driver, to)};`;
case "column":
return `alter table ${q} rename column ${ident(driver, o.column ?? "")} to ${ident(driver, to)};`;
case "index":
@@ -239,6 +242,12 @@ export function dropDatabaseSql(driver: DbDriver, name: string, force: boolean):
return `drop database ${db}${force && driver === "postgres" ? " with (force)" : ""};`;
}
/** The statement renaming database `name` of a server to `to` (PostgreSQL, SQL Server). */
export function renameDatabaseSql(driver: DbDriver, name: string, to: string): string {
if (driver === "sqlServer") return `alter database ${ident(driver, name)} modify name = ${ident(driver, to)};`;
return `alter database ${ident(driver, name)} rename to ${ident(driver, to)};`;
}
export type ScriptKind = "selectAll" | "selectFirst" | "insert" | "update" | "delete";
export const SCRIPT_LABELS: Record<ScriptKind, string> = {
@@ -0,0 +1,49 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { getAction } from "@/platform/actions";
import type { DbNode } from "./nodes";
import { useDatabase } from "./store";
import { registerDatabaseTreeActions } from "./treeActions";
import { nodeMenu } from "./treeMenu";
const database = (current: boolean): DbNode => ({ kind: "database", key: "db", id: "pg:shop", name: "shop", current });
const schema: DbNode = { kind: "schema", id: "pg:shop", key: "schema", schema: "sales" };
const renameItem = (n: DbNode) =>
nodeMenu(n).find((item) => "action" in item && item.action === "db.rename") as { disabled?: boolean } | undefined;
let dispose: () => void;
beforeEach(() => {
dispose = registerDatabaseTreeActions();
useDatabase.setState({ sources: [{ id: "pg", driver: "postgres" }], dialog: null, loaded: true });
});
afterEach(() => dispose());
describe("Rename on databases and schemas", () => {
it("is offered on a database other than the connected one", () => {
expect(renameItem(database(false))?.disabled).toBe(false);
expect(renameItem(database(true))?.disabled).toBe(true);
});
it("is offered on a schema", () => {
expect(renameItem(schema)?.disabled).toBe(false);
});
it("is not offered on a read-only data source", () => {
useDatabase.setState({ sources: [{ id: "pg", driver: "postgres", readOnly: true }] });
expect(renameItem(database(false))?.disabled).toBe(true);
});
it("opens the rename dialog through db.rename", async () => {
await getAction("db.rename")!.run({ arg: database(false) } as never);
expect(useDatabase.getState().dialog).toEqual({ kind: "renameDatabase", id: "pg", database: "shop" });
useDatabase.setState({ dialog: null });
await getAction("db.rename")!.run({ arg: database(true) } as never);
expect(useDatabase.getState().dialog).toBeNull();
await getAction("db.rename")!.run({ arg: schema } as never);
expect(useDatabase.getState().dialog).toMatchObject({
kind: "rename",
id: "pg:shop",
object: { kind: "schema", name: "sales" },
});
});
});
+9
View File
@@ -135,6 +135,7 @@ export type DialogState =
| { kind: "sourceUrl" }
/** Rename a data source (`object` null) or a schema object of target `id`. */
| { kind: "rename"; id: string; object: DbObjectRef | null }
| { kind: "renameDatabase"; id: string; database: string }
/** Confirm Drop / Truncate, with a preview of the statement. */
| { kind: "drop"; id: string; object: DbObjectRef }
| { kind: "truncate"; id: string; schema: string; table: string }
@@ -1349,6 +1350,14 @@ export async function dropDatabase(id: string, database: string, sql: string): P
return true;
}
/** Renames `database` of data source `id` with `sql` after closing the sessions on it. */
export async function renameDatabase(id: string, database: string, sql: string): Promise<boolean> {
await disconnect(`${id}:${database}`);
if (!(await runSql(id, [sql]))) return false;
void refresh(id);
return true;
}
/** Opens the query console of `id` with `text` appended and selected (SQL Scripts › …). */
export async function openConsoleWith(id: string, text: string): Promise<void> {
let path: string;
+3
View File
@@ -346,6 +346,9 @@ export function registerDatabaseTreeActions(): () => void {
if (!n) return;
const id = nodeTarget(n);
if (n.kind === "source" && id) return openDialog({ kind: "rename", id, object: null });
const source = sourceById(id);
if (n.kind === "database" && !n.current && !source?.readOnly && createsDatabases(source))
return openDialog({ kind: "renameDatabase", id: splitTarget(n.id).id, database: n.name });
const o = objectOf(n);
if (id && o && canRename(driverOf(id), o)) openDialog({ kind: "rename", id, object: o });
},
+2 -1
View File
@@ -178,6 +178,7 @@ export function nodeMenu(n: DbNode | null): MenuItem[] {
{ label: "Copy/Paste", submenu: [copyRef] },
refresh,
act("db.disconnect", n, { disabled: !useDatabase.getState().connected.has(id) || n.current }),
...(createsDatabases(sourceById(id)) ? [sep, act("db.rename", n, { disabled: n.current || readOnly })] : []),
sep,
navigation(),
sqlScripts(n, false),
@@ -191,7 +192,7 @@ export function nodeMenu(n: DbNode | null): MenuItem[] {
...(n.kind === "schema" ? [{ label: "Copy/Paste", submenu: [copyRef] }] : []),
refresh,
sep,
...(n.kind === "schema" ? [quickDoc] : []),
...(n.kind === "schema" ? [rename, sep, quickDoc] : []),
navigation(),
sep,
sqlScripts(n, false),
@@ -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]);
});
});
@@ -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
View File
@@ -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(),
@@ -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
View File
@@ -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>
) : (
+77
View File
@@ -0,0 +1,77 @@
/** The npm tool window: the project's packages and their scripts; activating a script runs it. */
import { useMemo, useState, type ReactNode } from "react";
import { tx } from "@/platform/i18n";
import { useProject } from "@/platform/project";
import { Icon, Tree, showContextMenu, type MenuItem, type TreeRowState } from "@/ui";
import { runScriptNode, useNpmScripts, type NpmNode } from "./npmScripts";
import { scriptMenuItems } from "./npmGutter";
import { call, commands } from "@/platform/ipc";
import styles from "./Run.module.css";
function scriptMenuItemsFor(node: NpmNode): Promise<MenuItem[]> {
if (node.kind !== "script") return Promise.resolve([]);
return call(commands.fsReadText(node.path))
.catch(() => "")
.then((content) => scriptMenuItems({ name: node.name, line: 0 }, node.path, content ?? ""));
}
export function NpmScriptsView() {
const packages = useNpmScripts((s) => s.packages);
const loaded = useNpmScripts((s) => s.loaded);
const hasProject = useProject((s) => !!s.project);
const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(() => new Set());
const roots = useMemo(() => packages, [packages]);
const expanded = useMemo(
() => new Set(roots.filter((n) => n.kind === "package" && !collapsed.has(n.key)).map((n) => n.key)),
[roots, collapsed],
);
if (!loaded || !hasProject || roots.length === 0) return null;
const renderNode = (n: NpmNode, state: TreeRowState): ReactNode => {
if (n.kind === "package") {
return (
<span className={styles.scriptsRow} title={n.label}>
<Icon name="file-npm" size={16} />
<span className={state.selected ? styles.scriptsStrong : undefined}>{n.label}</span>
<span className={styles.scriptsMeta}>{n.scripts.length}</span>
</span>
);
}
return (
<span className={styles.scriptsRow} title={n.name}>
<Icon name="runnable-mark" size={14} />
<span>{n.name}</span>
</span>
);
};
return (
<Tree<NpmNode>
aria-label={tx`npm scripts`}
roots={roots}
getKey={(n) => n.key}
getLabel={(n) => (n.kind === "package" ? n.label : n.name)}
getChildren={(n) => (n.kind === "package" ? n.scripts : undefined)}
isExpandable={(n) => n.kind === "package"}
expanded={expanded}
onExpandedChange={(_next, node, isOpen) =>
setCollapsed((prev) => {
const s = new Set(prev);
if (isOpen) s.delete(node.key);
else s.add(node.key);
return s;
})
}
onActivate={(n) => {
if (n.kind === "script") void runScriptNode(n, false);
}}
onContextMenu={(n, _sel, e) => {
if (n?.kind !== "script") return;
void scriptMenuItemsFor(n).then((items) => showContextMenu({ clientX: e.clientX, clientY: e.clientY }, items));
}}
renderNode={renderNode}
/>
);
}
+17
View File
@@ -6,6 +6,23 @@
min-width: 0;
}
.scriptsRow {
display: flex;
align-items: center;
gap: var(--space-1);
min-width: 0;
}
.scriptsStrong {
font-weight: 500;
}
.scriptsMeta {
flex: none;
color: var(--fg-subtle);
font-size: var(--fs-small);
}
.tabs {
min-width: 0;
border: 0;
+12
View File
@@ -82,6 +82,18 @@ describe("run context menu group", () => {
expect(items[0]).toMatchObject({ arg: { path: `${SCRATCHES}/hi.ts`, line: 0, dir: false } });
});
it("editor: offers Run / Debug '<script>' on a package.json script line", () => {
const text = '{\n "scripts": {\n "dev": "vite",\n "build": "vite build"\n }\n}\n';
// Line 2 (0-based) is the "dev" entry.
const items = contextMenuItems("editor", { paths: [`${ROOT}/package.json`], text, line: 2 });
expect(items.map((i) => ("label" in i ? i.label : i.kind))).toEqual(["Run 'dev'", "Debug 'dev'"]);
expect(items[0]).toMatchObject({ icon: "run" });
expect(items[1]).toMatchObject({ icon: "debug" });
// Other lines get the usual menu.
const other = contextMenuItems("editor", { paths: [`${ROOT}/package.json`], text, line: 0 });
expect(other.map((i) => ("label" in i ? i.label : i.kind))).not.toContain("Run 'dev'");
});
it("editor: the element at the caret names the entries", () => {
const text = "describe('math', () => {\n it('adds', () => {\n expect(1).toBe(1);\n });\n});\n";
const at = (line: number) => contextMenuItems("editor", { paths: [`${ROOT}/src/m.test.ts`], text, line })[0];
+19
View File
@@ -34,6 +34,7 @@ import {
} from "./producers";
import { runWithExecutor } from "./executors";
import { jdwpLaunch } from "./javaDebug";
import { scriptEntries, scriptMenuItems, type ScriptEntry } from "./npmGutter";
import { goModulePath, loadGoModules } from "./goModules";
import { isPythonPackage, loadPythonPackages } from "./pythonPackages";
import { remoteDebugBlocked } from "./remote";
@@ -392,6 +393,19 @@ export async function prepareMenu(_menu: ContextMenuId, ctx: MenuGroupContext):
peeked.set(path, { at: Date.now(), text: text.slice(0, CONTENT_LIMIT) });
}
/** Run / Debug for a `package.json` script line, through `scriptMenuItems`. */
function npmScriptItems(entry: ScriptEntry, path: string, content: string): MenuItem[] {
const run = async (debug: boolean) => {
const items = await scriptMenuItems(entry, path, content);
const item = items[debug ? 1 : 0];
if (item && "run" in item) item.run?.();
};
return [
{ label: tx`Run '${entry.name}'`, icon: "run", run: () => void run(false) },
{ label: tx`Debug '${entry.name}'`, icon: "debug", run: () => void run(true) },
];
}
/** The run group of a context menu: Run / Debug '<name>', Modify Run Configuration…. */
export function contextMenuItems(menu: ContextMenuId, ctx: MenuGroupContext): MenuItem[] {
if (ctx.paths.length !== 1) return [];
@@ -402,6 +416,11 @@ export function contextMenuItems(menu: ContextMenuId, ctx: MenuGroupContext): Me
const dir = !!ctx.dirs?.[0];
const content = ctx.text ?? peekContent(path);
const line = menu === "editor" ? ctx.line : undefined;
// A `package.json` script line runs that script.
if (!dir && /(^|\/)package\.json$/.test(path) && content !== undefined && line !== undefined) {
const entry = scriptEntries(content.slice(0, CONTENT_LIMIT)).find((e) => e.line === line);
if (entry) return npmScriptItems(entry, path, content);
}
const input: ContextInput = {
...projectContext(),
root,
+2
View File
@@ -70,6 +70,7 @@ import { junitType } from "./junitType";
import { listenForApplicationDeactivation, showApplicationUpdate, updatableSessions } from "./applicationUpdate";
import { hotReload, hotReloadSession, hotRestart } from "./flutterHotReload";
import { npmGutter } from "./npmGutter";
import { startNpmScriptsWatch } from "./npmScripts";
import { launchSettingsGutter } from "./launchSettingsGutter";
import { runGutter } from "./runGutter";
import { markdownCommandGutter } from "./markdownCommands";
@@ -435,6 +436,7 @@ export function activate(): () => void {
headerContent: lazyComponent(() => import("./RunView").then((m) => m.RunTabs)),
useBadge: useRunningCount,
}),
startNpmScriptsWatch(),
registerTitleItem({ id: "run.widget", title: "Run Widget", align: "right", priority: 0, component: RunWidget }),
registerRunAnythingProvider(runConfigsRunAnything),
registerBuiltinTypes(),
+186
View File
@@ -0,0 +1,186 @@
/**
* The npm tool window's data: the project's `package.json` files (root, workspace members and
* detected module roots) read from disk, independent of run configuration detection. Running a
* script goes through `scriptMenuItems`, which reuses a matching configuration or makes a temporary one.
*/
import { create } from "zustand";
import { call, commands, isTauri, onIdeEvent } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { useProjectRoots } from "@/platform/projectRoots";
import { lazyComponent } from "@/ui";
import { registerToolWindow } from "@/workbench/contributions";
import { objectEntries, scriptMenuItems, type ScriptEntry } from "./npmGutter";
/** A package (the directory of a `package.json`) or one of its scripts. */
export type NpmNode = { kind: "package"; key: string; label: string; scripts: NpmScript[] } | NpmScript;
export interface NpmScript {
kind: "script";
key: string;
/** Directory relative to the project root ("" for the root package). */
dir: string;
/** Absolute path of the `package.json`. */
path: string;
name: string;
}
interface NpmScriptsState {
loaded: boolean;
packages: NpmNode[];
}
export const useNpmScripts = create<NpmScriptsState>(() => ({ loaded: false, packages: [] }));
const safeJson = (text: string): Record<string, unknown> | null => {
try {
return JSON.parse(text) as Record<string, unknown>;
} catch {
return null;
}
};
/** Member directories (relative to the root) of the root package's `workspaces`: plain paths and one `*` level. */
async function workspaceDirs(pkg: Record<string, unknown>, root: string): Promise<string[]> {
const ws = pkg.workspaces;
const list = Array.isArray(ws)
? (ws as unknown[])
: Array.isArray((ws as { packages?: unknown[] })?.packages)
? (ws as { packages: unknown[] }).packages
: [];
const out: string[] = [];
for (const pattern of list) {
if (typeof pattern !== "string" || !pattern || pattern.includes("..")) continue;
const star = pattern.indexOf("*");
if (star < 0) {
out.push(pattern.replace(/\/+$/, ""));
continue;
}
const parent = pattern.slice(0, star).replace(/\/+$/, "");
const suffix = pattern.slice(star + 1);
const entries = await call(commands.fsReadDir(parent ? `${root}/${parent}` : root)).catch(() => []);
for (const e of entries) {
const isDir = e.kind === "dir" || e.targetKind === "dir";
if (!isDir || e.ignored || e.excluded || e.name === "node_modules") continue;
if (suffix && !e.name.endsWith(suffix)) continue;
out.push(parent ? `${parent}/${e.name}` : e.name);
}
}
return out;
}
let loadGen = 0;
/** Rescans the packages and their scripts. */
export async function loadNpmScripts(): Promise<void> {
const root = useProject.getState().project?.root ?? null;
const gen = ++loadGen;
if (!root || !isTauri()) {
useNpmScripts.setState({ loaded: true, packages: [] });
return;
}
const rootName = useProject.getState().project?.name ?? root;
const dirs = new Set([""]);
const rootText = await call(commands.fsReadText(`${root}/package.json`)).catch(() => null);
const rootPkg = rootText !== null ? safeJson(rootText) : null;
if (rootPkg) for (const dir of await workspaceDirs(rootPkg, root)) dirs.add(dir);
// Detected roots cover a front end in a subdirectory. A node module's own directory only shows
// up in `detectedFrom` ("<dir>/package.json"). Roots outside the project (absolute) are skipped.
for (const r of useProjectRoots.getState().detected) {
const abs = r.path.startsWith(`${root}/`) ? r.path.slice(root.length + 1) : r.path;
const rel = /^[A-Za-z]:[\\/]|^\//.test(abs) ? null : abs;
if (rel === null) continue;
if (r.kind !== "excluded" && rel) dirs.add(rel);
if (r.detectedFrom) {
const moduleDir = r.detectedFrom.replace(/\/[^/]+$/, "");
if (moduleDir && !/^[A-Za-z]:[\\/]|^\//.test(moduleDir)) dirs.add(moduleDir);
}
}
// Any other package.json the index knows, outside node_modules.
const indexed = await call(commands.findFilesNamed("package.json")).catch(() => []);
for (const file of indexed.slice(0, 500)) {
const path = String(file).replace(/\\/g, "/");
if (!path.startsWith(`${root}/`) || path.includes("/node_modules/")) continue;
dirs.add(path.slice(root.length + 1).replace(/\/?package\.json$/, ""));
}
const packages: NpmNode[] = [];
await Promise.all(
[...dirs].map(async (dir) => {
const path = dir ? `${root}/${dir}/package.json` : `${root}/package.json`;
const text = await call(commands.fsReadText(path)).catch(() => null);
if (text === null) return;
const scripts: NpmScript[] = objectEntries(text, "scripts").map((e: ScriptEntry) => ({
kind: "script" as const,
key: `npm:${dir ? `${dir}:` : ""}${e.name}`,
dir,
path,
name: e.name,
}));
if (scripts.length === 0) return;
scripts.sort((a, b) => a.name.localeCompare(b.name));
packages.push({ kind: "package", key: `pkg:${dir}`, label: dir === "" ? rootName : dir, scripts });
}),
);
if (gen !== loadGen) return;
packages.sort((a, b) =>
a.kind === "package" && b.kind === "package"
? a.label === rootName
? -1
: b.label === rootName
? 1
: a.label.localeCompare(b.label)
: 0,
);
useNpmScripts.setState({ loaded: true, packages });
}
/** Runs or debugs a script the way its gutter icon does. */
export async function runScriptNode(node: NpmScript, debug: boolean): Promise<void> {
const content = await call(commands.fsReadText(node.path)).catch(() => "");
const entry: ScriptEntry = { name: node.name, line: 0 };
const items = await scriptMenuItems(entry, node.path, content ?? "");
const item = items[debug ? 1 : 0];
if (item && "run" in item) item.run?.();
}
/** Keeps the scripts current and shows the npm tool window while the project has any. */
export function startNpmScriptsWatch(): () => void {
let unregister: (() => void) | null = null;
let indexing = true;
const syncToolWindow = (has: boolean) => {
if (has && !unregister)
unregister = registerToolWindow({
id: "npm-scripts",
title: "npm",
icon: "file-npm",
anchor: "right",
order: 13,
component: lazyComponent(() => import("./NpmScriptsView").then((m) => m.NpmScriptsView)),
});
else if (!has && unregister) {
unregister();
unregister = null;
}
};
const disposers = [
useNpmScripts.subscribe((s) => syncToolWindow(s.packages.length > 0)),
useProject.subscribe((s, prev) => {
if (s.project?.root !== prev.project?.root) void loadNpmScripts();
}),
useProjectRoots.subscribe((s, prev) => {
if (s.detected !== prev.detected || s.root !== prev.root) void loadNpmScripts();
}),
onIdeEvent("indexState", (e) => {
if (indexing && !e.indexing) void loadNpmScripts();
indexing = e.indexing;
}),
onIdeEvent("fsChanged", (e) => {
const changed = [...e.created, ...e.modified, ...e.removed];
if (changed.some((p) => /(^|\/)package\.json$/.test(p) && !p.includes("/node_modules/"))) void loadNpmScripts();
}),
];
void loadNpmScripts();
return () => {
disposers.forEach((d) => d());
syncToolWindow(false);
};
}
@@ -227,8 +227,14 @@
}
.shortcut {
flex: none;
max-width: 55%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--fg-subtle);
font-family: var(--font-keys);
font-size: var(--fs-small);
font-weight: 600;
}
.right {
flex: none;
@@ -249,6 +255,9 @@
align-items: center;
gap: var(--space-1-5);
}
.actionRow > .right {
max-width: 30%;
}
.disabled .name,
.disabled .location,
.disabled .shortcut,
@@ -872,11 +872,16 @@ function ResultRow({
<span
className={clsx(styles.actionRow, !row.enabled && styles.disabled)}
aria-disabled={!row.enabled || undefined}
title={row.title}
>
<span className={styles.icon}>{row.icon ? <Icon name={row.icon} size={16} /> : null}</span>
<span className={styles.main}>
<HighlightedText className={styles.name} text={row.title} indices={row.indices} tone={tone} />
{shortcut && <span className={styles.shortcut}>{shortcut}</span>}
{shortcut && (
<kbd className={styles.shortcut} title={shortcut}>
{shortcut}
</kbd>
)}
</span>
{toggled !== undefined ? (
<span
@@ -896,7 +901,11 @@ function ResultRow({
/>
</span>
) : (
row.category && <span className={styles.right}>{row.category}</span>
row.category && (
<span className={styles.right} title={row.category}>
{row.category}
</span>
)
)}
</span>
);
@@ -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
View File
@@ -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>
+10 -1
View File
@@ -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;
+7 -1
View File
@@ -56,7 +56,13 @@ function FilterButton({ label, value, onOpen, onClear, hidden }: LogFilter & { h
className={clsx(styles.filterButton, value && styles.filterActive, hidden && styles.filterHidden)}
inert={hidden}
>
<button type="button" className={styles.filterMain} onClick={(e) => onOpen(e.currentTarget)} aria-haspopup="menu">
<button
type="button"
className={styles.filterMain}
onClick={(e) => onOpen(e.currentTarget)}
aria-haspopup="menu"
title={value ?? undefined}
>
{value ? (
<>
{tx(label)}: <span className={styles.filterValue}>{value}</span>
+7
View File
@@ -1,4 +1,6 @@
{
"Fix Stylelint Problems": "Fix Stylelint Problems",
"No Stylelint problems to fix": "No Stylelint problems to fix",
"Reformat with Biome": "Reformat with Biome",
"Biome path": "Biome path",
"Biome formats an enabled language instead of Prettier and oxfmt below a Biome configuration file (biome.json, biome.jsonc) or installation, or when it is the selected provider.": "Biome formats an enabled language instead of Prettier and oxfmt below a Biome configuration file (biome.json, biome.jsonc) or installation, or when it is the selected provider.",
@@ -1482,6 +1484,8 @@
"Updated to {0}. New sessions will use this version.": "Updated to {0}. New sessions will use this version.",
"Installed: {0} · No newer npm release.": "Installed: {0} · No newer npm release.",
"Installed: {0}. Use your installer to manage this release channel.": "Installed: {0}. Use your installer to manage this release channel.",
"npm scripts": "npm scripts",
"database": "database",
"npm could not complete the operation ({0}).": "npm could not complete the operation ({0}).",
"An update for this agent is already running.": "An update for this agent is already running.",
"This is not a global npm install OpenIDEA can update. Use its original installer.": "This is not a global npm install OpenIDEA can update. Use its original installer.",
@@ -2070,6 +2074,9 @@
"Add Request Breakpoint": "Add Request Breakpoint",
"Java Exception Breakpoints": "Java Exception Breakpoints",
"Add Java Exception Breakpoint": "Add Java Exception Breakpoint",
"Create exception breakpoint on {name}": "Create exception breakpoint on {name}",
"Enable exception breakpoint on {name}": "Enable exception breakpoint on {name}",
"Disable exception breakpoint on {name}": "Disable exception breakpoint on {name}",
"Any exception": "Any exception",
"Enable Any exception": "Enable Any exception",
"Stops at every exception thrown in a Java debug session.": "Stops at every exception thrown in a Java debug session.",
+7
View File
@@ -1,4 +1,6 @@
{
"Fix Stylelint Problems": "修复 Stylelint 问题",
"No Stylelint problems to fix": "没有可修复的 Stylelint 问题",
"Reformat with Biome": "使用 Biome 重新格式化",
"Biome path": "Biome 路径",
"Biome formats an enabled language instead of Prettier and oxfmt below a Biome configuration file (biome.json, biome.jsonc) or installation, or when it is the selected provider.": "在 Biome 配置文件(biome.json、biome.jsonc)或 Biome 安装所在目录及其子目录中,或选择 Biome 作为格式化工具时,Biome 将代替 Prettier 和 oxfmt 格式化已启用的语言。",
@@ -1493,6 +1495,9 @@
"Exception breakpoints": "异常断点",
"Java Exception Breakpoints": "Java 异常断点",
"Add Java Exception Breakpoint": "添加 Java 异常断点",
"Create exception breakpoint on {name}": "在 {name} 上创建异常断点",
"Enable exception breakpoint on {name}": "启用 {name} 上的异常断点",
"Disable exception breakpoint on {name}": "禁用 {name} 上的异常断点",
"Any exception": "任何异常",
"Enable Any exception": "启用“任何异常”",
"Stops at every exception thrown in a Java debug session.": "在 Java 调试会话中抛出的每个异常处停止。",
@@ -5556,6 +5561,7 @@
"trigger": "触发器",
"sequence": "序列",
"data source": "数据源",
"database": "数据库",
"{count} library frames hidden": "已隐藏 {count} 个库帧",
"unverified": "未验证",
"temp": "临时",
@@ -7907,6 +7913,7 @@
"Updated to {0}. New sessions will use this version.": "已更新到 {0}。新会话将使用此版本。",
"Installed: {0} · No newer npm release.": "已安装:{0} · 没有更新的 npm 版本。",
"Installed: {0}. Use your installer to manage this release channel.": "已安装:{0}。请使用原安装工具管理此发布渠道。",
"npm scripts": "npm 脚本",
"npm could not complete the operation ({0}).": "npm 无法完成操作({0})。",
"An update for this agent is already running.": "此智能体已有更新正在进行。",
"This is not a global npm install OpenIDEA can update. Use its original installer.": "这不是 OpenIDEA 能更新的 npm 全局安装。请使用原安装工具更新。",