260703_01_FST: First Commit

This commit is contained in:
2026-07-03 14:56:06 +09:00
commit 084b34a6cc
74 changed files with 1936 additions and 0 deletions

130
src/args.ts Normal file
View File

@@ -0,0 +1,130 @@
import path from "node:path";
import type { ParsedArguments } from "./types.js";
const requireValue = (args: string[], index: number, option: string): string => {
const value = args[index + 1];
if (!value || value.startsWith("-")) {
throw new Error(`${option} 옵션의 값이 필요합니다.`);
}
return value;
};
export function parseArguments(argv: string[]): ParsedArguments {
const parsed: ParsedArguments = {
yes: false,
install: true,
installUi: true,
build: true,
jenkins: true,
force: false,
help: false,
};
for (let index = 0; index < argv.length; index += 1) {
const arg = argv[index];
if (!arg.startsWith("-")) {
if (parsed.projectName) throw new Error(`알 수 없는 인자입니다: ${arg}`);
parsed.projectName = arg;
continue;
}
switch (arg) {
case "--help":
case "-h":
parsed.help = true;
break;
case "--yes":
case "-y":
parsed.yes = true;
break;
case "--force":
parsed.force = true;
break;
case "--skip-install":
parsed.install = false;
parsed.installUi = false;
parsed.build = false;
break;
case "--skip-ui":
parsed.installUi = false;
break;
case "--skip-build":
parsed.build = false;
break;
case "--no-jenkins":
parsed.jenkins = false;
break;
case "--target-dir":
parsed.targetDir = path.resolve(requireValue(argv, index, arg));
index += 1;
break;
case "--display-name":
parsed.displayName = requireValue(argv, index, arg);
index += 1;
break;
case "--description":
parsed.description = requireValue(argv, index, arg);
index += 1;
break;
case "--port": {
const value = Number(requireValue(argv, index, arg));
if (!Number.isInteger(value) || value < 1 || value > 65535) {
throw new Error("--port는 1~65535 사이의 정수여야 합니다.");
}
parsed.port = value;
index += 1;
break;
}
case "--repo-url":
parsed.repoUrl = requireValue(argv, index, arg);
index += 1;
break;
case "--app-root":
parsed.appRoot = requireValue(argv, index, arg);
index += 1;
break;
case "--service-name":
parsed.serviceName = requireValue(argv, index, arg);
index += 1;
break;
case "--branch":
parsed.branch = requireValue(argv, index, arg);
index += 1;
break;
case "--agent-label":
parsed.agentLabel = requireValue(argv, index, arg);
index += 1;
break;
default:
throw new Error(`알 수 없는 옵션입니다: ${arg}`);
}
}
return parsed;
}
export function printHelp(): void {
console.log(`
사용법:
npx @kri/create-next-app <project-name> [options]
옵션:
--display-name <name> 화면 표시 이름
--description <text> 프로젝트 설명
--port <number> 개발/실행 포트 (기본 4000)
--repo-url <url> Gitea 저장소 URL
--app-root <path> Ubuntu 배포 경로
--service-name <name> systemd 서비스 이름
--branch <name> 배포 브랜치 (기본 master)
--agent-label <label> Jenkins Agent label (기본 ubuntu-build)
--target-dir <path> 생성 경로
--yes, -y 질문 없이 기본값 사용
--skip-install npm 설치, UI 설치, 검증 생략
--skip-ui KRI UI Registry 설치 생략
--skip-build typecheck/build 생략
--no-jenkins Jenkinsfile 생성 안 함
--force 비어 있지 않은 대상 폴더 사용
--help, -h 도움말
`);
}

97
src/cli.ts Normal file
View File

