forked from r.muellner/velum-raycast
fix: skip unreadable Office files during project review
This commit is contained in:
@@ -12,6 +12,7 @@ export type { ProjectWhitelistEntry } from "./project-whitelist";
|
||||
|
||||
export type ProjectRule = { type: "BEGRIFF" | "PERSON" | "ORG" | "ORT" | "FIRMA" | "KUNDE"; value: string };
|
||||
export type ProjectFile = { relPath: string; absPath: string; kind: "text" | "document"; size: number };
|
||||
export type SkippedProjectFile = { path: string; reason: string };
|
||||
export type RunFile = { source: string; output: string; kind: ProjectFile["kind"] };
|
||||
export type ProjectRun = {
|
||||
version: 2;
|
||||
@@ -61,6 +62,15 @@ async function isBinary(path: string): Promise<boolean> {
|
||||
} finally { await file.close(); }
|
||||
}
|
||||
|
||||
async function isOfficeArchive(path: string): Promise<boolean> {
|
||||
const file = await fs.open(path, "r");
|
||||
try {
|
||||
const header = Buffer.alloc(4);
|
||||
const { bytesRead } = await file.read(header, 0, header.length, 0);
|
||||
return bytesRead === 4 && header.equals(Buffer.from([0x50, 0x4b, 0x03, 0x04]));
|
||||
} finally { await file.close(); }
|
||||
}
|
||||
|
||||
export function projectDataRoot(projectPath: string, support = environment.supportPath): string {
|
||||
return join(support, "velum-projects", projectIdFor(projectPath));
|
||||
}
|
||||
@@ -176,32 +186,41 @@ export function forceMasks(rules: ProjectRule[]): Record<string, string[]> {
|
||||
}
|
||||
|
||||
export async function scanProjectFiles(root: string, maxSize = 20 * 1024 * 1024): Promise<{
|
||||
files: ProjectFile[]; skipped: string[];
|
||||
files: ProjectFile[]; skipped: SkippedProjectFile[];
|
||||
}> {
|
||||
const files: ProjectFile[] = [];
|
||||
const skipped: string[] = [];
|
||||
const skipped: SkippedProjectFile[] = [];
|
||||
const skip = (path: string, reason: string) => skipped.push({ path, reason });
|
||||
async function walk(directory: string): Promise<void> {
|
||||
for (const entry of await fs.readdir(directory, { withFileTypes: true })) {
|
||||
const path = join(directory, entry.name);
|
||||
const relPath = relative(root, path).split(sep).join("/");
|
||||
if (entry.isSymbolicLink()) { skipped.push(relPath); continue; }
|
||||
if (entry.isSymbolicLink()) { skip(relPath, "Symbolischer Link"); continue; }
|
||||
if (entry.isDirectory()) {
|
||||
if (EXCLUDES.has(entry.name)) { skipped.push(relPath); continue; }
|
||||
if (EXCLUDES.has(entry.name)) { skip(relPath, "Ausgeschlossener Ordner"); continue; }
|
||||
await walk(path);
|
||||
continue;
|
||||
}
|
||||
if (!entry.isFile()) continue;
|
||||
if (entry.name.startsWith("~$") || entry.name.startsWith("._")) {
|
||||
skip(relPath, "Temporäre Office-/macOS-Datei");
|
||||
continue;
|
||||
}
|
||||
if (entry.name === ".env" || entry.name.startsWith(".env.") || SECRET_EXTENSIONS.has(extname(entry.name).toLowerCase())) {
|
||||
skipped.push(relPath);
|
||||
skip(relPath, "Vertraulicher Dateityp");
|
||||
continue;
|
||||
}
|
||||
const stat = await fs.stat(path);
|
||||
if (stat.size > maxSize) { skipped.push(relPath); continue; }
|
||||
if (stat.size > maxSize) { skip(relPath, "Datei zu groß"); continue; }
|
||||
const kind = DOCUMENTS.has(extname(path).toLowerCase()) ? "document" : "text";
|
||||
if (kind === "document" && extname(path).toLowerCase() !== ".pdf" && !(await isOfficeArchive(path))) {
|
||||
skip(relPath, "Kein lesbares Office-ZIP-Archiv (beschädigt, verschlüsselt oder falsche Endung)");
|
||||
continue;
|
||||
}
|
||||
if (kind === "text") {
|
||||
if (await isBinary(path)) { skipped.push(relPath); continue; }
|
||||
if (await isBinary(path)) { skip(relPath, "Binärdatei"); continue; }
|
||||
try { new TextDecoder("utf-8", { fatal: true }).decode(await fs.readFile(path)); }
|
||||
catch { skipped.push(relPath); continue; }
|
||||
catch { skip(relPath, "Keine gültige UTF-8-Textdatei"); continue; }
|
||||
}
|
||||
files.push({ relPath, absPath: path, kind, size: stat.size });
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
loadProjectWhitelist, matchesPreviousOutput, replaceProjectFilesInPlace, resolveWithin, safeRelativePath, saveProjectRules,
|
||||
saveProjectEntityTypes, saveProjectWhitelist, saveRun, scanProjectFiles, toUtf16Offsets, whitelistKey,
|
||||
} from "./lib/velum-project";
|
||||
import type { ProjectFile, ProjectRule, ProjectWhitelistEntry, RunFile } from "./lib/velum-project";
|
||||
import type { ProjectFile, ProjectRule, ProjectWhitelistEntry, RunFile, SkippedProjectFile } from "./lib/velum-project";
|
||||
import {
|
||||
canonicalPerson, filenameScanText, groupReviewHits, makeTextBatches, mappingForSelection, mergePeople, spansBySegment,
|
||||
withoutPlaceholderHits, withoutWhitelistedHits, withoutWhitelistedRules,
|
||||
@@ -30,7 +30,7 @@ type PathDraft = { key: string; value: string; hits: Hit[] };
|
||||
type Preview = { drafts: Draft[]; retained: Array<{ file: ProjectFile; hash: string }>;
|
||||
paths: PathDraft[]; mapping: PlaceholderMapping; previousMapping: PlaceholderMapping;
|
||||
matchModes?: Record<string, "token" | "anywhere">; hits: Hit[]; entityTypes: EntityType[];
|
||||
skipped: number; sourceInPlace: boolean };
|
||||
skipped: SkippedProjectFile[]; sourceInPlace: boolean };
|
||||
|
||||
const typeLabels: Record<string, string> = {
|
||||
PERSON: "Personen", ORT: "Orte", ORG: "Organisationen", FIRMA: "Firmen",
|
||||
@@ -66,6 +66,12 @@ function textFromBytes(data: Buffer): string {
|
||||
return new TextDecoder("utf-8", { fatal: true }).decode(data);
|
||||
}
|
||||
|
||||
function isUnreadableDocument(error: unknown): boolean {
|
||||
const message = error instanceof Error ? error.message : "";
|
||||
return /request failed: 422\b/i.test(message)
|
||||
&& /konnte nicht gelesen werden|not a zip file|BadZipFile/i.test(message);
|
||||
}
|
||||
|
||||
function contentHits(file: ProjectFile, spans: Array<{
|
||||
start: number; end: number; type: string; score: number; placeholder: string; original: string;
|
||||
}>, text: string): Hit[] {
|
||||
@@ -96,7 +102,7 @@ function pathSegments(files: ProjectFile[]): PathDraft[] {
|
||||
}
|
||||
|
||||
async function prepare(root: string, files: ProjectFile[], rules: ProjectRule[], whitelist: ProjectWhitelistEntry[], entityTypes: EntityType[],
|
||||
skipped: number, onProgress: (message: string) => void): Promise<Preview> {
|
||||
skipped: SkippedProjectFile[], onProgress: (message: string) => void): Promise<Preview> {
|
||||
await requireProjectCapabilities();
|
||||
const masks = forceMasks(withoutWhitelistedRules(rules, whitelist));
|
||||
const latestEntry = (await listRuns(root))[0];
|
||||
@@ -150,13 +156,27 @@ async function prepare(root: string, files: ProjectFile[], rules: ProjectRule[],
|
||||
for (const [index, draft] of documents.entries()) {
|
||||
onProgress(`Dokumente analysieren: ${index + 1}/${documents.length}`);
|
||||
const data = await fs.readFile(draft.file.absPath);
|
||||
const result = await pseudonymizeDocument(basename(draft.file.relPath), data, mapping, masks, undefined, entityTypes);
|
||||
mapping = result.mapping;
|
||||
addHits(draft, documentHits(draft.file, result.hits));
|
||||
try {
|
||||
const result = await pseudonymizeDocument(basename(draft.file.relPath), data, mapping, masks, undefined, entityTypes);
|
||||
mapping = result.mapping;
|
||||
addHits(draft, documentHits(draft.file, result.hits));
|
||||
} catch (error) {
|
||||
if (!isUnreadableDocument(error)) {
|
||||
throw new Error(`${draft.file.relPath}: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
skipped.push({ path: draft.file.relPath, reason: "Office-/PDF-Inhalt konnte nicht gelesen werden" });
|
||||
drafts.splice(drafts.indexOf(draft), 1);
|
||||
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 paths = pathSegments(files);
|
||||
const eligibleFiles = [...drafts.map((draft) => draft.file), ...retained.map((item) => item.file)];
|
||||
if (!eligibleFiles.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 knownTerms = [...Object.keys(mapping), ...Object.values(mapping).map((entry) => entry.original),
|
||||
...withoutWhitelistedRules(rules, whitelist).map((rule) => rule.value)];
|
||||
const pathBatches = makeTextBatches(paths.map((path) => ({
|
||||
@@ -427,12 +447,19 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje
|
||||
<List.Section title="Abschluss">
|
||||
<List.Item key="apply" icon={Icon.Play}
|
||||
title={`${selectedGroups.size} von ${groups.length} Zuordnungen ausgewählt`}
|
||||
subtitle={`${selectedOccurrences} Vorkommen · ${props.preview.drafts.length} neue/geänderte Dateien · ${props.preview.retained.length} unverändert · ${props.preview.skipped} übersprungen`}
|
||||
subtitle={`${selectedOccurrences} Vorkommen · ${props.preview.drafts.length} neue/geänderte Dateien · ${props.preview.retained.length} unverändert · ${props.preview.skipped.length} übersprungen`}
|
||||
actions={<ActionPanel>
|
||||
<Action title="Auswahl abschließen und Personen prüfen" icon={Icon.ArrowRight}
|
||||
onAction={() => setStage("merge")} />
|
||||
</ActionPanel>} />
|
||||
</List.Section>
|
||||
{props.preview.skipped.length > 0 && <List.Section title="Nicht verarbeitet">
|
||||
<List.Item key="skipped" icon={Icon.ExclamationMark}
|
||||
title={`${props.preview.skipped.length} Dateien oder Ordner übersprungen`}
|
||||
subtitle="Ansehen, bevor du die Auswahl anwendest"
|
||||
actions={<ActionPanel><Action.Push title="Übersprungene Dateien anzeigen"
|
||||
target={<SkippedFiles files={props.preview.skipped} />} /></ActionPanel>} />
|
||||
</List.Section>}
|
||||
{[...byType].map(([type, entries]) => <List.Section key={type}
|
||||
title={`${labelForType(type)} · ${entries.filter((entry) => selectedGroups.has(entry.key)).length}/${entries.length}`}>
|
||||
{entries.map((group) => <List.Item key={group.key}
|
||||
@@ -475,6 +502,14 @@ function ProjectWhitelist(props: { entries: ProjectWhitelistEntry[]; onRemove: (
|
||||
</List>;
|
||||
}
|
||||
|
||||
function SkippedFiles(props: { files: SkippedProjectFile[] }) {
|
||||
return <List navigationTitle="Übersprungene Dateien" searchBarPlaceholder="Datei suchen">
|
||||
<List.Section title={`${props.files.length} nicht verarbeitet`}>
|
||||
{props.files.map((file) => <List.Item key={file.path} title={file.path} subtitle={file.reason} />)}
|
||||
</List.Section>
|
||||
</List>;
|
||||
}
|
||||
|
||||
export default function Command() {
|
||||
const { push } = useNavigation();
|
||||
const [root, setRoot] = useState("");
|
||||
@@ -556,9 +591,12 @@ export default function Command() {
|
||||
await saveProjectRules(root, parsed);
|
||||
toast.title = "Dateien werden erfasst";
|
||||
const scan = await scanProjectFiles(root);
|
||||
if (!scan.files.length) throw new Error("Keine geeigneten Dateien im Projektordner gefunden.");
|
||||
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.length,
|
||||
const preview = await prepare(root, scan.files, parsed, currentWhitelist, selectedTypes, scan.skipped,
|
||||
(message) => { toast.title = message; });
|
||||
toast.style = Toast.Style.Success;
|
||||
toast.title = `${groupReviewHits(preview.hits).length} Zuordnungen zur Prüfung`;
|
||||
|
||||
@@ -99,6 +99,24 @@ describe("Velum-Projektstände", () => {
|
||||
expect(await project.loadProjectEntityTypes(other, support)).toBeNull();
|
||||
});
|
||||
|
||||
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);
|
||||
await fs.writeFile(join(root, "Notiz.txt"), "Nur ein künstlicher Testtext");
|
||||
await fs.writeFile(join(root, "Bericht.xlsx"), "Kein Excel-Archiv");
|
||||
await fs.writeFile(join(root, "~$Entwurf.xlsx"), "Sperrdatei");
|
||||
await fs.writeFile(join(root, "._Tabelle.xlsx"), "AppleDouble");
|
||||
await fs.writeFile(join(root, "Gültig.xlsx"), Buffer.from([0x50, 0x4b, 0x03, 0x04, 0x00]));
|
||||
|
||||
const scan = await project.scanProjectFiles(root);
|
||||
expect(scan.files.map((file) => file.relPath)).toEqual(["Gültig.xlsx", "Notiz.txt"]);
|
||||
expect(scan.skipped).toEqual(expect.arrayContaining([
|
||||
{ path: "Bericht.xlsx", reason: expect.stringContaining("Office-ZIP-Archiv") },
|
||||
{ path: "~$Entwurf.xlsx", reason: "Temporäre Office-/macOS-Datei" },
|
||||
{ path: "._Tabelle.xlsx", reason: "Temporäre Office-/macOS-Datei" },
|
||||
]));
|
||||
});
|
||||
|
||||
it("stellt aktuelle In-Place-Dateien aus dem Projektordner und frühere Stände aus dem Snapshot bereit", async () => {
|
||||
const root = await fs.mkdtemp(join(tmpdir(), "velum-current-source-test-"));
|
||||
roots.push(root);
|
||||
|
||||
Reference in New Issue
Block a user