forked from r.muellner/velum-raycast
fix: guide project mapping recovery and allow manual table entries
This commit is contained in:
@@ -2,7 +2,7 @@ import { createHash, randomUUID } from "node:crypto";
|
||||
import { constants as fsConstants, promises as fs } from "node:fs";
|
||||
import { basename, dirname, extname, join, relative, resolve, sep } from "node:path";
|
||||
import { environment } from "@raycast/api";
|
||||
import type { EntityType, PlaceholderMapping } from "../types";
|
||||
import type { EntityType, MappingEntry, PlaceholderMapping } from "../types";
|
||||
import { whitelistKey } from "./project-whitelist";
|
||||
import type { ProjectWhitelistEntry } from "./project-whitelist";
|
||||
import { restoreOriginalCase } from "./restore-case";
|
||||
@@ -382,6 +382,78 @@ export async function saveRun(directory: string, run: ProjectRun): Promise<void>
|
||||
await fs.rename(tmp, dest);
|
||||
}
|
||||
|
||||
export function prepareManualMappingEntry(current: PlaceholderMapping, earlier: PlaceholderMapping[],
|
||||
input: { original: string; type: string; placeholder?: string }): { placeholder: string; entry: MappingEntry } {
|
||||
const original = input.original.trim();
|
||||
const type = input.type.trim().toUpperCase();
|
||||
if (!original) throw new Error("Bitte einen Klartext-Begriff eingeben.");
|
||||
if (!/^[A-ZÄÖÜ][A-ZÄÖÜ0-9_]*$/u.test(type)) throw new Error("Ungültige Kategorie.");
|
||||
if (Object.values(current).some((entry) => entry.type === type
|
||||
&& entry.original.toLocaleLowerCase("de") === original.toLocaleLowerCase("de"))) {
|
||||
throw new Error("Dieser Begriff ist in der Kategorie bereits vorhanden.");
|
||||
}
|
||||
const known = [current, ...earlier];
|
||||
const keys = known.flatMap((mapping) => Object.keys(mapping));
|
||||
const placeholderPattern = new RegExp(`^${type}_(\\d+)$`, "u");
|
||||
const placeholder = input.placeholder?.trim().toUpperCase() || (() => {
|
||||
const max = keys.reduce((currentMax, key) => Math.max(currentMax,
|
||||
Number(placeholderPattern.exec(key)?.[1] ?? 0)), 0);
|
||||
return `${type}_${String(max + 1).padStart(2, "0")}`;
|
||||
})();
|
||||
if (!placeholderPattern.test(placeholder)) {
|
||||
throw new Error("Platzhalter muss zur Kategorie passen, z. B. PERSON_61.");
|
||||
}
|
||||
if (Object.keys(current).some((key) => key.toUpperCase() === placeholder)) {
|
||||
throw new Error("Dieser Platzhalter ist im aktuellen Stand bereits belegt.");
|
||||
}
|
||||
for (const mapping of earlier) for (const [key, entry] of Object.entries(mapping)) {
|
||||
if (key.toUpperCase() === placeholder && (entry.type !== type || entry.original !== original)) {
|
||||
throw new Error("Dieser Platzhalter hatte früher eine andere Bedeutung. Bitte die betroffene Datei einzeln zuordnen.");
|
||||
}
|
||||
}
|
||||
return { placeholder, entry: { original, type } };
|
||||
}
|
||||
|
||||
/** Save a mapping correction as a new immutable project stand without rewriting project files. */
|
||||
export async function addProjectMappingEntry(projectPath: string,
|
||||
input: { original: string; type: string; placeholder?: string }, support = environment.supportPath): Promise<ProjectRun> {
|
||||
const entries = await listRuns(projectPath, support);
|
||||
const latest = entries[0];
|
||||
if (!latest) throw new Error("Für dieses Projekt gibt es noch keinen gespeicherten Stand.");
|
||||
const { placeholder, entry } = prepareManualMappingEntry(latest.run.mapping,
|
||||
entries.slice(1).map((saved) => saved.run.mapping), input);
|
||||
const created = await createRun(projectPath, support);
|
||||
const { run, directory } = created;
|
||||
run.createdAt = new Date(Math.max(Date.now(), Date.parse(latest.run.createdAt) + 1)).toISOString();
|
||||
run.origin = latest.run.origin;
|
||||
run.revisedFrom = latest.run.id;
|
||||
run.mapping = { ...latest.run.mapping, [placeholder]: entry };
|
||||
run.matchModes = { ...latest.run.matchModes };
|
||||
run.files = latest.run.files.map((file) => ({ ...file }));
|
||||
run.inPlace = latest.run.inPlace;
|
||||
run.sourceInPlace = latest.run.sourceInPlace;
|
||||
run.commentAuthorCoverage = latest.run.commentAuthorCoverage;
|
||||
run.reviewAuthorCoverage = latest.run.reviewAuthorCoverage;
|
||||
run.copyPath = latest.run.copyPath;
|
||||
try {
|
||||
for (const file of run.files) {
|
||||
const source = resolveWithin(join(latest.directory, "files"), file.output);
|
||||
const target = resolveWithin(join(directory, "files"), file.output);
|
||||
await fs.mkdir(dirname(target), { recursive: true, mode: 0o700 });
|
||||
await fs.copyFile(source, target, fsConstants.COPYFILE_EXCL | fsConstants.COPYFILE_FICLONE);
|
||||
await fs.chmod(target, 0o600);
|
||||
}
|
||||
if ((await listRuns(projectPath, support))[0]?.run.id !== latest.run.id) {
|
||||
throw new Error("Es gibt bereits einen neueren Projektstand. Bitte die Liste aktualisieren.");
|
||||
}
|
||||
await saveRun(directory, run);
|
||||
} catch (error) {
|
||||
await fs.rm(directory, { recursive: true, force: true });
|
||||
throw error;
|
||||
}
|
||||
return run;
|
||||
}
|
||||
|
||||
export function runCopiesPath(run: ProjectRun, directory: string): string {
|
||||
return run.copyPath ?? join(directory, "files");
|
||||
}
|
||||
@@ -469,6 +541,17 @@ export async function matchesPreviousOutput(directory: string, relPath: string,
|
||||
}
|
||||
}
|
||||
|
||||
/** 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<PlaceholderMapping> {
|
||||
const matching = await Promise.all(earlier.filter(({ run }) =>
|
||||
run.files.some((file) => file.output === relPath))
|
||||
.map(async ({ run, directory }) => await matchesPreviousOutput(directory, relPath, currentHash)
|
||||
? run.mapping : undefined));
|
||||
return withUnambiguousHistoricalMappings({},
|
||||
matching.filter((mapping): mapping is PlaceholderMapping => Boolean(mapping)));
|
||||
}
|
||||
|
||||
export async function listAllRuns(support = environment.supportPath): Promise<Array<{
|
||||
run: ProjectRun; directory: string;
|
||||
}>> {
|
||||
|
||||
@@ -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)} />
|
||||
|
||||
@@ -2,14 +2,16 @@ import {
|
||||
Action,
|
||||
ActionPanel,
|
||||
Detail,
|
||||
Form,
|
||||
Icon,
|
||||
List,
|
||||
showToast,
|
||||
Toast,
|
||||
useNavigation,
|
||||
} from "@raycast/api";
|
||||
import { useEffect, useState } from "react";
|
||||
import { canonicalProjectPath, listAllRuns } from "./lib/velum-project";
|
||||
import { listSessions } from "./sessions";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { addProjectMappingEntry, canonicalProjectPath, listAllRuns, prepareManualMappingEntry } from "./lib/velum-project";
|
||||
import { getSession, listSessions, updateSessionMapping } from "./sessions";
|
||||
import type { PlaceholderMapping } from "./types";
|
||||
import { markdownCodeBlock } from "./ui";
|
||||
|
||||
@@ -20,15 +22,48 @@ type TableSource = {
|
||||
mapping: PlaceholderMapping;
|
||||
};
|
||||
|
||||
type ManualEntry = { original: string; type: string; placeholder?: string };
|
||||
|
||||
function AddMappingForm(props: { onAdd: (input: ManualEntry) => Promise<PlaceholderMapping>;
|
||||
onSaved: (mapping: PlaceholderMapping) => void }) {
|
||||
const { pop } = useNavigation();
|
||||
const [busy, setBusy] = useState(false);
|
||||
async function save(values: { original: string; type: string; placeholder: string }) {
|
||||
setBusy(true);
|
||||
try {
|
||||
const type = values.type.trim() || /^([A-ZÄÖÜ][A-ZÄÖÜ0-9_]*)_\d+$/iu.exec(values.placeholder.trim())?.[1] || "BEGRIFF";
|
||||
const mapping = await props.onAdd({ ...values, type });
|
||||
props.onSaved(mapping);
|
||||
await showToast({ style: Toast.Style.Success, title: "Zuordnung gespeichert" });
|
||||
pop();
|
||||
} catch (error) {
|
||||
await showToast({ style: Toast.Style.Failure, title: "Zuordnung nicht gespeichert",
|
||||
message: (error as Error).message });
|
||||
} finally { setBusy(false); }
|
||||
}
|
||||
return <Form isLoading={busy} navigationTitle="Zuordnung ergänzen"
|
||||
actions={<ActionPanel><Action.SubmitForm title="Zuordnung speichern" onSubmit={save} /></ActionPanel>}>
|
||||
<Form.Description text="Der Eintrag wird zur Wiederherstellung verwendet. Für eine garantierte Maskierung bei künftigen Projektläufen zusätzlich eine Projektregel anlegen." />
|
||||
<Form.TextField id="original" title="Klartext-Begriff" placeholder="Originalwert" />
|
||||
<Form.TextField id="type" title="Kategorie (optional)" placeholder="Aus Platzhalter ableiten; sonst BEGRIFF" />
|
||||
<Form.TextField id="placeholder" title="Platzhalter (optional)" placeholder="z. B. PERSON_61; leer = nächste freie Nummer" />
|
||||
</Form>;
|
||||
}
|
||||
|
||||
export function TranslationTable({
|
||||
title,
|
||||
mapping,
|
||||
onAdd,
|
||||
}: {
|
||||
title: string;
|
||||
mapping: PlaceholderMapping;
|
||||
onAdd?: (input: ManualEntry) => Promise<PlaceholderMapping>;
|
||||
}) {
|
||||
const { push } = useNavigation();
|
||||
const [visibleMapping, setVisibleMapping] = useState(mapping);
|
||||
useEffect(() => setVisibleMapping(mapping), [mapping]);
|
||||
const groups = new Map<string, Array<[string, PlaceholderMapping[string]]>>();
|
||||
for (const entry of Object.entries(mapping).sort(([a], [b]) =>
|
||||
for (const entry of Object.entries(visibleMapping).sort(([a], [b]) =>
|
||||
a.localeCompare(b),
|
||||
)) {
|
||||
const type = entry[1].type || "Sonstige";
|
||||
@@ -46,6 +81,12 @@ export function TranslationTable({
|
||||
title="Keine Zuordnungen"
|
||||
description="Für diesen Stand sind noch keine Übersetzungen gespeichert."
|
||||
/>
|
||||
{onAdd && <List.Section title="Pflege">
|
||||
<List.Item icon={Icon.Plus} title="Begriff oder fehlenden Platzhalter hinzufügen"
|
||||
subtitle="Neuer Eintrag für diese Übersetzungstabelle"
|
||||
actions={<ActionPanel><Action title="Zuordnung hinzufügen" icon={Icon.Plus}
|
||||
onAction={() => push(<AddMappingForm onAdd={onAdd} onSaved={setVisibleMapping} />)} /></ActionPanel>} />
|
||||
</List.Section>}
|
||||
{[...groups]
|
||||
.sort(([a], [b]) => a.localeCompare(b))
|
||||
.map(([type, entries]) => (
|
||||
@@ -122,8 +163,8 @@ export default function Command() {
|
||||
const [sessions, setSessions] = useState<TableSource[]>([]);
|
||||
const [busy, setBusy] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
Promise.all([listAllRuns(), listSessions()])
|
||||
const refresh = useCallback(async () => {
|
||||
await Promise.all([listAllRuns(), listSessions()])
|
||||
.then(([runs, savedSessions]) => {
|
||||
const latest = new Map<string, TableSource>();
|
||||
for (const { run } of runs) {
|
||||
@@ -147,16 +188,13 @@ export default function Command() {
|
||||
mapping: session.mapping,
|
||||
})),
|
||||
);
|
||||
})
|
||||
.catch((error: Error) =>
|
||||
showToast({
|
||||
style: Toast.Style.Failure,
|
||||
title: "Übersetzungstabellen nicht lesbar",
|
||||
message: error.message,
|
||||
}),
|
||||
)
|
||||
.finally(() => setBusy(false));
|
||||
});
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
refresh().catch((error: Error) => showToast({ style: Toast.Style.Failure,
|
||||
title: "Übersetzungstabellen nicht lesbar", message: error.message }))
|
||||
.finally(() => setBusy(false));
|
||||
}, [refresh]);
|
||||
|
||||
return (
|
||||
<List
|
||||
@@ -187,6 +225,11 @@ export default function Command() {
|
||||
<TranslationTable
|
||||
title={source.title}
|
||||
mapping={source.mapping}
|
||||
onAdd={async (input) => {
|
||||
const run = await addProjectMappingEntry(source.id, input);
|
||||
await refresh();
|
||||
return run.mapping;
|
||||
}}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
@@ -211,6 +254,19 @@ export default function Command() {
|
||||
<TranslationTable
|
||||
title={source.title}
|
||||
mapping={source.mapping}
|
||||
onAdd={async (input) => {
|
||||
const session = await getSession(source.id);
|
||||
if (!session) throw new Error("Sitzung nicht gefunden.");
|
||||
const normalized = Object.fromEntries(Object.entries(session.mapping)
|
||||
.map(([key, entry]) => [key.replace(/^<|>$/g, ""), entry]));
|
||||
const { placeholder, entry } = prepareManualMappingEntry(normalized, [], input);
|
||||
const bracketed = Object.keys(session.mapping).some((key) => key.startsWith("<"));
|
||||
const key = bracketed ? `<${placeholder}>` : placeholder;
|
||||
const updated = await updateSessionMapping(session.id,
|
||||
{ ...session.mapping, [key]: entry }, session.entityTypes);
|
||||
await refresh();
|
||||
return updated.mapping;
|
||||
}}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
|
||||
@@ -201,6 +201,54 @@ describe("Velum-Projektstände", () => {
|
||||
expect(project.isMarkdownFile("Notizen.MD")).toBe(true);
|
||||
});
|
||||
|
||||
it("löst eine wiederverwendete ID nur über eine identische gespeicherte Datei auf", async () => {
|
||||
const root = await fs.mkdtemp(join(tmpdir(), "velum-exact-snapshot-"));
|
||||
roots.push(root);
|
||||
const first = await project.createRun(join(root, "Quelle"), root);
|
||||
const second = await project.createRun(join(root, "Quelle"), root);
|
||||
const relPath = "Fragenliste.md";
|
||||
first.run.files = [{ source: relPath, output: relPath, kind: "text" }];
|
||||
second.run.files = [{ source: relPath, output: relPath, kind: "text" }];
|
||||
first.run.mapping = { PERSON_61: { original: "Alex Beispiel", type: "PERSON" } };
|
||||
second.run.mapping = { PERSON_61: { original: "Mara Muster", type: "PERSON" } };
|
||||
const source = Buffer.from("Kommentar PERSON_61");
|
||||
await fs.writeFile(join(first.directory, "files", relPath), source);
|
||||
await fs.writeFile(join(second.directory, "files", relPath), "anderer Inhalt");
|
||||
const exact = await project.mappingForMatchingSnapshots(relPath, project.digest(source), [first, second]);
|
||||
expect(exact.PERSON_61?.original).toBe("Alex Beispiel");
|
||||
const unknown = await project.mappingForMatchingSnapshots(relPath, project.digest(Buffer.from("neu")), [first, second]);
|
||||
expect(unknown.PERSON_61).toBeUndefined();
|
||||
});
|
||||
|
||||
it("ergänzt einen fehlenden Platzhalter in einem neuen Projektstand ohne alte Daten zu ändern", async () => {
|
||||
const root = await fs.mkdtemp(join(tmpdir(), "velum-manual-mapping-"));
|
||||
roots.push(root);
|
||||
const source = join(root, "Quelle");
|
||||
await fs.mkdir(source);
|
||||
const saved = await project.createRun(source, root);
|
||||
saved.run.mapping = { PERSON_01: { original: "Alex Beispiel", type: "PERSON" } };
|
||||
saved.run.files = [{ source: "Notiz.md", output: "Notiz.md", kind: "text" }];
|
||||
await fs.writeFile(join(saved.directory, "files", "Notiz.md"), "PERSON_61");
|
||||
await project.saveRun(saved.directory, saved.run);
|
||||
const updated = await project.addProjectMappingEntry(source,
|
||||
{ placeholder: "PERSON_61", original: "Mara Muster", type: "PERSON" }, root);
|
||||
expect(updated.mapping.PERSON_61?.original).toBe("Mara Muster");
|
||||
expect((await project.listRuns(source, root))[0].run.id).toBe(updated.id);
|
||||
expect(await fs.readFile(join(saved.directory, "files", "Notiz.md"), "utf8")).toBe("PERSON_61");
|
||||
expect((await project.listRuns(source, root))[1].run.mapping.PERSON_61).toBeUndefined();
|
||||
expect(await fs.readFile(join(project.projectDataRoot(source, root), "runs", updated.id, "files", "Notiz.md"), "utf8"))
|
||||
.toBe("PERSON_61");
|
||||
expect(project.prepareManualMappingEntry(updated.mapping, [],
|
||||
{ original: "Weiterer Begriff", type: "PERSON" }).placeholder).toBe("PERSON_62");
|
||||
});
|
||||
|
||||
it("verhindert eine neue projektweite Zuordnung für eine früher anders belegte ID", () => {
|
||||
expect(() => project.prepareManualMappingEntry({}, [
|
||||
{ PERSON_61: { original: "Alex Beispiel", type: "PERSON" } },
|
||||
], { placeholder: "PERSON_61", original: "Mara Muster", type: "PERSON" }))
|
||||
.toThrow("andere Bedeutung");
|
||||
});
|
||||
|
||||
it("übernimmt API-Trefferpositionen auch nach einem Emoji korrekt", () => {
|
||||
const text = "😀 Max";
|
||||
const spans = project.toUtf16Offsets(text, [{ id: "max", start: 2, end: 5, placeholder: "PERSON_01" }]);
|
||||
|
||||
Reference in New Issue
Block a user