fix: guide project mapping recovery and allow manual table entries

This commit is contained in:
muena
2026-10-15 09:24:26 +02:00
parent 1ac11988af
commit 4801908faf
4 changed files with 337 additions and 46 deletions

View File

@@ -1,16 +1,57 @@
import { Action, ActionPanel, Alert, confirmAlert, Icon, List, showInFinder, showToast, Toast, useNavigation } from "@raycast/api";
import { Action, ActionPanel, Alert, confirmAlert, Form, Icon, List, showInFinder, showToast, Toast, useNavigation } from "@raycast/api";
import { promises as fs } from "node:fs";
import { homedir } from "node:os";
import { basename, dirname, join } from "node:path";
import { useEffect, useState } from "react";
import { depseudonymizeDocument } from "./velum";
import { canonicalProjectPath, isMarkdownFile, listAllRuns, resolveWithin, restorePath, restoreTextWithCount, runCopiesPath, scanRestorableCopyFiles, unresolvedPlaceholderIds, withUnambiguousHistoricalMappings } from "./lib/velum-project";
import { addProjectMappingEntry, canonicalProjectPath, digest, isMarkdownFile, listAllRuns, mappingForMatchingSnapshots, resolveWithin, restorePath, restoreTextWithCount, runCopiesPath, scanRestorableCopyFiles, unresolvedPlaceholderIds, withUnambiguousHistoricalMappings } from "./lib/velum-project";
import type { ProjectFile, ProjectRun } from "./lib/velum-project";
import type { MappingEntry, PlaceholderMapping } from "./types";
import { canonicalPerson, mergePeople } from "./lib/project-review";
import { planProjectRevision, reviseProjectRun } from "./lib/project-revision";
import { TranslationTable } from "./show-translation-tables";
type SavedRun = { run: ProjectRun; directory: string };
type RestoreDecision = MappingEntry | null;
class UnresolvedRestoreError extends Error {
constructor(readonly file: string, readonly ids: string[]) {
super(`${file}: ${ids.length} Platzhalter benötigen eine Zuordnung.`);
}
}
function RestoreDecisionForm(props: { file: string; id: string; candidates: MappingEntry[];
onSave: (decision: RestoreDecision) => void }) {
const { pop } = useNavigation();
async function save(values: { choice: string; original: string }) {
const original = values.original.trim();
const candidate = values.choice.startsWith("candidate:")
? props.candidates[Number(values.choice.slice("candidate:".length))] : undefined;
if (original) props.onSave({ original, type: candidate?.type ?? props.id.replace(/_\d+$/, "") });
else if (candidate) props.onSave(candidate);
else if (values.choice === "keep") props.onSave(null);
else {
await showToast({ style: Toast.Style.Failure, title: "Bitte einen Klartext wählen oder bewusst unverändert lassen" });
return;
}
pop();
}
return <Form navigationTitle={`${props.id} in ${props.file}`}
actions={<ActionPanel><Action.SubmitForm title="Entscheidung für diesen Export übernehmen" onSubmit={save} /></ActionPanel>}>
<Form.Description text={props.candidates.length > 1
? "Dieser Platzhalter hat in gespeicherten Projektständen unterschiedliche Bedeutungen. Wähle die passende Zuordnung für diese Datei."
: props.candidates.length === 1
? "Ein früherer Projektstand enthält diesen Eintrag. Prüfe, ob er zu dieser Datei gehört."
: "Für diesen Platzhalter gibt es in den gespeicherten Projektständen keine Zuordnung. Trage den Klartext ein oder bestätige, dass er absichtlich stehen bleiben soll."} />
<Form.Dropdown id="choice" title="Zuordnung" defaultValue="choose">
<Form.Dropdown.Item value="choose" title="Bitte auswählen" />
{props.candidates.map((entry, index) => <Form.Dropdown.Item key={index}
value={`candidate:${index}`} title={`${entry.original} · ${entry.type}`} />)}
<Form.Dropdown.Item value="keep" title="Platzhalter absichtlich unverändert lassen" />
</Form.Dropdown>
<Form.TextField id="original" title="Anderen Klartext eingeben" placeholder="Optional; überschreibt die Auswahl oben" />
</Form>;
}
function RevisionReview(props: { saved: SavedRun; onSaved: () => Promise<void> }) {
const { pop } = useNavigation();
@@ -132,12 +173,30 @@ function RevisionReview(props: { saved: SavedRun; onSaved: () => Promise<void> }
</List>;
}
function FilePicker(props: { run: ProjectRun; directory: string; historical?: boolean; earlierRuns: ProjectRun[] }) {
function FilePicker(props: { run: ProjectRun; directory: string; historical?: boolean; earlierRuns: SavedRun[] }) {
const { push } = useNavigation();
const [files, setFiles] = useState<ProjectFile[]>([]);
const [sourceRoot, setSourceRoot] = useState("");
const [selected, setSelected] = useState<Set<string>>(new Set());
const [skipped, setSkipped] = useState(0);
const [busy, setBusy] = useState(false);
const [unresolved, setUnresolved] = useState<Array<{ file: string; id: string }>>([]);
const [decisions, setDecisions] = useState<Record<string, Record<string, RestoreDecision>>>({});
const mappings = [props.run.mapping, ...props.earlierRuns.map((entry) => entry.run.mapping)];
const baseMapping = withUnambiguousHistoricalMappings(props.run.mapping, mappings.slice(1));
const candidatesFor = (id: string): MappingEntry[] => {
const unique = new Map<string, MappingEntry>();
for (const mapping of mappings) for (const [key, entry] of Object.entries(mapping)) {
if (key.toUpperCase() === id.toUpperCase()) unique.set(`${entry.type}\0${entry.original}`, entry);
}
return [...unique.values()];
};
function saveDecision(file: string, id: string, decision: RestoreDecision) {
setDecisions((current) => ({ ...current,
[file]: { ...current[file], [id.toUpperCase()]: decision },
}));
setUnresolved((current) => current.filter((item) => item.file !== file || item.id !== id));
}
useEffect(() => {
let active = true;
async function load() {
@@ -173,64 +232,91 @@ function FilePicker(props: { run: ProjectRun; directory: string; historical?: bo
const parent = join(homedir(), "Downloads", "Velum");
let targetRoot: string | undefined;
try {
const mappings = [props.run.mapping, ...props.earlierRuns.map((run) => run.mapping)];
const mapping = withUnambiguousHistoricalMappings(props.run.mapping, mappings.slice(1));
if (!Object.keys(mapping).length) throw new Error("Dieser Projektstand hat keine Übersetzungstabelle.");
const names = new Set<string>();
const planned = files.filter((item) => selected.has(item.relPath)).map((file) => ({
file, restoredName: restorePath(file.relPath, mapping, props.run.matchModes),
}));
const renamedFiles = planned.filter(({ file, restoredName }) => restoredName !== file.relPath).length;
let contentReplacements = 0;
for (const { restoredName } of planned) {
if (names.has(restoredName)) throw new Error(`Mehrdeutiger Ausgabename: ${restoredName}`);
names.add(restoredName);
if (!Object.keys(baseMapping).length && !Object.keys(decisions).length) {
throw new Error("Dieser Projektstand hat keine Übersetzungstabelle.");
}
const names = new Set<string>();
const planned = files.filter((item) => selected.has(item.relPath));
let renamedFiles = 0;
let contentReplacements = 0;
await fs.mkdir(parent, { recursive: true, mode: 0o700 });
targetRoot = await fs.mkdtemp(join(parent, `${basename(props.run.projectName)}-${stamp}-`));
for (const { file, restoredName } of planned) {
for (const file of planned) {
const source = resolveWithin(sourceRoot, file.relPath);
const target = resolveWithin(targetRoot, restoredName);
if (!(await fs.lstat(source)).isFile()) throw new Error(`Keine reguläre Datei: ${file.relPath}`);
const data = await fs.readFile(source);
const mapping: PlaceholderMapping = { ...baseMapping };
const manual = decisions[file.relPath] ?? {};
for (const [id, entry] of Object.entries(manual)) if (entry) mapping[id] = entry;
let restoredName = restorePath(file.relPath, mapping, props.run.matchModes);
let result: Buffer;
if (file.kind === "document") {
result = await depseudonymizeDocument(basename(file.relPath), data, mapping);
} else {
const markdown = isMarkdownFile(file.relPath);
const restored = restoreTextWithCount(data.toString("utf8"), mapping, props.run.matchModes, markdown);
const text = data.toString("utf8");
let restored = restoreTextWithCount(text, mapping, props.run.matchModes, markdown);
if (markdown) {
const unresolved = unresolvedPlaceholderIds(`${restoredName}\n${restored.text}`, mappings);
if (unresolved.length) throw new Error(`${file.relPath}: Platzhalter ohne eindeutige Zuordnung: ${unresolved.slice(0, 5).join(", ")}${unresolved.length > 5 ? " …" : ""}. Bitte Projektstand prüfen.`);
let missing = unresolvedPlaceholderIds(`${restoredName}\n${restored.text}`, mappings)
.filter((id) => manual[id.toUpperCase()] !== null);
if (missing.length) {
const exactMapping = await mappingForMatchingSnapshots(file.relPath, digest(data), props.earlierRuns);
for (const id of missing) {
const match = Object.entries(exactMapping).find(([key]) => key.toUpperCase() === id.toUpperCase());
if (match && !Object.keys(mapping).some((key) => key.toUpperCase() === id.toUpperCase())) {
mapping[match[0]] = match[1];
}
}
restoredName = restorePath(file.relPath, mapping, props.run.matchModes);
restored = restoreTextWithCount(text, mapping, props.run.matchModes, true);
missing = unresolvedPlaceholderIds(`${restoredName}\n${restored.text}`, mappings)
.filter((id) => manual[id.toUpperCase()] !== null);
}
if (missing.length) throw new UnresolvedRestoreError(file.relPath, missing);
}
contentReplacements += restored.replacements;
result = Buffer.from(restored.text, "utf8");
}
if (names.has(restoredName)) throw new Error(`Mehrdeutiger Ausgabename: ${restoredName}`);
names.add(restoredName);
if (restoredName !== file.relPath) renamedFiles++;
const target = resolveWithin(targetRoot, restoredName);
await fs.mkdir(dirname(target), { recursive: true, mode: 0o700 });
await fs.writeFile(target, result, { flag: "wx", mode: 0o600 });
}
if (!renamedFiles && !contentReplacements && planned.every(({ file }) => file.kind === "text")) {
if (!renamedFiles && !contentReplacements && planned.every((file) => file.kind === "text")
&& !planned.some((file) => Object.values(decisions[file.relPath] ?? {}).includes(null))) {
throw new Error("Keine passenden Velum-Platzhalter in den ausgewählten Textdateien oder Dateinamen gefunden. Bitte Quelle und Projektstand prüfen.");
}
setUnresolved([]);
toast.style = Toast.Style.Success;
toast.title = `${selected.size} Klartext-Dateien in Downloads`;
const deliberatelyKept = planned.reduce((count, file) => count
+ Object.values(decisions[file.relPath] ?? {}).filter((entry) => entry === null).length, 0);
toast.message = `${contentReplacements} Textersetzungen · ${renamedFiles} Dateinamen geändert`
+ (planned.some(({ file }) => file.kind === "document") ? " · Office-Inhalte nicht gezählt" : "");
+ (deliberatelyKept ? ` · ${deliberatelyKept} Platzhalter bewusst belassen` : "")
+ (planned.some((file) => file.kind === "document") ? " · Office-Inhalte nicht gezählt" : "");
await showInFinder(targetRoot).catch(() => undefined);
} catch (error) {
if (targetRoot) await fs.rm(targetRoot, { recursive: true, force: true });
if (error instanceof UnresolvedRestoreError) setUnresolved(error.ids.map((id) => ({ file: error.file, id })));
toast.style = Toast.Style.Failure;
toast.title = "Klartext-Export fehlgeschlagen";
toast.message = (error as Error).message;
toast.title = error instanceof UnresolvedRestoreError ? "Platzhalter zuordnen" : "Klartext-Export fehlgeschlagen";
toast.message = error instanceof UnresolvedRestoreError
? `${error.file}: ${error.ids.join(", ")}. Bitte die Einträge unten klären und den Export erneut starten.`
: (error as Error).message;
} finally { setBusy(false); }
}
const textFiles = files.filter((file) => file.kind === "text");
const complexFiles = files.filter((file) => file.kind === "document");
const sourceLabel = props.historical ? "Gespeicherter Projektstand"
: props.run.inPlace || props.run.sourceInPlace ? "Aktueller Projektordner" : "Pseudonymisierte Kopien";
const renderFile = (file: ProjectFile) => <List.Item key={file.relPath}
const renderFile = (file: ProjectFile) => {
const displayMapping: PlaceholderMapping = { ...baseMapping };
for (const [id, entry] of Object.entries(decisions[file.relPath] ?? {})) if (entry) displayMapping[id] = entry;
return <List.Item key={file.relPath}
icon={selected.has(file.relPath) ? Icon.CheckCircle : Icon.Circle}
title={restorePath(file.relPath, props.run.mapping, props.run.matchModes)} subtitle={file.relPath}
title={restorePath(file.relPath, displayMapping, props.run.matchModes)} subtitle={file.relPath}
accessories={file.kind === "document" ? [{ text: "Office · manuell auswählen" }] : []}
actions={<ActionPanel>
<Action title={selected.has(file.relPath) ? "Datei abwählen" : "Datei auswählen"} onAction={() => toggle(file.relPath)} />
@@ -239,6 +325,7 @@ function FilePicker(props: { run: ProjectRun; directory: string; historical?: bo
<Action title="Alle Dateien auswählen (inklusive Office)" onAction={() => setSelected(new Set(files.map((item) => item.relPath)))} />
<Action title="Keine auswählen" onAction={() => setSelected(new Set())} />
</ActionPanel>} />;
};
return <List isLoading={busy || !sourceRoot} navigationTitle={`${props.run.projectName}: Dateien für Klartext wählen`}
searchBarPlaceholder="Dateien filtern">
<List.Section title={`${selected.size} von ${files.length} Dateien ausgewählt · ${skipped} übersprungen`}>
@@ -249,6 +336,18 @@ function FilePicker(props: { run: ProjectRun; directory: string; historical?: bo
<List.Item key="source" icon={Icon.Folder} title={sourceLabel} subtitle={sourceRoot}
actions={<ActionPanel><Action title="Quellordner im Finder anzeigen" onAction={() => showInFinder(sourceRoot)} /></ActionPanel>} />
</List.Section>
{unresolved.some((item) => selected.has(item.file)) && <List.Section title="Platzhalter für diesen Export klären">
{unresolved.filter((item) => selected.has(item.file)).map(({ file, id }) => {
const candidates = candidatesFor(id);
return <List.Item key={`${file}:${id}`} icon={Icon.ExclamationMark}
title={id} subtitle={file}
accessories={[{ text: candidates.length > 1 ? `${candidates.length} verschiedene alte Zuordnungen`
: candidates.length ? "Gespeicherter Eintrag – bitte prüfen" : "Kein gespeicherter Eintrag" }]}
actions={<ActionPanel><Action title="Zuordnung festlegen" icon={Icon.Pencil}
onAction={() => push(<RestoreDecisionForm file={file} id={id} candidates={candidates}
onSave={(decision) => saveDecision(file, id, decision)} />)} /></ActionPanel>} />;
})}
</List.Section>}
<List.Section title={`Textdateien · ${textFiles.length} · standardmäßig ausgewählt`}>
{textFiles.map(renderFile)}
</List.Section>
@@ -269,7 +368,7 @@ function ProjectHistory(props: { projectName: string; entries: SavedRun[] }) {
actions={<ActionPanel>
<Action title="Gespeicherten Stand wiederherstellen" icon={Icon.Download}
onAction={() => push(<FilePicker run={run} directory={directory} historical
earlierRuns={props.entries.slice(index + 1).map((entry) => entry.run)} />)} />
earlierRuns={props.entries.slice(index + 1)} />)} />
<Action.Push title="Übersetzungstabelle anzeigen" icon={Icon.List}
target={<TranslationTable title={`${props.projectName} · ${new Date(run.createdAt).toLocaleString("de-AT")}`}
mapping={run.mapping} />} />
@@ -278,7 +377,7 @@ function ProjectHistory(props: { projectName: string; entries: SavedRun[] }) {
<Action.CopyToClipboard title="Speicherpfad kopieren" content={runCopiesPath(run, directory)} />
{run.copyPath && <Action title="Aktuelle Dateien dieses Kopienordners wiederherstellen" icon={Icon.Download}
onAction={() => push(<FilePicker run={run} directory={directory}
earlierRuns={props.entries.slice(index + 1).map((entry) => entry.run)} />)} />}
earlierRuns={props.entries.slice(index + 1)} />)} />}
</ActionPanel>} />)}
</List.Section>
</List>;
@@ -334,9 +433,14 @@ export default function Command() {
actions={<ActionPanel>
<Action title="Projektdateien als Klartext wiederherstellen" icon={Icon.Download}
onAction={() => push(<FilePicker run={run} directory={directory}
earlierRuns={entries.slice(1).map((entry) => entry.run)} />)} />
earlierRuns={entries.slice(1)} />)} />
<Action.Push title="Übersetzungstabelle anzeigen" icon={Icon.List}
target={<TranslationTable title={run.projectName} mapping={run.mapping} />} />
target={<TranslationTable title={run.projectName} mapping={run.mapping}
onAdd={async (input) => {
const updated = await addProjectMappingEntry(run.projectPath, input);
await refresh();
return updated.mapping;
}} />} />
<Action title="Pseudonymisierte Kopien im Finder anzeigen" icon={Icon.Folder}
onAction={() => showInFinder(runCopiesPath(run, directory))} />
<Action.CopyToClipboard title="Speicherpfad kopieren" content={runCopiesPath(run, directory)} />