Files
velum-raycast/src/lib/project-revision.ts

190 lines
9.0 KiB
TypeScript

import { promises as fs } from "node:fs";
import { basename, dirname, join } from "node:path";
import type { PlaceholderMapping } from "../types";
import { canonicalPerson } from "./project-review";
import {
createRun, digest, isRestorableDocument, listRuns, loadProjectWhitelist, publishProjectCopies,
replaceProjectFilesInPlace, resolveWithin, restorePath, restoreText,
saveProjectWhitelist, saveRun,
} from "./velum-project";
import type { ProjectRun, ProjectWhitelistEntry } from "./velum-project";
export type RevisionPlan = {
mapping: PlaceholderMapping;
replacements: PlaceholderMapping;
whitelist: ProjectWhitelistEntry[];
released: string[];
merged: string[];
};
function existingRoot(key: string, mapping: PlaceholderMapping): string {
const seen = new Set<string>();
let current = key;
while (mapping[current]?.merged_into) {
if (seen.has(current)) throw new Error("Zyklische Personen-Zuordnung.");
seen.add(current);
current = mapping[current].merged_into!;
if (!mapping[current] || mapping[current].type !== "PERSON") {
throw new Error("Personen-Zuordnung verweist auf ein ungültiges Ziel.");
}
}
return current;
}
/** Build a single direct substitution for each changed placeholder; no replacement chains. */
export function planProjectRevision(
previous: PlaceholderMapping, selectedRelease: Set<string>, requestedMerges: Record<string, string>,
): RevisionPlan {
for (const key of selectedRelease) if (!previous[key]) throw new Error(`Unbekannter Platzhalter: ${key}`);
const releasedRoots = new Set([...selectedRelease].map((key) => existingRoot(key, previous)));
const released = Object.keys(previous).filter((key) => releasedRoots.has(existingRoot(key, previous)));
const releaseSet = new Set(released);
const roots = new Set(Object.keys(previous).filter((key) =>
previous[key].type === "PERSON" && existingRoot(key, previous) === key && !releaseSet.has(key)));
const merges: Record<string, string> = {};
for (const [source, target] of Object.entries(requestedMerges)) {
if (!roots.has(source) || !roots.has(target) || source === target) {
throw new Error("Zusammenführung benötigt zwei aktive Personen.");
}
merges[source] = target;
}
for (const root of roots) {
const seen = new Set<string>();
let cursor = root;
while (merges[cursor]) {
if (seen.has(cursor)) throw new Error("Zyklische Zusammenführung.");
seen.add(cursor);
cursor = merges[cursor];
}
const final = canonicalPerson(root, merges);
if (!roots.has(final)) throw new Error("Ungültiges Ziel der Zusammenführung.");
}
const mapping: PlaceholderMapping = {};
const replacements: PlaceholderMapping = {};
const merged: string[] = [];
for (const [key, entry] of Object.entries(previous)) {
const oldRoot = entry.type === "PERSON" ? existingRoot(key, previous) : key;
if (releaseSet.has(key)) {
// A canonical placeholder can stand for several spelling variants. Its
// visible text restores to the canonical original; every variant is excluded.
replacements[key] = { original: entry.original, type: entry.type };
continue;
}
const finalRoot = entry.type === "PERSON" ? canonicalPerson(oldRoot, merges) : key;
mapping[key] = { ...entry };
if (entry.type === "PERSON") {
if (finalRoot === key) delete mapping[key].merged_into;
else mapping[key].merged_into = finalRoot;
}
if (finalRoot !== oldRoot) {
replacements[key] = { original: finalRoot, type: entry.type };
merged.push(key);
}
}
// A saved alias may still occur in older output files. Rewrite it together
// with its former canonical root when that root is merged now.
return {
mapping, replacements,
whitelist: released.map((key) => ({ type: previous[key].type, original: previous[key].original })),
released, merged,
};
}
export async function reviseProjectRun(args: {
previous: ProjectRun;
previousDirectory: string;
release: Set<string>;
merges: Record<string, string>;
rewriteDocument: (filename: string, data: Buffer, replacements: PlaceholderMapping) => Promise<Buffer>;
support?: string;
}): Promise<{ run: ProjectRun; directory: string }> {
const { previous, previousDirectory, rewriteDocument, support } = args;
const latest = (await listRuns(previous.projectPath, support))[0];
if (latest?.run.id !== previous.id) {
throw new Error("Es gibt bereits einen neueren Projektstand. Bitte die Liste aktualisieren.");
}
const plan = planProjectRevision(previous.mapping, args.release, args.merges);
if (!plan.released.length && !plan.merged.length) throw new Error("Bitte mindestens einen Begriff freigeben oder Personen zusammenführen.");
const inPlace = Boolean(previous.inPlace || previous.sourceInPlace);
const previousWhitelist = plan.whitelist.length
? await loadProjectWhitelist(previous.projectPath, support) : [];
const created = await createRun(previous.projectPath, support);
const { directory, run } = created;
run.origin = previous.origin;
run.revisedFrom = previous.id;
run.commentAuthorCoverage = previous.commentAuthorCoverage;
run.reviewAuthorCoverage = previous.reviewAuthorCoverage;
run.mapping = plan.mapping;
run.matchModes = Object.fromEntries(Object.entries(previous.matchModes ?? {})
.filter(([key]) => key in plan.mapping));
run.sourceInPlace = inPlace;
const usedPaths = new Set<string>();
const hashes = new Map<string, string>();
// "anywhere" placeholders from imported code projects can be prefixes of
// other placeholders. Match unchanged identifiers first as identity entries.
const textReplacements: PlaceholderMapping = Object.fromEntries(Object.entries(previous.mapping)
.filter(([key]) => !(key in plan.replacements))
.map(([key, entry]) => [key, { original: key, type: entry.type }]));
Object.assign(textReplacements, plan.replacements);
let replacementAttempted = false;
let whitelistChanged = false;
let publishedCopyPath: string | undefined;
try {
for (const file of previous.files) {
const source = resolveWithin(join(previousDirectory, "files"), file.output);
if (!(await fs.lstat(source)).isFile()) throw new Error(`Keine reguläre Datei im Projektstand: ${file.output}`);
const data = await fs.readFile(source);
hashes.set(file.output, digest(data));
const outputPath = restorePath(file.output, textReplacements, previous.matchModes);
if (usedPaths.has(outputPath)) throw new Error(`Doppelter Dateiname nach Änderung: ${outputPath}`);
usedPaths.add(outputPath);
const target = resolveWithin(join(directory, "files"), outputPath);
await fs.mkdir(dirname(target), { recursive: true, mode: 0o700 });
const output = file.kind === "document" && isRestorableDocument(file.output)
? await rewriteDocument(basename(file.output), data, plan.replacements)
: file.kind === "document" ? data
: Buffer.from(restoreText(data.toString("utf8"), textReplacements, previous.matchModes), "utf8");
await fs.writeFile(target, output, { flag: "wx", mode: 0o600 });
run.files.push({ source: file.output, output: outputPath, kind: file.kind });
}
if (plan.whitelist.length) {
await saveProjectWhitelist(previous.projectPath, [...previousWhitelist, ...plan.whitelist], support);
whitelistChanged = true;
}
if (inPlace) {
// The source folder must still be exactly the snapshot being revised.
// This prevents a later local edit from being silently overwritten.
for (const file of previous.files) {
const current = resolveWithin(previous.projectPath, file.output);
if (!(await fs.lstat(current)).isFile() || digest(await fs.readFile(current)) !== hashes.get(file.output)) {
throw new Error(`Projektdatei wurde seit dem letzten Stand geändert: ${file.output}`);
}
}
run.inPlace = true;
await saveRun(directory, run);
replacementAttempted = true;
await replaceProjectFilesInPlace(previous.projectPath, directory, run.files);
} else {
publishedCopyPath = await publishProjectCopies(run, directory);
run.copyPath = publishedCopyPath;
await saveRun(directory, run);
}
} catch (error) {
// Keep the backup if replacing the project folder was attempted, even when
// its own rollback reports an error.
if (!replacementAttempted) {
await fs.rm(directory, { recursive: true, force: true });
if (publishedCopyPath) await fs.rm(publishedCopyPath, { recursive: true, force: true });
} else await fs.rm(join(directory, "run.json"), { force: true });
if (whitelistChanged) {
try { await saveProjectWhitelist(previous.projectPath, previousWhitelist, support); }
catch (rollbackError) {
throw new Error(`${(error as Error).message} Die Ausnahmeliste konnte nicht zurückgesetzt werden: ${(rollbackError as Error).message}`);
}
}
if (replacementAttempted) throw new Error(`${(error as Error).message} Sicherung des vorigen Projektstands: ${directory}`);
throw error;
}
return { run, directory };
}