feat: allow project files to be excluded before analysis

This commit is contained in:
muena
2026-10-19 10:35:41 +02:00
parent 19434c6c0b
commit 031eaa978f
3 changed files with 193 additions and 29 deletions

View File

@@ -91,6 +91,46 @@ export function entityTypesPath(projectPath: string, support = environment.suppo
return join(projectDataRoot(projectPath, support), "entity-types.json");
}
export function fileExclusionsPath(projectPath: string, support = environment.supportPath): string {
return join(projectDataRoot(projectPath, support), "excluded-files.json");
}
function checkedFileExclusions(value: unknown): string[] {
if (!Array.isArray(value) || value.some((path) => typeof path !== "string")) {
throw new Error("Ungültige Dateiauswahl für dieses Projekt.");
}
try { return [...new Set(value.map((path: string) => safeRelativePath(path)))]; }
catch { throw new Error("Ungültiger Dateipfad in der Projektauswahl."); }
}
export async function loadProjectFileExclusions(projectPath: string, support?: string): Promise<string[]> {
try {
return checkedFileExclusions(JSON.parse(await fs.readFile(fileExclusionsPath(projectPath, support), "utf8")));
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
throw error;
}
}
export async function saveProjectFileExclusions(projectPath: string, paths: string[], support?: string): Promise<void> {
const unique = checkedFileExclusions(paths);
const path = fileExclusionsPath(projectPath, support);
await fs.mkdir(dirname(path), { recursive: true, mode: 0o700 });
const temp = `${path}.${randomUUID()}.tmp`;
try {
await fs.writeFile(temp, JSON.stringify(unique), { encoding: "utf8", mode: 0o600 });
await fs.rename(temp, path);
} catch (error) {
await fs.rm(temp, { force: true });
throw error;
}
}
export function withoutExcludedProjectFiles(files: ProjectFile[], excluded: readonly string[]): ProjectFile[] {
const paths = new Set(excluded);
return files.filter((file) => !paths.has(file.relPath));
}
export async function loadProjectEntityTypes(projectPath: string, support?: string): Promise<EntityType[] | null> {
try {
const value = JSON.parse(await fs.readFile(entityTypesPath(projectPath, support), "utf8")) as unknown;

View File

@@ -8,9 +8,9 @@ import type { EntityType, PlaceholderMapping } from "./types";
import { getEntityTypes, pseudonymize, pseudonymizeDocument, requireProjectCapabilities } from "./velum";
import type { DocumentHit } from "./velum";
import {
createRun, digest, forceMasks, listRuns, loadProjectEntityTypes, loadProjectRules, parseProjectRules, publishProjectCopies, replaceSpans,
loadProjectWhitelist, reusableProjectOutput, replaceProjectFilesInPlace, resolveWithin, safeRelativePath, saveProjectRules,
saveProjectEntityTypes, saveProjectWhitelist, saveRun, scanProjectFiles, toUtf16Offsets, whitelistKey,
createRun, digest, forceMasks, listRuns, loadProjectEntityTypes, loadProjectFileExclusions, loadProjectRules, parseProjectRules, publishProjectCopies, replaceSpans,
loadProjectWhitelist, reusableProjectOutput, replaceProjectFilesInPlace, resolveWithin, safeRelativePath, saveProjectFileExclusions, saveProjectRules,
saveProjectEntityTypes, saveProjectWhitelist, saveRun, scanProjectFiles, toUtf16Offsets, whitelistKey, withoutExcludedProjectFiles,
} from "./lib/velum-project";
import type { ProjectFile, ProjectRule, ProjectWhitelistEntry, RunFile, SkippedProjectFile } from "./lib/velum-project";
import {
@@ -235,13 +235,15 @@ function OccurrenceReview(props: { original: string; placeholder: string; hits:
}
function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: ProjectWhitelistEntry[];
preview: Preview; onWhitelistChanged: (entries: ProjectWhitelistEntry[]) => void }) {
preview: Preview; fileSelectionChanged: boolean;
onWhitelistChanged: (entries: ProjectWhitelistEntry[]) => void }) {
const groups = useMemo(() => groupReviewHits(props.preview.hits), [props.preview.hits]);
const [selectedGroups, setSelectedGroups] = useState<Set<string>>(() => new Set(groups.map((group) => group.key)));
const [stage, setStage] = useState<"selection" | "merge">("selection");
const [personMerges, setPersonMerges] = useState<Record<string, string>>({});
const [busy, setBusy] = useState(false);
const [completed, setCompleted] = useState<{ directory: string; inPlace: boolean; files: number } | null>(null);
const [completed, setCompleted] = useState<{ directory: string; inPlace: boolean; files: number;
replaced: number } | null>(null);
const accepted = useMemo(() => new Set(groups.filter((group) => selectedGroups.has(group.key))
.flatMap((group) => group.hits.map((hit) => hit.id))), [groups, selectedGroups]);
const selectedOccurrences = accepted.size;
@@ -274,7 +276,7 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje
});
}
async function apply(inPlace = true) {
if (!props.preview.drafts.length && !accepted.size) {
if (!props.preview.drafts.length && !accepted.size && !props.fileSelectionChanged) {
try {
const rejected = groups.map((group) => ({ type: group.type, original: group.original }));
if (rejected.length) {
@@ -340,7 +342,9 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje
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);
// A prior copy-only run did not change the source files. Switching to in-place
// must install its reviewed outputs even when their names are unchanged.
if (file.source !== file.output || (inPlace && !props.preview.sourceInPlace)) replacements.push(file);
}
for (const draft of props.preview.drafts) {
const data = await fs.readFile(draft.file.absPath);
@@ -377,7 +381,7 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje
await saveRun(directory, run);
persisted = true;
if (inPlace) {
await replaceProjectFilesInPlace(props.root, directory, replacements);
if (replacements.length) await replaceProjectFilesInPlace(props.root, directory, replacements);
run.inPlace = true;
await saveRun(directory, run);
}
@@ -391,10 +395,13 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje
props.onWhitelistChanged(await loadProjectWhitelist(props.root));
}
toast.style = Toast.Style.Success;
toast.title = inPlace ? `${replacements.length} Dateien ersetzt` : `${run.files.length} Kopien erstellt`;
toast.message = inPlace ? "Die Sicherung ist im Raycast-Datenordner gespeichert."
toast.title = inPlace ? (replacements.length ? `${replacements.length} Dateien ersetzt` : "Dateiauswahl aktualisiert")
: `${run.files.length} Kopien erstellt`;
toast.message = inPlace && replacements.length ? "Die Sicherung ist im Raycast-Datenordner gespeichert."
: inPlace ? "Ausgeschlossene Dateien wurden im neuen Projektstand weggelassen."
: "Die Kopien liegen neben dem Projektordner.";
setCompleted({ directory: inPlace ? join(directory, "backup") : publishedCopyPath!, inPlace, files: run.files.length });
setCompleted({ directory: inPlace && replacements.length ? join(directory, "backup")
: inPlace ? props.root : publishedCopyPath!, inPlace, files: run.files.length, replaced: replacements.length });
await showInFinder(inPlace ? props.root : publishedCopyPath!).catch(() => undefined);
} catch (error) {
if (directory && !persisted) await fs.rm(directory, { recursive: true, force: true });
@@ -407,11 +414,14 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje
if (completed) return <List navigationTitle="Pseudonymisierung abgeschlossen">
<List.Item icon={Icon.CheckCircle}
title={completed.inPlace ? "Projektdateien ersetzt" : `${completed.files} pseudonymisierte Kopien erstellt`}
subtitle={completed.inPlace ? "Die Originale wurden gesichert."
title={completed.inPlace ? (completed.replaced ? "Projektdateien ersetzt" : "Dateiauswahl aktualisiert")
: `${completed.files} pseudonymisierte Kopien erstellt`}
subtitle={completed.inPlace ? (completed.replaced ? "Die Originale wurden gesichert."
: "Der neue Projektstand enthält nur die ausgewählten Dateien.")
: completed.directory}
actions={<ActionPanel>
<Action title={completed.inPlace ? "Sicherung im Finder anzeigen" : "Kopien im Finder anzeigen"}
<Action title={completed.inPlace ? (completed.replaced ? "Sicherung im Finder anzeigen" : "Projekt im Finder anzeigen")
: "Kopien im Finder anzeigen"}
icon={Icon.Folder} onAction={() => showInFinder(completed.directory)} />
<Action.CopyToClipboard title="Speicherpfad kopieren" content={completed.directory} />
</ActionPanel>} />
@@ -523,6 +533,100 @@ function SkippedFiles(props: { files: SkippedProjectFile[] }) {
</List>;
}
function FileSelection(props: { root: string; files: ProjectFile[]; skipped: SkippedProjectFile[];
excluded: string[]; rules: ProjectRule[]; types: EntityType[]; reanalyzeUnchanged: boolean;
onWhitelistChanged: (entries: ProjectWhitelistEntry[]) => void }) {
const { push } = useNavigation();
const [selected, setSelected] = useState<Set<string>>(() => new Set(
withoutExcludedProjectFiles(props.files, props.excluded).map((file) => file.relPath)));
const [busy, setBusy] = useState(false);
const byFolder = useMemo(() => {
const folders = new Map<string, ProjectFile[]>();
for (const file of props.files) {
const folder = dirname(file.relPath);
(folders.get(folder) ?? (folders.set(folder, []), folders.get(folder)!)).push(file);
}
return folders;
}, [props.files]);
function toggle(path: string) {
setSelected((current) => {
const next = new Set(current);
if (next.has(path)) next.delete(path);
else next.add(path);
return next;
});
}
async function continueToHits() {
if (!selected.size) {
await showToast({ style: Toast.Style.Failure, title: "Bitte mindestens eine Datei auswählen" });
return;
}
setBusy(true);
const toast = await showToast({ style: Toast.Style.Animated, title: "Dateiauswahl wird gespeichert" });
try {
const visiblePaths = new Set(props.files.map((file) => file.relPath));
const excluded = [
...props.excluded.filter((path) => !visiblePaths.has(path)),
...props.files.filter((file) => !selected.has(file.relPath)).map((file) => file.relPath),
];
const previous = new Set(props.excluded);
const fileSelectionChanged = props.files.some((file) => previous.has(file.relPath) === selected.has(file.relPath));
await saveProjectFileExclusions(props.root, excluded);
const files = props.files.filter((file) => selected.has(file.relPath));
const skipped = [...props.skipped, ...props.files.filter((file) => !selected.has(file.relPath))
.map((file) => ({ path: file.relPath, reason: "Für dieses Projekt abgewählt" }))];
const whitelist = await loadProjectWhitelist(props.root);
const preview = await prepare(props.root, files, props.rules, whitelist, props.types, skipped,
props.reanalyzeUnchanged, (message) => { toast.title = message; });
if (!preview.drafts.length && !preview.hits.length && !fileSelectionChanged) {
toast.style = Toast.Style.Success;
toast.title = "Alle ausgewählten Projektdateien unverändert";
toast.message = `${preview.retained.length} Dateien aus dem letzten Stand übernommen. Keine erneute Analyse nötig.`;
return;
}
toast.style = Toast.Style.Success;
toast.title = `${groupReviewHits(preview.hits).length} Zuordnungen zur Prüfung`;
push(<HitReview root={props.root} rules={props.rules} whitelist={whitelist} preview={preview}
fileSelectionChanged={fileSelectionChanged} onWhitelistChanged={props.onWhitelistChanged} />);
} catch (error) {
toast.style = Toast.Style.Failure;
toast.title = "Analyse fehlgeschlagen";
toast.message = (error as Error).message;
} finally { setBusy(false); }
}
return <List isLoading={busy} navigationTitle="Projektdateien auswählen"
searchBarPlaceholder="Datei oder Ordner suchen">
<List.Section title="Auswahl">
<List.Item icon={Icon.ArrowRight} title="Dateiauswahl bestätigen und Treffer prüfen"
subtitle={`${selected.size} von ${props.files.length} Dateien ausgewählt · ${props.files.length - selected.size} für dieses Projekt ausgeschlossen`}
actions={<ActionPanel>
<Action title="Treffer prüfen" icon={Icon.ArrowRight} onAction={continueToHits} />
<Action title="Alle Dateien auswählen" onAction={() => setSelected(new Set(props.files.map((file) => file.relPath)))} />
<Action title="Alle Dateien abwählen" onAction={() => setSelected(new Set())} />
</ActionPanel>} />
</List.Section>
{props.skipped.length > 0 && <List.Section title="Nicht auswählbar">
<List.Item icon={Icon.ExclamationMark} title={`${props.skipped.length} Dateien oder Ordner nicht verarbeitet`}
actions={<ActionPanel><Action.Push title="Gründe anzeigen"
target={<SkippedFiles files={props.skipped} />} /></ActionPanel>} />
</List.Section>}
{[...byFolder].map(([folder, files]) => <List.Section key={folder}
title={`${folder === "." ? "Projektordner" : folder} · ${files.filter((file) => selected.has(file.relPath)).length}/${files.length}`}>
{files.map((file) => <List.Item key={file.relPath}
icon={{ source: selected.has(file.relPath) ? Icon.CheckCircle : Icon.Circle,
tintColor: selected.has(file.relPath) ? Color.Green : Color.SecondaryText }}
title={basename(file.relPath)} subtitle={folder === "." ? undefined : file.relPath}
accessories={[{ text: file.kind === "document" ? "Dokument" : "Textdatei" }]}
actions={<ActionPanel>
<Action title={selected.has(file.relPath) ? "Datei ausschließen" : "Datei auswählen"}
onAction={() => toggle(file.relPath)} />
<Action title="Treffer prüfen" icon={Icon.ArrowRight} onAction={continueToHits} />
<Action title="Alle Dateien auswählen" onAction={() => setSelected(new Set(props.files.map((item) => item.relPath)))} />
</ActionPanel>} />)}
</List.Section>)}
</List>;
}
export default function Command() {
const { push } = useNavigation();
const [root, setRoot] = useState("");
@@ -610,20 +714,11 @@ export default function Command() {
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;
}
const excluded = await loadProjectFileExclusions(root);
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}
toast.title = `${scan.files.length} Dateien zur Auswahl`;
push(<FileSelection root={root} files={scan.files} skipped={scan.skipped} excluded={excluded}
rules={parsed} types={selectedTypes} reanalyzeUnchanged={reanalyzeUnchanged}
onWhitelistChanged={setWhitelist} />);
} catch (error) {
toast.style = Toast.Style.Failure;
@@ -638,7 +733,7 @@ export default function Command() {
message: "Bitte den Ordner im Finder öffnen oder unten manuell auswählen." });
}
return <Form isLoading={busy} actions={<ActionPanel>
<Action title={existingRuns ? "Bestehendes Projekt erneut prüfen" : "Zuordnungen prüfen"} onAction={next} />
<Action title="Projektdateien auswählen" onAction={next} />
<Action title="Geöffneten Finder-Ordner übernehmen" icon={Icon.Folder} onAction={useFinderFolder} />
<Action.Push title="Projekt-Whitelist bearbeiten" icon={Icon.List}
target={<ProjectWhitelist entries={whitelist} onRemove={removeFromWhitelist} />} />
@@ -661,6 +756,6 @@ export default function Command() {
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.Description title="Ablauf" text="Dateien und Kategorien wählen, Zuordnungen prüfen und Personen bei Bedarf zusammenfassen. Abgewählte Dateien bleiben für diesen Projektordner ausgeschlossen. Standardmäßig werden die Originaldateien nach Bestätigung ersetzt; Kopien sind als Alternative verfügbar." />
</Form>;
}

View File

@@ -103,6 +103,35 @@ describe("Velum-Projektstände", () => {
expect(await project.loadProjectEntityTypes(other, support)).toBeNull();
});
it("behält abgewählte Dateien pro Projekt und gibt sie nicht an die Analyse weiter", async () => {
const root = await fs.mkdtemp(join(tmpdir(), "velum-file-selection-test-"));
roots.push(root);
const source = join(root, "Quelle");
const other = join(root, "Anderes Projekt");
const support = join(root, "Raycast");
await fs.mkdir(join(source, "Unterordner"), { recursive: true });
await fs.mkdir(other);
await fs.writeFile(join(source, "Behalten.txt"), "Künstlicher Testtext");
await fs.writeFile(join(source, "Unterordner", "Auslassen.md"), "Künstlicher Testtext");
expect(await project.loadProjectFileExclusions(source, support)).toEqual([]);
await project.saveProjectFileExclusions(`${source}/`, ["Unterordner/Auslassen.md", "Unterordner/Auslassen.md"], support);
expect(await project.loadProjectFileExclusions(source, support)).toEqual(["Unterordner/Auslassen.md"]);
expect(await project.loadProjectFileExclusions(other, support)).toEqual([]);
const scan = await project.scanProjectFiles(source, undefined, false);
const chosen = project.withoutExcludedProjectFiles(scan.files, await project.loadProjectFileExclusions(source, support));
expect(chosen.map((file) => file.relPath)).toEqual(["Behalten.txt"]);
const run = await project.createRun(source, support);
await fs.writeFile(join(run.directory, "files", "Behalten.txt"), "PERSON_01");
await project.replaceProjectFilesInPlace(source, run.directory,
chosen.map((file) => ({ source: file.relPath, output: file.relPath, kind: file.kind })));
expect(await fs.readFile(join(source, "Behalten.txt"), "utf8")).toBe("PERSON_01");
expect(await fs.readFile(join(source, "Unterordner", "Auslassen.md"), "utf8"))
.toBe("Künstlicher Testtext");
await expect(project.saveProjectFileExclusions(source, ["../Anderes Projekt/Datei.txt"], support))
.rejects.toThrow("Ungültiger Dateipfad");
});
it("überspringt temporäre und falsch benannte Office-Dateien vor der API-Analyse", async () => {
const root = await fs.mkdtemp(join(tmpdir(), "velum-office-scan-test-"));
roots.push(root);