@@ -0,0 +1,97 @@
#!/usr/bin/env node
import path from "node:path";
import process from "node:process";
import { parseArguments, printHelp } from "./args.js";
import { createProject } from "./create-project.js";
import { ask, confirm } from "./prompts.js";
import type { CliOptions } from "./types.js";
const PROJECT_NAME_PATTERN = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/;
function validateProjectName(name: string): string {
const normalized = name.trim();
if (!PROJECT_NAME_PATTERN.test(normalized)) {
throw new Error("프로젝트명은 npm package 이름으로 사용할 수 있는 영문 소문자, 숫자, -, _, . 조합이어야 합니다.");
}
return normalized;
}
async function resolveOptions(): Promise<CliOptions> {
const parsed = parseArguments(process.argv.slice(2));
if (parsed.help) {
printHelp();
process.exit(0);
}
let projectName = parsed.projectName;
if (!projectName && !parsed.yes) projectName = await ask("프로젝트명");
if (!projectName) throw new Error("프로젝트명이 필요합니다.");
projectName = validateProjectName(projectName);
const displayName = parsed.displayName
?? (parsed.yes ? projectName : await ask("프로젝트 표시 이름", projectName));
const description = parsed.description
?? (parsed.yes ? `${displayName} 시스템` : await ask("프로젝트 설명", `${displayName} 시스템`));
const portText = parsed.port
? String(parsed.port)
: parsed.yes
? "4000"
: await ask("개발/실행 포트", "4000");
const port = Number(portText);
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("포트는 1~65535 사이의 정수여야 합니다.");
const repoDefault = `https://gitea.kric.com/Project/${projectName}.git`;
const repoUrl = parsed.repoUrl ?? (parsed.yes ? repoDefault : await ask("Gitea Repository URL", repoDefault));
const appRootDefault = `/opt/project/${projectName}`;
const appRoot = parsed.appRoot ?? (parsed.yes ? appRootDefault : await ask("Ubuntu 배포 경로", appRootDefault));
const serviceDefault = `${projectName}.service`;
const serviceName = parsed.serviceName ?? (parsed.yes ? serviceDefault : await ask("systemd 서비스 이름", serviceDefault));
const branch = parsed.branch ?? "master";
const agentLabel = parsed.agentLabel ?? "ubuntu-build";
const targetDir = parsed.targetDir ?? path.resolve(process.cwd(), projectName);
const jenkins = parsed.yes ? parsed.jenkins : parsed.jenkins && await confirm("Jenkinsfile을 생성할까요?", true);
return {
projectName,
targetDir,
displayName,
description,
port,
repoUrl,
appRoot,
serviceName,
branch,
agentLabel,
yes: parsed.yes,
install: parsed.install,
installUi: parsed.installUi,
build: parsed.build,
jenkins,
force: parsed.force,
};
}
async function main(): Promise<void> {
const major = Number(process.versions.node.split(".")[0]);
if (major < 20) throw new Error(`Node.js 20 이상이 필요합니다. 현재: ${process.version}`);
const options = await resolveOptions();
console.log(`
[KRI] ${options.projectName} 생성 시작`);
console.log(`[KRI] target=${options.targetDir}`);
await createProject(options);
console.log("\n[KRI] 프로젝트 생성 완료");
console.log(` cd ${options.targetDir}`);
if (!options.install) console.log(" npm install");
console.log(` npm run dev`);
}
main().catch((error: unknown) => {
const message = error instanceof Error ? error.message : String(error);
console.error(`
[ERROR] ${message}`);
process.exitCode = 1;
});

13
src/constants.ts Normal file
View File

@@ -0,0 +1,13 @@
export const REGISTRY_BASE_URL = "https://ui-registry.kric.com/r";
export const KRI_REGISTRY_ITEMS = [
"kri-select",
"kri-date-range-picker",
"kri-password",
"kri-auto-complete",
"kri-data-table",
"kri-loading-overlay",
"kri-editor",
"kri-layout",
"kri-dialog",
] as const;

114
src/create-project.ts Normal file
View File

