forked from r.muellner/velum-raycast
feat: relink moved project folders
This commit is contained in:
83
src/lib/project-relocation.ts
Normal file
83
src/lib/project-relocation.ts
Normal file
@@ -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<boolean> {
|
||||||
|
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<boolean> {
|
||||||
|
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<string | undefined> {
|
||||||
|
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<RelocationResult> {
|
||||||
|
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,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -770,7 +770,7 @@ export default function Command() {
|
|||||||
onChange={(paths) => setRoot(paths[0] ?? "")} />
|
onChange={(paths) => setRoot(paths[0] ?? "")} />
|
||||||
<Form.Description title="Projektstatus" text={existingRuns === null ? "Projektordner auswählen."
|
<Form.Description title="Projektstatus" text={existingRuns === null ? "Projektordner auswählen."
|
||||||
: existingRuns ? `Bereits angelegt · ${existingRuns} gespeicherte Stände. Ein erneuter Lauf aktualisiert dieses Projekt; es wird kein zweites angelegt.`
|
: existingRuns ? `Bereits angelegt · ${existingRuns} gespeicherte Stände. Ein erneuter Lauf aktualisiert dieses Projekt; es wird kein zweites angelegt.`
|
||||||
: "Neues Projekt. Der erste Stand wird nach der Prüfung angelegt."} />
|
: "Neues Projekt. Falls dieser Ordner aus einem bestehenden Projekt verschoben wurde, aktualisiere zuerst dessen Pfad über „Projektdateien wiederherstellen“ → „Projektordner ändern“."} />
|
||||||
<Form.TextArea id="projectRules" title="Begriffe nur für dieses Projekt" value={rules}
|
<Form.TextArea id="projectRules" title="Begriffe nur für dieses Projekt" value={rules}
|
||||||
onChange={setRules} placeholder={"BEGRIFF: KundenSuite\nPERSON: Max Mustermann"}
|
onChange={setRules} placeholder={"BEGRIFF: KundenSuite\nPERSON: Max Mustermann"}
|
||||||
info="Ein Begriff pro Zeile. Ohne Typ wird BEGRIFF verwendet. Diese Regeln werden nur für dieses Projekt gespeichert und bei der Velum-Anfrage mitgesendet." />
|
info="Ein Begriff pro Zeile. Ohne Typ wird BEGRIFF verwendet. Diese Regeln werden nur für dieses Projekt gespeichert und bei der Velum-Anfrage mitgesendet." />
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import { releaseProjectMapping } from "./project-mapping-actions";
|
|||||||
import { projectMappingCreatedAt } from "./lib/mapping-created-at";
|
import { projectMappingCreatedAt } from "./lib/mapping-created-at";
|
||||||
import { listRestorableFolders, selectRestorableFolder } from "./lib/restore-file-selection";
|
import { listRestorableFolders, selectRestorableFolder } from "./lib/restore-file-selection";
|
||||||
import type { RestorableFolder } 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 SavedRun = { run: ProjectRun; directory: string };
|
||||||
type RestoreDecision = MappingEntry | null;
|
type RestoreDecision = MappingEntry | null;
|
||||||
@@ -428,6 +429,48 @@ function ProjectHistory(props: { projectName: string; entries: SavedRun[] }) {
|
|||||||
</List>;
|
</List>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function RelocateProjectForm(props: { projectName: string; oldPath: string; onMoved: () => Promise<void> }) {
|
||||||
|
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 <Form isLoading={busy} navigationTitle={`${props.projectName}: Projektordner ändern`}
|
||||||
|
actions={<ActionPanel><Action.SubmitForm title="Projektpfad aktualisieren" icon={Icon.Folder}
|
||||||
|
onSubmit={save} /></ActionPanel>}>
|
||||||
|
<Form.Description title="Bisheriger Projektordner" text={props.oldPath} />
|
||||||
|
<Form.FilePicker id="newPath" title="Neuer Projektordner" allowMultipleSelection={false}
|
||||||
|
canChooseDirectories canChooseFiles={false} />
|
||||||
|
<Form.Description text="Gespeicherte Stände, Ausnahmen und Projektbegriffe bleiben erhalten. Dateien im neuen Ordner werden weder analysiert noch geändert." />
|
||||||
|
</Form>;
|
||||||
|
}
|
||||||
|
|
||||||
export default function Command() {
|
export default function Command() {
|
||||||
const { push } = useNavigation();
|
const { push } = useNavigation();
|
||||||
const [runs, setRuns] = useState<SavedRun[]>([]);
|
const [runs, setRuns] = useState<SavedRun[]>([]);
|
||||||
@@ -510,6 +553,9 @@ export default function Command() {
|
|||||||
<Action.CopyToClipboard title="Speicherpfad kopieren" content={runCopiesPath(run, directory)} />
|
<Action.CopyToClipboard title="Speicherpfad kopieren" content={runCopiesPath(run, directory)} />
|
||||||
<Action title="Aktuellen Stand nachbearbeiten" icon={Icon.Pencil}
|
<Action title="Aktuellen Stand nachbearbeiten" icon={Icon.Pencil}
|
||||||
onAction={() => push(<RevisionReview saved={{ run, directory }} onSaved={refresh} />)} />
|
onAction={() => push(<RevisionReview saved={{ run, directory }} onSaved={refresh} />)} />
|
||||||
|
<Action title="Projektordner ändern" icon={Icon.Folder}
|
||||||
|
onAction={() => push(<RelocateProjectForm projectName={run.projectName}
|
||||||
|
oldPath={path} onMoved={refresh} />)} />
|
||||||
{Object.values(run.mapping).some((entry) => entry.type === "PERSON" && entry.merged_into)
|
{Object.values(run.mapping).some((entry) => entry.type === "PERSON" && entry.merged_into)
|
||||||
&& <Action title="Zusammengeführte Personen in Dateien reparieren" icon={Icon.Pencil}
|
&& <Action title="Zusammengeführte Personen in Dateien reparieren" icon={Icon.Pencil}
|
||||||
onAction={() => repairMergedPeople({ run, directory })} />}
|
onAction={() => repairMergedPeople({ run, directory })} />}
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ mock.module("@raycast/api", () => ({ environment: { supportPath: tmpdir() },
|
|||||||
const project = await import("../src/lib/velum-project");
|
const project = await import("../src/lib/velum-project");
|
||||||
const { mappingForRestoration } = await import("../src/lib/mapping-groups");
|
const { mappingForRestoration } = await import("../src/lib/mapping-groups");
|
||||||
const { mergeMappingGroups } = 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[] = [];
|
const roots: string[] = [];
|
||||||
afterEach(async () => { await Promise.all(roots.splice(0).map((root) => fs.rm(root, { recursive: true, force: true }))); });
|
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());
|
.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 () => {
|
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-"));
|
const root = await fs.mkdtemp(join(tmpdir(), "velum-sibling-copy-test-"));
|
||||||
roots.push(root);
|
roots.push(root);
|
||||||
|
|||||||
Reference in New Issue
Block a user