fix(vcs): use symlink target history in the editor (#7891)

The repository scan skips symlinks, so a file opened through a file symlink or a symlinked directory whose target lies outside the registered Git roots had no Git Blame or change markers, even when Git tracked the target. Read-only editor commands (blame, line hunks) now use the target's repository, discovered with the restricted read policy and never registered for status or Commit; excluded mappings and a disabled Git integration are honoured. The editor probes once per open file whether the link has committed history: only then do Annotate and the markers apply, and ordinary files in projects without Git make no further backend calls on edits.

Co-authored-by: igallart <[email protected]>
Цей коміт міститься в:
Isaac Gallartтаigallart authored and GitHub committed 2026-12-04 18:57:51 +08:00
1 джерело 4eab243ef2
коміт 091dd85ef0
14 files changed
+531 -80

No files matched your search

+26 -5
Переглянути файл
@@ -725,13 +725,22 @@ pub async fn vcs_check_incoming(
result
}
/// Whether an editor file reached through a symlink has a tracked file at its target's HEAD.
#[command(trust = always)]
pub async fn vcs_linked_file_has_history(host: &Host, window: &str, path: PathBuf) -> IdeResult<bool> {
let project = host.project(window)?;
blocking(move || project.linked_file_has_history(&path)).await
}
/// Gutter change markers for a file, computed against its current (unsaved) text.
#[command(trust = always)]
pub async fn vcs_line_hunks(host: &Host, window: &str, path: PathBuf) -> IdeResult<Vec<LineHunk>> {
let project = host.project(window)?;
blocking(move || {
let text = project.text_of(&path)?;
project.with_backend_of(&path, |r| r.line_hunks(&path, &text, false, project.vcs_encoding(&path, None)?))
project.with_editor_backend_of(&path, |repo, repo_path| {
let text = project.text_of(&path)?;
repo.line_hunks(repo_path, &text, false, project.vcs_encoding(&path, None)?)
})
})
.await
}
@@ -745,6 +754,11 @@ pub async fn vcs_staging_line_hunks(
) -> IdeResult<Option<ide_vcs::StagingLineHunks>> {
let project = host.project(window)?;
blocking(move || {
// A linked editor file uses the target's HEAD for markers, not the
// index of a repository that might track the link itself.
if project.linked_file_target(&path).is_some() {
return Ok(None);
}
let text = project.text_of(&path)?;
project.with_repo_of(&path, |repo| {
repo.staging_line_hunks(
@@ -881,14 +895,20 @@ pub async fn vcs_blame(
// An explicit text wins (merge view annotates its side panes, not the worktree).
blocking(move || {
let text = text.or_else(|| project.documents.text_of(&path));
project.with_backend_of(&path, |backend| {
project.with_editor_backend_of(&path, |backend, repo_path| {
let encoding = project.vcs_encoding(&path, revision.as_deref())?;
let text = text.as_deref();
let revision = revision.as_deref();
if let Some(repo) = backend.as_git() {
repo.blame_with_options(&path, text, revision, encoding, project.settings.effective().vcs.git.annotate)
repo.blame_with_options(
repo_path,
text,
revision,
encoding,
project.settings.effective().vcs.git.annotate,
)
} else {
backend.blame(&path, text, revision, encoding)
backend.blame(repo_path, text, revision, encoding)
}
})
})
@@ -3770,6 +3790,7 @@ ide_command::domain!(
vcs_has_hook,
vcs_ignore_blame_revision,
vcs_init,
vcs_linked_file_has_history,
vcs_line_hunks,
vcs_staging_line_hunks,
vcs_log,
+73 -6
Переглянути файл
@@ -1499,15 +1499,17 @@ fn repository_scan_skips(settings: &ide_core::settings::Settings) -> impl Fn(&Pa
/// Whether a scan of the project at `root` would look for a repository at `dir` and keep it.
fn repository_searched(root: &Path, dir: &Path, settings: &ide_core::settings::Settings) -> bool {
settings.vcs.git.enabled
&& !settings
.vcs
.mappings
.excluded
.iter()
.any(|p| dunce::canonicalize(VcsMappings::resolve(root, p)).is_ok_and(|e| e == dir))
&& !repository_excluded(root, dir, &settings.vcs.mappings)
&& Repos::searched(root, dir, &repository_scan_skips(settings))
}
fn repository_excluded(project_root: &Path, repo_root: &Path, mappings: &VcsMappings) -> bool {
mappings.excluded.iter().any(|entry| {
let excluded = VcsMappings::resolve(project_root, entry);
excluded == repo_root || dunce::canonicalize(excluded).is_ok_and(|path| path == repo_root)
})
}
/// When `dir`'s working-copy marker last changed.
fn marker_time(dir: &Path, markers: &[String]) -> Option<std::time::SystemTime> {
markers.iter().find_map(|m| dir.join(m).metadata().and_then(|m| m.modified()).ok())
@@ -1818,6 +1820,71 @@ impl Project {
self.with_repo_of(path, |r| f(r as &dyn Backend))
}
/// Read-only editor commands can use the worktree reached through a project symlink
/// without registering it for status, staging or other repository operations.
pub(crate) fn with_editor_backend_of<T>(
&self,
path: &Path,
f: impl FnOnce(&dyn Backend, &Path) -> IdeResult<T>,
) -> IdeResult<T> {
let Some(target) = self.linked_file_target(path) else {
return self.with_backend_of(path, |backend| f(backend, path));
};
let unavailable = || IdeError::unavailable(format!("{} is not in a git repository", path.display()));
if !self.git_enabled() {
let backend = self.backend_of(path).ok_or_else(unavailable)?;
return f(backend.as_ref(), path);
}
let Some(repo) = self.linked_editor_repo(path, &target)? else {
return self.with_backend_of(path, |backend| f(backend, path));
};
f(repo.as_ref(), &target)
}
pub(crate) fn linked_file_has_history(&self, path: &Path) -> IdeResult<bool> {
if !self.git_enabled() {
return Ok(false);
}
let Some(target) = self.linked_file_target(path) else {
return Ok(false);
};
let Some(repo) = self.linked_editor_repo(path, &target)? else {
return Ok(false);
};
Ok(repo.file_mode_at(&target, None)?.is_some_and(|mode| mode.starts_with("100")))
}
fn linked_editor_repo(&self, path: &Path, target: &Path) -> IdeResult<Option<Arc<Repo>>> {
let Some(repo) = Repo::discover(target)? else {
return Ok(None);
};
let mappings = self.settings.read_effective(|settings| settings.vcs.mappings.clone());
if repository_excluded(&self.root, repo.root(), &mappings) {
return Err(IdeError::unavailable(format!("{} is not in a git repository", path.display())));
}
// An unregistered target may have its own Git filters and executable settings.
// Use the restricted read policy even when the editor's project is trusted.
Ok(Some(self.repos().at_root(repo.root()).cloned().unwrap_or_else(|| Arc::new(repo))))
}
/// Resolves a file reached through a symlink under one of the workspace project folders.
pub(crate) fn linked_file_target(&self, path: &Path) -> Option<PathBuf> {
let project_root = self.root_of(path);
let relative = path.strip_prefix(&project_root).ok()?;
if relative.components().any(|component| !matches!(component, std::path::Component::Normal(_))) {
return None;
}
let target = dunce::canonicalize(path).ok()?;
if target == path || !target.is_file() {
return None;
}
// A different spelling of the same path is not by itself evidence of a symlink.
path.ancestors()
.take_while(|ancestor| *ancestor != project_root.as_path())
.any(|ancestor| ancestor.symlink_metadata().is_ok_and(|metadata| metadata.is_symlink()))
.then_some(target)
}
fn run_in<T>(&self, repo: &Repo, f: impl FnOnce(&Repo) -> IdeResult<T>) -> IdeResult<T> {
let settings = self.settings.effective();
repo.set_ignored_names(settings.ignored_names());
+9
Переглянути файл
@@ -152,6 +152,14 @@ async fn restricted_vcs_commands_run_no_program_of_the_repository() {
let host = &host;
let w = "main";
let file = project.root.join("src/a.txt");
#[cfg(unix)]
let history_path = {
let link = project.root.join("linked.txt");
std::os::unix::fs::symlink(external.root.join("src/a.txt"), &link).unwrap();
link
};
#[cfg(not(unix))]
let history_path = file.clone();
let root = || Some(project.root.clone());
let log = || Some(external.root.clone());
@@ -169,6 +177,7 @@ async fn restricted_vcs_commands_run_no_program_of_the_repository() {
call!("vcs_detected_roots", "", vcs::vcs_detected_roots(host, w)),
call!("vcs_branch_info", "", vcs::vcs_branch_info(host, w, root())),
call!("vcs_line_hunks", "", vcs::vcs_line_hunks(host, w, file.clone())),
call!("vcs_linked_file_has_history", "", vcs::vcs_linked_file_has_history(host, w, history_path)),
call!("vcs_staging_line_hunks", "", vcs::vcs_staging_line_hunks(host, w, file.clone(), None)),
call!("vcs_file_at", "", vcs::vcs_file_at(host, w, file.clone(), None)),
call!("vcs_image_at", "", vcs::vcs_image_at(host, w, project.root.join("asset.jpg"), ":0".into())),
+104
Переглянути файл
@@ -74,6 +74,110 @@ impl Drop for Fixture {
}
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn linked_editor_files_use_target_history_and_unsaved_text() {
use ide_workspace::settings::SettingsScope;
use std::os::unix::fs::symlink;
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let target = base.join("target");
let root = base.join("workspace");
std::fs::create_dir(&target).unwrap();
std::fs::create_dir(&root).unwrap();
let target_file = target.join("notes.txt");
let original = "first\nsecond\n";
std::fs::write(&target_file, original).unwrap();
git(&target, &["init", "-b", "main"]);
git(&target, &["add", "notes.txt"]);
git(
&target,
&[
"-c",
"user.name=Target",
"-c",
"[email protected]",
"-c",
"commit.gpgsign=false",
"commit",
"-m",
"Add notes",
],
);
symlink("../target", root.join("linked")).unwrap();
let directory_link_file = root.join("linked/notes.txt");
let file_link = root.join("notes.txt");
symlink("../target/notes.txt", &file_link).unwrap();
let new_file = target.join("new.txt");
std::fs::write(&new_file, "not committed\n").unwrap();
git(&target, &["add", "new.txt"]);
symlink("../target/new.txt", root.join("new.txt")).unwrap();
std::fs::write(root.join("plain.txt"), "not a link\n").unwrap();
let host = Host::new(common::host_config(&base));
let project = host.open_project("main", &root).unwrap();
for path in [root.join("plain.txt"), root.join("new.txt"), new_file] {
assert!(!vcs::vcs_linked_file_has_history(&host, "main", path).await.unwrap());
}
for path in [&directory_link_file, &file_link] {
assert!(vcs::vcs_linked_file_has_history(&host, "main", path.clone()).await.unwrap());
let blame = vcs::vcs_blame(&host, "main", path.clone(), None, None).await.unwrap();
assert_eq!(blame.len(), 2);
assert!(blame.iter().all(|line| line.author == "Target"));
assert!(vcs::vcs_line_hunks(&host, "main", path.clone()).await.unwrap().is_empty());
let doc = project.documents.open(path).unwrap().id;
project.documents.replace_all(doc, "first\nupdated\n").unwrap();
let hunks = vcs::vcs_line_hunks(&host, "main", path.clone()).await.unwrap();
assert_eq!(hunks.len(), 1);
assert_eq!((hunks[0].start, hunks[0].lines, hunks[0].old_text.as_str()), (1, 1, "second\n"));
let blame = vcs::vcs_blame(&host, "main", path.clone(), None, None).await.unwrap();
assert_eq!(blame[0].author, "Target");
assert!(blame[1].commit.chars().all(|character| character == '0'));
assert!(vcs::vcs_staging_line_hunks(&host, "main", path.clone(), None).await.unwrap().is_none());
project.documents.close(doc);
}
assert_eq!(std::fs::read_to_string(&target_file).unwrap(), original);
assert!(project.repos().is_empty());
assert!(vcs::vcs_line_hunks(&host, "main", target_file).await.is_err());
// The workspace's Git history can contain the link itself, but the editor reads its target.
git(&root, &["init", "-b", "main"]);
git(&root, &["add", "linked", "notes.txt"]);
git(
&root,
&[
"-c",
"user.name=Workspace",
"-c",
"[email protected]",
"-c",
"commit.gpgsign=false",
"commit",
"-m",
"Add links",
],
);
project.refresh_repositories();
assert_eq!(project.repos().roots(), vec![root.clone()]);
let blame = vcs::vcs_blame(&host, "main", file_link.clone(), None, None).await.unwrap();
assert_eq!(blame[0].author, "Target");
assert!(vcs::vcs_staging_line_hunks(&host, "main", file_link, None).await.unwrap().is_none());
for excluded in ["linked".to_owned(), target.to_string_lossy().into_owned()] {
project.settings.set(SettingsScope::Project, "vcs.mappings.excluded", serde_json::json!([excluded])).unwrap();
assert!(vcs::vcs_linked_file_has_history(&host, "main", directory_link_file.clone()).await.is_err());
assert!(vcs::vcs_line_hunks(&host, "main", directory_link_file.clone()).await.is_err());
assert!(vcs::vcs_blame(&host, "main", directory_link_file.clone(), None, None).await.is_err());
}
project.settings.set(SettingsScope::Project, "vcs.mappings.excluded", serde_json::json!([])).unwrap();
project.settings.set(SettingsScope::Project, "vcs.git.enabled", serde_json::json!(false)).unwrap();
assert!(!vcs::vcs_linked_file_has_history(&host, "main", directory_link_file.clone()).await.unwrap());
assert!(vcs::vcs_line_hunks(&host, "main", directory_link_file.clone()).await.is_err());
assert!(vcs::vcs_blame(&host, "main", directory_link_file, None, None).await.is_err());
host.close_project("main");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn checkout_reloads_clean_open_documents_before_returning() {
let f = Fixture::new().await;
+64 -1
Переглянути файл
@@ -1,4 +1,67 @@
import { expect, openFromTree, stubDesktop, test } from "./fixtures";
import { expect, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures";
test("the gutter only offers blame without Git roots once a linked target has confirmed history", async ({
workbench: page,
}) => {
const root = "/dev/acme-api";
const plain = `${root}/plain.txt`;
const linked = `${root}/linked.txt`;
await stubDesktop(page);
await page.evaluate(
async ({ plain, linked }) => {
const handlers = window.__ipc.handlers;
handlers.fs_probe = () => ({ size: 15, binary: false, tooLarge: false });
handlers.fs_read_text = () => "Committed line\n";
handlers.vcs_linked_file_has_history = ({ path }) => path === linked;
handlers.vcs_line_hunks = () => [];
handlers.vcs_blame = () => [
{ commit: "a".repeat(40), author: "Demo Author", timeMs: Date.UTC(2026, 4, 3), summary: "Add note" },
];
const storeModule = "/src/features/vcs/store.ts";
const { useVcs } = await import(/* @vite-ignore */ storeModule);
useVcs.setState({ available: false, roots: [] });
const contextModule = "/src/platform/context.ts";
const { setContext } = await import(/* @vite-ignore */ contextModule);
setContext("vcsAvailable", false);
const serviceModule = "/src/workbench/contributions.ts";
const { editorService } = await import(/* @vite-ignore */ serviceModule);
await editorService().openFile(plain);
},
{ plain, linked },
);
const gutter = page.locator(".cm-lineNumbers .cm-gutterElement").filter({ hasText: /^1$/ });
const annotate = page.getByRole("menuitem", { name: "Annotate with Git Blame", exact: true });
await expect.poll(() => ipcCalls(page, "vcs_linked_file_has_history")).toContainEqual({ path: plain });
await gutter.click({ button: "right" });
await expect(page.getByRole("menu")).toBeVisible();
await expect(annotate).toHaveCount(0);
await page.keyboard.press("Escape");
await page.locator(".cm-content").click();
await page.keyboard.press("Meta+Shift+A");
const search = page.getByRole("combobox");
const action = page.getByRole("option", { name: /Annotate with Git Blame/ });
await search.fill("Annotate with Git Blame");
await expect(action).toHaveCount(0);
await page.keyboard.press("Escape");
expect(await ipcCalls(page, "vcs_line_hunks")).toEqual([]);
await page.evaluate(async (path) => {
const serviceModule = "/src/workbench/contributions.ts";
const { editorService } = await import(/* @vite-ignore */ serviceModule);
await editorService().openFile(path);
}, linked);
await expect.poll(() => ipcCalls(page, "vcs_line_hunks")).toContainEqual({ path: linked });
await page.locator(".cm-content").click();
await page.keyboard.press("Meta+Shift+A");
await search.fill("Annotate with Git Blame");
await expect(action).toBeVisible();
await page.keyboard.press("Escape");
await gutter.click({ button: "right" });
await annotate.click();
await expect(page.locator(`.cm-vcs-blame [data-commit="${"a".repeat(40)}"] .cm-vcs-blame-author`)).toHaveText(
"Author",
);
});
test("Git annotations align dates and full author names at UI text size", async ({ workbench: page }) => {
const editor = await openFromTree(page, "build.gradle.kts");
+1 -1
Переглянути файл
@@ -35,7 +35,7 @@ test("an inline change keeps its actions and original code readable at the edito
];
const storeModule = "/src/features/vcs/store.ts";
const { useVcs } = await import(/* @vite-ignore */ storeModule);
useVcs.setState({ available: true, version: useVcs.getState().version + 1 });
useVcs.setState({ available: true, roots: ["/dev/acme-api"], version: useVcs.getState().version + 1 });
},
{ original, content },
);
+1
Переглянути файл
@@ -933,6 +933,7 @@ vcs_invalidate_log_signatures always project_host bin
vcs_keep_amend_commit trusted project_host bindings async
vcs_lfs_status trusted project_host bindings async
vcs_line_hunks always project_host bindings async
vcs_linked_file_has_history always project_host bindings async
vcs_log always project_host bindings async
vcs_log_details always project_host bindings async
vcs_log_details_batch always project_host bindings async
+2
Переглянути файл
@@ -2762,6 +2762,8 @@ export const commands = {
vcsLfsStatus: (repo: string, request: RequestId) => typedError<LfsStatus, IdeError>(__TAURI_INVOKE("vcs_lfs_status", { repo, request })),
/** Gutter change markers for a file, computed against its current (unsaved) text. */
vcsLineHunks: (path: string) => typedError<LineHunk[], IdeError>(__TAURI_INVOKE("vcs_line_hunks", { path })),
/** Whether an editor file reached through a symlink has a tracked file at its target's HEAD. */
vcsLinkedFileHasHistory: (path: string) => typedError<boolean, IdeError>(__TAURI_INVOKE("vcs_linked_file_has_history", { path })),
vcsLog: (repo: string | null, query: LogQuery) => typedError<Commit_Serialize[], IdeError>(__TAURI_INVOKE("vcs_log", { repo, query })),
vcsLogDetails: (repo: string | null, revision: string) => typedError<LogDetails, IdeError>(__TAURI_INVOKE("vcs_log_details", { repo, revision })),
vcsLogDetailsBatch: (repo: string | null, revisions: string[], request: RequestId) => typedError<LogDetails[], IdeError>(__TAURI_INVOKE("vcs_log_details_batch", { repo, revisions, request })),
+15 -1
Переглянути файл
@@ -3,7 +3,7 @@ import { getAction, isActionEnabled } from "@/platform/actions";
import { registerVcsActions } from "../actions";
import { useVcs } from "../store";
afterEach(() => useVcs.setState({ byPath: new Map() }));
afterEach(() => useVcs.setState({ byPath: new Map(), roots: [] }));
const status = (path: string, staged: string | null, unstaged: string | null) =>
[path, { path, relPath: path.slice(6), staged, unstaged, renamedFrom: null }] as const;
@@ -13,6 +13,7 @@ describe("Annotate with Git Blame", () => {
const unregister = registerVcsActions();
try {
useVcs.setState({
roots: ["/repo"],
byPath: new Map([
status("/repo/new.py", null, "untracked"),
status("/repo/ignored_test.py", null, "ignored"),
@@ -34,4 +35,17 @@ describe("Annotate with Git Blame", () => {
unregister();
}
});
it("does not offer annotation for files outside a registered root without confirmed history", () => {
const unregister = registerVcsActions();
try {
const path = "/repo/linked.txt";
useVcs.setState({ roots: ["/repo"], byPath: new Map([status(path, null, "untracked")]) as never });
const action = getAction("vcs.annotate")!;
expect(isActionEnabled(action, { vcsAvailable: true }, "/outside/notes.txt")).toBe(false);
expect(isActionEnabled(action, { projectOpen: true }, path)).toBe(false);
} finally {
unregister();
}
});
});
+105 -2
Переглянути файл
@@ -13,8 +13,14 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
calls.push(`base:${path}`);
return Promise.resolve({ status: "ok", data: [hunk] });
},
vcsLinkedFileHasHistory: (path: string) => {
calls.push(`history:${path}`);
return Promise.resolve({ status: "ok", data: path === "/p/linked/notes.txt" });
},
vcsStagingLineHunks: (path: string) => {
calls.push(`index:${path}`);
if (path === "/p/linked/notes.txt" || path === "/p/plain.txt")
return Promise.resolve({ status: "ok", data: null });
// A working copy has no index.
return Promise.resolve({ status: "error", error: { message: "not a git repository" } });
},
@@ -24,16 +30,113 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { getAction, isActionEnabled } from "@/platform/actions";
import { useProject } from "@/platform/project";
import { _addEditor, _removeEditor, _setActiveEditor, documentSynced, type EditorDocContext } from "@/editor/api";
import { registerVcsActions } from "../actions";
import { changeMarkers, editorHunks } from "../gutter";
import { useVcs } from "../store";
afterEach(() => {
useVcs.setState({ available: false, roots: [], kinds: {} });
useProject.setState({ settings: null });
useVcs.setState({ available: false, roots: [], kinds: {}, byPath: new Map() });
useProject.setState({ project: null, settings: null });
vi.useRealTimers();
calls.length = 0;
});
function openEditor(path: string) {
const ctx = { path } as EditorDocContext;
const sync = vi.fn(async () => {});
const view = new EditorView({
parent: document.body,
state: EditorState.create({ doc: "new\n", extensions: [changeMarkers(ctx), documentSynced.of(sync)] }),
});
const handle = { view, ctx };
_addEditor(handle);
_setActiveEditor(handle);
return {
view,
sync,
close() {
_removeEditor(handle);
view.destroy();
},
};
}
it("probes ordinary files in a non-VCS project once and does not request hunks on edits", async () => {
vi.useFakeTimers();
useProject.setState({ project: { root: "/p" } as never });
const path = "/p/plain.txt";
const editor = openEditor(path);
const unregister = registerVcsActions();
try {
await vi.advanceTimersByTimeAsync(40);
editor.view.dispatch({ changes: { from: 0, insert: "edit " } });
await vi.advanceTimersByTimeAsync(350);
expect(calls).toEqual([`history:${path}`]);
expect(editor.sync).not.toHaveBeenCalled();
expect(isActionEnabled(getAction("vcs.annotate")!, { projectOpen: true })).toBe(false);
} finally {
unregister();
editor.close();
}
});
it("keeps the staging gutter empty when an ordinary Git file has no index entry", async () => {
vi.useFakeTimers();
const settings = { vcs: { git: { stagingArea: true }, commit: { nonModal: true } } } as never;
useProject.setState({ project: { root: "/p", settings } as never, settings });
useVcs.setState({ available: true, roots: ["/p"] });
const path = "/p/plain.txt";
const { close, view } = openEditor(path);
try {
await vi.advanceTimersByTimeAsync(40);
view.dispatch({ changes: { from: 0, insert: "edit " } });
await vi.advanceTimersByTimeAsync(350);
expect(editorHunks(view.state)).toHaveLength(0);
expect(calls).toEqual([`index:${path}`, `history:${path}`, `index:${path}`]);
} finally {
close();
}
});
it.each([
{ available: false, roots: [] },
{ available: true, roots: ["/p"] },
])("shows linked-file changes against HEAD (registered roots: $roots)", async ({ available, roots }) => {
const settings = { vcs: { git: { stagingArea: true }, commit: { nonModal: true } } } as never;
useProject.setState({ project: { root: "/p", settings } as never, settings });
useVcs.setState({ available, roots });
const path = "/p/linked/notes.txt";
if (available)
useVcs.setState({
byPath: new Map([
[path, { path, relPath: "linked/notes.txt", staged: null, unstaged: "untracked", renamedFrom: null }],
]),
});
vi.useFakeTimers();
const { view, close } = openEditor(path);
const unregister = registerVcsActions();
try {
const action = getAction("vcs.annotate")!;
const context = { projectOpen: true, vcsAvailable: available };
expect(isActionEnabled(action, context, path)).toBe(false);
await vi.advanceTimersByTimeAsync(40);
expect(editorHunks(view.state)).toHaveLength(1);
expect(editorHunks(view.state)[0]?.staging).toBeUndefined();
expect(isActionEnabled(action, context, path)).toBe(true);
expect(isActionEnabled(action, context)).toBe(true);
expect(isActionEnabled(action, { ...context, vcsAvailable: false, gitDisabled: true }, path)).toBe(false);
view.dispatch({ changes: { from: 0, insert: "edit " } });
await vi.advanceTimersByTimeAsync(350);
expect(calls).toEqual([`history:${path}`, `base:${path}`, `base:${path}`]);
} finally {
unregister();
close();
}
});
describe("change markers of a working copy's file in a project with Git's staging area on", () => {
it("are read against its base, not Git's index (Review #2 P0 7)", async () => {
useProject.setState({ settings: { vcs: { git: { stagingArea: true }, commit: { nonModal: true } } } as never });
+22 -22
Переглянути файл
@@ -82,6 +82,7 @@ import {
editableHunk,
equivalentStagingHunk,
gotoChange,
hasLinkedHistory,
hunksInSelection,
rollbackSelectedLines,
updateStagedLines,
@@ -114,7 +115,17 @@ import {
} from "./gitMenuDialogs";
import { showNewWorktree } from "./NewWorktreeDialog";
import { OPEN_WORKTREE_REVIEW } from "./worktreeReviews";
import { currentRepo, currentRepoRoot, refreshNow, repoName, repoOf, rootOfKind, statusOf, useVcs } from "./store";
import {
currentRepo,
currentRepoRoot,
hasNoCommits,
refreshNow,
repoName,
repoOf,
rootOfKind,
statusOf,
useVcs,
} from "./store";
import {
bulkStagePaths,
canRestoreUnstaged,
@@ -167,18 +178,6 @@ function argPath(arg: unknown): string | undefined {
return undefined;
}
/** Whether Git has no commit of the file: unversioned, ignored, or added and not committed yet. */
function hasNoCommits(status: { staged: string | null; unstaged: string | null }): boolean {
return (
status.staged === "added" ||
// Subversion schedules an addition in the working copy (no staging area).
status.unstaged === "added" ||
status.unstaged === "untracked" ||
status.unstaged === "ignored" ||
status.staged === "ignored"
);
}
function argPaths(arg: unknown): string[] | undefined {
if (Array.isArray(arg)) return arg.filter((x): x is string => typeof x === "string");
const p = argPath(arg);
@@ -1101,7 +1100,7 @@ export function registerVcsActions(): () => void {
title: "Annotate with Git Blame",
category: "Git",
icon: "history",
when: VCS,
when: "vcsAvailable || (projectOpen && !gitDisabled)",
keywords: ["blame", "annotations"],
toggled: () => {
if (getContext().diffEditorFocus) {
@@ -1111,15 +1110,16 @@ export function registerVcsActions(): () => void {
const ed = activeEditor();
return !!ed && annotationsShown(ed.view);
},
// As in IDEA, a file Git has no commit of (unversioned, ignored, or added and not yet
// committed) has nothing to annotate; shown annotations can always be closed.
enabled: ({ arg, ctx }) => {
if (!argPath(arg) && ctx.diffEditorFocus) return !!focusedBlamePane();
const ed = activeEditor();
const path = argPath(arg) ?? ed?.ctx.path;
if (!path || (ed?.ctx.path === path && annotationsShown(ed.view))) return true;
const status = statusOf(path);
return !status || !hasNoCommits(status);
const target = argPath(arg);
if (!target && ctx.diffEditorFocus) return !!ctx.vcsAvailable && !!focusedBlamePane();
const active = activeEditor();
const path = target ?? active?.ctx.path;
if (!path) return false;
const editor = active?.ctx.path === path ? active : editorsFor(path)[0];
if (editor && (annotationsShown(editor.view) || (!ctx.gitDisabled && hasLinkedHistory(editor.view.state))))
return true;
return !!ctx.vcsAvailable && !!repoOf(path) && !hasNoCommits(statusOf(path));
},
run: ({ arg }) => annotate(arg),
},
+87 -36
Переглянути файл
@@ -9,6 +9,9 @@ import { EditorView, GutterMarker, ViewPlugin, type PluginValue, type ViewUpdate
import { foldState, foldedRanges } from "@codemirror/language";
import type { HunkKind, LineHunk } from "@/bindings";
import { call, commands, isTauri } from "@/platform/ipc";
import { gitEnabled } from "@/platform/gitEnabled";
import { useProject } from "@/platform/project";
import { onWorkflowSettingsChange } from "@/platform/workflowSettings";
import {
LaneMarker,
changeMarkerDisplay,
@@ -22,7 +25,7 @@ import {
import { renamedFromPath } from "./changes";
import { currentHunkText, lineStarts, rollbackEdit } from "./hunks";
import { hasIndex, onStagingAreaChange, stagingAreaOn } from "./staging";
import { statusOf, useVcs } from "./store";
import { hasNoCommits, repoOf, statusOf, useVcs } from "./store";
import { tx } from "@/platform/i18n";
import { runOp } from "./ops";
@@ -44,6 +47,14 @@ export interface EditorHunk extends TrackedHunk {
}
export const setHunksEffect = StateEffect.define<TrackedHunk[]>();
const setLinkedHistory = StateEffect.define<boolean>();
const linkedHistoryField = StateField.define<boolean>({
create: () => false,
update(value, tr) {
for (const effect of tr.effects) if (effect.is(setLinkedHistory)) return effect.value;
return value;
},
});
interface HunkState {
hunks: EditorHunk[];
@@ -144,33 +155,36 @@ export function editorHunks(state: EditorState): EditorHunk[] {
return state.field(hunkField, false)?.hunks ?? [];
}
export function hasLinkedHistory(state: EditorState): boolean {
return state.field(linkedHistoryField, false) ?? false;
}
export function editableHunk(view: EditorView, hunk: EditorHunk): boolean {
const state = view.state.field(hunkField, false);
return !!state?.hunks.includes(hunk) && (!hunk.staging || (state.fresh && stagingAreaOn()));
}
async function stagingHunks(path: string): Promise<TrackedHunk[]> {
async function stagingHunks(path: string): Promise<TrackedHunk[] | null> {
const file = statusOf(path);
const headPath = file?.staged === "renamed" ? renamedFromPath(file) : null;
const result = await call(commands.vcsStagingLineHunks(path, headPath));
return (
result?.hunks.map((h) => ({
kind: h.kind,
start: h.start,
lines: h.lines,
oldStart: h.headStart,
oldLines: h.headLines,
oldText: h.headText,
staging: {
indexVersion: result.indexVersion,
indexStart: h.indexStart,
indexLines: h.indexLines,
indexText: h.indexText,
staged: h.staged,
unstaged: h.unstaged,
},
})) ?? []
);
if (!result) return null;
return result.hunks.map((hunk) => ({
kind: hunk.kind,
start: hunk.start,
lines: hunk.lines,
oldStart: hunk.headStart,
oldLines: hunk.headLines,
oldText: hunk.headText,
staging: {
indexVersion: result.indexVersion,
indexStart: hunk.indexStart,
indexLines: hunk.indexLines,
indexText: hunk.indexText,
staged: hunk.staged,
unstaged: hunk.unstaged,
},
}));
}
function sameRange(a: TrackedHunk, b: TrackedHunk): boolean {
@@ -221,6 +235,7 @@ async function editStagingHunks(
await whenSynced(view);
const current = await stagingHunks(path);
if (
!current ||
view.state.doc !== doc ||
!stagingAreaOn() ||
!hunks.every((hunk) => current.some((range) => sameRange(hunk, range)))
@@ -340,6 +355,8 @@ class HunkFetcher implements PluginValue {
private destroyed = false;
private readonly unsub: () => void;
private readonly offStaging: () => void;
private readonly offGitSettings: () => void;
private linkedHistoryProbe: Promise<boolean> | undefined;
constructor(
private readonly view: EditorView,
@@ -347,13 +364,26 @@ class HunkFetcher implements PluginValue {
) {
this.schedule(30);
this.unsub = useVcs.subscribe((s, prev) => {
if (s.version !== prev.version || s.available !== prev.available) this.schedule(60);
const repositoryChanged =
s.available !== prev.available ||
(s.roots !== prev.roots && repoOf(this.path, s.roots) !== repoOf(this.path, prev.roots));
if (repositoryChanged) this.linkedHistoryProbe = undefined;
const historyStatusChanged = hasNoCommits(s.byPath.get(this.path)) !== hasNoCommits(prev.byPath.get(this.path));
if (s.version !== prev.version || repositoryChanged || historyStatusChanged) this.schedule(60);
});
this.offStaging = onStagingAreaChange(() => {
this.view.dispatch({ effects: setHunksEffect.of([]) });
popupHooks?.docChanged(this.view);
this.schedule(0);
});
this.offGitSettings = onWorkflowSettingsChange(
(s) => [s.vcs.git.enabled, s.vcs.mappings],
() => {
this.linkedHistoryProbe = undefined;
this.view.dispatch({ effects: setLinkedHistory.of(false) });
this.schedule(0);
},
);
}
update(u: ViewUpdate) {
@@ -370,31 +400,51 @@ class HunkFetcher implements PluginValue {
}
async fetch(ticket: number) {
if (this.destroyed) return;
if (!useVcs.getState().available || !isTauri()) {
if (editorHunks(this.view.state).length) this.view.dispatch({ effects: setHunksEffect.of([]) });
return;
}
// A file of another system (a Subversion working copy) has no index: its markers are
// against its base, also while the staging area is on for the Git repositories.
const staging = stagingAreaOn() && hasIndex(this.path);
if (this.destroyed || ticket !== this.seq || !isTauri()) return;
const { available } = useVcs.getState();
const inRepository = available && !!repoOf(this.path);
const canProbe = !!useProject.getState().project && gitEnabled();
// Both positive and negative probes are reused on edits.
const probe = () =>
(this.linkedHistoryProbe ??= call(commands.vcsLinkedFileHasHistory(this.path)).catch(() => false));
const current = () => !this.destroyed && ticket === this.seq;
try {
if (staging) await whenSynced(this.view);
if (this.destroyed || ticket !== this.seq) return;
const hunks = staging ? await stagingHunks(this.path) : await call(commands.vcsLineHunks(this.path));
if (this.destroyed || ticket !== this.seq) return;
this.view.dispatch({ effects: setHunksEffect.of(hunks) });
if (staging) popupHooks?.stagingChanged?.(this.view);
const mayBeLinked = !inRepository || hasNoCommits(statusOf(this.path)) || !!this.linkedHistoryProbe;
let linked = canProbe && mayBeLinked && (await probe());
if (!current()) return;
if (!inRepository && !linked) {
this.clearHunks();
return;
}
await whenSynced(this.view);
if (!current()) return;
// Linked files and non-Git working copies use base markers, not the workspace's index.
const staging = !linked && stagingAreaOn() && hasIndex(this.path);
const staged = staging ? await stagingHunks(this.path) : null;
if (staging && !staged && canProbe) linked = await probe();
if (!current()) return;
const hunks = staged ?? (!staging || linked ? await call(commands.vcsLineHunks(this.path)) : []);
if (!current()) return;
this.view.dispatch({ effects: [setHunksEffect.of(hunks), setLinkedHistory.of(linked)] });
if (staged) popupHooks?.stagingChanged?.(this.view);
} catch {
// Paths outside the repository etc.: no markers.
if (current()) this.clearHunks();
}
}
private clearHunks() {
const { state } = this.view;
if (editorHunks(state).length || hasLinkedHistory(state))
this.view.dispatch({ effects: [setHunksEffect.of([]), setLinkedHistory.of(false)] });
}
destroy() {
this.destroyed = true;
clearTimeout(this.timer);
this.unsub();
this.offStaging();
this.offGitSettings();
}
}
@@ -481,6 +531,7 @@ export function changeMarkers(ctx: EditorDocContext): Extension {
const path = ctx.path;
return [
hunkField,
linkedHistoryField,
gutterLaneMarkers.compute([hunkField, foldState, changeMarkerDisplay], laneMarkers),
scrollbarMarks.compute([hunkField, changeMarkerDisplay], scrollMarks),
laneClicks(path),
+10 -6
Переглянути файл
@@ -21,8 +21,7 @@ import {
registerTitleItem,
registerToolWindow,
} from "@/workbench/contributions";
import { executeAction, registerActions } from "@/platform/actions";
import { getContext } from "@/platform/context";
import { executeAction, getAction, isActionEnabled, registerActions } from "@/platform/actions";
import { lazyComponent } from "@/ui";
import { commitWindowFocused, registerVcsActions } from "./actions";
import { installChangelists } from "./changelists";
@@ -52,7 +51,7 @@ import { activateDiffViewer } from "./diffViewer";
import { installDiffEditorHost } from "./DiffWindow";
import { VcsDialogHost } from "./dialogs";
import { installCloneHandoff } from "./clone";
import { changeMarkers } from "./gutter";
import { changeMarkers, hasLinkedHistory } from "./gutter";
import { installHunkPopup } from "./HunkPopup";
import { LOCAL_HISTORY_KIND } from "./localHistoryKind";
import { DIRECTORY_COMPARE_KIND, directoryCompareTitle, type DirectoryCompareData } from "./directoryCompareKind";
@@ -232,11 +231,16 @@ function registerGitContributions(): () => void {
menus: ["editorGutter"],
order: 10,
items: (_menu, { paths: [path] }) => {
if (!path || !getContext().vcsAvailable) return [];
const shown = editorsFor(path).some((h) => annotationsShown(h.view));
const action = getAction("vcs.annotate");
if (!path || !action || !isActionEnabled(action, undefined, path)) return [];
const editors = editorsFor(path);
const shown = editors.some((h) => annotationsShown(h.view));
const label = editors.some(({ view }) => hasLinkedHistory(view.state))
? "Annotate with Git Blame"
: annotateLabel(path);
return [
{
label: shown ? "Close Annotations" : annotateLabel(path),
label: shown ? "Close Annotations" : label,
run: () => void executeAction("vcs.annotate", path),
},
];
+12
Переглянути файл
@@ -663,6 +663,18 @@ export function statusOf(path: string): FileStatus | undefined {
return useVcs.getState().byPath.get(stripSlash(path));
}
/** Whether the workspace's status says the path has no committed history. */
export function hasNoCommits(status: FileStatus | undefined): boolean {
return (
status?.staged === "added" ||
// Subversion schedules an addition in the working copy (no staging area).
status?.unstaged === "added" ||
status?.unstaged === "untracked" ||
status?.unstaged === "ignored" ||
status?.staged === "ignored"
);
}
/** Repositories found below a project that is not itself under git (scanned in the background). */
export async function discoverRoots() {
if (!useVcs.getState().root || !isTauri()) return;