@@ -0,0 +1,114 @@
import { fileURLToPath } from "node:url";
import path from "node:path";
import { writeFile } from "node:fs/promises";
import { KRI_REGISTRY_ITEMS, REGISTRY_BASE_URL } from "./constants.js";
import { copyTemplate, ensureTargetDirectory, removeJenkinsfile, replacePlaceholders } from "./files.js";
import { run } from "./process.js";
import type { CliOptions } from "./types.js";
const currentDir = path.dirname(fileURLToPath(import.meta.url));
const templateDir = path.resolve(currentDir, "../templates/base");
function packageJson(options: CliOptions) {
return {
name: options.projectName,
version: "0.1.0",
private: true,
scripts: {
dev: `next dev -p ${options.port}`,
build: "next build",
start: `next start -p ${options.port}`,
lint: "eslint",
typecheck: "tsc --noEmit",
},
dependencies: {
"@kri/common": "latest",
"@tanstack/react-query": "latest",
"class-variance-authority": "latest",
clsx: "latest",
jotai: "latest",
"lucide-react": "latest",
next: "latest",
react: "latest",
"react-dom": "latest",
"server-only": "latest",
sonner: "latest",
"tailwind-merge": "latest",
},
devDependencies: {
"@tailwindcss/postcss": "latest",
"@types/node": "latest",
"@types/react": "latest",
"@types/react-dom": "latest",
"babel-plugin-react-compiler": "latest",
eslint: "^9",
"eslint-config-next": "latest",
tailwindcss: "latest",
"tw-animate-css": "latest",
typescript: "^5",
},
};
}
export async function createProject(options: CliOptions): Promise<void> {
await ensureTargetDirectory(options.targetDir, options.force);
await copyTemplate(templateDir, options.targetDir);
if (!options.jenkins) await removeJenkinsfile(options.targetDir);
await replacePlaceholders(options.targetDir, {
"__PROJECT_NAME__": options.projectName,
"__DISPLAY_NAME__": options.displayName,
"__DESCRIPTION__": options.description,
"__PORT__": String(options.port),
"__REPO_URL__": options.repoUrl,
"__APP_ROOT__": options.appRoot,
"__SERVICE_NAME__": options.serviceName,
"__BRANCH__": options.branch,
"__AGENT_LABEL__": options.agentLabel,
});
await writeFile(
path.join(options.targetDir, "package.json"),
`${JSON.stringify(packageJson(options), null, 2)}
`,
"utf8",
);
if (!options.install) {
console.log("[SKIP] npm install");
return;
}
console.log("\n[1/4] npm 의존성 설치");
await run("npm", ["install"], options.targetDir);
console.log("\n[2/4] 최신 @kri/common 설치");
await run("npm", ["install", "--save-exact", "@kri/common@latest"], options.targetDir);
if (options.installUi) {
console.log("\n[3/4] shadcn 및 KRI UI Registry 설치");
await run("npx", ["--yes", "shadcn@latest", "add", "card", "--yes", "--overwrite"], options.targetDir);
for (const item of KRI_REGISTRY_ITEMS) {
await run(
"npx",
["--yes", "shadcn@latest", "add", `${REGISTRY_BASE_URL}/${item}.json`, "--yes", "--overwrite"],
options.targetDir,
);
}
} else {
console.log("[SKIP] UI Registry 설치");
}
if (options.build) {
if (!options.installUi) {
console.warn("[WARN] --skip-ui 때문에 typecheck/build를 생략합니다.");
return;
}
console.log("\n[4/4] TypeScript 및 production build 검증");
await run("npm", ["run", "typecheck"], options.targetDir);
await run("npm", ["run", "build"], options.targetDir);
} else {
console.log("[SKIP] typecheck/build");
}
}

64
src/files.ts Normal file
View File

