дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-04 09:11:10 +02:00
feat(vcs): get files from the branch comparison window (#7953)
The Compare with Branch window gets a Get action (toolbar and dialog button) that replaces the selected local files with their content in the compared revision: missing files are created, files the revision lacks are deleted, and a renamed file is restored under its old path. The window can be maximized where the app draws its own title bar. A file of the revision that is back in the working tree as an untracked file is now one change (modified, or omitted when identical) instead of a deletion plus an untracked file. Closes #7917
Цей коміт міститься в:
1 джерело
34739e181d
коміт
b16d485f35
6 files changed
+168
-21
No files matched your search
@@ -167,6 +167,14 @@ impl Repos {
|
||||
let own = self.at_root(&absolute).or_else(|| self.for_path(&absolute));
|
||||
own.is_some_and(|r| r.root() == repo.root()) && paths.iter().any(|p| absolute.starts_with(p))
|
||||
};
|
||||
let untracked: Vec<String> = run(&["ls-files", "--others", "--exclude-standard", "-z"])?
|
||||
.stdout_str()
|
||||
.split('\0')
|
||||
.filter(|p| !p.is_empty() && contains(p))
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
let local: std::collections::HashSet<&str> = untracked.iter().map(String::as_str).collect();
|
||||
let mut reappeared = std::collections::BTreeSet::new();
|
||||
for mut file in ops::parse_name_status(&names.stdout_str()) {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
@@ -186,6 +194,16 @@ impl Repos {
|
||||
file.kind = ChangeKind::Added;
|
||||
}
|
||||
}
|
||||
if file.kind == ChangeKind::Renamed
|
||||
&& let Some(old) = file.old_path.take_if(|old| local.contains(old.as_str()))
|
||||
{
|
||||
file.kind = ChangeKind::Added;
|
||||
reappeared.insert(old);
|
||||
}
|
||||
if file.kind == ChangeKind::Deleted && local.contains(file.path.as_str()) {
|
||||
reappeared.insert(file.path);
|
||||
continue;
|
||||
}
|
||||
let count = |path: &str| stats.get(path).copied().unwrap_or_default();
|
||||
let (added, removed) = match &file.old_path {
|
||||
Some(old) => (count(&original).0, count(old).1),
|
||||
@@ -226,8 +244,35 @@ impl Repos {
|
||||
}
|
||||
}
|
||||
}
|
||||
let untracked = run(&["ls-files", "--others", "--exclude-standard", "-z"])?;
|
||||
for path in untracked.stdout_str().split('\0').filter(|p| !p.is_empty() && contains(p)) {
|
||||
// A path of the revision that is back as an untracked file is one change, not a
|
||||
// deletion plus an untracked file: modified when its content differs, else unchanged.
|
||||
if !reappeared.is_empty() {
|
||||
let gix = repo.gix()?;
|
||||
for path in &reappeared {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let old = crate::repo::blob_at(&gix, path, &resolved)?.unwrap_or_default();
|
||||
let new = std::fs::read(repo.root().join(path));
|
||||
if new.as_ref().is_ok_and(|new| *new == old) {
|
||||
continue;
|
||||
}
|
||||
let (added, removed) = match new {
|
||||
Ok(new) if old.len().max(new.len()) <= 10 * 1024 * 1024 => {
|
||||
crate::diff::line_counts(&old, &new)
|
||||
}
|
||||
_ => (0, 0),
|
||||
};
|
||||
files.push(WorkingTreeChange {
|
||||
path: path.clone(),
|
||||
kind: ChangeKind::Modified,
|
||||
old_path: None,
|
||||
added,
|
||||
removed,
|
||||
});
|
||||
}
|
||||
}
|
||||
for path in untracked.iter().filter(|p| !reappeared.contains(*p)) {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
@@ -246,7 +291,7 @@ impl Repos {
|
||||
0
|
||||
};
|
||||
files.push(WorkingTreeChange {
|
||||
path: path.to_owned(),
|
||||
path: path.clone(),
|
||||
kind: ChangeKind::Untracked,
|
||||
old_path: None,
|
||||
added,
|
||||
@@ -349,6 +394,35 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revision_files_back_as_untracked_files_are_one_change() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = normalized(temp.path());
|
||||
init(&root, "main");
|
||||
write(&root, "src/same.txt", "same\n");
|
||||
write(&root, "src/edited.txt", "one\ntwo\n");
|
||||
git(&root, &["add", "."]);
|
||||
git(&root, &["commit", "-qm", "release files"]);
|
||||
git(&root, &["branch", "release"]);
|
||||
git(&root, &["rm", "-q", "src/same.txt", "src/edited.txt"]);
|
||||
git(&root, &["mv", "src/move.txt", "src/moved.txt"]);
|
||||
git(&root, &["commit", "-qm", "drop them"]);
|
||||
write(&root, "src/same.txt", "same\n");
|
||||
write(&root, "src/edited.txt", "one\nthree\nfour\n");
|
||||
write(&root, "src/move.txt", "move\n");
|
||||
let repos = Repos::discover(&root, &|_| false).unwrap();
|
||||
let result = repos.compare_paths(&[root.join("src")], "release", None, &CancellationToken::new()).unwrap();
|
||||
let files: Vec<_> = result.repositories[0]
|
||||
.files
|
||||
.iter()
|
||||
.map(|f| (f.path.as_str(), f.kind, f.old_path.as_deref(), f.added, f.removed))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
files,
|
||||
[("src/edited.txt", ChangeKind::Modified, None, 2, 1), ("src/moved.txt", ChangeKind::Added, None, 1, 0)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn workspace_roots_missing_revision_loose_paths_and_empty_results() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -27,6 +27,17 @@ fn raw_hunks(old: &[&str], new: &[&str]) -> Vec<(Range<u32>, Range<u32>)> {
|
||||
diff.hunks().map(|h| (h.before, h.after)).collect()
|
||||
}
|
||||
|
||||
/// Lines added and removed from `old` to `new`, like `git diff --numstat`; binary content counts 0.
|
||||
pub(crate) fn line_counts(old: &[u8], new: &[u8]) -> (u32, u32) {
|
||||
if old.contains(&0) || new.contains(&0) {
|
||||
return (0, 0);
|
||||
}
|
||||
let (old, new) = (String::from_utf8_lossy(old), String::from_utf8_lossy(new));
|
||||
raw_hunks(&split_lines(&old), &split_lines(&new))
|
||||
.into_iter()
|
||||
.fold((0, 0), |(added, removed), (before, after)| (added + after.len() as u32, removed + before.len() as u32))
|
||||
}
|
||||
|
||||
/// Gutter hunks of `new` against `old` (both are normalised to LF first).
|
||||
pub fn line_hunks(old: &str, new: &str) -> Vec<LineHunk> {
|
||||
let old = normalize_eol(old);
|
||||
|
||||
@@ -173,7 +173,7 @@ export function ComparisonWindow() {
|
||||
}, [full]);
|
||||
return (
|
||||
<main className={clsx(styles.comparisonWindow, os === "linux" && styles.comparisonWindowEdge)}>
|
||||
{ownTitleBar && <TitleBar minimal dialog title={title} />}
|
||||
{ownTitleBar && <TitleBar minimal dialog maximize title={title} />}
|
||||
{error ? (
|
||||
<div className={styles.error} role="alert">
|
||||
{error}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { comparisonRevisionFiles, type ComparisonFile } from "../operations";
|
||||
|
||||
const file = (kind: ComparisonFile["kind"], more: Partial<ComparisonFile> = {}): ComparisonFile =>
|
||||
({ path: "src/a.ts", kind, root: "/repo", revision: "main", ...more }) as ComparisonFile;
|
||||
|
||||
it("takes the compared revision's content, deletes what it lacks and restores a renamed file's old name", () => {
|
||||
expect(comparisonRevisionFiles(file("modified"))).toEqual([
|
||||
{ path: "/repo/src/a.ts", from: { path: "/repo/src/a.ts", rev: "main" } },
|
||||
]);
|
||||
expect(comparisonRevisionFiles(file("deleted"))).toEqual([
|
||||
{ path: "/repo/src/a.ts", from: { path: "/repo/src/a.ts", rev: "main" } },
|
||||
]);
|
||||
expect(comparisonRevisionFiles(file("added"))).toEqual([{ path: "/repo/src/a.ts" }]);
|
||||
expect(comparisonRevisionFiles(file("untracked"))).toEqual([{ path: "/repo/src/a.ts" }]);
|
||||
expect(comparisonRevisionFiles(file("renamed", { oldPath: "src/old.ts" }))).toEqual([
|
||||
{ path: "/repo/src/a.ts" },
|
||||
{ path: "/repo/src/old.ts", from: { path: "/repo/src/old.ts", rev: "main" } },
|
||||
]);
|
||||
});
|
||||
@@ -372,46 +372,62 @@ export function canOpenRepositoryVersion(changes: readonly LogChange[]): boolean
|
||||
return changes.some((change) => !!change.after && change.link !== "dir" && !!(change.repo ?? currentRepoRoot()));
|
||||
}
|
||||
|
||||
/** A working file and the revision content it takes; none: the file is deleted. */
|
||||
export interface RevisionFile {
|
||||
path: string;
|
||||
from?: { path: string; rev: string };
|
||||
}
|
||||
|
||||
/**
|
||||
* Get from Revision: the working files take their content after the change; a file the
|
||||
* change deleted is deleted.
|
||||
*/
|
||||
export async function getFromRevision(changes: readonly LogChange[]) {
|
||||
if (changes.some((c) => c.readOnly)) return;
|
||||
if (!changes.length) return;
|
||||
await getFilesFromRevision(
|
||||
changes.map((c) => {
|
||||
const path = absolutePath(c.path, c.repo);
|
||||
return { path, from: c.after ? { path, rev: c.after } : undefined };
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/** Replaces working files with revision content after a confirmation; true when it ran. */
|
||||
export async function getFilesFromRevision(files: readonly RevisionFile[]): Promise<boolean> {
|
||||
if (!files.length) return false;
|
||||
const ok = await confirmDialog({
|
||||
title: "Get from Revision",
|
||||
message:
|
||||
changes.length === 1
|
||||
? tx`Replace '${baseName(changes[0]!.path)}' with its content from the revision? Local changes to it are lost.`
|
||||
: tx`Replace ${changes.length} files with their content from the revision? Local changes to them are lost.`,
|
||||
files.length === 1
|
||||
? tx`Replace '${baseName(files[0]!.path)}' with its content from the revision? Local changes to it are lost.`
|
||||
: tx`Replace ${files.length} files with their content from the revision? Local changes to them are lost.`,
|
||||
okLabel: "Get",
|
||||
danger: true,
|
||||
});
|
||||
if (!ok) return;
|
||||
if (!ok) return false;
|
||||
await saveAll();
|
||||
await runOp(
|
||||
tx("Get from Revision"),
|
||||
async () => {
|
||||
for (const c of changes) {
|
||||
const path = absolutePath(c.path, c.repo);
|
||||
if (!c.after) {
|
||||
for (const f of files) {
|
||||
if (!f.from) {
|
||||
// oxlint-disable-next-line no-await-in-loop -- a deleted file is removed only after checking it still exists; working-tree operations stay ordered
|
||||
if ((await readWorkingText(path)) !== null) await call(commands.fsDelete(path));
|
||||
if ((await readWorkingText(f.path)) !== null) await call(commands.fsDelete(f.path));
|
||||
continue;
|
||||
}
|
||||
// oxlint-disable-next-line no-await-in-loop -- the file's revision text must be read before it can be written to the working tree
|
||||
const text = await call(commands.vcsFileAt(path, c.after));
|
||||
const text = await call(commands.vcsFileAt(f.from.path, f.from.rev));
|
||||
if (text === null) continue;
|
||||
// oxlint-disable-next-line no-await-in-loop -- a missing working file is created before its content is written, one file at a time
|
||||
if ((await readWorkingText(path)) === null) await call(commands.fsCreateFile(path));
|
||||
if ((await readWorkingText(f.path)) === null) await call(commands.fsCreateFile(f.path));
|
||||
// oxlint-disable-next-line no-await-in-loop -- files are written in selection order so the working tree is updated deterministically
|
||||
await writeFileText(path, text, { save: true });
|
||||
await writeFileText(f.path, text, { save: true });
|
||||
}
|
||||
return changes.length;
|
||||
return files.length;
|
||||
},
|
||||
{ success: (n) => (n === 1 ? tx("Got 1 file from revision") : tx`Got ${n} files from revision`) },
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Revert Selected Changes: applies the reverse of the selected files' changes to the working tree. */
|
||||
|
||||
@@ -61,7 +61,7 @@ import tagStyles from "./TagDialog.module.css";
|
||||
import { ComparisonTree, chainedDiff } from "./ComparisonTree";
|
||||
import { showWorktreeComparison } from "./compareTool";
|
||||
import { buildFileTree, type FileTreeNode } from "./fileTree";
|
||||
import { filesUnder } from "./logChanges";
|
||||
import { filesUnder, getFilesFromRevision, type RevisionFile } from "./logChanges";
|
||||
import { tx, txPart } from "@/platform/i18n";
|
||||
import { displayPath } from "./compareData";
|
||||
import { repositoryPath } from "./repositoryPaths";
|
||||
@@ -1141,6 +1141,18 @@ export function comparisonDiffData(
|
||||
return swapped ? { path, left: right, right: left } : { path, left, right };
|
||||
}
|
||||
|
||||
/**
|
||||
* Get: what the working files take from the compared revision. A file the revision lacks is
|
||||
* deleted; a renamed one goes back to its old name.
|
||||
*/
|
||||
export function comparisonRevisionFiles(file: ComparisonFile): RevisionFile[] {
|
||||
const path = repositoryPath(file.root, file.path);
|
||||
if (file.kind === "added" || file.kind === "untracked") return [{ path }];
|
||||
if (!file.oldPath) return [{ path, from: { path, rev: file.revision } }];
|
||||
const old = repositoryPath(file.root, file.oldPath);
|
||||
return [{ path }, { path: old, from: { path: old, rev: file.revision } }];
|
||||
}
|
||||
|
||||
export function comparisonEmpty(revision: string, repositories: number): string {
|
||||
return repositories === 1
|
||||
? tx`No changes against ${revision} in 1 repository`
|
||||
@@ -1188,6 +1200,7 @@ export function ChangesBetweenDialog({
|
||||
const [result, setResult] = useState<ComparisonResults | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [current, setCurrentState] = useState<ComparisonFile | null>(null);
|
||||
const [loads, setLoads] = useState(0);
|
||||
const setCurrent = (file: ComparisonFile | null) => {
|
||||
setCurrentState(file);
|
||||
onSelect?.(file);
|
||||
@@ -1247,7 +1260,7 @@ export function ChangesBetweenDialog({
|
||||
alive = false;
|
||||
if (scope && pending) void commands.cancelRequest(request);
|
||||
};
|
||||
}, [fromRev, toRev, repo, root, scope, repositories]);
|
||||
}, [fromRev, toRev, repo, root, scope, repositories, loads]);
|
||||
const files = useMemo(() => result?.repositories.flatMap((repo) => repo.files) ?? null, [result]);
|
||||
const tree = useMemo(() => {
|
||||
if (!grouped) return buildFileTree(files ?? [], (f) => f.path);
|
||||
@@ -1295,6 +1308,13 @@ export function ChangesBetweenDialog({
|
||||
const showDiff = () => {
|
||||
if (current) showFileDiff(current);
|
||||
};
|
||||
// Against the working tree only: the selected file takes its content from the compared revision.
|
||||
const canGet = !to && !listOnly;
|
||||
const getFile = async () => {
|
||||
if (!current || !(await getFilesFromRevision(comparisonRevisionFiles(current)))) return;
|
||||
setCurrent(null);
|
||||
setLoads((n) => n + 1);
|
||||
};
|
||||
const contents = (
|
||||
<>
|
||||
{error && (
|
||||
@@ -1374,6 +1394,11 @@ export function ChangesBetweenDialog({
|
||||
{!listOnly && (
|
||||
<Toolbar className={styles.comparisonWindowToolbar} aria-label="Comparison actions">
|
||||
{diffButton}
|
||||
{canGet && (
|
||||
<Button variant="ghost" size="small" icon="download" disabled={!current} onClick={() => void getFile()}>
|
||||
Get
|
||||
</Button>
|
||||
)}
|
||||
</Toolbar>
|
||||
)}
|
||||
<div className={styles.comparisonWindowBody}>{contents}</div>
|
||||
@@ -1393,8 +1418,9 @@ export function ChangesBetweenDialog({
|
||||
resizable="both"
|
||||
className={styles.comparisonDialog}
|
||||
buttons={[
|
||||
{ label: "Show Diff", role: "default", disabled: !current, onClick: showDiff },
|
||||
{ label: "Close", role: "cancel" },
|
||||
...(canGet ? [{ label: "Get", disabled: !current, onClick: () => void getFile() }] : []),
|
||||
{ label: "Show Diff", role: "default" as const, disabled: !current, onClick: showDiff },
|
||||
{ label: "Close", role: "cancel" as const },
|
||||
]}
|
||||
>
|
||||
{contents}
|
||||
|
||||
Reference in new issue
Заблокувати користувача