189 lines
5.8 KiB
JavaScript
189 lines
5.8 KiB
JavaScript
import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
|
|
import path from "node:path";
|
|
import { API_DOC_SYSTEM_CONFIG } from "./config.mjs";
|
|
|
|
const MODULE_LIFECYCLE_FILE = "_module.lifecycle.json";
|
|
|
|
function formatLocalDateTime(input = new Date()) {
|
|
const date = input instanceof Date ? input : new Date(input);
|
|
const year = String(date.getFullYear());
|
|
const month = String(date.getMonth() + 1).padStart(2, "0");
|
|
const day = String(date.getDate()).padStart(2, "0");
|
|
const hours = String(date.getHours()).padStart(2, "0");
|
|
const minutes = String(date.getMinutes()).padStart(2, "0");
|
|
const seconds = String(date.getSeconds()).padStart(2, "0");
|
|
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
|
|
}
|
|
|
|
async function readJsonIfExists(filePath, fallbackValue = null) {
|
|
try {
|
|
const content = await readFile(filePath, "utf8");
|
|
return JSON.parse(content);
|
|
} catch (error) {
|
|
if (error?.code === "ENOENT") {
|
|
return fallbackValue;
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
async function writeJson(filePath, data) {
|
|
await mkdir(path.dirname(filePath), { recursive: true });
|
|
await writeFile(filePath, `${JSON.stringify(data, null, 2)}\n`, "utf8");
|
|
}
|
|
|
|
async function listModuleFolders(moduleRootDir) {
|
|
await mkdir(moduleRootDir, { recursive: true });
|
|
const entries = await readdir(moduleRootDir, { withFileTypes: true });
|
|
return entries
|
|
.filter((entry) => entry.isDirectory())
|
|
.map((entry) => entry.name)
|
|
.sort((a, b) => a.localeCompare(b, "zh-CN"));
|
|
}
|
|
|
|
async function getLatestDailyFile(targetDir) {
|
|
try {
|
|
const files = await readdir(targetDir);
|
|
const latest = files
|
|
.filter((fileName) => /^\d{8}\.json$/.test(fileName))
|
|
.sort()
|
|
.reverse()[0];
|
|
return latest ? path.join(targetDir, latest) : null;
|
|
} catch (error) {
|
|
if (error?.code === "ENOENT") {
|
|
return null;
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
function toEmptyPendingPayload(nowIso, nowLocal) {
|
|
return {
|
|
generatedAt: nowIso,
|
|
generatedAtLocal: nowLocal,
|
|
summary: {
|
|
moduleAdded: 0,
|
|
moduleDeleted: 0,
|
|
moduleUpdated: 0,
|
|
moduleSplit: 0,
|
|
moduleMerged: 0,
|
|
moduleReplaced: 0,
|
|
interfaceAdded: 0,
|
|
interfaceDeleted: 0,
|
|
interfaceParamsUpdated: 0,
|
|
interfaceResponseUpdated: 0,
|
|
movedAcrossModules: 0,
|
|
totalChangedItems: 0,
|
|
},
|
|
moduleUpdates: {
|
|
added: [],
|
|
deleted: [],
|
|
updated: [],
|
|
split: [],
|
|
merged: [],
|
|
replaced: [],
|
|
},
|
|
interfaceUpdates: {
|
|
added: [],
|
|
deleted: [],
|
|
paramsUpdated: [],
|
|
responseUpdated: [],
|
|
},
|
|
legacy: [],
|
|
versionWindow: {
|
|
keepLatest: API_DOC_SYSTEM_CONFIG.retentionDays,
|
|
recentVersions: [],
|
|
},
|
|
cleanup: {
|
|
performedAt: nowLocal,
|
|
note: "Marked deleted modules/interfaces have been cleaned.",
|
|
},
|
|
};
|
|
}
|
|
|
|
async function cleanupMarkedItems() {
|
|
const now = new Date();
|
|
const nowIso = now.toISOString();
|
|
const nowLocal = formatLocalDateTime(now);
|
|
const moduleDir = API_DOC_SYSTEM_CONFIG.file.moduleDir;
|
|
|
|
const pendingUpdates = await readJsonIfExists(API_DOC_SYSTEM_CONFIG.file.pendingUpdates, null);
|
|
const deletedModuleFoldersFromPending = new Set(
|
|
Array.isArray(pendingUpdates?.moduleUpdates?.deleted)
|
|
? pendingUpdates.moduleUpdates.deleted.map((item) => item?.folder).filter(Boolean)
|
|
: [],
|
|
);
|
|
const deletedMethods = new Set(
|
|
Array.isArray(pendingUpdates?.interfaceUpdates?.deleted)
|
|
? pendingUpdates.interfaceUpdates.deleted.map((item) => item?.method).filter(Boolean)
|
|
: [],
|
|
);
|
|
|
|
const moduleFolders = await listModuleFolders(moduleDir);
|
|
let removedModuleCount = 0;
|
|
let removedInterfaceCount = 0;
|
|
let updatedSnapshotCount = 0;
|
|
|
|
for (const folderName of moduleFolders) {
|
|
const folderPath = path.join(moduleDir, folderName);
|
|
const lifecycle = await readJsonIfExists(path.join(folderPath, MODULE_LIFECYCLE_FILE), null);
|
|
const shouldRemoveFolder = lifecycle?.status === "deleted" || deletedModuleFoldersFromPending.has(folderName);
|
|
if (shouldRemoveFolder) {
|
|
await rm(folderPath, { recursive: true, force: true });
|
|
removedModuleCount += 1;
|
|
continue;
|
|
}
|
|
|
|
if (deletedMethods.size === 0) {
|
|
continue;
|
|
}
|
|
|
|
const latestFile = await getLatestDailyFile(folderPath);
|
|
if (!latestFile) {
|
|
continue;
|
|
}
|
|
|
|
const snapshot = await readJsonIfExists(latestFile, null);
|
|
const oldInterfaces = Array.isArray(snapshot?.interfaces) ? snapshot.interfaces : [];
|
|
if (oldInterfaces.length === 0) {
|
|
continue;
|
|
}
|
|
|
|
const newInterfaces = oldInterfaces.filter((item) => !deletedMethods.has(item?.method));
|
|
const removedCount = oldInterfaces.length - newInterfaces.length;
|
|
if (removedCount <= 0) {
|
|
continue;
|
|
}
|
|
|
|
removedInterfaceCount += removedCount;
|
|
updatedSnapshotCount += 1;
|
|
await writeJson(latestFile, {
|
|
...snapshot,
|
|
generatedAt: nowIso,
|
|
generatedAtLocal: nowLocal,
|
|
module: {
|
|
...(snapshot?.module ?? {}),
|
|
interfaceCount: newInterfaces.length,
|
|
},
|
|
interfaces: newInterfaces,
|
|
cleanup: {
|
|
performedAt: nowLocal,
|
|
removedMethods: [...deletedMethods].sort((a, b) => a.localeCompare(b, "zh-CN")),
|
|
},
|
|
});
|
|
}
|
|
|
|
await writeJson(API_DOC_SYSTEM_CONFIG.file.pendingUpdates, toEmptyPendingPayload(nowIso, nowLocal));
|
|
|
|
console.log(`执行时间: ${nowLocal}`);
|
|
console.log(`清理完成,删除模块文件夹: ${removedModuleCount}`);
|
|
console.log(`清理完成,删除接口条目: ${removedInterfaceCount}`);
|
|
console.log(`更新模块快照文件: ${updatedSnapshotCount}`);
|
|
console.log(`已重置待更新接口文件: ${API_DOC_SYSTEM_CONFIG.file.pendingUpdates}`);
|
|
}
|
|
|
|
cleanupMarkedItems().catch((error) => {
|
|
console.error("清理标记删除模块/接口失败:", error.message);
|
|
process.exitCode = 1;
|
|
});
|