fix: reuse unchanged project files by source hash
This commit is contained in:
@@ -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<string, "token" | "anywhere">; 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<Preview> {
|
||||
skipped: SkippedProjectFile[], reanalyzeUnchanged: boolean,
|
||||
onProgress: (message: string) => void): Promise<Preview> {
|
||||
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<string, string>();
|
||||
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<string | null>(null);
|
||||
const [whitelist, setWhitelist] = useState<ProjectWhitelistEntry[]>([]);
|
||||
const [existingRuns, setExistingRuns] = useState<number | null>(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(<HitReview root={root} rules={parsed} whitelist={currentWhitelist} preview={preview}
|
||||
@@ -637,6 +656,10 @@ export default function Command() {
|
||||
onChange={setSelectedTypes} info="Die Auswahl wird beim Prüfen für diesen Projektordner gespeichert. Word-Kommentatoren und Bearbeiter von Änderungen werden mit der Kategorie Personen maskiert. Bei neuen Projekten sind Orte zunächst abgewählt.">
|
||||
{availableTypes.map((type) => <Form.TagPicker.Item key={type} value={type} title={labelForType(type)} />)}
|
||||
</Form.TagPicker>
|
||||
<Form.Checkbox id="reanalyzeUnchanged" title="Erneute Analyse"
|
||||
label="Auch unveränderte Dateien erneut analysieren" value={reanalyzeUnchanged}
|
||||
onChange={setReanalyzeUnchanged}
|
||||
info="Standardmäßig werden nur neue oder geänderte Dateien an Velum gesendet. Für neue Regeln, Kategorien oder Word-Erkennung auch bestehende Dateien ausdrücklich erneut prüfen." />
|
||||
<Form.Description title="Projekt-Whitelist" text={`${whitelist.length} Begriffe werden bei diesem Ordner nicht mehr vorgeschlagen. Über die Aktionen kannst du sie wieder freigeben.`} />
|
||||
<Form.Description title="Ablauf" text="Kategorien wählen, Zuordnungen auswählen und Personen bei Bedarf zusammenfassen. Standardmäßig werden die Originaldateien nach Bestätigung ersetzt; Kopien sind als Alternative verfügbar." />
|
||||
</Form>;
|
||||
|
||||
Reference in New Issue
Block a user