Files
ci/src/core/config.ts
T

81 lines
2.6 KiB
TypeScript

import * as fs from "node:fs";
import * as path from "node:path";
import { CIConfig, DEFAULT_CI_CONFIG } from "../types/config.js";
const CI_DIR = ".ci";
const CONFIG_FILE = "config.json";
export function getCIConfigPath(projectPath: string): string {
return path.join(projectPath, CI_DIR, CONFIG_FILE);
}
export function getCIDir(projectPath: string): string {
return path.join(projectPath, CI_DIR);
}
export function ensureCIDir(projectPath: string): void {
const ciDir = getCIDir(projectPath);
if (!fs.existsSync(ciDir)) {
fs.mkdirSync(ciDir, { recursive: true });
}
}
function deepMerge(base: CIConfig, override: Record<string, unknown>): CIConfig {
const result = { ...base } as Record<string, unknown>;
for (const key of Object.keys(override)) {
const baseVal = result[key];
const overrideVal = override[key];
if (
baseVal && typeof baseVal === "object" && !Array.isArray(baseVal) &&
overrideVal && typeof overrideVal === "object" && !Array.isArray(overrideVal)
) {
result[key] = deepMerge(
baseVal as unknown as CIConfig,
overrideVal as Record<string, unknown>
) as unknown;
} else if (overrideVal !== undefined) {
result[key] = overrideVal;
}
}
return result as unknown as CIConfig;
}
export function loadConfig(projectPath: string): CIConfig {
const configPath = getCIConfigPath(projectPath);
if (!fs.existsSync(configPath)) {
return { ...DEFAULT_CI_CONFIG };
}
const raw = fs.readFileSync(configPath, "utf-8");
const parsed = JSON.parse(raw);
return deepMerge(DEFAULT_CI_CONFIG, parsed);
}
export function saveConfig(projectPath: string, config: CIConfig): void {
ensureCIDir(projectPath);
const configPath = getCIConfigPath(projectPath);
fs.writeFileSync(configPath, JSON.stringify(config, null, 2), "utf-8");
}
export function isCIInitialized(projectPath: string): boolean {
const ciDir = getCIDir(projectPath);
const configPath = getCIConfigPath(projectPath);
return fs.existsSync(ciDir) && fs.existsSync(configPath);
}
export function initCI(projectPath: string, config?: Partial<CIConfig>): CIConfig {
ensureCIDir(projectPath);
const fullConfig: CIConfig = {
...DEFAULT_CI_CONFIG,
...config,
autonomy: { ...DEFAULT_CI_CONFIG.autonomy, ...config?.autonomy },
parallelization: {
...DEFAULT_CI_CONFIG.parallelization,
...config?.parallelization,
},
verification: { ...DEFAULT_CI_CONFIG.verification, ...config?.verification },
security: { ...DEFAULT_CI_CONFIG.security, ...config?.security },
git: { ...DEFAULT_CI_CONFIG.git, ...config?.git },
};
saveConfig(projectPath, fullConfig);
return fullConfig;
}