ktx/packages/cli/src/project-resolver.ts

57 lines
1.6 KiB
TypeScript
Raw Permalink Normal View History

2026-05-10 23:12:26 +02:00
import { existsSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
2026-05-10 23:51:24 +02:00
export interface KtxProjectResolverOptions {
2026-05-10 23:12:26 +02:00
explicitProjectDir?: string;
2026-05-10 23:51:24 +02:00
env?: Partial<Pick<NodeJS.ProcessEnv, 'KTX_PROJECT_DIR'>>;
2026-05-10 23:12:26 +02:00
cwd?: string;
}
function nonEmptyValue(value: string | undefined): string | undefined {
if (value === undefined) {
return undefined;
}
const trimmed = value.trim();
return trimmed.length > 0 ? value : undefined;
}
2026-05-10 23:51:24 +02:00
export function findNearestKtxProjectDir(startDir = process.cwd()): string | undefined {
2026-05-10 23:12:26 +02:00
let current = resolve(startDir);
while (true) {
2026-05-10 23:51:24 +02:00
if (existsSync(join(current, 'ktx.yaml'))) {
2026-05-10 23:12:26 +02:00
return current;
}
const parent = dirname(current);
if (parent === current) {
return undefined;
}
current = parent;
}
}
2026-05-10 23:51:24 +02:00
export function resolveKtxProjectDir(options: KtxProjectResolverOptions = {}): string {
2026-05-10 23:12:26 +02:00
const cwd = options.cwd ?? process.cwd();
if (options.explicitProjectDir !== undefined) {
const explicit = nonEmptyValue(options.explicitProjectDir);
if (!explicit) {
throw new Error('--project-dir requires a value');
}
return resolve(cwd, explicit);
}
2026-05-10 23:51:24 +02:00
const rawEnvProjectDir = options.env ? options.env.KTX_PROJECT_DIR : process.env.KTX_PROJECT_DIR;
2026-05-10 23:12:26 +02:00
const envProjectDir = nonEmptyValue(rawEnvProjectDir);
if (rawEnvProjectDir !== undefined && envProjectDir === undefined) {
2026-05-10 23:51:24 +02:00
throw new Error('KTX_PROJECT_DIR must not be empty');
2026-05-10 23:12:26 +02:00
}
if (envProjectDir !== undefined) {
return resolve(cwd, envProjectDir);
}
const resolvedCwd = resolve(cwd);
2026-05-10 23:51:24 +02:00
return findNearestKtxProjectDir(resolvedCwd) ?? resolvedCwd;
2026-05-10 23:12:26 +02:00
}