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

...
Автор SHA1 Повідомлення Дата
l0ng-ai cdc228daf0 feat(deployment): use a server group as the default deployment target
A server group can now be marked as the default in Settings | Deployment
(context menu or toolbar). Upload to <group> then uploads the selection to each
of its servers in turn, and automatic upload and remote deletes on save reach
every server of the default group.

Closes #4322
2026-11-19 00:08:44 +08:00
l0ng-ai 0527ff4218 feat(project-view): show user scopes as Project view panes (#4356)
Scopes defined in Settings > Scopes were only used by File Colors and Find in Files. The Project view's pane switcher now lists them after the built-in panes. Choosing one shows only that scope's files under their folders, like Open Files and All Changed Files. The pane updates as files are created or removed and as the scopes change. The new scope_files command lists a scope's files, at most 20000.

Closes #4315
2026-11-19 00:01:47 +08:00
l0ng-ai e5b2f4dfc7 feat(toolwindows): remember size for each tool window (#4353)
Tool windows on one side shared a single size, so switching from a resized Terminal to Debug and back lost the Terminal's height. The new Appearance option "Remember size for each tool window" (off by default) keeps each window's last size along its side and restores it when the window shows again. The size comes from dragging or from the Resize Tool Window actions. It is saved with the project layout and in saved tool window layouts.

Closes #4326
2026-11-18 23:53:47 +08:00
l0ng-ai a3617aa3e9 fix(structure): keep File Structure from jumping on unmatched queries (#4329)
With Narrow down on typing off, a query that matched nothing selected the first symbol, and Enter jumped to it. The popup now clears the selection when nothing matches and shows No matches next to the field, so Enter leaves the caret where it is. Adds Tree.clearSelection.

Closes #4212
2026-11-18 23:51:40 +08:00
l0ng-ai bd7d4c475b fix(keymap): record double-modifier shortcuts (#4328)
The shortcut recorder (Find Actions by Shortcut and Add Keyboard Shortcut) only saw single keystrokes, so it ignored double-modifier gestures such as Shift, Shift or Ctrl, Ctrl that the dispatcher supports. Double-modifier recognition moves out of the dispatcher into a recognizer that the recorder now shares. A double tap records the gesture. Holding the second tap with a key records Modifier Modifier+Key. Focus loss, a mouse press or a trackpad swipe resets it.

Closes #4225
2026-11-18 23:51:33 +08:00
l0ng-ai 15e32d5af6 feat(vcs): edit Directory Mappings to exclude or add Git repositories (#4351)
Directory Mappings listed only the project root, read-only. It now lists the detected repositories and those added by hand. Setting a repository to <none> removes it from the Git and Commit tool windows and from IDE-wide Git operations, while its files stay in the project. + adds a repository root that detection does not reach, and - removes an added one. The mappings are saved per project (vcs.mappings) and apply on every rescan. Adds Repos::mapped and the vcs_detected_roots command.

Closes #4157
2026-11-18 23:43:10 +08:00
l0ng-ai 3de76f1a63 fix(search): Find Action hides actions that cannot run (#4327)
Find Action only checked an action's when clause, not its enabled() check, so Annotate with Git Blame on an untracked file, Show Current Revision, or Set NULL with no data grid focused were listed as enabled and did nothing. Matching now uses isActionEnabled, the same check menus and shortcuts use. When Include disabled actions is unchecked, unavailable actions are hidden, also from the recent list. The database cell actions are enabled only while a grid has focus (a popup opened from the grid keeps the grid it captured). An empty Actions tab says Nothing found.

Closes #4223
2026-11-18 23:41:40 +08:00
l0ng-ai 262b91d89a fix(bookmarks): keep bookmarks when files and folders are renamed (#4325)
A rename in the Project view reached the bookmark store as a removal: the watcher's fsChanged event dropped the bookmarks of the old path before the rename's own mapping arrived. Bookmarks now follow explicit moves through onFilesMoved. A watcher removal waits for any move in progress in the same project, and drops a bookmark only when its path is really gone (an Undo or rollback may already have restored it).

Closes #4210
2026-11-18 23:38:57 +08:00
l0ng-ai 4d6a21c695 fix(terminal): keep the active ConPTY prompt when a terminal resizes (#4324)
When a ConPTY terminal got narrower (for example, a split opened and then closed), xterm dropped the end of the active PowerShell prompt. PowerShell then echoed input at absolute columns without printing the prompt again, so it came back garbled. Local terminals and embedded Run consoles now turn on xterm's cursor-line reflow on Windows builds whose ConPTY needs it. Remote and non-Windows sessions are unchanged.

Closes #4155
2026-11-18 23:32:50 +08:00
l0ng-ai 7de8fb850e fix(bookmarks): keep bookmarks on surviving lines after edits (#4323)
Deleting a bookmarked line next to another bookmark mapped both gutter markers onto the same line and re-matched the stored bookmarks by index. The surviving bookmark lost its mnemonic, description and list. The gutter now carries each bookmark through the edit. A bookmark is dropped only when its own line was removed, and the others keep their metadata, also across Undo and Redo.

Closes #4207
2026-11-18 23:30:45 +08:00
l0ng-ai acb850758a feat(vcs): option to detect changes with the Git command line (#4350)
Encryption or file protection layers can make the file metadata gitoxide reads differ from what the system git sees, so unchanged files showed as modified while git status was clean. The new Git setting "Detect changes with the Git command line" (vcs.git.cliStatus, off by default) reads the full working-tree status with git status, the same reader the partial refresh already used.

Closes #4124
2026-11-18 23:30:30 +08:00
l0ng-ai 6bf69cfb2a feat(java): strike out deprecated classes in the Project view and editor tabs (#4349)
The JVM file presentation now reports whether a file's primary type is deprecated: annotated @Deprecated (Java and Kotlin), or a Java type whose Javadoc has a @deprecated tag. The Project view and editor tabs strike the name out, and an error marker on the same file still shows.

Closes #4151
2026-11-18 23:21:04 +08:00
l0ng-ai 6829022b71 feat(vcs): ask for the Git user name and email before committing without them (#4348)
Committing in a repository without user.name or user.email failed with Git's error. Commit now first opens the Git User Name Is Not Defined dialog. The dialog proposes the identity the other repositories share and validates the name and email. It sets them globally by default, or in each repository that lacks them when the box is unchecked, and then the commit continues. Adds Repo::set_user_identity and the trusted vcs_set_user_identity command.

Closes #4175
2026-11-18 23:14:15 +08:00
l0ng-ai 54611ff80a fix(lsp): launch Windows npm language servers with an overlong PATH (#4314)
cmd.exe drops an inherited PATH over 8,191 UTF-16 code units, so npm launchers such as vtsls.cmd could not find Node. Before a Windows batch launch, missing absolute drive paths are pruned from an overlong PATH when that makes it fit, keeping the order of the rest. Explicit environment variables are now set before process preparation so they take precedence.
2026-11-18 23:05:05 +08:00
l0ng-ai cacfc4142f fix(vfs): reject ambiguous Windows file destinations (#4312)
Windows strips a trailing period or space from a path component, so the project tree and the editor ended up with different names for one file. The name editor now explains the rule, and the VFS rejects such destinations before creating, copying or renaming (verbatim paths excepted).
2026-11-18 23:04:28 +08:00
l0ng-ai 237f7ee5a5 fix(templates): expand live templates across matching carets (#4313)
Live templates expand at every caret sharing the same eligible prefix, in one undo step, keeping the primary caret and linking fields across the expansions. Mixed prefixes or syntax contexts fall back to the normal Tab edit.
2026-11-18 23:03:29 +08:00
l0ng-ai 2321929709 fix(terminal): keep the terminal from sliding sideways while composing (#4347)
A TUI that leaves the cursor in the last column pushed xterm's input textarea and IME composition past the right edge, and Chromium (WebView2) scrolled the clipping pane to keep the caret visible. The xterm element now clips its overflow, so no ancestor can scroll.
2026-11-18 23:02:51 +08:00
l0ng-ai 6d788cb6f8 fix(project-view): restore the contents of the last deletion (#4309)
Project View Undo restores the snapshot taken by that specific Delete, including empty folders and the files' exact bytes (BOM, line endings); earlier deletions stay deleted. Entries that cannot be restored (contents not captured, path now occupied) are named in the warning, which points to the system Trash.
2026-11-18 22:59:48 +08:00
l0ng-ai 662c32eb05 fix(editor): discard gutter color previews on Escape (#4285)
The gutter color picker previews a color without editing the document. Escape or Cancel dismisses the preview; Apply or clicking outside commits the color, and one Undo restores the original.
2026-11-18 22:56:41 +08:00
l0ng-ai 82ff84e69e fix(vcs): activate diff hunk buttons with the keyboard (#4311)
Diff hunk buttons (arrows, hover Revert, unified Revert) apply the change on click, so Enter and Space work as well as the pointer; a pointer press still keeps editor focus. The unified Revert test added since now activates the button with a click.
2026-11-18 22:55:57 +08:00
l0ng-ai 7ec0d3dbec fix(workbench): restore focus before running main-menu actions (#4310)
The custom main menu returns focus to the editor or field that opened it before running an action, so Edit › Undo / Redo reach the editor and workspace history (e.g. after Rename) instead of running while the menu button holds focus.
2026-11-18 22:54:23 +08:00
l0ng-ai 466556603d fix(editor): keep completion open inside an identifier (#4304)
Basic Completion no longer auto-inserts a sole suggestion when the caret is inside an identifier; the lookup stays open so Tab replaces the whole identifier (including a Unicode suffix). A sole suggestion at the end of a prefix still inserts at once.
2026-11-18 22:54:05 +08:00
l0ng-ai 3b2deb6ad8 fix(java): keep a Maven build's processor output away from jdtls (#4344)
jdtls runs annotation processors itself and writes to the same generated-sources/annotations folder as javac. A Maven build's rewrite of those files reached jdtls as a watched-file change; jdtls compiled javac's copy, failed to resolve the mapper and overwrote target/classes with an 'Unresolved compilation problems' class. Changes under generated-sources/annotations and generated-test-sources/test-annotations are no longer sent to jdtls.
2026-11-18 22:53:28 +08:00
l0ng-ai f2429a8c14 docs: suggest XWayland first for a Linux window that stops responding (#4342)
XWayland keeps the GPU renderer and stayed responsive on the setup in #4244, so the troubleshooting entry suggests GDK_BACKEND=x11 before turning the DMA-BUF renderer off.
2026-11-18 22:44:01 +08:00
l0ng-ai f3e80ba020 feat(http-client): navigate from a request URL to its endpoint handler (#4341)
⌘-click / Go to Declaration on a request URL in a .http file opens the handler of the endpoint it reaches, matched by method and path ({var}/*/** in the mapping, {{var}} in the request, an optional context path).
2026-11-18 22:42:02 +08:00
l0ng-ai f767bd2e7c fix(http-client): resolve Spring mapping constants declared in other classes (#4340)
Mapping paths were evaluated with the controller file's own constants only, so paths built from another class's constants dropped out of Endpoints search and showed partial URLs in the gutter. A shared constant pool finds the referenced classes by name in the index (imported package first), reads them and resolves their constants, following static imports and superclasses up to three hops.
2026-11-18 22:39:20 +08:00
l0ng-ai 51174842cc fix(database): keep Save password ticked in the connect prompt (#4338)
The connect-time password prompt stored the password but left the data source's savePassword off, and saved passwords are only read when it is on, so every connection asked again. The prompt's checkbox now updates the data source setting; the SSH secret prompt does the same for a source's own SSH settings.
2026-11-18 22:32:53 +08:00
l0ng-ai e4ece2bd8d fix(search): list scratch files in Recent Files (#4337)
Recent Files only recorded paths inside the project, so scratch files never appeared in ⌘E. Files outside the project are now recorded and persisted by absolute path; the popup and Switcher show files under the Scratches root as Scratches/<path>.
2026-11-18 22:30:54 +08:00
l0ng-ai a5093c0cd1 fix(workbench): space project tabs from the island below by the island gap (#4336)
The tab bar's bottom padding was --space-0-5 (2px), so the selected project tab island sat 2px above the islands below while islands are --island-gap (6px) apart.
2026-11-18 22:23:47 +08:00
l0ng-ai 9a0256c7d4 fix(ui): show a resize cursor on splitters under WebKit on macOS 26.2 (#4334)
WebKit on macOS 26.2 renders ew-resize/ns-resize as the default arrow, so dividers gave no hover feedback. Dividers (tool window gaps and splits, editor splits, side tabs, diff gutter, column resizers, review handles) and the drag-time cursor lock now use col-resize/row-resize. Window and popup edge handles are unchanged.
2026-11-18 22:21:24 +08:00
l0ng-ai 78b478ee38 fix(plugins): say which project a document-changed path is relative to (#4332)
document-changed gave plugins the path relative to the file's own project but not which project, so with two open projects holding the same relative path a plugin couldn't tell which document changed. The event now carries project (the root the path is relative to); the SDK's DocumentChanged exposes it as Option<String>. The payload is JSON through other, so WIT is unchanged; plugin components are rebuilt for the SDK change.
2026-11-18 22:13:03 +08:00
261 змінених файлів з 4675 додано та 890 видалено

No files matched your search

+79 -4
Переглянути файл
@@ -16,18 +16,55 @@ pub const CREATE_NO_WINDOW: u32 = 0x0800_0000;
/// For a `tokio::process::Command`, pass `cmd.as_std_mut()`.
///
/// - Windows: release builds use the GUI subsystem, so without `CREATE_NO_WINDOW` every
/// console child flashes a `cmd` window.
/// console child flashes a `cmd` window. Batch files also need a PATH small enough for cmd.
/// - Linux AppImage, reloaded and project variables: see [`host_env`].
///
/// Variables the call site has already set are kept; call it before `env_clear` and after
/// `current_dir`, which picks the project environment.
/// Explicit variables take precedence over the host environment. Call after setting
/// `current_dir` and any explicit `PATH`, and before `env_clear`.
pub fn prepare(cmd: &mut Command) -> &mut Command {
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
cmd.creation_flags(CREATE_NO_WINDOW);
}
host_env(cmd)
host_env(cmd);
#[cfg(windows)]
compact_batch_path(cmd);
cmd
}
#[cfg(windows)]
fn compact_batch_path(cmd: &mut Command) {
use std::os::windows::ffi::OsStrExt;
use std::path::{Component, Prefix};
// Rust runs these files through cmd.exe, which drops inherited variables over this limit.
const CMD_ENV_LIMIT: usize = 8191;
let extension = Path::new(cmd.get_program()).extension();
if !extension.is_some_and(|ext| ext.eq_ignore_ascii_case("cmd") || ext.eq_ignore_ascii_case("bat")) {
return;
}
let path = match cmd.get_envs().find(|(key, _)| key.eq_ignore_ascii_case("PATH")) {
Some((_, path)) => path.map(OsStr::to_owned),
None => std::env::var_os("PATH"),
};
let Some(path) = path.filter(|p| p.encode_wide().count() > CMD_ENV_LIMIT) else { return };
// The IDE includes possible locations of as-yet uninstalled tools. Prune paths that are
// missing now, keeping search precedence and leaving UNC and relative paths alone.
let dirs = std::env::split_paths(&path).filter(|dir| {
let local = dir.is_absolute()
&& matches!(dir.components().next(), Some(Component::Prefix(p))
if matches!(p.kind(), Prefix::Disk(_) | Prefix::VerbatimDisk(_)));
!local
|| !std::fs::symlink_metadata(dir)
.is_err_and(|e| matches!(e.kind(), std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory))
});
if let Ok(compact) = std::env::join_paths(dirs)
&& compact.encode_wide().count() <= CMD_ENV_LIMIT
{
cmd.env("PATH", compact);
}
}
/// Starts the child as the leader of its own process group on Unix, so [`kill_tree`] and
@@ -885,6 +922,44 @@ mod tests {
assert!(!process_alive(pid));
}
#[cfg(windows)]
#[test]
fn batch_launch_keeps_runtime_paths_when_cmd_would_drop_path() {
let root = tempfile::tempdir().unwrap();
let script = root.path().join("server.CMD");
std::fs::write(&script, "@echo off\r\nif not defined PATH exit /b 42\r\n").unwrap();
let selected = root.path().join("Selected Runtime");
let fallback = root.path().join("Fallback Runtime");
std::fs::create_dir(&selected).unwrap();
std::fs::create_dir(&fallback).unwrap();
let relative = Path::new("relative");
let unc = Path::new(r"\\openidea-test\share\bin");
let missing = root.path().join("uninstalled-".repeat(12));
let path = std::env::join_paths(
std::iter::once(selected.as_path()).chain(std::iter::repeat_n(missing.as_path(), 60)).chain([
unc,
relative,
fallback.as_path(),
]),
)
.unwrap();
let compact = std::env::join_paths([selected.as_path(), unc, relative, fallback.as_path()]).unwrap();
let path_in = |cmd: &Command| {
cmd.get_envs()
.find_map(|(key, value)| key.eq_ignore_ascii_case("PATH").then(|| value.map(OsStr::to_owned)))
.flatten()
};
let mut cmd = Command::new(&script);
cmd.current_dir(root.path()).env("PATH", &path);
prepare(&mut cmd);
assert_eq!(path_in(&cmd), Some(compact));
assert!(cmd.status().unwrap().success());
let mut native = Command::new(root.path().join("server.exe"));
assert_eq!(path_in(prepare(native.env("PATH", &path))), Some(path));
}
#[cfg(unix)]
#[test]
fn process_alive_rejects_ids_that_are_not_a_single_process() {
+3
Переглянути файл
@@ -770,6 +770,8 @@ pub struct AppearanceSettings {
pub show_tool_window_names: bool,
pub show_tool_window_badges: bool,
pub widescreen_tool_windows: bool,
/// Each tool window keeps its own size; off, the windows of a side share one.
pub remember_tool_window_sizes: bool,
/// View › Appearance › Toolbar; hidden leaves IDEA's compact window header.
pub show_main_toolbar: bool,
pub show_status_bar: bool,
@@ -898,6 +900,7 @@ impl Default for AppearanceSettings {
show_tool_window_names: false,
show_tool_window_badges: true,
widescreen_tool_windows: false,
remember_tool_window_sizes: false,
show_main_toolbar: true,
show_status_bar: true,
navigation_bar: NavigationBarPosition::StatusBar,
+33
Переглянути файл
@@ -20,6 +20,34 @@ pub struct VcsSettings {
pub shelf: ShelfSettings,
/// Issue Navigation: commit-message patterns turned into links.
pub issue_navigation: Vec<IssueLink>,
/// Directory Mappings: repository roots added to or excluded from the detected ones.
pub mappings: VcsMappings,
}
/// Directory Mappings on top of repository detection. Paths are relative to the project
/// root (`.` for the root itself) or absolute outside it.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct VcsMappings {
/// Detected repositories the IDE leaves alone: no Git or Commit integration, files stay.
pub excluded: Vec<String>,
/// Repository roots detection does not reach (outside the project, or deeper).
pub added: Vec<String>,
}
impl VcsMappings {
pub fn is_empty(&self) -> bool {
self.excluded.is_empty() && self.added.is_empty()
}
/// `path` resolved against `project_root`.
pub fn resolve(project_root: &std::path::Path, path: &str) -> std::path::PathBuf {
match path {
"" | "." => project_root.to_path_buf(),
p if std::path::Path::new(p).is_absolute() => p.into(),
p => project_root.join(p),
}
}
}
impl Default for VcsSettings {
@@ -34,6 +62,7 @@ impl Default for VcsSettings {
confirmation: VcsConfirmationSettings::default(),
shelf: ShelfSettings::default(),
issue_navigation: Vec::new(),
mappings: VcsMappings::default(),
}
}
}
@@ -77,6 +106,9 @@ pub struct GitSettings {
/// The non-modal Commit tool window works on the index: Staged / Unstaged groups,
/// stage and unstage instead of inclusion checkboxes, and no change lists.
pub staging_area: bool,
/// Scan the working tree with `git status` (for file systems whose metadata only
/// the system git reads correctly) instead of in process.
pub cli_status: bool,
}
impl Default for GitSettings {
@@ -101,6 +133,7 @@ impl Default for GitSettings {
push_dialog_only_protected: false,
combine_stash_and_shelf: false,
staging_area: false,
cli_status: false,
}
}
}
+29 -7
Переглянути файл
@@ -3,6 +3,7 @@ use crate::Host;
use ide_command::command;
use ide_core::{IdeError, IdeResult, RequestId};
use ide_vfs::FileEntry;
use ide_workspace::DeletionUndo;
use std::path::{Path, PathBuf};
#[command(trust = always)]
@@ -163,14 +164,27 @@ pub fn fs_set_writable(host: &Host, window: &str, path: PathBuf, writable: bool)
/// Moving to the trash can take a while (large trees): kept off the main thread.
#[command(trust = always)]
pub async fn fs_delete(host: &Host, window: &str, path: PathBuf) -> IdeResult<()> {
// Local History keeps the contents so deleted files can be restored.
let project = host.project(window).ok();
let history = project.as_ref().map(|p| p.history.clone());
delete_with_history(host, window, path, false).await.map(|_| ())
}
/// Moves an item to the Trash and returns the snapshot for Project View Undo.
#[command(trust = always)]
pub async fn fs_delete_with_undo(host: &Host, window: &str, path: PathBuf) -> IdeResult<DeletionUndo> {
delete_with_history(host, window, path, true).await
}
async fn delete_with_history(host: &Host, window: &str, path: PathBuf, undoable: bool) -> IdeResult<DeletionUndo> {
let project = if undoable { Some(host.project(window)?) } else { host.project(window).ok() };
host.blocking(move || {
let paths = ide_workspace::file_ops::deletion_paths(&path)?;
if let Some(h) = history {
for p in &paths {
h.record_deletion(p, DELETE_SNAPSHOT_LIMIT);
let mut undo = DeletionUndo::default();
if let Some(p) = &project {
if undoable {
undo = p.history.capture_deletion_undo(&paths, DELETE_SNAPSHOT_LIMIT);
} else {
for pth in &paths {
p.history.record_deletion(pth, DELETE_SNAPSHOT_LIMIT);
}
}
}
ide_workspace::file_ops::delete(&path)?;
@@ -178,11 +192,17 @@ pub async fn fs_delete(host: &Host, window: &str, path: PathBuf) -> IdeResult<()
if let Some(p) = project {
let _ = p.with_backend_of(&path, |r| r.files_deleted(&paths));
}
Ok(())
Ok(undo)
})
.await
}
#[command(trust = always)]
pub async fn fs_undo_delete(host: &Host, window: &str, undo: DeletionUndo) -> IdeResult<Vec<ide_core::IpcPath>> {
let project = host.project(window)?;
host.blocking(move || Ok(project.history.restore_deletion_undo(undo))).await
}
#[command(trust = always)]
pub async fn fs_copy(host: &Host, window: &str, from: PathBuf, to: PathBuf) -> IdeResult<()> {
let project = host.project(window).ok();
@@ -280,9 +300,11 @@ ide_command::domain!(
fs_create_file,
fs_create_file_bytes,
fs_delete,
fs_delete_with_undo,
fs_entry_kind,
fs_read_dir,
fs_read_text,
fs_rename,
fs_set_writable,
fs_undo_delete,
);
+26
Переглянути файл
@@ -68,6 +68,31 @@ pub async fn find_files_named(host: &Host, window: &str, name: String) -> IdeRes
blocking(move || Ok(project.index.files_named(&name).into_iter().map(Into::into).collect())).await
}
/// The files of a custom scope (`file:src//*.ts`), for the Project view's scope panes.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct ScopeFiles {
pub paths: Vec<IpcPath>,
/// More files than `limit` matched; `paths` holds the first ones.
pub truncated: bool,
}
#[command(trust = always)]
pub async fn scope_files(host: &Host, window: &str, pattern: String, limit: u32) -> IdeResult<ScopeFiles> {
let project = host.project(window)?;
blocking(move || {
let mask = ide_search::FileMask::new(&[], &project.search_excludes())?;
let scope = ide_search::SearchScope::Pattern { pattern };
let mut files =
ide_search::scope_files(&project.root, &scope, &mask, None, &ide_core::CancellationToken::new())?;
files.sort_by(|a, b| a.rel_path.cmp(&b.rel_path));
let truncated = files.len() > limit as usize;
files.truncate(limit as usize);
Ok(ScopeFiles { paths: files.into_iter().map(|f| f.path.into()).collect(), truncated })
})
.await
}
/// Folders holding indexed files, for `@` references.
#[command(trust = always)]
pub async fn find_dirs(host: &Host, window: &str, query: String, limit: u32) -> IdeResult<Vec<FileMatch>> {
@@ -375,6 +400,7 @@ ide_command::domain!(
path_completions,
recent_files,
remove_recent,
scope_files,
web_goto,
web_unresolved_references,
);
+9
Переглянути файл
@@ -302,6 +302,15 @@ pub fn set_settings(
}
});
}
// Directory Mappings change which repositories the project has.
if key == "vcs" || key == "vcs.mappings" || key.starts_with("vcs.mappings.") {
let affected = affected();
host.runtime.spawn_blocking(move || {
for project in affected {
project.refresh_repositories();
}
});
}
if key == "ssh" || key.starts_with("ssh.") {
host.ssh.set_configs(host.global_settings.effective().ssh.configs);
}
+2
Переглянути файл
@@ -18,6 +18,7 @@ pub async fn vcs_status(host: &Host, window: &str) -> IdeResult<Vec<FileStatus>>
}
for r in repos.all() {
r.set_ignored_names(settings.ignored_names());
r.set_cli_status(settings.vcs.git.cli_status);
}
repos.status()
})
@@ -40,6 +41,7 @@ pub async fn vcs_status_paths(host: &Host, window: &str, paths: Vec<std::path::P
}
for r in repos.all() {
r.set_ignored_names(settings.ignored_names());
r.set_cli_status(settings.vcs.git.cli_status);
}
repos.status_paths(&paths)
})
+25
Переглянути файл
@@ -338,6 +338,13 @@ fn keep_private(root: &Path) {
}
}
/// Directory Mappings: the repository roots detection finds, before any are excluded or added.
#[command(trust = always)]
pub async fn vcs_detected_roots(host: &Host, window: &str) -> IdeResult<Vec<PathBuf>> {
let project = host.project(window)?;
blocking(move || project.detected_repository_roots()).await
}
/// The project's repositories, the primary one first.
#[command(trust = always)]
pub fn vcs_roots(host: &Host, window: &str) -> IdeResult<Vec<VcsRoot>> {
@@ -1061,6 +1068,22 @@ pub async fn vcs_config_get(
blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.config_get(&key))).await
}
/// Git User Name Is Not Defined: sets `user.name` / `user.email` for commits in the
/// repository, or globally.
#[command(trust = trusted)]
pub async fn vcs_set_user_identity(
host: &Host,
window: &str,
repo: Option<PathBuf>,
name: String,
email: String,
global: bool,
) -> IdeResult<()> {
host.require_trust(window)?;
let project = host.project(window)?;
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.set_user_identity(&name, &email, global))).await
}
/// Local history operation that may take a while (hooks, large checkouts); git's
/// output streams through `on_output`. Cancellable.
#[command(trust = trusted)]
@@ -1569,6 +1592,7 @@ ide_command::domain!(
vcs_compare_paths,
vcs_compare_scope,
vcs_config_get,
vcs_set_user_identity,
vcs_conflict_versions,
vcs_create_branch,
vcs_create_patch,
@@ -1616,6 +1640,7 @@ ide_command::domain!(
vcs_revision_files,
vcs_reword,
vcs_roots,
vcs_detected_roots,
vcs_shelf_delete,
vcs_shelf_diff,
vcs_shelf_import,
+3 -1
Переглянути файл
@@ -162,7 +162,8 @@ impl PluginHost {
.collect()
}
/// What a plugin receives for `document-changed`: the path relative to the file's own project.
/// What a plugin receives for `document-changed`: the path relative to the file's own
/// project, and that project's root, since two open projects can hold the same relative path.
pub(super) fn relativize_documents(
shared: &super::api::Shared,
client: Option<&str>,
@@ -181,6 +182,7 @@ impl PluginHost {
.to_string_lossy()
.replace('\\', "/");
change.path = relative;
change.project = Some(ide_core::ipc_path::to_ipc(&root));
Some(WorkbenchEvent::DocumentChanged(change))
})
.collect()
+28 -3
Переглянути файл
@@ -2,6 +2,7 @@
//! watchers and the per-project services, opened by [`crate::Host::open_project`].
use crate::Host;
use ide_core::workflow_settings::VcsMappings;
use ide_core::{CancellationToken, IdeError, IdeEvent, IdeResult, LanguageId, SharedSink};
use ide_index::ProjectIndex;
use ide_language::{FileTypes, LanguageRegistry, SyntaxCache};
@@ -955,10 +956,27 @@ fn scan_repositories(
}
}
/// The repository containing `root` and those nested below it or below a content root.
/// The repository containing `root` and those nested below it or below a content root,
/// with the project's Directory Mappings applied.
/// The project-open scan and the watcher's rescan share these skip rules.
fn discover_repositories(root: &Path, settings: &SettingsStore, build_cache: &Path, trusted: bool) -> IdeResult<Repos> {
let ignored = settings.effective().ignored_names();
let settings = settings.effective();
let found = detect_repositories(root, &settings, build_cache, trusted)?;
let mappings = &settings.vcs.mappings;
if mappings.is_empty() {
return Ok(found);
}
let resolve = |list: &[String]| -> Vec<PathBuf> { list.iter().map(|p| VcsMappings::resolve(root, p)).collect() };
Ok(found.mapped(&resolve(&mappings.excluded), &resolve(&mappings.added), root))
}
fn detect_repositories(
root: &Path,
settings: &ide_core::settings::Settings,
build_cache: &Path,
trusted: bool,
) -> IdeResult<Repos> {
let ignored = settings.ignored_names();
let skip = |p: &Path| {
p.file_name().is_some_and(|n| {
let name = n.to_string_lossy();
@@ -968,11 +986,17 @@ fn discover_repositories(root: &Path, settings: &SettingsStore, build_cache: &Pa
})
};
let mut roots = vec![root.to_path_buf()];
roots.extend(content_roots(&settings.effective(), root, build_cache, trusted));
roots.extend(content_roots(settings, root, build_cache, trusted));
Repos::discover_roots(&roots, &skip)
}
impl Project {
/// The repository roots detection finds, before Directory Mappings exclude or add any.
pub fn detected_repository_roots(&self) -> IdeResult<Vec<PathBuf>> {
let settings = self.settings.effective();
Ok(detect_repositories(&self.root, &settings, &self.build_cache_dir(), self.is_trusted())?.roots())
}
pub fn refresh_repositories(&self) {
scan_repositories(
&self.root,
@@ -1076,6 +1100,7 @@ impl Project {
apply_git_executable(&settings);
}
repo.set_ignored_names(settings.ignored_names());
repo.set_cli_status(settings.vcs.git.cli_status);
f(repo)
}
+3
Переглянути файл
@@ -5298,6 +5298,7 @@ fn document_changes_reach_plugins_relative_to_the_project() {
let deliver = |path: &str| {
let change = ide_plugin::DocumentChanged {
path: to_ipc(&f.project.join(path)),
project: None,
base_version: 1,
version: 2,
changes: Vec::new(),
@@ -5311,6 +5312,8 @@ fn document_changes_reach_plugins_relative_to_the_project() {
// Queued with the absolute path, filtered again at delivery, handed over project-relative.
deliver("config/app.yaml");
assert_eq!(f.run("test.path-events", "document", None).unwrap().as_deref(), Some("config/app.yaml"));
// With the project it is relative to: another open project may hold the same path.
assert_eq!(f.run("test.path-events", "document-project", None).unwrap(), Some(to_ipc(&f.project)));
}
#[test]
+9
Переглянути файл
@@ -241,6 +241,15 @@ impl PathFilter {
(!rel.is_empty()).then_some(rel)
}
/// Recent Files' stored form: the store key for a project file, the absolute
/// path for one outside it (a scratch file). Loading joins it to the root,
/// which leaves an absolute path as it is.
pub(crate) fn recent_key(&self, path: &Path) -> Option<String> {
self.store_key(path).or_else(|| {
(path.is_absolute() && !path.starts_with(&self.root)).then(|| path.to_str().map(str::to_owned))?
})
}
fn excluded_rel(&self, rel: &str) -> bool {
self.excludes.is_match(rel)
}
+18 -15
Переглянути файл
@@ -400,15 +400,10 @@ impl ProjectIndex {
/// Boost for "recent files" ranking.
/// Records a recently opened file; a virtual document's URI (library
/// class) is kept verbatim, like IDEA lists library classes in Recent Files.
/// class) is kept verbatim, and a file outside the project (a scratch file)
/// by its absolute path.
pub fn mark_recent(&self, path: &Path) {
let path = match path.to_str() {
Some(s) if ide_core::text::is_virtual_uri(s) => path.to_owned(),
_ => match self.normalize(path) {
Some(p) => p,
None => return,
},
};
let Some(path) = self.recent_key(path) else { return };
{
let mut r = self.shared.recent.lock();
r.retain(|p| p != &path);
@@ -420,13 +415,7 @@ impl ProjectIndex {
/// Drops a file from Recent Files (Delete in the ⌘E popup).
pub fn remove_recent(&self, path: &Path) {
let path = match path.to_str() {
Some(s) if ide_core::text::is_virtual_uri(s) => path.to_owned(),
_ => match self.normalize(path) {
Some(p) => p,
None => return,
},
};
let Some(path) = self.recent_key(path) else { return };
{
let mut r = self.shared.recent.lock();
let before = r.len();
@@ -473,6 +462,20 @@ impl ProjectIndex {
&self.root
}
/// How Recent Files stores `path`: a virtual URI verbatim, a project file normalized,
/// and an existing file outside the root canonicalized. Excluded files under the root
/// are left out.
fn recent_key(&self, path: &Path) -> Option<PathBuf> {
if path.to_str().is_some_and(ide_core::text::is_virtual_uri) {
return Some(path.to_owned());
}
if let Some(p) = self.normalize(path) {
return Some(p);
}
let p = dunce::canonicalize(path).ok().filter(|p| p.is_file())?;
(!p.starts_with(&self.root)).then_some(p)
}
/// Absolute path inside the root (or a content root), or `None` for paths outside the project.
fn normalize(&self, path: &Path) -> Option<PathBuf> {
let filter = self.shared.filter();
+20
Переглянути файл
@@ -251,6 +251,26 @@ fn recent_files_skip_deleted_files_but_keep_virtual_documents() {
assert_eq!(idx.recent_files(), vec![virt]);
}
#[test]
fn recent_files_keep_files_outside_the_project() {
let fx = sample();
let scratches = tempfile::tempdir().unwrap();
let scratch = dunce::canonicalize(scratches.path()).unwrap().join("generated-requests.http");
std::fs::write(&scratch, "GET http://localhost\n").unwrap();
let app = fx.root.join("web/app.py");
{
let idx = fx.open();
idx.mark_recent(&app);
idx.mark_recent(&scratch);
assert_eq!(idx.recent_files(), vec![scratch.clone(), app.clone()]);
assert!(idx.wait_idle(WAIT));
}
let idx = fx.open();
assert_eq!(idx.recent_files(), vec![scratch.clone(), app.clone()], "persisted by absolute path");
idx.remove_recent(&scratch);
assert_eq!(idx.recent_files(), vec![app]);
}
#[test]
fn persistence_skips_unchanged_files_on_reopen() {
let fx = sample();
+2 -2
Переглянути файл
@@ -591,7 +591,7 @@ impl Shared {
let update_elapsed = update_started.elapsed();
let snapshot_started = Instant::now();
if let Some(store) = &self.store {
let recent: Vec<String> = self.recent.lock().iter().filter_map(|p| filter.store_key(p)).collect();
let recent: Vec<String> = self.recent.lock().iter().filter_map(|p| filter.recent_key(p)).collect();
let d = self.data.read();
let snapshot_started = Instant::now();
if let Err(e) = store.save_snapshot(&d, &filter, guard) {
@@ -976,7 +976,7 @@ impl Shared {
}
}
if save_recent && let Some(store) = &self.store {
let rels: Vec<String> = self.recent.lock().iter().filter_map(|p| filter.store_key(p)).collect();
let rels: Vec<String> = self.recent.lock().iter().filter_map(|p| filter.recent_key(p)).collect();
if let Err(e) = store.save_recent(&rels) {
tracing::warn!("index cache: saving recent files failed: {e}");
}
+4 -8
Переглянути файл
@@ -407,18 +407,14 @@ impl Peer {
let resolved = resolve_spawn_program(command, env);
let mut cmd = tokio::process::Command::new(&resolved);
// The working directory first: it picks the project's environment.
cmd.current_dir(cwd);
cmd.current_dir(cwd)
.envs(ide_core::process::shell_env_in(cwd))
.envs(env.iter().map(|(k, v)| (k.as_str(), v.as_str())));
ide_core::process::prepare(cmd.as_std_mut());
// Wrappers (`npx`, `codex.cmd`, launcher scripts) start the real server as a child:
// stopping the connection stops the whole tree.
ide_core::process::own_group(cmd.as_std_mut());
cmd.args(args)
.envs(ide_core::process::shell_env_in(cwd))
.envs(env.iter().map(|(k, v)| (k.as_str(), v.as_str())))
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
cmd.args(args).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).kill_on_drop(true);
let mut child = cmd.spawn()?;
let stdin = child.stdin.take().ok_or_else(|| std::io::Error::other("child stdin unavailable"))?;
let stdout = child.stdout.take().ok_or_else(|| std::io::Error::other("child stdout unavailable"))?;
+1
Переглянути файл
@@ -23,6 +23,7 @@ pub(crate) mod configuration;
mod extract_interface;
mod formatter;
mod generated;
pub(crate) use generated::is_processor_output;
mod hierarchy;
pub(crate) mod jvm_inspect;
mod move_refactoring;
+26
Переглянути файл
@@ -25,6 +25,18 @@ pub(crate) struct GeneratedScan {
pub roots: Vec<GeneratedRoot>,
}
/// Whether `path` is in (or is) an annotation-processor output folder:
/// `generated-sources/annotations` or `generated-test-sources/test-annotations`. jdtls
/// runs the processors itself and writes there; javac (a Maven build) writes the same
/// files, and jdtls must not take those as edits (#4128).
pub(crate) fn is_processor_output(path: &Path) -> bool {
let parts: Vec<_> = path.components().map(|c| c.as_os_str()).collect();
parts.windows(2).any(|w| {
(w[0] == "generated-sources" && w[1] == "annotations")
|| (w[0] == "generated-test-sources" && w[1] == "test-annotations")
})
}
/// Generated Java source folders under `root` (a reactor or one module).
pub(crate) fn scan(root: &Path) -> GeneratedScan {
let mut modules = Vec::new();
@@ -260,6 +272,20 @@ fn plugins_removed(build: &str) -> String {
mod tests {
use super::*;
#[test]
fn recognizes_annotation_processor_output() {
for (path, expected) in [
("/p/m/target/generated-sources/annotations/com/x/FooMappingImpl.java", true),
("/p/m/target/generated-sources/annotations", true),
("/p/m/build-out/generated-test-sources/test-annotations/com/x/T.java", true),
("/p/m/target/generated-sources/protobuf/java/com/x/Hello.java", false),
("/p/m/src/main/java/annotations/Foo.java", false),
("/p/m/target/classes/com/x/FooMappingImpl.class", false),
] {
assert_eq!(is_processor_output(Path::new(path)), expected, "{path}");
}
}
fn write(root: &Path, rel: &str, text: &str) {
let path = root.join(rel);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
+4 -3
Переглянути файл
@@ -160,12 +160,13 @@ const DEAD_SHIM_MESSAGES: &[&str] =
/// server that dies like that on every start is missing (an install hint), not crashing.
/// Anything but a clear "not installed" answer from the shim counts as working.
fn reject_dead_shim(binary: PathBuf, search: &OsStr, root: &Path) -> Option<PathBuf> {
if !binary.parent().is_some_and(|d| d.file_name().is_some_and(|n| n == "shims")) {
if binary.parent().and_then(Path::file_name) != Some(OsStr::new("shims")) {
return Some(binary);
}
let Ok(mut child) = ide_core::process::prepare(std::process::Command::new(&binary).current_dir(root))
let mut cmd = std::process::Command::new(&binary);
cmd.current_dir(root).env("PATH", search);
let Ok(mut child) = ide_core::process::prepare(&mut cmd)
.arg("--version")
.env("PATH", search)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::piped())
+5
Переглянути файл
@@ -3057,7 +3057,12 @@ impl LspManager {
for s in servers {
let Some(run) = s.running() else { continue };
let open = open.get(&(s.id, run.generation)).filter(|_| run.caps.read().sync != SyncKind::None);
// jdtls owns its annotation-processor output; javac's copy of those files is not an edit.
let jdtls = s.name == "jdtls";
let send = |p: &PathBuf, change: Change| {
if jdtls && jdtls::is_processor_output(p) {
return false;
}
change == Change::Deleted
|| !open
.is_some_and(|paths| paths.contains(p) || canonical.get(p).is_some_and(|c| paths.contains(c)))
+1 -2
Переглянути файл
@@ -94,10 +94,9 @@ pub(crate) fn connect_or_start(
let args = substitute_args(&config.args, port, root);
let mut cmd = tokio::process::Command::new(binary);
cmd.current_dir(root);
cmd.current_dir(root).envs(env.iter().map(|(k, v)| (k.as_str(), v.as_str())));
ide_core::process::prepare(cmd.as_std_mut());
cmd.args(&args)
.envs(env.iter().map(|(k, v)| (k.as_str(), v.as_str())))
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
+27
Переглянути файл
@@ -991,6 +991,33 @@ async fn files_changed_on_disk_reach_the_servers_of_their_language() {
h.mgr.shutdown_all().await;
}
/// jdtls runs the annotation processors itself and writes their output; a Maven build's
/// copy of those files must not reach it as an edit, or jdtls recompiles javac's copy and
/// overwrites its classes with broken ones (#4128).
#[tokio::test(flavor = "multi_thread")]
async fn jdtls_does_not_hear_of_annotation_processor_output() {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
let (doc, _) = h.open("Open.java", "class Open {}");
h.wait_status("jdtls", ServerStatus::Ready).await;
let s = h.launcher.state("jdtls");
let source = h.root.join("m/src/main/java/com/x/FooMapping.java");
let generated = h.root.join("m/target/generated-sources/annotations/com/x/FooMappingImpl.java");
let test_generated = h.root.join("m/target/generated-test-sources/test-annotations/com/x/T.java");
h.mgr.watched_files_changed(
&[test_generated],
&[generated.clone(), source.clone()],
std::slice::from_ref(&generated),
&[h.root.join("m/target/generated-sources/annotations")],
);
eventually(|| !s.notified("workspace/didChangeWatchedFiles").is_empty()).await;
h.mgr.hover(doc, Pos::new(0, 0), Default::default()).await.unwrap();
assert_eq!(
s.notified("workspace/didChangeWatchedFiles"),
vec![json!({ "changes": [{ "uri": uri_of(&source), "type": 2 }] })]
);
h.mgr.shutdown_all().await;
}
/// An external change to a document open on the server's current instance reaches it only
/// through the reload's `didChange`: a watched-file change for it too would make a server
/// that re-reads the file on one (csharp-ls) apply the reload and then the diff computed
+3
Переглянути файл
@@ -250,6 +250,9 @@ pub struct DocumentTextChange {
#[serde(rename_all = "camelCase")]
pub struct DocumentChanged {
pub path: String,
/// The open project `path` is relative to, set when the event is handed to a plugin
/// (the editor posts the absolute path and `null`).
pub project: Option<String>,
pub base_version: u64,
pub version: u64,
pub changes: Vec<DocumentTextChange>,
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
c10d6f373bd3a701e201350d0272a211da72b23cef010144760db5bae44e2c11
ada68dfdf2875668eff1765ec22678315f18ac6f1364c5f7eda742cb58dc3c60
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
cd7a14b6d4464a559c197ba7fcba30fb045a8927c074fd0c310bec6039af0e0f
2279ae4f79c565c4cd59d9191f394c4d7d5b23ef955f1bd30c2e5396d608e46c
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
017cb719d8c3a226cb6178d75da7ae0396b2d78799658ef560f729e8e06f36e3
77be736c11c39de3a1b021a5e66e905c76e2d32352d889d6bcc9315607c54271
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
93a9660a0941f2f57d11ea7ae331bd6d209ddcb134729ee88ec2fd96e978e631
304690bf13cba5d262d54d709d6f18c627880954f0140919118aea0439fbaaf3
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
6a0008339af0935c7c0128d23bf3e885a642c335ad57097cffb3f000766aba33
b24767627e7445ec093cc79cd6c18844e4dcdf123c6b04c24bc37f109c5cdb0f
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
09369df431bb6922463a242484eb82325ce8af287654af97a99eefb3884115a5
0fa52a91772ceb3d45307db4f2561c132df4b966d15f7f9ce177b7a373f7163d
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
897898835f2f42763da34dad29b8f926b230b33f506830e4118e6c5914720bd4
34ea07edc731ab28748b99c398f7e1ee4d41aa22c0760d57027adad40759292f
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
b56b918d1ff51c902dc956a7da944163194fcc93ba5bcf8baafa44fc2b6b039b
470a54d825e84e8ec0418a244c1fc46426c02f299f4a456ff4cc83fa604d08a0
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
ec2f6463d1ce5d70ad7331ae51bca3c8205b55f1f9e5abfe2218d53be2b61437
20a4f662437478b20e5a80aa30afe20b155001f94c2934843ab11b69192833d4
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
8a25727e09b96b35bc90f906215e13d29697b3792ed81f7f80024299e8b23d44
c118a6562e0398e7f0deb64abc9913dd14acec74869d5c04c452923a81455463
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
33d331d6ab59aa44f9884504ecc77a474e99c7223253735983c327bee6e75984
194fa719b8c96ca23f2da73d2d7225c4805b5c48af67b1efff8e76852f0a6a1c
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
b804f22b06f924aebce86f8bc2c24b5306913f2d2a4a0167af10ce86c8f606db
3db661dd4d45a242b79caf642510d71841ba9f09b3b5eaa1854eabe9fcf6292e
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
27e24e96578471e51dace84968daa6ee189aae0d63d27f3054bf4f3a0841fe0c
196769808ae37ede0a7564f42cae087a18f756b3cd31acb7d99470f1bfd70ea6
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
283320b057d39decafce4f86e09ace4df46ef2f31524b6cac0af22bd62795b0c
dcd05de6c207f4594d347ad3dc44089204353dc898e53873f437e3db1928d629
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
dff4f3571bf72eedfbe2e0e2d6b8908e703e890639fb1b854eb4f35226ddbc98
ece50a864d5a85263cb30eb39dceae90fe174336904e9208ae5c9d5da5cbb036
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
f5d7f62056547beffaadf68a04e8393ee29d73d57501d9f8bb39e902e9d9bf61
a2854d3c357d976b5ee1bf7b31fa541a55581102d37ec85ea719d4fdedd962cb
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
8ea7d2a041efe6bcabe8f9bb58b216fe583a7ad39207f0f10b4bf423facc56e7
dbebe5cfa79092169689d43945e4d71e1a61303ce88f6b4f02216ab69083b955
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
3b5b541b94b674762d6c0494bb5e26bbc871460767015a669ecd2771dc063b8a
993b0f11e8cae470b0529fcfcbe9a520c855069ef63f242da3b26a3da2574d5d
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
64411ddd70ae2906710d03c90add26727aa319db38c5bd23971eb442943154c5
d803928d82cbb2991b3f0c53b73dbe2da625b7b2ce25050706b6da09687f2873
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
ff7468eabf0b09be01afda83ede9d8b540d17cbccb414e1972899bb851c19d84
1c779c4913a2b83fa51980ee0017e3f2625041f1b4de921cedcdcb3bd4120d67
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
b24fb8d5161006104698fb07a43432601b4f16fdc4a34cc70058cbef7e973066
bd09f3b47470087095ae50c3b0f134c471dd9ba1e5f812cd0285cef904065725
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
8ded9b882110bc6b1235b14797128d5999f20079178a6134f172f64f77922985
ada14d3aa0e462478de7dff28be356b2105f4d3ec8d4dff8a7a4a858d15c4613
+4
Переглянути файл
@@ -33,6 +33,10 @@ title = "off"
id = "document"
title = "document"
[[contributes.commands]]
id = "document-project"
title = "document-project"
[[contributes.commands]]
id = "count"
title = "count"
+2
Переглянути файл
@@ -33,6 +33,7 @@ impl Plugin for Fixture {
}
"count" => Ok(host::storage::get("count")?),
"document" => Ok(host::storage::get("document")?),
"document-project" => Ok(host::storage::get("document-project")?),
_ => Err(Error::NotFound(id.into())),
}
}
@@ -42,6 +43,7 @@ impl Plugin for Fixture {
for event in events {
if let Event::DocumentChanged(change) = event {
host::storage::set("document", &change.path).unwrap();
host::storage::set("document-project", change.project.as_deref().unwrap_or_default()).unwrap();
}
}
}
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
c38f6ca9e44f0a0674b9186ef105e73e0c66a914de92a1aec97b5985f31fc29a
3d628f747d13d3d2fae9a75adeb951c8af09b1db5fb15523fc71289857d97d99
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
a74d851ebf2cad085b9d0fb56ad26c7b18d737c8cc0ef32a592a8f1b05b9be06
43e7552ae0f8b42383cade84924adc81952c78253186a71c2693b11d98f01acd
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
ce5fc1e202210942f287b593fbb88f2f1d51b573702c476e9f2d96f684d546c6
373188558b7925b4f9c9f975b0b6aa7b13acdf8da0c622a4ab12f39b69c1f071
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
a9821d31a040a5b2244e205632bc4edf8ebeae5c34aa5911438b69254f767183
9c91a083fd31e57658f28c34329e061dc17cc08871fe09b3b96fa557bc085c8d
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
792cd02805a24a37655629a24da97d82c2cc4f385dea21720167792302a75236
1a2182ca4e272d3473084451932a1d8df861ac2e67ad1814c0e01e089584ab3f
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
e6235b32744d6e5b3042ff2231e1a30eb4966324e790d01176f88fc9955db638
d5e8c538e410f480d79454c616bf9b0e7eaa7e502ed0268bf20f75214ca93d17
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
c277285eab80d917597ca26bcee94c5bde17cb7d0d38f3bd2866ce75b048f226
756f2a459f2aa17d6eb1d9dbe089a3d6dc5079012ed68ee47e55d5256c589359
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
84e2be128daa6dbe04df383fee1250cd2b6d65d90a3de2afdaed98be147599cb
28327a76a68737fda8ae0b22a439f5bbe86dd53347a7ee2806bb66ae90714238
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
3a492f0664ed153d631ec3c1089e7bdf5dcf31f969cb75654516290ac35cf984
ac3a564273429fcaad2c443e3463f06694953889ad894c9f68b824e87e291ae0
+1 -1
Переглянути файл
@@ -14,7 +14,7 @@ pub use deploy::{
Deployment, DeploymentCoverage, SyncAction, SyncEntry, SyncStatus, SyncStep, TransferReport, coverage,
};
pub use mapping::{Excludes, Mappings, ResolvedMapping};
pub use service::{DeployedPath, DeploymentRoot, RemoteService};
pub use service::{DeployedPath, DeploymentRoot, RemoteService, default_targets};
pub use target::{RemoteRuns, RemoteStart};
pub mod plugin_target;
+51 -10
Переглянути файл
@@ -1,7 +1,7 @@
//! Deployment over SFTP, FTP or local folders, and SSH run targets.
//! Shared by IPC commands and project save/delete hooks.
use crate::deploy::{Deployment, FileStamp, SyncEntry, SyncStatus, SyncStep, TransferReport, status};
use crate::deploy::{Deployment, FileStamp, SyncEntry, SyncStatus, SyncStep, TransferError, TransferReport, status};
use crate::mapping::{Excludes, Mappings, ResolvedMapping, posix};
use crate::target::{RemoteRuns, RemoteStart, SyncFn, rewrite_external_classpath};
use ide_core::remote_settings::{AutoUpload, DeploymentServer, DeploymentType, RunTarget};
@@ -65,6 +65,39 @@ pub fn server(settings: &Settings, id: Option<&str>) -> IdeResult<DeploymentServ
.ok_or_else(|| IdeError::not_found(format!("no deployment server {id}")))
}
/// The servers automatic upload goes to: the default server, or each server of the default group.
pub fn default_targets(settings: &Settings) -> Vec<String> {
let d = &settings.deployment;
match d.groups.iter().find(|g| g.id == d.default_server) {
Some(group) => group.servers.iter().filter(|id| d.servers.iter().any(|s| &s.id == *id)).cloned().collect(),
None if d.default_server.is_empty() => Vec::new(),
None => vec![d.default_server.clone()],
}
}
/// One report for transfers to several servers, failures named after their server.
fn merge_reports(reports: Vec<(String, IdeResult<TransferReport>)>) -> IdeResult<TransferReport> {
if let [(_, _)] = reports.as_slice() {
return reports.into_iter().next().map(|(_, r)| r).unwrap_or_else(|| Ok(TransferReport::default()));
}
let mut out = TransferReport::default();
for (server, report) in reports {
match report {
Ok(r) => {
out.files += r.files;
out.skipped += r.skipped;
out.errors.extend(
r.errors.into_iter().map(|e| TransferError { message: format!("{server}: {}", e.message), ..e }),
);
}
Err(e) => {
out.errors.push(TransferError { path: String::new(), message: format!("{server}: {}", e.message) })
}
}
}
Ok(out)
}
pub fn run_target(settings: &Settings, id: &str) -> IdeResult<RunTarget> {
settings
.run_targets
@@ -391,15 +424,17 @@ impl RemoteService {
.await;
return Some(r);
}
if settings.deployment.auto_upload == AutoUpload::Never
|| settings.deployment.default_server.is_empty()
|| !path.starts_with(root)
{
let targets = default_targets(settings);
if settings.deployment.auto_upload == AutoUpload::Never || targets.is_empty() || !path.starts_with(root) {
return None;
}
Some(
self.upload(settings, root, None, &[path.to_path_buf()], CancellationToken::new(), &mut |_, _, _| {}).await,
)
let mut reports = Vec::new();
for id in targets {
let paths = [path.to_path_buf()];
let r = self.upload(settings, root, Some(&id), &paths, CancellationToken::new(), &mut |_, _, _| {}).await;
reports.push((id, r));
}
Some(merge_reports(reports))
}
/// After files were deleted locally: their remote copies too (automatic upload + Delete remote files).
@@ -410,10 +445,16 @@ impl RemoteService {
paths: &[PathBuf],
) -> Option<IdeResult<TransferReport>> {
let d = &settings.deployment;
if d.auto_upload == AutoUpload::Never || !d.delete_remote || d.default_server.is_empty() {
let targets = default_targets(settings);
if d.auto_upload == AutoUpload::Never || !d.delete_remote || targets.is_empty() {
return None;
}
Some(self.delete_remote(settings, root, None, paths).await)
let mut reports = Vec::new();
for id in targets {
let r = self.delete_remote(settings, root, Some(&id), paths).await;
reports.push((id, r));
}
Some(merge_reports(reports))
}
// --- run targets ---------------------------------------------------------------
+38 -1
Переглянути файл
@@ -1,6 +1,6 @@
//! Local deployment uses the service entry points used by SFTP and save hooks.
use ide_core::CancellationToken;
use ide_core::remote_settings::{AutoUpload, DeploymentMapping, DeploymentServer, DeploymentType};
use ide_core::remote_settings::{AutoUpload, DeploymentGroup, DeploymentMapping, DeploymentServer, DeploymentType};
use ide_core::settings::Settings;
use ide_remote::{RemoteService, SyncAction, SyncStatus, SyncStep};
use ide_ssh::{FsConnection, SshFiles, SshManager};
@@ -410,3 +410,40 @@ async fn download_into_copies_only_the_selected_items() {
.unwrap();
assert_eq!((report.files, report.errors.len()), (0, 1), "{report:?}");
}
#[tokio::test]
async fn automatic_upload_to_a_default_group_reaches_each_of_its_servers() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("project");
let (staging, live) = (tmp.path().join("staging"), tmp.path().join("live"));
for dir in [root.join("src"), staging.clone(), live.clone()] {
std::fs::create_dir_all(dir).unwrap();
}
std::fs::write(root.join("src/a.txt"), "v1").unwrap();
let mut settings = settings(&staging);
settings.deployment.servers.push(DeploymentServer {
id: "live".into(),
kind: DeploymentType::Local,
root_path: live.to_string_lossy().into_owned(),
mappings: vec![DeploymentMapping { deployment: "app".into(), ..Default::default() }],
..Default::default()
});
settings.deployment.groups.push(DeploymentGroup {
id: "all".into(),
name: "All".into(),
servers: vec!["local".into(), "live".into(), "gone".into()],
});
settings.deployment.default_server = "all".into();
assert_eq!(ide_remote::default_targets(&settings), ["local", "live"]);
let service = service(tmp.path());
let saved = service.on_saved(&settings, &root, &root.join("src/a.txt")).await.unwrap().unwrap();
assert_eq!((saved.files, saved.errors.len()), (2, 0), "{saved:?}");
for target in [&staging, &live] {
assert_eq!(std::fs::read_to_string(target.join("app/src/a.txt")).unwrap(), "v1");
}
std::fs::remove_file(root.join("src/a.txt")).unwrap();
let deleted = service.on_deleted(&settings, &root, &[root.join("src/a.txt")]).await.unwrap().unwrap();
assert!(deleted.errors.is_empty(), "{deleted:?}");
assert!(!staging.join("app/src/a.txt").exists() && !live.join("app/src/a.txt").exists());
}
+18 -1
Переглянути файл
@@ -24,6 +24,8 @@ pub struct JvmPresentation {
pub kind: Option<JvmTypeKind>,
pub spring_boot: bool,
pub runnable: bool,
/// `@Deprecated`, or a Java `@deprecated` Javadoc tag.
pub deprecated: bool,
}
fn text<'a>(node: Node, source: &'a str) -> &'a str {
@@ -139,6 +141,19 @@ pub fn jvm_type_header(source: &str) -> Option<&str> {
None
}
/// The Javadoc right before `node` has a `@deprecated` block tag.
fn javadoc_deprecated(node: Node, source: &str) -> bool {
let Some(doc) = node.prev_named_sibling().filter(|n| n.kind() == "block_comment") else {
return false;
};
let doc = text(doc, source);
doc.starts_with("/**")
&& doc.lines().any(|line| {
let line = line.trim_start().trim_start_matches("/**").trim_start_matches('*').trim_start();
line.strip_prefix("@deprecated").is_some_and(|rest| !rest.starts_with(|c: char| c.is_alphanumeric()))
})
}
fn is_type(node: Node) -> bool {
matches!(
node.kind(),
@@ -221,7 +236,9 @@ impl StructureService {
})
})
});
Ok(JvmPresentation { kind: Some(kind), spring_boot, runnable })
let deprecated = modifiers.is_some_and(|m| annotation(m, snap.text, "Deprecated"))
|| cx.grammar == "java" && javadoc_deprecated(node, snap.text);
Ok(JvmPresentation { kind: Some(kind), spring_boot, runnable, deprecated })
})
}
}
+26
Переглянути файл
@@ -103,3 +103,29 @@ fn a_cut_off_file_is_classified_by_its_type_header() {
let closed = format!("{}}}", jvm_type_header(cut).unwrap());
assert_eq!(presentation("java", &closed).kind, Some(AbstractClass));
}
#[test]
fn deprecated_primary_types() {
for (language, source) in [
("java", "@Deprecated public class Foo {}"),
("java", "@java.lang.Deprecated(since = \"2\") interface Foo {}"),
("java", "/**\n * Old.\n * @deprecated use Bar\n */\npublic class Foo {}"),
("java", "/** @deprecated */ class Foo {}"),
("kotlin", "@Deprecated(\"use Bar\") class Foo"),
("kotlin", "@kotlin.Deprecated(\"x\", level = DeprecationLevel.ERROR) object Foo {}"),
] {
assert!(presentation(language, source).deprecated, "{language}: {source}");
}
for (language, source) in [
("java", "public class Foo {}"),
("java", "/* @deprecated */ class Foo {}"),
("java", "// @Deprecated\nclass Foo {}"),
("java", "/** See {@link Old}; @deprecatedSince is not a tag. */ class Foo {}"),
("java", "class Foo { @Deprecated void old() {} }"),
("java", "@Deprecated class Other {} class Foo {}"),
("kotlin", "class Foo { @Deprecated(\"x\") fun old() {} }"),
("kotlin", "/** @deprecated */ class Foo"),
] {
assert!(!presentation(language, source).deprecated, "{language}: {source}");
}
}
+21
Переглянути файл
@@ -768,6 +768,8 @@ pub struct Repo {
git_dir: PathBuf,
inner: std::sync::Mutex<repo::Cache>,
ignored: std::sync::RwLock<IgnoredNames>,
/// Working-tree status from `git status` instead of gitoxide.
cli_status: std::sync::atomic::AtomicBool,
log_index: std::sync::Mutex<log_index::LogIndex>,
log_signatures: std::sync::Mutex<std::collections::HashMap<String, LogDetails>>,
}
@@ -794,6 +796,11 @@ impl Repo {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
*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
/// (encryption or protection layers) whose metadata only the system git reads correctly.
pub fn set_cli_status(&self, on: bool) {
self.cli_status.store(on, std::sync::atomic::Ordering::Release);
}
/// 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>> {
@@ -1164,6 +1171,20 @@ impl Repo {
Ok((out.code == Some(0)).then(|| out.stdout_str().trim().to_string()))
}
/// 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 = if global { "--global" } else { "--local" };
for (key, value) in [("user.name", name.trim()), ("user.email", email.trim())] {
if value.is_empty() {
return Err(IdeError::invalid(format!("{key} must not be empty")));
}
cli::run(&self.root, &["config", scope, key, value], None)?;
}
Ok(())
}
// ---- writes (git CLI) ----
pub fn stage(&self, paths: &[PathBuf]) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
+1
Переглянути файл
@@ -76,6 +76,7 @@ pub(crate) fn discover(path: &Path) -> IdeResult<Option<Repo>> {
git_dir,
inner: std::sync::Mutex::new(cache),
ignored: Default::default(),
cli_status: Default::default(),
log_index: Default::default(),
log_signatures: Default::default(),
}))
+51
Переглянути файл
@@ -76,6 +76,29 @@ impl Repos {
Ok(Self::new(Repo::discover(project_root)?.into_iter().collect(), project_root))
}
/// Directory Mappings applied: the repositories at `excluded` roots are dropped (their
/// files stay in the project) and those at `added` roots join, the primary one being the
/// repository of `project_root` if it remains.
pub fn mapped(&self, excluded: &[PathBuf], added: &[PathBuf], project_root: &Path) -> Self {
let same = |a: &Path, b: &Path| a == b || dunce::canonicalize(a).ok() == dunce::canonicalize(b).ok();
let mut repos: Vec<Arc<Repo>> =
self.repos.iter().filter(|r| !excluded.iter().any(|e| same(e, r.root()))).cloned().collect();
for root in added {
if excluded.iter().any(|e| same(e, root)) || repos.iter().any(|r| same(r.root(), root)) {
continue;
}
match Repo::discover(root) {
Ok(Some(r)) if same(r.root(), root) => repos.push(Arc::new(r)),
Ok(_) => tracing::debug!("mapped directory {} is not a git root", root.display()),
Err(e) => tracing::debug!("mapped directory {}: {}", root.display(), e.message),
}
}
repos.sort_by(|a, b| a.root().cmp(b.root()));
let roots: Vec<&Path> = repos.iter().map(|r| r.root()).collect();
let primary = innermost(&roots, project_root, false).or((!repos.is_empty()).then_some(0));
Self { repos, primary }
}
/// Worktree roots, sorted.
pub fn roots(&self) -> Vec<PathBuf> {
self.repos.iter().map(|r| r.root().to_path_buf()).collect()
@@ -222,6 +245,34 @@ mod tests {
assert!(ok, "git init in {}", dir.display());
}
#[test]
fn directory_mappings_exclude_and_add_repositories() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap().join("project");
let outside = root.parent().unwrap().join("sdk");
git_init(&root);
git_init(&root.join("app"));
git_init(&root.join("reference-sdk"));
git_init(&root.join("a/b/c/d/deep"));
git_init(&outside);
let detected = Repos::discover(&root, &|_| false).unwrap();
let mapped =
detected.mapped(&[root.join("reference-sdk")], &[outside.clone(), root.join("a/b/c/d/deep")], &root);
let roots: Vec<&Path> = mapped.all().iter().map(|r| r.root()).collect();
assert_eq!(roots, [root.as_path(), &root.join("a/b/c/d/deep"), &root.join("app"), &outside]);
assert_eq!(mapped.primary().unwrap().root(), root);
// The excluded repository's files belong to the enclosing one again.
assert_eq!(mapped.for_path(&root.join("reference-sdk/lib.rs")).unwrap().root(), root);
// The project root excluded: only the other repositories remain; a folder that is no
// repository root is not added.
let without_root = detected.mapped(std::slice::from_ref(&root), &[root.join("a")], &root);
let roots: Vec<&Path> = without_root.all().iter().map(|r| r.root()).collect();
assert_eq!(roots, [&root.join("app"), &root.join("reference-sdk")]);
assert!(without_root.for_path(&root.join("README.md")).is_none());
}
#[test]
fn finds_nested_repositories_and_routes_paths() {
let tmp = tempfile::tempdir().unwrap();
+8 -4
Переглянути файл
@@ -20,10 +20,14 @@ pub(crate) fn status(r: &Repo) -> IdeResult<Vec<FileStatus>> {
let ignored = r.ignored.read().unwrap_or_else(|p| p.into_inner()).clone();
// gitoxide stops at the first IO error (a directory it may not read), where git warns
// and lists the rest: git answers then.
let (map, conflicts) = gix_status(r, &ignored).or_else(|e| {
tracing::debug!("status via gitoxide failed, asking git: {}", e.message);
cli_status(r, &ignored)
})?;
let (map, conflicts) = if r.cli_status.load(std::sync::atomic::Ordering::Acquire) {
cli_status(r, &ignored)?
} else {
gix_status(r, &ignored).or_else(|e| {
tracing::debug!("status via gitoxide failed, asking git: {}", e.message);
cli_status(r, &ignored)
})?
};
Ok(collect(r, &ignored, map, conflicts))
}
+36
Переглянути файл
@@ -2252,3 +2252,39 @@ fn status_paths_reads_only_the_named_paths() {
// An empty list is the full status, so a caller that lost the paths stays correct.
assert_eq!(repo.status_paths(&[]).unwrap().len(), 4);
}
#[test]
fn sets_the_commit_identity_in_the_repository() {
let fx = Fixture::new();
fx.git(&["config", "--unset", "user.name"]);
fx.git(&["config", "--unset", "user.email"]);
let repo = fx.repo();
repo.set_user_identity(" Ada Lovelace ", "[email protected]", false).unwrap();
assert_eq!(fx.git(&["config", "--local", "user.name"]), "Ada Lovelace");
assert_eq!(fx.git(&["config", "--local", "user.email"]), "[email protected]");
assert_eq!(repo.config_get("user.email").unwrap().as_deref(), Some("[email protected]"));
let blank = repo.set_user_identity("Ada", " ", false).unwrap_err();
assert_eq!(blank.kind, ErrorKind::InvalidInput);
}
#[test]
fn status_from_the_git_command_line_matches_the_in_process_one() {
let fx = Fixture::new();
fx.write("a.txt", "a\n");
fx.write("staged.txt", "a\n");
fx.write("gone.txt", "a\n");
fx.commit_all("base");
fx.write("a.txt", "b\n");
fx.write("staged.txt", "b\n");
fx.git(&["add", "staged.txt"]);
std::fs::remove_file(fx.path("gone.txt")).unwrap();
fx.write("dir/new.txt", "n\n");
let repo = fx.repo();
repo.set_ignored_names(ide_core::settings::Settings::default().ignored_names());
let show = |s: Vec<FileStatus>| s.into_iter().map(|f| (f.rel_path, f.staged, f.unstaged)).collect::<Vec<_>>();
let in_process = show(repo.status().unwrap());
repo.set_cli_status(true);
let from_git = show(repo.status().unwrap());
assert_eq!(from_git, in_process);
assert_eq!(from_git.len(), 4, "{from_git:#?}");
}
+30 -6
Переглянути файл
@@ -17,6 +17,31 @@ fn exists(path: &Path) -> bool {
fs::symlink_metadata(path).is_ok()
}
fn validate_destination(path: &Path) -> IdeResult<()> {
#[cfg(windows)]
{
use std::path::Component;
if matches!(path.components().next(), Some(Component::Prefix(prefix)) if prefix.kind().is_verbatim()) {
return Ok(());
}
// Win32 can silently strip trailing periods and spaces when resolving a path.
for component in path.components() {
if let Component::Normal(name) = component
&& matches!(name.as_encoded_bytes().last(), Some(b'.' | b' '))
{
return Err(IdeError::invalid(format!(
"Windows file and folder names cannot end with a period or space ({:?})",
name,
)));
}
}
}
#[cfg(not(windows))]
let _ = path;
Ok(())
}
fn ensure_parent(path: &Path) -> IdeResult<()> {
if let Some(parent) = path.parent()
&& !parent.as_os_str().is_empty()
@@ -27,16 +52,12 @@ fn ensure_parent(path: &Path) -> IdeResult<()> {
}
pub(crate) fn create_file(path: &Path) -> IdeResult<()> {
if exists(path) {
return Err(already_exists(path));
}
ensure_parent(path)?;
fs::OpenOptions::new().write(true).create_new(true).open(path)?;
Ok(())
create_file_bytes(path, &[])
}
pub(crate) fn create_file_bytes(path: &Path, data: &[u8]) -> IdeResult<()> {
use std::io::Write;
validate_destination(path)?;
if exists(path) {
return Err(already_exists(path));
}
@@ -64,6 +85,7 @@ pub(crate) fn set_writable(path: &Path, writable: bool) -> IdeResult<()> {
}
pub(crate) fn create_dir(path: &Path) -> IdeResult<()> {
validate_destination(path)?;
if exists(path) {
return Err(already_exists(path));
}
@@ -95,6 +117,7 @@ pub(crate) fn validate_rename(from: &Path, to: &Path) -> IdeResult<()> {
if from == to {
return Ok(());
}
validate_destination(to)?;
// A case-only rename on a case-insensitive file system sees `to` as existing.
if exists(to) && !same_file(from, to) {
return Err(already_exists(to));
@@ -151,6 +174,7 @@ pub(crate) fn delete(path: &Path, use_trash: bool) -> IdeResult<()> {
pub(crate) fn copy(from: &Path, to: &Path) -> IdeResult<()> {
let meta = fs::symlink_metadata(from).map_err(|_| not_found(from))?;
validate_destination(to)?;
if exists(to) {
return Err(already_exists(to));
}
+48
Переглянути файл
@@ -428,6 +428,54 @@ fn create_file_bytes_creates_parents() {
assert_eq!(std::fs::read(path).unwrap(), [0, 255]);
}
#[cfg(windows)]
#[test]
fn windows_file_operations_reject_ambiguous_destinations_before_mutating() {
let (_tmp, root) = root();
let source = root.join("source.txt");
write(&source, "original");
for name in ["example.txt.", "example.txt ", "first/nested./child", "first/nested /child"] {
let destination = root.join(name);
for result in [
create_file(&destination),
create_file_bytes(&destination, b"new"),
create_dir(&destination),
validate_rename(&source, &destination),
rename(&source, &destination),
copy(&source, &destination),
] {
assert_eq!(result.unwrap_err().kind, ErrorKind::InvalidInput, "{name:?}");
}
let names: Vec<_> = fs::read_dir(&root).unwrap().map(|entry| entry.unwrap().file_name()).collect();
assert_eq!(names, ["source.txt"], "{name:?}");
assert_eq!(fs::read(&source).unwrap(), b"original");
}
create_file(&root.join(".config.d/file.txt")).unwrap();
assert!(root.join(".config.d/file.txt").is_file());
}
#[cfg(windows)]
#[test]
fn create_file_preserves_literal_verbatim_path() {
let (_tmp, root) = root();
let path = fs::canonicalize(&root).unwrap().join("example.txt.");
create_file(&path).unwrap();
assert!(path.is_file());
assert!(!root.join("example.txt").exists());
fs::remove_file(path).unwrap();
}
#[cfg(not(windows))]
#[test]
fn create_file_preserves_trailing_dots_and_spaces() {
let (_tmp, root) = root();
let path = root.join("folder./example.txt ");
create_file(&path).unwrap();
assert!(path.is_file());
}
#[cfg(unix)]
#[test]
fn create_file_bytes_does_not_follow_existing_symlink() {
+305 -47
Переглянути файл
@@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::{HashMap, HashSet};
use std::fs;
use std::io::Write;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
@@ -30,6 +30,35 @@ pub struct HistoryEntry {
pub size: u64,
#[serde(default)]
pub kind: HistoryKind,
/// Exact on-disk bytes for Undo when document text omits a BOM or line endings.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(skip)]
undo_blob: Option<UndoBlob>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
struct UndoBlob {
id: String,
size: u64,
}
impl HistoryEntry {
fn snapshot(path: &Path, text: &str, label: &str, timestamp_ms: f64) -> Self {
Self {
id: blake3::hash(text.as_bytes()).to_hex().to_string(),
path: path.into(),
timestamp_ms,
label: label.to_owned(),
size: text.len() as u64,
kind: HistoryKind::Snapshot,
undo_blob: None,
}
}
fn blobs(&self) -> impl Iterator<Item = (&str, u64)> {
std::iter::once((self.id.as_str(), self.size))
.chain(self.undo_blob.iter().map(|blob| (blob.id.as_str(), blob.size)))
}
}
/// Changes under a folder (Show History on a directory).
@@ -42,6 +71,23 @@ pub struct DirectoryHistory {
pub deleted: Vec<ide_core::IpcPath>,
}
/// Paths and contents captured for one delete operation. Directory history is
/// intentionally broader and can contain paths deleted in an earlier operation.
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct DeletionUndo {
directories: Vec<ide_core::IpcPath>,
files: Vec<DeletedFile>,
skipped: Vec<ide_core::IpcPath>,
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct DeletedFile {
path: ide_core::IpcPath,
id: String,
}
/// How much history is kept (Settings › Advanced › Local History).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Retention {
@@ -108,22 +154,56 @@ fn valid_id(id: &str) -> bool {
fn valid_entry(e: &HistoryEntry) -> bool {
match e.kind {
HistoryKind::Snapshot => valid_id(&e.id),
HistoryKind::Snapshot => valid_id(&e.id) && e.undo_blob.as_ref().is_none_or(|blob| valid_id(&blob.id)),
HistoryKind::Label => e.id.is_empty(),
}
}
/// Text of a file for an automatic snapshot: small, non-binary files only.
fn read_snapshot_text(path: &Path) -> Option<String> {
read_snapshot_disk_text(path).map(|text| document_text(&text).into_owned())
}
fn read_snapshot_disk_text(path: &Path) -> Option<String> {
let meta = fs::metadata(path).ok()?;
if !meta.is_file() || meta.len() > AUTO_SNAPSHOT_LIMIT {
return None;
}
let bytes = fs::read(path).ok()?;
if bytes.iter().take(8192).any(|b| *b == 0) {
let mut bytes = Vec::new();
fs::File::open(path).ok()?.take(AUTO_SNAPSHOT_LIMIT + 1).read_to_end(&mut bytes).ok()?;
if bytes.len() as u64 > AUTO_SNAPSHOT_LIMIT || bytes.iter().take(8192).any(|b| *b == 0) {
return None;
}
String::from_utf8(bytes).ok().map(|text| document_text(&text).into_owned())
String::from_utf8(bytes).ok()
}
/// Directory junctions and similar reparse points must not be traversed.
fn is_link(metadata: &fs::Metadata) -> bool {
#[cfg(windows)]
{
use std::os::windows::fs::MetadataExt;
metadata.file_attributes() & 0x400 != 0
}
#[cfg(not(windows))]
{
metadata.file_type().is_symlink()
}
}
fn restore_deleted_bytes(path: &Path, bytes: &[u8]) -> IdeResult<()> {
let parent = path.parent().ok_or_else(|| IdeError::invalid("missing parent for deleted file"))?;
// Publish only a complete file, and never replace a new file at that path.
let mut builder = tempfile::Builder::new();
builder.prefix(".undo.openidea-tmp-");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
builder.permissions(fs::Permissions::from_mode(0o666));
}
let mut pending = builder.tempfile_in(parent)?;
pending.write_all(bytes)?;
pending.persist_noclobber(path).map_err(|error| error.error)?;
Ok(())
}
/// `text` as a document holds it: without the UTF-8 BOM and with `\n` line endings. Saves
@@ -191,55 +271,60 @@ impl LocalHistory {
Ok(())
}
fn store(&self, path: &Path, content: &str, label: &str, force: bool) -> IdeResult<()> {
let id = blake3::hash(content.as_bytes()).to_hex().to_string();
let mut state = self.state.lock();
if !force && state.last.get(path) == Some(&id) {
return Ok(());
/// Called with the history lock held, so prune cannot remove a blob before its entry exists.
fn store_blob(&self, id: &str, bytes: &[u8]) -> IdeResult<()> {
let blob = self.blob_path(id);
if !blob.exists() {
fs::create_dir_all(blob.parent().expect("blob has a parent"))?;
ide_vfs::write_atomic(&blob, bytes)?;
}
self.store_locked(&mut state, path, id, content, label, now_ms())
Ok(())
}
fn store(&self, path: &Path, content: &str, label: &str, force: bool, original: Option<&str>) -> IdeResult<String> {
let mut state = self.state.lock();
let entry = HistoryEntry::snapshot(path, content, label, now_ms());
if !force && state.last.get(path) == Some(&entry.id) {
return Ok(entry.id);
}
self.store_locked(&mut state, entry, content, original)
}
fn store_locked(
&self,
state: &mut HistoryState,
path: &Path,
id: String,
mut entry: HistoryEntry,
content: &str,
label: &str,
timestamp_ms: f64,
) -> IdeResult<()> {
let blob = self.blob_path(&id);
if !blob.exists() {
fs::create_dir_all(blob.parent().expect("blob has a parent"))?;
ide_vfs::write_atomic(&blob, content.as_bytes())?;
}
let entry = HistoryEntry {
id,
path: path.into(),
timestamp_ms,
label: label.to_owned(),
size: content.len() as u64,
kind: HistoryKind::Snapshot,
original: Option<&str>,
) -> IdeResult<String> {
self.store_blob(&entry.id, content.as_bytes())?;
entry.undo_blob = if let Some(original) = original.filter(|text| *text != content) {
let id = blake3::hash(original.as_bytes()).to_hex().to_string();
self.store_blob(&id, original.as_bytes())?;
Some(UndoBlob { id, size: original.len() as u64 })
} else {
None
};
self.append(state, entry)
let undo_id = entry.undo_blob.as_ref().map_or_else(|| entry.id.clone(), |blob| blob.id.clone());
self.append(state, entry)?;
Ok(undo_id)
}
/// Records a snapshot unless it equals the latest one recorded for `path`.
pub fn record(&self, path: &Path, content: &str, label: &str) -> IdeResult<()> {
self.store(path, content, label, false)
self.store(path, content, label, false, None).map(|_| ())
}
/// Records a snapshot even when the content did not change, so the event
/// ("Deleted", "Before refactoring: Move") shows in the history.
pub fn record_event(&self, path: &Path, content: &str, label: &str) -> IdeResult<()> {
self.store(path, content, label, true)
self.store(path, content, label, true, None).map(|_| ())
}
/// Snapshots the file on disk (small text files only); `force` as in [`record_event`](Self::record_event).
pub fn record_file(&self, path: &Path, label: &str, force: bool) -> IdeResult<bool> {
match read_snapshot_text(path) {
Some(text) => self.store(path, &text, label, force).map(|()| true),
Some(text) => self.store(path, &text, label, force, None).map(|_| true),
None => Ok(false),
}
}
@@ -265,8 +350,8 @@ impl LocalHistory {
(Some(modified), Some(oldest)) => modified.max(oldest - 1.0).min(now),
_ => now,
};
let id = blake3::hash(text.as_bytes()).to_hex().to_string();
self.store_locked(&mut state, path, id, &text, ORIGINAL, timestamp).map(|()| true)
let entry = HistoryEntry::snapshot(path, &text, ORIGINAL, timestamp);
self.store_locked(&mut state, entry, &text, None).map(|_| true)
}
/// Snapshots `path`, or every file below it when it is a folder (at most `limit`
@@ -290,6 +375,92 @@ impl LocalHistory {
.count()
}
/// Captures only paths that belong to this delete, including empty folders.
/// The backup observes the same content limit as automatic history, but
/// keeps exact bytes so a recreated file does not pick up new file defaults.
pub fn capture_deletion_undo(&self, paths: &[PathBuf], limit: usize) -> DeletionUndo {
let mut undo = DeletionUndo::default();
let mut remaining = limit;
for path in paths {
self.capture_deleted_entry(path, &mut remaining, &mut undo);
}
undo
}
fn capture_deleted_entry(&self, path: &Path, remaining: &mut usize, undo: &mut DeletionUndo) {
if *remaining == 0 {
undo.skipped.push(path.into());
return;
}
*remaining -= 1;
let Ok(metadata) = fs::symlink_metadata(path) else {
undo.skipped.push(path.into());
return;
};
if is_link(&metadata) {
undo.skipped.push(path.into());
} else if metadata.is_dir() {
if path.file_name().is_some_and(|name| name == ".git") {
undo.skipped.push(path.into());
return;
}
undo.directories.push(path.into());
let Ok(entries) = fs::read_dir(path) else {
undo.skipped.push(path.into());
return;
};
for entry in entries {
if *remaining == 0 {
// Identify the unscanned subtree without enumerating the rest of it.
undo.skipped.push(path.into());
break;
}
if let Ok(entry) = entry {
self.capture_deleted_entry(&entry.path(), remaining, undo);
} else if !undo.skipped.iter().any(|entry| entry.as_ref() == path) {
undo.skipped.push(path.into());
}
}
} else if let Some(id) = read_snapshot_disk_text(path)
.and_then(|raw| self.store(path, &document_text(&raw), DELETED, true, Some(&raw)).ok())
{
undo.files.push(DeletedFile { path: path.into(), id });
} else {
undo.skipped.push(path.into());
}
}
/// Returns entries the caller should direct the user to recover from the
/// system Trash. A newly occupied path and its subtree are left alone.
pub fn restore_deletion_undo(&self, undo: DeletionUndo) -> Vec<ide_core::IpcPath> {
let mut skipped = undo.skipped;
let mut blocked: Vec<ide_core::IpcPath> = Vec::new();
for path in undo.directories {
if blocked.iter().any(|parent| path.starts_with(parent)) {
continue;
}
if let Err(error) = fs::create_dir(&*path) {
tracing::debug!("cannot restore deleted directory {}: {error}", path.display());
skipped.push(path.clone());
blocked.push(path);
}
}
for file in undo.files {
if blocked.iter().any(|parent| file.path.starts_with(parent)) {
continue;
}
let restored = self.read_blob(&file.id).and_then(|bytes| restore_deleted_bytes(&file.path, &bytes));
if let Err(error) = restored {
tracing::debug!("cannot restore deleted file {}: {error}", file.path.display());
skipped.push(file.path);
}
}
skipped.sort();
skipped.dedup();
skipped
}
/// The watcher saw `paths` disappear: files with history that are gone get a
/// "Deleted" entry pointing at their last content (unless one was recorded already).
pub fn note_removed(&self, paths: &[PathBuf]) -> IdeResult<()> {
@@ -315,6 +486,7 @@ impl LocalHistory {
label: DELETED.into(),
size,
kind: HistoryKind::Snapshot,
undo_blob: None,
};
self.append(&mut state, entry)?;
}
@@ -334,6 +506,7 @@ impl LocalHistory {
label: label.to_owned(),
size: 0,
kind: HistoryKind::Label,
undo_blob: None,
};
let mut state = self.state.lock();
self.append(&mut state, entry)
@@ -379,15 +552,12 @@ impl LocalHistory {
Ok(DirectoryHistory { entries, deleted })
}
pub fn content(&self, id: &str) -> IdeResult<String> {
fn read_blob(&self, id: &str) -> IdeResult<Vec<u8>> {
if !valid_id(id) {
return Err(IdeError::invalid(format!("invalid history id {id:?}")));
}
match fs::read(self.blob_path(id)) {
Ok(bytes) => {
let text = String::from_utf8(bytes).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into());
Ok(document_text(&text).into_owned())
}
Ok(bytes) => Ok(bytes),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
Err(IdeError::not_found(format!("history snapshot {id} not found")))
}
@@ -395,11 +565,24 @@ impl LocalHistory {
}
}
pub fn content(&self, id: &str) -> IdeResult<String> {
let bytes = self.read_blob(id)?;
let text = String::from_utf8(bytes).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into());
Ok(document_text(&text).into_owned())
}
/// Bytes stored in blobs.
pub fn stored_bytes(&self) -> u64 {
let state = self.state.lock();
let mut seen = HashSet::new();
state.entries.iter().filter(|e| e.kind == HistoryKind::Snapshot && seen.insert(&e.id)).map(|e| e.size).sum()
state
.entries
.iter()
.filter(|e| e.kind == HistoryKind::Snapshot)
.flat_map(HistoryEntry::blobs)
.filter(|(id, _)| seen.insert(*id))
.map(|(_, size)| size)
.sum()
}
/// Drops entries older than `max_age_days` calendar days and unreferenced blobs.
@@ -430,7 +613,7 @@ impl LocalHistory {
}
ide_vfs::write_atomic(&self.index_path(), text.as_bytes())?;
let referenced: HashSet<&str> = kept.iter().map(|e| e.id.as_str()).collect();
let referenced: HashSet<&str> = kept.iter().flat_map(HistoryEntry::blobs).map(|(id, _)| id).collect();
for shard in fs::read_dir(self.dir.join("blobs"))?.flatten() {
let Ok(files) = fs::read_dir(shard.path()) else { continue };
let mut remaining = 0usize;
@@ -467,8 +650,8 @@ fn retain(entries: Vec<HistoryEntry>, retention: Retention) -> Vec<HistoryEntry>
};
// Size bound: unique blob bytes, oldest snapshots dropped first.
let mut refs: HashMap<String, (usize, u64)> = HashMap::new();
for e in kept.iter().filter(|e| e.kind == HistoryKind::Snapshot) {
refs.entry(e.id.clone()).or_insert((0, e.size)).0 += 1;
for (id, size) in kept.iter().filter(|e| e.kind == HistoryKind::Snapshot).flat_map(HistoryEntry::blobs) {
refs.entry(id.to_owned()).or_insert((0, size)).0 += 1;
}
let mut total: u64 = refs.values().map(|(_, size)| size).sum();
if total <= retention.max_bytes {
@@ -482,10 +665,12 @@ fn retain(entries: Vec<HistoryEntry>, retention: Retention) -> Vec<HistoryEntry>
break;
}
drop[i] = true;
let r = refs.get_mut(&kept[i].id).expect("counted");
r.0 -= 1;
if r.0 == 0 {
total -= r.1;
for (id, _) in kept[i].blobs() {
let r = refs.get_mut(id).expect("counted");
r.0 -= 1;
if r.0 == 0 {
total -= r.1;
}
}
}
let mut i = 0;
@@ -578,6 +763,7 @@ mod tests {
label: "Saved".into(),
size,
kind,
undo_blob: None,
}
}
@@ -660,6 +846,78 @@ mod tests {
assert_eq!(h.stored_bytes(), 0);
}
#[test]
fn deletion_undo_captures_current_bytes_and_empty_folders() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("project");
let folder = root.join("subject");
let empty = folder.join("empty-child/leaf");
fs::create_dir_all(&empty).unwrap();
let history = LocalHistory::open(&tmp.path().join("history"), &root).unwrap();
let obsolete = folder.join("obsolete.txt");
fs::write(&obsolete, "deleted before the folder").unwrap();
history.capture_deletion_undo(std::slice::from_ref(&obsolete), 100);
fs::remove_file(&obsolete).unwrap();
let current = folder.join("current.txt");
let original = b"\xEF\xBB\xBFheader\r\nbody\n";
fs::write(&current, original).unwrap();
history.record(&current, "header\nbody\n", "Saved").unwrap();
let large = folder.join("sample.bin");
fs::write(&large, vec![0; 2_300_000]).unwrap();
let undo = history.capture_deletion_undo(std::slice::from_ref(&folder), 100);
let revisions = history.list(&current).unwrap();
assert!(revisions.iter().any(|entry| entry.label == DELETED));
assert_eq!(revisions[0].id, revisions[1].id, "visible revisions share the normalized content");
let blob = undo.files[0].id.clone();
assert_ne!(blob, revisions[0].id);
assert_eq!(
history.stored_bytes(),
("deleted before the folder".len() + "header\nbody\n".len() + original.len()) as u64
);
history.apply_retention(Retention::default()).unwrap();
fs::remove_dir_all(&folder).unwrap();
assert_eq!(history.restore_deletion_undo(undo), vec![large]);
assert_eq!(fs::read(&current).unwrap(), original);
assert!(empty.is_dir());
assert!(!obsolete.exists());
history.clear().unwrap();
assert!(!history.blob_path(&blob).exists(), "pruning removes the exact bytes too");
}
#[test]
fn deletion_undo_preserves_new_files_and_reports_unavailable_entries() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("project");
let folder = root.join("folder");
fs::create_dir_all(&folder).unwrap();
let history = LocalHistory::open(&tmp.path().join("history"), &root).unwrap();
let file = folder.join("old.txt");
fs::write(&file, "before deletion").unwrap();
let undo = history.capture_deletion_undo(std::slice::from_ref(&folder), 100);
fs::remove_dir_all(&folder).unwrap();
fs::create_dir_all(&folder).unwrap();
fs::write(&file, "recreated").unwrap();
assert_eq!(history.restore_deletion_undo(undo), vec![folder.clone()]);
assert_eq!(fs::read_to_string(&file).unwrap(), "recreated");
let file_only = history.capture_deletion_undo(std::slice::from_ref(&file), 100);
fs::write(&file, "new contents").unwrap();
assert_eq!(history.restore_deletion_undo(file_only), vec![file.clone()]);
assert_eq!(fs::read_to_string(&file).unwrap(), "new contents");
let limited = history.capture_deletion_undo(std::slice::from_ref(&folder), 1);
assert_eq!(limited.skipped, vec![folder]);
assert!(limited.files.is_empty());
let expired = history.capture_deletion_undo(std::slice::from_ref(&file), 100);
fs::remove_file(&file).unwrap();
history.clear().unwrap();
assert_eq!(history.restore_deletion_undo(expired), vec![file.clone()]);
assert!(!file.exists());
}
#[test]
fn retention_keeps_working_days_and_bounds_size() {
let id = |c: char| c.to_string().repeat(64);
Loaded 100 of 261 files, more files were not shown because too many files have changed in this diff. Show more