diff --git a/src/lib/project-revision.ts b/src/lib/project-revision.ts index 949ccaf..de239b5 100644 --- a/src/lib/project-revision.ts +++ b/src/lib/project-revision.ts @@ -116,6 +116,7 @@ export async function reviseProjectRun(args: { run.commentAuthorCoverage = previous.commentAuthorCoverage; run.reviewAuthorCoverage = previous.reviewAuthorCoverage; run.mapping = plan.mapping; + run.sourceState = {}; run.matchModes = Object.fromEntries(Object.entries(previous.matchModes ?? {}) .filter(([key]) => key in plan.mapping)); run.sourceInPlace = inPlace; @@ -153,6 +154,15 @@ export async function reviseProjectRun(args: { isMarkdownFile(file.output)), "utf8"); await fs.writeFile(target, output, { flag: "wx", mode: 0o600 }); run.files.push({ source: file.output, output: outputPath, kind: file.kind }); + if (inPlace) run.sourceState[outputPath] = { hash: digest(output), output: outputPath }; + } + if (!inPlace && previous.sourceState) { + const revisedOutput = new Map(run.files.map((file) => [file.source, file.output])); + run.sourceState = Object.fromEntries(Object.entries(previous.sourceState) + .filter(([, state]) => revisedOutput.has(state.output)) + .map(([path, state]) => [path, { + hash: state.hash, output: revisedOutput.get(state.output)!, + }])); } if (plan.whitelist.length) { await saveProjectWhitelist(previous.projectPath, [...previousWhitelist, ...plan.whitelist], support); diff --git a/src/lib/velum-project.ts b/src/lib/velum-project.ts index 7125c9e..8e96b1c 100644 --- a/src/lib/velum-project.ts +++ b/src/lib/velum-project.ts @@ -23,6 +23,8 @@ export type ProjectRun = { projectName: string; createdAt: string; mapping: PlaceholderMapping; + /** Hash of each live project file and its immutable output in this run. */ + sourceState?: Record; /** Generic replacement mode for placeholders embedded in code identifiers. */ matchModes?: Record; files: RunFile[]; @@ -187,7 +189,8 @@ export function forceMasks(rules: ProjectRule[]): Record { return result; } -export async function scanProjectFiles(root: string, maxSize = 20 * 1024 * 1024): Promise<{ +export async function scanProjectFiles(root: string, maxSize = 20 * 1024 * 1024, + validateText = true): Promise<{ files: ProjectFile[]; skipped: SkippedProjectFile[]; }> { const files: ProjectFile[] = []; @@ -219,7 +222,7 @@ export async function scanProjectFiles(root: string, maxSize = 20 * 1024 * 1024) skip(relPath, "Kein lesbares Office-ZIP-Archiv (beschädigt, verschlüsselt oder falsche Endung)"); continue; } - if (kind === "text") { + if (kind === "text" && validateText) { if (await isBinary(path)) { skip(relPath, "Binärdatei"); continue; } try { new TextDecoder("utf-8", { fatal: true }).decode(await fs.readFile(path)); } catch { skip(relPath, "Keine gültige UTF-8-Textdatei"); continue; } @@ -431,6 +434,7 @@ export async function updateProjectMapping(projectPath: string, run.mapping = mapping; run.matchModes = { ...latest.run.matchModes }; run.files = latest.run.files.map((file) => ({ ...file })); + run.sourceState = latest.run.sourceState ? { ...latest.run.sourceState } : undefined; run.inPlace = latest.run.inPlace; run.sourceInPlace = latest.run.sourceInPlace; run.commentAuthorCoverage = latest.run.commentAuthorCoverage; @@ -550,6 +554,26 @@ export async function matchesPreviousOutput(directory: string, relPath: string, } } +/** Reuse only an output proven to correspond to the current source bytes. */ +export async function reusableProjectOutput(run: ProjectRun, directory: string, + relPath: string, currentHash: string): Promise { + const state = run.sourceState?.[relPath]; + if (state) { + if (state.hash !== currentHash || !run.files.some((file) => file.output === state.output)) return undefined; + try { + const output = resolveWithin(join(directory, "files"), state.output); + return (await fs.lstat(output)).isFile() ? state.output : undefined; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined; + throw error; + } + } + // Older in-place snapshots lack source hashes. An identical saved output is + // still authoritative; copy-mode source bytes cannot be reconstructed. + if (!(run.inPlace || run.sourceInPlace) || !run.files.some((file) => file.output === relPath)) return undefined; + return await matchesPreviousOutput(directory, relPath, currentHash) ? relPath : undefined; +} + /** Only an identical saved file can disambiguate a placeholder reused across runs. */ export async function mappingForMatchingSnapshots(relPath: string, currentHash: string, earlier: Array<{ run: ProjectRun; directory: string }>): Promise { diff --git a/src/pseudonymize-project-files.tsx b/src/pseudonymize-project-files.tsx index e448a0d..2fd9626 100644 --- a/src/pseudonymize-project-files.tsx +++ b/src/pseudonymize-project-files.tsx @@ -1,5 +1,5 @@ import { Action, ActionPanel, Alert, Color, confirmAlert, Form, getSelectedFinderItems, Icon, List, showInFinder, showToast, Toast, useNavigation } from "@raycast/api"; -import { promises as fs } from "node:fs"; +import { constants as fsConstants, promises as fs } from "node:fs"; import { basename, dirname, extname, join } from "node:path"; import { execFile } from "node:child_process"; import { promisify } from "node:util"; @@ -9,7 +9,7 @@ import { getEntityTypes, pseudonymize, pseudonymizeDocument, requireProjectCapab import type { DocumentHit } from "./velum"; import { createRun, digest, forceMasks, listRuns, loadProjectEntityTypes, loadProjectRules, parseProjectRules, publishProjectCopies, replaceSpans, - loadProjectWhitelist, matchesPreviousOutput, replaceProjectFilesInPlace, resolveWithin, safeRelativePath, saveProjectRules, + loadProjectWhitelist, reusableProjectOutput, replaceProjectFilesInPlace, resolveWithin, safeRelativePath, saveProjectRules, saveProjectEntityTypes, saveProjectWhitelist, saveRun, scanProjectFiles, toUtf16Offsets, whitelistKey, } from "./lib/velum-project"; import type { ProjectFile, ProjectRule, ProjectWhitelistEntry, RunFile, SkippedProjectFile } from "./lib/velum-project"; @@ -28,7 +28,7 @@ type Hit = { }; type Draft = { file: ProjectFile; hash: string; hits: Hit[] }; type PathDraft = { key: string; value: string; hits: Hit[] }; -type Preview = { drafts: Draft[]; retained: Array<{ file: ProjectFile; hash: string }>; +type Preview = { drafts: Draft[]; retained: Array<{ file: ProjectFile; hash: string; output: string; directory: string }>; paths: PathDraft[]; mapping: PlaceholderMapping; previousMapping: PlaceholderMapping; matchModes?: Record; hits: Hit[]; entityTypes: EntityType[]; skipped: SkippedProjectFile[]; sourceInPlace: boolean }; @@ -103,7 +103,8 @@ function pathSegments(files: ProjectFile[]): PathDraft[] { } async function prepare(root: string, files: ProjectFile[], rules: ProjectRule[], whitelist: ProjectWhitelistEntry[], entityTypes: EntityType[], - skipped: SkippedProjectFile[], onProgress: (message: string) => void): Promise { + skipped: SkippedProjectFile[], reanalyzeUnchanged: boolean, + onProgress: (message: string) => void): Promise { await requireProjectCapabilities(); const masks = forceMasks(withoutWhitelistedRules(rules, whitelist)); const latestEntry = (await listRuns(root))[0]; @@ -117,25 +118,26 @@ async function prepare(root: string, files: ProjectFile[], rules: ProjectRule[], const hits: Hit[] = []; const texts = new Map(); const sourceInPlace = Boolean(latest?.inPlace || latest?.sourceInPlace); - // A migrated snapshot may differ from the source folder. Recheck its files - // unless an earlier run actually replaced them in place. - const previousOutputs = new Set(sourceInPlace ? latest?.files.map((file) => file.output) : []); const previousDirectory = latestEntry?.directory; for (const file of files) { const data = await fs.readFile(file.absPath); const hash = digest(data); - const recheckWordReviews = entityTypes.includes("PERSON") && file.kind === "document" - && extname(file.relPath).toLowerCase() === ".docx" - && (!latest?.commentAuthorCoverage || !latest?.reviewAuthorCoverage); - if (!recheckWordReviews && previousDirectory && previousOutputs.has(file.relPath) - && await matchesPreviousOutput(previousDirectory, file.relPath, hash)) { - retained.push({ file, hash }); + const previousOutput = !reanalyzeUnchanged && latest && previousDirectory + ? await reusableProjectOutput(latest, previousDirectory, file.relPath, hash) : undefined; + if (previousOutput && previousDirectory) { + retained.push({ file, hash, output: previousOutput, directory: previousDirectory }); continue; } + let decoded: string | undefined; + if (file.kind === "text") { + if (data.includes(0)) { skipped.push({ path: file.relPath, reason: "Binärdatei" }); continue; } + try { decoded = textFromBytes(data); } + catch { skipped.push({ path: file.relPath, reason: "Keine gültige UTF-8-Textdatei" }); continue; } + } const draft: Draft = { file, hash, hits: [] }; drafts.push(draft); draftsByPath.set(file.relPath, draft); - if (file.kind === "text") texts.set(file.relPath, textFromBytes(data)); + if (decoded !== undefined) texts.set(file.relPath, decoded); } const addHits = (draft: Draft, found: Hit[]) => { draft.hits = withoutWhitelistedHits(withoutPlaceholderHits(found, previousPlaceholders), whitelist); @@ -167,14 +169,13 @@ async function prepare(root: string, files: ProjectFile[], rules: ProjectRule[], draftsByPath.delete(draft.file.relPath); } } - // Recheck names even when an in-place file's contents are unchanged. An - // earlier run may have masked the content but left the filename clear. - const eligibleFiles = [...drafts.map((draft) => draft.file), ...retained.map((item) => item.file)]; - if (!eligibleFiles.length) { + // Names of retained files already have a reviewed output in the saved stand. + // Only new or changed files need another filename analysis. + if (!drafts.length && !retained.length) { const first = skipped[0]; throw new Error(`Keine lesbaren Dateien im Projektordner gefunden.${first ? ` Übersprungen: ${first.path} (${first.reason}).` : ""}`); } - const paths = pathSegments(eligibleFiles); + const paths = pathSegments(drafts.map((draft) => draft.file)); const knownTerms = [...Object.keys(mapping), ...Object.values(mapping).map((entry) => entry.original), ...withoutWhitelistedRules(rules, whitelist).map((rule) => rule.value)]; const pathBatches = makeTextBatches(paths.map((path) => ({ @@ -316,6 +317,7 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje selectedPeople.has(source) && availableTargets.has(canonicalPerson(target, personMerges)))); run.mapping = mappingForSelection(props.preview.mapping, props.preview.previousMapping, acceptedHits, activeMerges); + run.sourceState = {}; run.commentAuthorCoverage = props.preview.entityTypes.includes("PERSON"); run.reviewAuthorCoverage = props.preview.entityTypes.includes("PERSON"); run.matchModes = props.preview.matchModes; @@ -325,15 +327,19 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje for (const retained of props.preview.retained) { const data = await fs.readFile(retained.file.absPath); if (digest(data) !== retained.hash) throw new Error(`Datei wurde seit der Vorschau geändert: ${retained.file.relPath}`); - const relPath = outputPath(retained.file.relPath, props.preview.paths, accepted, - retained.file.kind === "document", activeMerges); + const relPath = retained.output; if (usedPaths.has(relPath)) throw new Error(`Zwei Dateien hätten denselben Ausgabenamen: ${relPath}`); usedPaths.add(relPath); const target = resolveWithin(join(directory, "files"), relPath); await fs.mkdir(dirname(target), { recursive: true, mode: 0o700 }); - await fs.writeFile(target, data, { mode: 0o600 }); + await fs.copyFile(resolveWithin(join(retained.directory, "files"), retained.output), target, + fsConstants.COPYFILE_EXCL | fsConstants.COPYFILE_FICLONE); + await fs.chmod(target, 0o600); const file: RunFile = { source: retained.file.relPath, output: relPath, kind: retained.file.kind }; run.files.push(file); + run.sourceState[inPlace ? relPath : file.source] = { + hash: inPlace ? digest(await fs.readFile(target)) : retained.hash, output: relPath, + }; if (file.source !== file.output) replacements.push(file); } for (const draft of props.preview.drafts) { @@ -359,6 +365,9 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje await fs.writeFile(target, output, { mode: 0o600 }); const file: RunFile = { source: draft.file.relPath, output: relPath, kind: draft.file.kind }; run.files.push(file); + run.sourceState[inPlace ? relPath : file.source] = { + hash: inPlace ? digest(output) : draft.hash, output: relPath, + }; replacements.push(file); } if (!inPlace) { @@ -524,6 +533,7 @@ export default function Command() { const [typesReadyFor, setTypesReadyFor] = useState(null); const [whitelist, setWhitelist] = useState([]); const [existingRuns, setExistingRuns] = useState(null); + const [reanalyzeUnchanged, setReanalyzeUnchanged] = useState(false); const [busy, setBusy] = useState(false); useEffect(() => { finderFolder().then((path) => { if (path) setRoot((current) => current || path); }); }, []); useEffect(() => { @@ -565,6 +575,7 @@ export default function Command() { }, [root]); useEffect(() => { if (!root) { setExistingRuns(null); return; } + setReanalyzeUnchanged(false); setExistingRuns(null); let active = true; listRuns(root).then((found) => { if (active) setExistingRuns(found.length); }) @@ -594,14 +605,22 @@ export default function Command() { await saveProjectEntityTypes(root, selectedTypes); await saveProjectRules(root, parsed); toast.title = "Dateien werden erfasst"; - const scan = await scanProjectFiles(root); + const scan = await scanProjectFiles(root, undefined, false); if (!scan.files.length) { const first = scan.skipped[0]; throw new Error(`Keine geeigneten Dateien im Projektordner gefunden.${first ? ` Übersprungen: ${first.path} (${first.reason}).` : ""}`); } const currentWhitelist = await loadProjectWhitelist(root); const preview = await prepare(root, scan.files, parsed, currentWhitelist, selectedTypes, scan.skipped, + reanalyzeUnchanged, (message) => { toast.title = message; }); + if (!preview.drafts.length && !preview.hits.length) { + toast.style = Toast.Style.Success; + toast.title = preview.skipped.length ? "Keine neuen analysierbaren Dateien" : "Alle Projektdateien unverändert"; + toast.message = `${preview.retained.length} Dateien aus dem letzten Stand übernommen.${preview.skipped.length + ? ` ${preview.skipped.length} Dateien übersprungen.` : " Keine erneute Analyse nötig."}`; + return; + } toast.style = Toast.Style.Success; toast.title = `${groupReviewHits(preview.hits).length} Zuordnungen zur Prüfung`; push( {availableTypes.map((type) => )} + ; diff --git a/tests/project-revision.test.ts b/tests/project-revision.test.ts index 4f66558..5dfb0cb 100644 --- a/tests/project-revision.test.ts +++ b/tests/project-revision.test.ts @@ -26,6 +26,7 @@ describe("Nachbearbeitung von Projektständen", () => { PERSON_04: { type: "PERSON", original: "Franz F." }, }; saved.run.files = [{ source: "Bericht.txt", output: "PERSON_01-PERSON_03.txt", kind: "text" }]; + saved.run.sourceState = { "Bericht.txt": { hash: "synthetic-hash", output: "PERSON_01-PERSON_03.txt" } }; await fs.writeFile(join(saved.directory, "files", "PERSON_01-PERSON_03.txt"), "PERSON_01 traf PERSON_02 und PERSON_03. PERSON_04 blieb."); await project.saveRun(saved.directory, saved.run); @@ -35,6 +36,9 @@ describe("Nachbearbeitung von Projektständen", () => { rewriteDocument: async () => { throw new Error("Unerwartetes Office-Dokument"); }, }); expect(result.run.files[0].output).toBe("Falsch Positiv-PERSON_02.txt"); + expect(result.run.sourceState?.["Bericht.txt"]).toEqual({ + hash: "synthetic-hash", output: "Falsch Positiv-PERSON_02.txt", + }); expect(await fs.readFile(join(result.directory, "files", result.run.files[0].output), "utf8")) .toBe("Falsch Positiv traf PERSON_02 und PERSON_02. PERSON_02 blieb."); expect(result.run.copyPath?.startsWith(join(root, "Quelle-Velum-"))).toBe(true); @@ -152,6 +156,10 @@ describe("Nachbearbeitung von Projektständen", () => { }); expect(await fs.readFile(join(source, "Fachbegriff.md"), "utf8")) .toBe("Fachbegriff und PERSON_02; später ergänzt"); + expect(result.run.sourceState?.["Fachbegriff.md"]).toEqual({ + hash: project.digest(Buffer.from("Fachbegriff und PERSON_02; später ergänzt")), + output: "Fachbegriff.md", + }); expect(await fs.readFile(join(result.directory, "backup", "PERSON_01.md"), "utf8")) .toBe("PERSON_01 und PERSON_02; später ergänzt"); expect(await fs.readFile(join(saved.directory, "files", "PERSON_01.md"), "utf8")) diff --git a/tests/velum-project.test.ts b/tests/velum-project.test.ts index 80c3ba1..43deca5 100644 --- a/tests/velum-project.test.ts +++ b/tests/velum-project.test.ts @@ -363,4 +363,26 @@ describe("Velum-Projektstände", () => { expect(await project.matchesPreviousOutput(created.directory, filename, project.digest(await fs.readFile(current)))).toBe(false); }); + + it("übernimmt unveränderte Quelldateien aus Kopien- und In-Place-Ständen ohne erneute Analyse", async () => { + const root = await fs.mkdtemp(join(tmpdir(), "velum-reuse-test-")); + roots.push(root); + const source = join(root, "Quelle"); + const support = join(root, "Raycast"); + await fs.mkdir(source); + const created = await project.createRun(source, support); + await fs.writeFile(join(created.directory, "files", "PERSON_01.txt"), "PERSON_01"); + created.run.files = [{ source: "Name.txt", output: "PERSON_01.txt", kind: "text" }]; + const originalHash = project.digest(Buffer.from("Max Mustermann")); + created.run.sourceState = { "Name.txt": { hash: originalHash, output: "PERSON_01.txt" } }; + expect(await project.reusableProjectOutput(created.run, created.directory, "Name.txt", originalHash)) + .toBe("PERSON_01.txt"); + expect(await project.reusableProjectOutput(created.run, created.directory, "Name.txt", + project.digest(Buffer.from("Änderung")))).toBeUndefined(); + created.run.sourceState = undefined; + created.run.inPlace = true; + created.run.files = [{ source: "Name.txt", output: "PERSON_01.txt", kind: "text" }]; + expect(await project.reusableProjectOutput(created.run, created.directory, "PERSON_01.txt", + project.digest(Buffer.from("PERSON_01")))).toBe("PERSON_01.txt"); + }); });