@@ -0,0 +1,64 @@
import { cp, mkdir, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
import path from "node:path";
const RENAMES: Record<string, string> = {
"_gitignore": ".gitignore",
"_npmrc": ".npmrc",
"_env": ".env",
"_env.local": ".env.local",
"_env.development": ".env.development",
"_env.production": ".env.production",
"_env.example": ".env.example",
"README.md.template": "README.md",
"Jenkinsfile.template": "Jenkinsfile",
};
export async function ensureTargetDirectory(targetDir: string, force: boolean): Promise<void> {
await mkdir(targetDir, { recursive: true });
const entries = await readdir(targetDir);
if (entries.length > 0 && !force) {
throw new Error(`대상 폴더가 비어 있지 않습니다: ${targetDir}
--force 옵션을 사용하거나 빈 폴더를 선택하세요.`);
}
}
export async function copyTemplate(templateDir: string, targetDir: string): Promise<void> {
await cp(templateDir, targetDir, { recursive: true, force: true });
for (const [sourceName, targetName] of Object.entries(RENAMES)) {
const source = path.join(targetDir, sourceName);
try {
await stat(source);
await rename(source, path.join(targetDir, targetName));
} catch {
// 선택 파일은 없을 수 있습니다.
}
}
}
export async function removeJenkinsfile(targetDir: string): Promise<void> {
await rm(path.join(targetDir, "Jenkinsfile"), { force: true });
}
export async function replacePlaceholders(rootDir: string, replacements: Record<string, string>): Promise<void> {
const visit = async (directory: string): Promise<void> => {
const entries = await readdir(directory, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(directory, entry.name);
if (entry.isDirectory()) {
await visit(fullPath);
continue;
}
if (!entry.isFile() || /\.(png|ico|jpg|jpeg|gif|webp)$/i.test(entry.name)) continue;
let content = await readFile(fullPath, "utf8");
for (const [key, value] of Object.entries(replacements)) {
content = content.split(key).join(value);
}
await writeFile(fullPath, content, "utf8");
}
};
await visit(rootDir);
}

33
src/process.ts Normal file
View File

@@ -0,0 +1,33 @@
import { spawn } from "node:child_process";
export async function run(command: string, args: string[], cwd: string): Promise<void> {
const isWindows = process.platform === "win32";
const executable = isWindows ? (process.env.ComSpec ?? "cmd.exe") : command;
const executableArgs = isWindows
? ["/d", "/s", "/c", `${command}.cmd`, ...args]
: args;
await new Promise<void>((resolve, reject) => {
const child = spawn(executable, executableArgs, {
cwd,
env: process.env,
stdio: "inherit",
shell: false,
windowsHide: true,
});
child.once("error", reject);
child.once("exit", (code, signal) => {
if (code === 0) {
resolve();
return;
}
reject(
new Error(
`${command} ${args.join(" ")} 실패 (code=${code ?? "null"}, signal=${signal ?? "none"})`,
),
);
});
});
}

20
src/prompts.ts Normal file
View File

@@ -0,0 +1,20 @@
import { createInterface } from "node:readline/promises";
import { stdin as input, stdout as output } from "node:process";
export async function ask(question: string, defaultValue?: string): Promise<string> {
const rl = createInterface({ input, output });
try {
const suffix = defaultValue ? ` (${defaultValue})` : "";
const answer = (await rl.question(`${question}${suffix}: `)).trim();
return answer || defaultValue || "";
} finally {
rl.close();
}
}
export async function confirm(question: string, defaultValue = true): Promise<boolean> {
const defaultText = defaultValue ? "Y/n" : "y/N";
const answer = (await ask(`${question} [${defaultText}]`)).toLowerCase();
if (!answer) return defaultValue;
return answer === "y" || answer === "yes" || answer === "예";
}

38
src/types.ts Normal file
View File

@@ -0,0 +1,38 @@
export interface CliOptions {
projectName: string;
targetDir: string;
displayName: string;
description: string;
port: number;
repoUrl: string;
appRoot: string;
serviceName: string;
branch: string;
agentLabel: string;
yes: boolean;
install: boolean;
installUi: boolean;
build: boolean;
jenkins: boolean;
force: boolean;
}
export interface ParsedArguments {
projectName?: string;
targetDir?: string;
displayName?: string;
description?: string;
port?: number;
repoUrl?: string;
appRoot?: string;
serviceName?: string;
branch?: string;
agentLabel?: string;
yes: boolean;
install: boolean;
installUi: boolean;
build: boolean;
jenkins: boolean;
force: boolean;
help: boolean;
}