diff --git a/src/lib/project-relocation.ts b/src/lib/project-relocation.ts new file mode 100644 index 0000000..f577210 --- /dev/null +++ b/src/lib/project-relocation.ts @@ -0,0 +1,83 @@ +import { promises as fs } from "node:fs"; +import { basename, dirname, join } from "node:path"; +import { environment } from "@raycast/api"; +import { canonicalProjectPath, listRuns, projectDataRoot, saveRun } from "./velum-project"; +import type { ProjectRun } from "./velum-project"; + +export type RelocationResult = { runsMoved: number; copiesRelinked: number; copiesMissing: number }; + +async function isDirectory(path: string): Promise { + try { return (await fs.stat(path)).isDirectory(); } + catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return false; + throw error; + } +} + +async function exists(path: string): Promise { + try { await fs.lstat(path); return true; } + catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return false; + throw error; + } +} + +async function relocatedCopyPath(run: ProjectRun, newProjectPath: string): Promise { + if (!run.copyPath || await isDirectory(run.copyPath)) return run.copyPath; + const parent = dirname(newProjectPath); + const candidates = [ + join(parent, basename(run.copyPath)), + join(parent, `${basename(newProjectPath)}-Velum-${run.id}`), + ]; + for (const candidate of candidates) if (await isDirectory(candidate)) return candidate; + return run.copyPath; +} + +/** Change the path identity of a project, preserving every saved run and its private rules. */ +export async function relocateProject(oldPath: string, chosenPath: string, + support = environment.supportPath): Promise { + const previous = canonicalProjectPath(oldPath); + const next = canonicalProjectPath(chosenPath); + if (previous === next) throw new Error("Der neue Ordner ist bereits der Projektordner."); + if (!await isDirectory(next)) throw new Error("Der neue Projektordner ist nicht vorhanden."); + const sourceRoot = projectDataRoot(previous, support); + const targetRoot = projectDataRoot(next, support); + if (await exists(targetRoot)) { + throw new Error("Für diesen Ordner gibt es bereits ein Velum-Projekt. Die Projekte wurden nicht zusammengeführt."); + } + const runs = await listRuns(previous, support); + if (!runs.length) throw new Error("Für den bisherigen Ordner gibt es keinen gespeicherten Projektstand."); + const originals = await Promise.all(runs.map(async ({ directory }) => + await fs.readFile(join(directory, "run.json"), "utf8"))); + const updated = await Promise.all(runs.map(async ({ run }) => ({ + ...run, + projectPath: next, + projectName: basename(next), + copyPath: await relocatedCopyPath(run, next), + }))); + const copyExists = await Promise.all(updated.map(async (run) => + !run.copyPath || await isDirectory(run.copyPath))); + await fs.rename(sourceRoot, targetRoot); + try { + for (let index = 0; index < runs.length; index++) { + await saveRun(join(targetRoot, "runs", basename(runs[index].directory)), updated[index]); + } + } catch (error) { + try { + for (let index = 0; index < runs.length; index++) { + await fs.writeFile(join(targetRoot, "runs", basename(runs[index].directory), "run.json"), + originals[index], { encoding: "utf8", mode: 0o600 }); + } + await fs.rename(targetRoot, sourceRoot); + } catch (rollbackError) { + throw new Error(`Projektpfad konnte nicht vollständig aktualisiert werden: ${(error as Error).message}. ` + + `Bitte die Projektstände prüfen; Rücksetzung fehlgeschlagen: ${(rollbackError as Error).message}`); + } + throw error; + } + return { + runsMoved: runs.length, + copiesRelinked: updated.filter((run, index) => run.copyPath !== runs[index].run.copyPath).length, + copiesMissing: copyExists.filter((available) => !available).length, + }; +} diff --git a/src/pseudonymize-project-files.tsx b/src/pseudonymize-project-files.tsx index f372f74..2e52689 100644 --- a/src/pseudonymize-project-files.tsx +++ b/src/pseudonymize-project-files.tsx @@ -770,7 +770,7 @@ export default function Command() { onChange={(paths) => setRoot(paths[0] ?? "")} /> + : "Neues Projekt. Falls dieser Ordner aus einem bestehenden Projekt verschoben wurde, aktualisiere zuerst dessen Pfad über „Projektdateien wiederherstellen“ → „Projektordner ändern“."} /> diff --git a/src/restore-project-files.tsx b/src/restore-project-files.tsx index cad01c8..6bfc07f 100644 --- a/src/restore-project-files.tsx +++ b/src/restore-project-files.tsx @@ -15,6 +15,7 @@ import { releaseProjectMapping } from "./project-mapping-actions"; import { projectMappingCreatedAt } from "./lib/mapping-created-at"; import { listRestorableFolders, selectRestorableFolder } from "./lib/restore-file-selection"; import type { RestorableFolder } from "./lib/restore-file-selection"; +import { relocateProject } from "./lib/project-relocation"; type SavedRun = { run: ProjectRun; directory: string }; type RestoreDecision = MappingEntry | null; @@ -428,6 +429,48 @@ function ProjectHistory(props: { projectName: string; entries: SavedRun[] }) { ; } +function RelocateProjectForm(props: { projectName: string; oldPath: string; onMoved: () => Promise }) { + const { pop } = useNavigation(); + const [busy, setBusy] = useState(false); + async function save(values: { newPath: string[] }) { + const newPath = values.newPath[0]; + if (!newPath) { + await showToast({ style: Toast.Style.Failure, title: "Bitte den neuen Projektordner wählen" }); + return; + } + if (!(await confirmAlert({ + title: "Projektordner aktualisieren?", + message: `Alle gespeicherten Projektstände und Regeln werden künftig ${newPath} zugeordnet. ` + + `Bisheriger Pfad: ${props.oldPath}. Die Dateien im gewählten Ordner werden nicht verändert.`, + primaryAction: { title: "Projektpfad aktualisieren" }, + }))) return; + setBusy(true); + const toast = await showToast({ style: Toast.Style.Animated, title: "Projektpfad wird aktualisiert" }); + try { + const result = await relocateProject(props.oldPath, newPath); + await props.onMoved(); + toast.style = Toast.Style.Success; + toast.title = "Projektordner aktualisiert"; + toast.message = `${result.runsMoved} Projektstände übernommen` + + (result.copiesRelinked ? ` · ${result.copiesRelinked} Kopienordner neu gefunden` : "") + + (result.copiesMissing ? ` · ${result.copiesMissing} Kopienordner nicht gefunden; gespeicherte Stände bleiben verfügbar` : ""); + pop(); + } catch (error) { + toast.style = Toast.Style.Failure; + toast.title = "Projektpfad nicht aktualisiert"; + toast.message = (error as Error).message; + } finally { setBusy(false); } + } + return
}> + + + + ; +} + export default function Command() { const { push } = useNavigation(); const [runs, setRuns] = useState([]); @@ -510,6 +553,9 @@ export default function Command() { push()} /> + push()} /> {Object.values(run.mapping).some((entry) => entry.type === "PERSON" && entry.merged_into) && repairMergedPeople({ run, directory })} />} diff --git a/tests/velum-project.test.ts b/tests/velum-project.test.ts index 231e8c6..9453536 100644 --- a/tests/velum-project.test.ts +++ b/tests/velum-project.test.ts @@ -10,6 +10,7 @@ mock.module("@raycast/api", () => ({ environment: { supportPath: tmpdir() }, const project = await import("../src/lib/velum-project"); const { mappingForRestoration } = await import("../src/lib/mapping-groups"); const { mergeMappingGroups } = await import("../src/lib/mapping-groups"); +const { relocateProject } = await import("../src/lib/project-relocation"); const roots: string[] = []; afterEach(async () => { await Promise.all(roots.splice(0).map((root) => fs.rm(root, { recursive: true, force: true }))); }); @@ -57,6 +58,74 @@ describe("Velum-Projektstände", () => { .toEqual([first.run.id, second.run.id].sort()); }); + it("übernimmt nach einem Umzug alle Projektstände, Regeln und verschobenen Kopien", async () => { + const root = await fs.mkdtemp(join(tmpdir(), "velum-relocate-test-")); + roots.push(root); + const oldParent = join(root, "Alt"); + const newParent = join(root, "Neu"); + const oldPath = join(oldParent, "Projekt"); + const newPath = join(newParent, "Projekt"); + const support = join(root, "Raycast"); + await fs.mkdir(oldPath, { recursive: true }); + await fs.writeFile(join(oldPath, "Notiz.txt"), "PERSON_01"); + await project.saveProjectRules(oldPath, [{ type: "BEGRIFF", value: "Testsystem" }], support); + await project.saveProjectWhitelist(oldPath, [{ type: "PERSON", original: "Kein Name" }], support); + await project.saveProjectEntityTypes(oldPath, ["PERSON", "ORG"], support); + await project.saveProjectFileExclusions(oldPath, ["Ausnahme.txt"], support); + const first = await project.createRun(oldPath, support); + first.run.mapping = { PERSON_01: { original: "Erika Beispiel", type: "PERSON" } }; + first.run.files = [{ source: "Notiz.txt", output: "Notiz.txt", kind: "text" }]; + first.run.inPlace = true; + await fs.writeFile(join(first.directory, "files", "Notiz.txt"), "PERSON_01"); + const oldCopy = join(oldParent, `Projekt-Velum-${first.run.id}`); + await fs.mkdir(oldCopy); + await fs.writeFile(join(oldCopy, "Notiz.txt"), "PERSON_01"); + first.run.copyPath = oldCopy; + await project.saveRun(first.directory, first.run); + const second = await project.createRun(oldPath, support); + second.run.createdAt = new Date(Date.parse(first.run.createdAt) + 1000).toISOString(); + second.run.mapping = first.run.mapping; + second.run.files = first.run.files; + second.run.inPlace = true; + await fs.writeFile(join(second.directory, "files", "Notiz.txt"), "PERSON_01"); + await project.saveRun(second.directory, second.run); + + await fs.rename(oldParent, newParent); + expect(await relocateProject(oldPath, newPath, support)) + .toEqual({ runsMoved: 2, copiesRelinked: 1, copiesMissing: 0 }); + expect(await project.listRuns(oldPath, support)).toHaveLength(0); + const moved = await project.listRuns(newPath, support); + expect(moved.map(({ run }) => run.id)).toEqual([second.run.id, first.run.id]); + expect(moved.every(({ run }) => run.projectPath === newPath && run.projectName === "Projekt")).toBe(true); + expect(moved[1].run.copyPath).toBe(join(newParent, `Projekt-Velum-${first.run.id}`)); + expect(moved[0].run.mapping).toEqual(first.run.mapping); + expect(await project.loadProjectRules(newPath, support)).toEqual([{ type: "BEGRIFF", value: "Testsystem" }]); + expect(await project.loadProjectWhitelist(newPath, support)).toEqual([{ type: "PERSON", original: "Kein Name" }]); + expect(await project.loadProjectEntityTypes(newPath, support)).toEqual(["PERSON", "ORG"]); + expect(await project.loadProjectFileExclusions(newPath, support)).toEqual(["Ausnahme.txt"]); + expect((await project.scanRestorableCopyFiles(moved[0].run, moved[0].directory)).root).toBe(newPath); + expect((await project.listAllRuns(support)).filter(({ run }) => run.projectPath === newPath)).toHaveLength(2); + }); + + it("verhindert das Umhängen auf einen bereits belegten Projektordner", async () => { + const root = await fs.mkdtemp(join(tmpdir(), "velum-relocate-conflict-test-")); + roots.push(root); + const oldPath = join(root, "Alt"); + const newPath = join(root, "Neu"); + const support = join(root, "Raycast"); + await fs.mkdir(oldPath); + await fs.mkdir(newPath); + const oldRun = await project.createRun(oldPath, support); + const targetRun = await project.createRun(newPath, support); + await project.saveRun(oldRun.directory, oldRun.run); + await project.saveRun(targetRun.directory, targetRun.run); + await expect(relocateProject(oldPath, oldPath, support)).rejects.toThrow("bereits der Projektordner"); + await expect(relocateProject(oldPath, join(root, "Fehlt"), support)).rejects.toThrow("nicht vorhanden"); + await expect(relocateProject(oldPath, newPath, support)).rejects.toThrow("bereits ein Velum-Projekt"); + expect(await project.listRuns(oldPath, support)).toHaveLength(1); + expect(await project.listRuns(newPath, support)).toHaveLength(1); + }); + it("legt pseudonymisierte Kopien neben dem Projekt ab und behält die Tabelle privat", async () => { const root = await fs.mkdtemp(join(tmpdir(), "velum-sibling-copy-test-")); roots.push(root);