Files
openidea/src/features/vcs/partialCommitProjection.ts
T
l0ng-ai 401c542647 feat(vcs): improve Git workflows (#5174)
Improve OpenIDEA's Git workflows across commit and staging, branch and remote operations, merge and rebase, Git Log and signing, worktrees, stash and shelf, patch application, and clone settings. Adds a one-click stash for tracked changes across Git roots and lets users open a worktree branch's associated GitHub review from its context menu. Cloning now includes submodules by default (Settings › Version Control › Git, can be turned off).

Repository entry points added here run in each repository's execution scope, so they use the project's own git executable.
2026-11-22 21:57:30 +08:00

61 lines
2.3 KiB
TypeScript

import { ChangeSet, Text } from "@codemirror/state";
import type { HunkRange, LineHunk, PartialCommitFile } from "@/bindings";
import { currentHunkText, lineStarts, rollbackEdit } from "./hunks";
const key = (h: HunkRange) => `${h.oldStart}:${h.oldLines}:${h.start}:${h.lines}`;
/** Inverts the hunk selection so edits can be mapped back to their original working lines. */
export function partialCommitProjection(
working: Text,
selected: Text,
hunks: readonly LineHunk[],
file: PartialCommitFile,
): ChangeSet | null {
const text = working.toString();
const starts = lineStarts(text);
const whole = new Set(file.hunks.map(key));
const lines = new Map((file.lineHunks ?? []).map((h) => [key(h.range), h]));
const edits = [];
for (const hunk of hunks) {
const id = key(hunk);
if (whole.delete(id)) continue;
const partial = lines.get(id);
if (!partial) {
edits.push(rollbackEdit(text, hunk));
continue;
}
lines.delete(id);
if (partial.oldText !== hunk.oldText || partial.newText !== currentHunkText(text, hunk)) return null;
const additions = new Set(partial.additions);
const deletions = new Set(partial.deletions);
const oldLines = hunk.oldText.match(/[^\n]*\n|[^\n]+$/g) ?? [];
let kept = oldLines.filter((_, line) => !deletions.has(line)).join("");
if (kept && !kept.endsWith("\n") && additions.size) kept += "\n";
if (kept) edits.push({ from: starts[hunk.start]!, insert: kept });
for (let line = 0; line < hunk.lines; line++) {
if (additions.has(line)) continue;
const start = hunk.start + line;
edits.push({ from: starts[start]!, to: starts[start + 1]! });
}
}
if (whole.size || lines.size) return null;
const reverted = ChangeSet.of(edits, working.length);
if (!reverted.apply(working).eq(selected)) return null;
return reverted.invert(working);
}
/** A fix can change shared text but must leave every excluded edit in place. */
export function keepsExcludedChanges(changes: ChangeSet, excluded: ChangeSet): boolean {
let overlaps = false;
excluded.iterChangedRanges((from, to) => {
changes.iterChangedRanges((start, end) => {
if (from === to || start === end) {
overlaps ||= from <= end && start <= to;
} else {
overlaps ||= from < end && start < to;
}
});
});
return !overlaps;
}