223 lines
8.0 KiB
TypeScript
223 lines
8.0 KiB
TypeScript
import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
import { homedir } from "node:os";
|
|
import { dirname, join } from "node:path";
|
|
import { CorpConfig, CorpConfigSchema, GlobalConfig, GlobalConfigSchema } from "./types.js";
|
|
|
|
const CONFIG_ENV = "HOSE_ENTERPRISES_DIR";
|
|
const USER_DIR_ENV = "HOSE_USER_ENTERPRISES_DIR";
|
|
const GLOBAL_CONFIG_ENV = "HOSE_CONFIG_FILE";
|
|
|
|
export const PRIMARY_USER_ENTERPRISES_DIR = join(homedir(), ".config", "hose-use", "enterprises");
|
|
export const LEGACY_USER_ENTERPRISES_DIR = join(homedir(), ".cache", "ekb-mcp", "enterprises");
|
|
export const USER_ENTERPRISES_DIR = PRIMARY_USER_ENTERPRISES_DIR;
|
|
|
|
export const PRIMARY_GLOBAL_CONFIG_FILE = join(homedir(), ".config", "hose-use", "config.json");
|
|
export const LEGACY_GLOBAL_CONFIG_FILE = join(homedir(), ".cache", "ekb-mcp", "config.json");
|
|
|
|
const LEGACY_CLEANUP_GRACE_MS = 7 * 24 * 60 * 60 * 1000;
|
|
|
|
function ensureDir(dir: string): void {
|
|
mkdirSync(dir, { recursive: true });
|
|
}
|
|
|
|
export function resolveEnterprisesDirs(): string[] {
|
|
const configured = process.env[CONFIG_ENV]?.trim();
|
|
if (configured) {
|
|
return existsSync(configured) ? [configured] : [];
|
|
}
|
|
|
|
const configuredUserDir = process.env[USER_DIR_ENV]?.trim();
|
|
const userDirs = configuredUserDir
|
|
? (existsSync(configuredUserDir) ? [configuredUserDir] : [])
|
|
: (() => {
|
|
try {
|
|
syncLegacyEnterprisesDir();
|
|
} catch {
|
|
// Legacy migration must never prevent normal CLI startup.
|
|
}
|
|
return [PRIMARY_USER_ENTERPRISES_DIR, LEGACY_USER_ENTERPRISES_DIR];
|
|
})();
|
|
|
|
const globalConfig = loadGlobalConfig();
|
|
const testDir = globalConfig.testEnterprisesDir?.trim();
|
|
|
|
const candidates = testDir ? [testDir, ...userDirs] : userDirs;
|
|
const uniqueExisting: string[] = [];
|
|
for (const d of candidates) {
|
|
if (existsSync(d) && !uniqueExisting.includes(d)) {
|
|
uniqueExisting.push(d);
|
|
}
|
|
}
|
|
return uniqueExisting;
|
|
}
|
|
|
|
export function resolvePrimaryEnterprisesDir(): string | undefined {
|
|
return resolveEnterprisesDirs()[0];
|
|
}
|
|
|
|
export function resolveWritableEnterprisesDir(): string {
|
|
const configured = process.env[CONFIG_ENV]?.trim();
|
|
if (configured) return configured;
|
|
const configuredUserDir = process.env[USER_DIR_ENV]?.trim();
|
|
if (configuredUserDir) return configuredUserDir;
|
|
const testDir = loadGlobalConfig().testEnterprisesDir?.trim();
|
|
if (testDir && existsSync(testDir)) return testDir;
|
|
return PRIMARY_USER_ENTERPRISES_DIR;
|
|
}
|
|
|
|
export function getEnterprisesDirCandidates(): string[] {
|
|
const testDir = loadGlobalConfig().testEnterprisesDir?.trim();
|
|
return [
|
|
`${CONFIG_ENV}=<path>`,
|
|
...(testDir ? [`testEnterprisesDir: ${testDir}`] : []),
|
|
PRIMARY_USER_ENTERPRISES_DIR,
|
|
LEGACY_USER_ENTERPRISES_DIR,
|
|
];
|
|
}
|
|
|
|
export function resolveGlobalConfigFile(): string {
|
|
const configured = process.env[GLOBAL_CONFIG_ENV]?.trim();
|
|
if (configured) return configured;
|
|
try {
|
|
syncLegacyGlobalConfig();
|
|
} catch {
|
|
// Legacy migration must never prevent normal CLI startup.
|
|
}
|
|
if (existsSync(PRIMARY_GLOBAL_CONFIG_FILE)) return PRIMARY_GLOBAL_CONFIG_FILE;
|
|
if (existsSync(LEGACY_GLOBAL_CONFIG_FILE)) return LEGACY_GLOBAL_CONFIG_FILE;
|
|
return PRIMARY_GLOBAL_CONFIG_FILE;
|
|
}
|
|
|
|
export function syncLegacyEnterprisesDir(
|
|
primaryDir: string = PRIMARY_USER_ENTERPRISES_DIR,
|
|
legacyDir: string = LEGACY_USER_ENTERPRISES_DIR
|
|
): { copied: string[]; deletedLegacyDir: boolean } {
|
|
if (!existsSync(legacyDir)) return { copied: [], deletedLegacyDir: false };
|
|
|
|
mkdirSync(primaryDir, { recursive: true, mode: 0o700 });
|
|
const copied: string[] = [];
|
|
const files = readdirSync(legacyDir).filter((file) => file.endsWith(".json"));
|
|
|
|
for (const file of files) {
|
|
const legacyPath = join(legacyDir, file);
|
|
const primaryPath = join(primaryDir, file);
|
|
if (!existsSync(primaryPath) || statSync(legacyPath).mtimeMs > statSync(primaryPath).mtimeMs) {
|
|
copyFileSync(legacyPath, primaryPath);
|
|
copied.push(file);
|
|
}
|
|
}
|
|
|
|
const now = Date.now();
|
|
const hasRecentEntry = readdirSync(legacyDir).some((file) => now - statSync(join(legacyDir, file)).mtimeMs < LEGACY_CLEANUP_GRACE_MS);
|
|
const hasNewerLegacyFile = files.some((file) => {
|
|
const legacyPath = join(legacyDir, file);
|
|
const primaryPath = join(primaryDir, file);
|
|
return existsSync(primaryPath) && statSync(legacyPath).mtimeMs > statSync(primaryPath).mtimeMs;
|
|
});
|
|
const directoryIsRecent = now - statSync(legacyDir).mtimeMs < LEGACY_CLEANUP_GRACE_MS;
|
|
const deletedLegacyDir = !hasRecentEntry && !hasNewerLegacyFile && !directoryIsRecent;
|
|
if (deletedLegacyDir) rmSync(legacyDir, { recursive: true, force: true });
|
|
return { copied, deletedLegacyDir };
|
|
}
|
|
|
|
export function syncLegacyGlobalConfig(
|
|
primaryFile: string = PRIMARY_GLOBAL_CONFIG_FILE,
|
|
legacyFile: string = LEGACY_GLOBAL_CONFIG_FILE
|
|
): { copied: boolean; deletedLegacyFile: boolean } {
|
|
if (!existsSync(legacyFile)) return { copied: false, deletedLegacyFile: false };
|
|
mkdirSync(dirname(primaryFile), { recursive: true, mode: 0o700 });
|
|
|
|
let copied = false;
|
|
if (!existsSync(primaryFile) || statSync(legacyFile).mtimeMs > statSync(primaryFile).mtimeMs) {
|
|
copyFileSync(legacyFile, primaryFile);
|
|
copied = true;
|
|
}
|
|
|
|
const oldEnough = Date.now() - statSync(legacyFile).mtimeMs >= LEGACY_CLEANUP_GRACE_MS;
|
|
const safeToDelete = existsSync(primaryFile) && statSync(legacyFile).mtimeMs <= statSync(primaryFile).mtimeMs && oldEnough;
|
|
if (safeToDelete) {
|
|
rmSync(legacyFile, { force: true });
|
|
return { copied, deletedLegacyFile: true };
|
|
}
|
|
return { copied, deletedLegacyFile: false };
|
|
}
|
|
|
|
export function loadGlobalConfig(): GlobalConfig {
|
|
const file = resolveGlobalConfigFile();
|
|
try {
|
|
if (existsSync(file)) {
|
|
const content = readFileSync(file, "utf-8");
|
|
return GlobalConfigSchema.parse(JSON.parse(content));
|
|
}
|
|
} catch {
|
|
// 容错返回默认
|
|
}
|
|
|
|
return GlobalConfigSchema.parse({});
|
|
}
|
|
|
|
export function saveGlobalConfig(config: Partial<GlobalConfig>): GlobalConfig {
|
|
const current = loadGlobalConfig();
|
|
const updated = GlobalConfigSchema.parse({
|
|
...current,
|
|
...config,
|
|
});
|
|
|
|
const configured = process.env[GLOBAL_CONFIG_ENV]?.trim();
|
|
const targetFile = configured || PRIMARY_GLOBAL_CONFIG_FILE;
|
|
ensureDir(dirname(targetFile));
|
|
writeFileSync(targetFile, JSON.stringify(updated, null, 2), "utf-8");
|
|
return updated;
|
|
}
|
|
|
|
export function loadCorpConfigs(overrideDirs?: string[]): CorpConfig[] {
|
|
const dirs = overrideDirs ? overrideDirs.filter(existsSync) : resolveEnterprisesDirs();
|
|
const byId = new Map<string, CorpConfig>();
|
|
|
|
for (const dir of dirs) {
|
|
try {
|
|
const files = readdirSync(dir)
|
|
.filter((item) => item.endsWith(".json"))
|
|
.filter((item) => !item.startsWith("example."));
|
|
|
|
for (const file of files) {
|
|
try {
|
|
const content = readFileSync(join(dir, file), "utf-8");
|
|
const parsed = JSON.parse(content);
|
|
const corp = CorpConfigSchema.parse(parsed);
|
|
// 相同企业 ID 以先出现的为准(工作区优先于全局,全局优先于历史)
|
|
if (!byId.has(corp.id)) {
|
|
byId.set(corp.id, corp);
|
|
}
|
|
} catch (error) {
|
|
console.error(
|
|
`[config] failed to load ${file} from ${dir}: ${error instanceof Error ? error.message : String(error)}`
|
|
);
|
|
}
|
|
}
|
|
} catch (error) {
|
|
console.error(
|
|
`[config] failed to read enterprises directory ${dir}: ${error instanceof Error ? error.message : String(error)}`
|
|
);
|
|
}
|
|
}
|
|
|
|
return Array.from(byId.values());
|
|
}
|
|
|
|
export function saveCorpConfig(config: CorpConfig, dir?: string): string {
|
|
const targetDir = dir || resolveWritableEnterprisesDir();
|
|
ensureDir(targetDir);
|
|
const validated = CorpConfigSchema.parse(config);
|
|
const filePath = join(targetDir, `${validated.id}.json`);
|
|
writeFileSync(filePath, JSON.stringify(validated, null, 2), "utf-8");
|
|
return filePath;
|
|
}
|
|
|
|
export function saveMultipleCorpConfigs(
|
|
configs: CorpConfig[],
|
|
dir?: string
|
|
): string[] {
|
|
return configs.map((config) => saveCorpConfig(config, dir));
|
|
}
|