260703_01_FST: First Commit

This commit is contained in:
2026-07-03 16:20:48 +09:00
commit 34b8d41a28
55 changed files with 2127 additions and 0 deletions

138
src/args.ts Normal file
View File

@@ -0,0 +1,138 @@
import path from "node:path";
import type { DatabaseType, 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;
};
const parseDatabase = (value: string): DatabaseType => {
if (value === "mysql" || value === "mssql") return value;
throw new Error("--database는 mysql 또는 mssql이어야 합니다.");
};
export function parseArguments(argv: string[]): ParsedArguments {
const parsed: ParsedArguments = {
yes: false,
build: true,
jenkins: true,
mybatis: false,
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-build":
parsed.build = false;
break;
case "--no-jenkins":
parsed.jenkins = false;
break;
case "--mybatis":
parsed.mybatis = true;
break;
case "--target-dir":
parsed.targetDir = path.resolve(requireValue(argv, index, arg));
index += 1;
break;
case "--base-package":
parsed.basePackage = 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 "--database":
parsed.database = parseDatabase(requireValue(argv, index, arg));
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;
case "--maven-credential-id":
parsed.mavenCredentialId = requireValue(argv, index, arg);
index += 1;
break;
default:
throw new Error(`알 수 없는 옵션입니다: ${arg}`);
}
}
return parsed;
}
export function printHelp(): void {
console.log(`
사용법:
npx @kri/create-spring-app <project-name> [options]
옵션:
--base-package <package> 기본 패키지
--description <text> 프로젝트 설명
--port <number> 서버 포트 (기본 8080)
--database mysql|mssql DB 종류 (기본 mysql)
--mybatis MyBatis 예제 포함
--repo-url <url> Gitea 저장소 URL
--app-root <path> Ubuntu 배포 경로
--service-name <name> systemd 서비스 이름
--branch <name> 배포 브랜치 (기본 master)
--agent-label <label> Jenkins Agent label (기본 ubuntu-build)
--maven-credential-id <id> Jenkins Maven Credential ID
--target-dir <path> 생성 경로
--yes, -y 질문 없이 기본값 사용
--skip-build Gradle build 생략
--no-jenkins Jenkinsfile 생성 안 함
--force 비어 있지 않은 대상 폴더 사용
--help, -h 도움말
`);
}

145
src/cli.ts Normal file
View File

@@ -0,0 +1,145 @@
#!/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, DatabaseType } from "./types.js";
const PROJECT_NAME_PATTERN = /^[a-z0-9][a-z0-9._-]*$/;
const PACKAGE_PATTERN = /^[a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)+$/;
function validateProjectName(name: string): string {
const normalized = name.trim();
if (!PROJECT_NAME_PATTERN.test(normalized)) {
throw new Error("프로젝트명은 영문 소문자, 숫자, -, _, . 조합이어야 합니다.");
}
return normalized;
}
function defaultBasePackage(projectName: string): string {
const suffix = projectName
.toLowerCase()
.replace(/[^a-z0-9]+/g, ".")
.replace(/^\.+|\.+$/g, "")
.split(".")
.filter(Boolean)
.map((part) => (/^[0-9]/.test(part) ? `app${part}` : part))
.join(".");
return `com.kri.${suffix}`;
}
function validateBasePackage(value: string): string {
const normalized = value.trim();
if (!PACKAGE_PATTERN.test(normalized)) {
throw new Error("base package 형식이 올바르지 않습니다. 예: com.kri.sample.server");
}
return normalized;
}
function toApplicationClass(projectName: string): string {
const name = projectName
.split(/[^a-zA-Z0-9]+/)
.filter(Boolean)
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
.join("");
return `${name || "KriServer"}Application`;
}
function validateDatabase(value: string): DatabaseType {
if (value === "mysql" || value === "mssql") return value;
throw new Error("database는 mysql 또는 mssql이어야 합니다.");
}
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 basePackageDefault = defaultBasePackage(projectName);
const basePackage = validateBasePackage(
parsed.basePackage ?? (parsed.yes ? basePackageDefault : await ask("Base package", basePackageDefault)),
);
const applicationClass = toApplicationClass(projectName);
const description = parsed.description
?? (parsed.yes ? `${projectName} Spring Boot application` : await ask("프로젝트 설명", `${projectName} Spring Boot application`));
const portText = parsed.port
? String(parsed.port)
: parsed.yes
? "8080"
: await ask("서버 포트", "8080");
const port = Number(portText);
if (!Number.isInteger(port) || port < 1 || port > 65535) {
throw new Error("포트는 1~65535 사이의 정수여야 합니다.");
}
const database = parsed.database
?? (parsed.yes ? "mysql" : validateDatabase((await ask("Database (mysql/mssql)", "mysql")).toLowerCase()));
const mybatis = parsed.yes ? parsed.mybatis : parsed.mybatis || await confirm("MyBatis 예제를 포함할까요?", false);
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 mavenCredentialId = parsed.mavenCredentialId ?? "gitea-package-credential";
const targetDir = parsed.targetDir ?? path.resolve(process.cwd(), projectName);
const jenkins = parsed.yes ? parsed.jenkins : parsed.jenkins && await confirm("Jenkinsfile을 생성할까요?", true);
return {
projectName,
targetDir,
basePackage,
applicationClass,
description,
port,
database,
mybatis,
repoUrl,
appRoot,
serviceName,
branch,
agentLabel,
mavenCredentialId,
yes: parsed.yes,
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}`);
console.log(`[KRI] package=${options.basePackage}`);
console.log(`[KRI] database=${options.database}, mybatis=${options.mybatis}`);
await createProject(options);
console.log("\n[KRI] 프로젝트 생성 완료");
console.log(` cd ${options.targetDir}`);
console.log(process.platform === "win32" ? " .\\gradlew.bat bootRun" : " ./gradlew bootRun");
}
main().catch((error: unknown) => {
const message = error instanceof Error ? error.message : String(error);
console.error(`
[ERROR] ${message}`);
process.exitCode = 1;
});

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

@@ -0,0 +1,87 @@
import { fileURLToPath } from "node:url";
import path from "node:path";
import {
copyTemplate,
ensureTargetDirectory,
movePackageDirectories,
removeJenkinsFiles,
removeMyBatisFiles,
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");
const databaseSettings = (database: CliOptions["database"]) => {
if (database === "mssql") {
return {
dependency: "runtimeOnly 'com.microsoft.sqlserver:mssql-jdbc:13.2.1.jre11'",
driver: "com.microsoft.sqlserver.jdbc.SQLServerDriver",
localUrl: "jdbc:sqlserver://localhost:1433;databaseName=sample;encrypt=false",
};
}
return {
dependency: "runtimeOnly 'com.mysql:mysql-connector-j'",
driver: "com.mysql.cj.jdbc.Driver",
localUrl: "jdbc:mysql://localhost:3306/sample?characterEncoding=UTF-8&rewriteBatchedStatements=true",
};
};
export async function createProject(options: CliOptions): Promise<void> {
await ensureTargetDirectory(options.targetDir, options.force);
await copyTemplate(templateDir, options.targetDir);
await movePackageDirectories(options.targetDir, options.basePackage, options.applicationClass);
if (!options.mybatis) await removeMyBatisFiles(options.targetDir, options.basePackage);
if (!options.jenkins) await removeJenkinsFiles(options.targetDir);
const database = databaseSettings(options.database);
const mybatisDependency = options.mybatis
? "implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:3.0.5'"
: "";
const mybatisTestDependency = options.mybatis
? "testImplementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter-test:3.0.5'"
: "";
const mybatisConfig = options.mybatis
? `mybatis:
mapper-locations: classpath:/mybatis/mapper/**/*.xml
type-aliases-package: ${options.basePackage}.persistence.entity
configuration:
map-underscore-to-camel-case: true
`
: "";
await replacePlaceholders(options.targetDir, {
"__PROJECT_NAME__": options.projectName,
"__BASE_PACKAGE__": options.basePackage,
"__APPLICATION_CLASS__": options.applicationClass,
"__DESCRIPTION__": options.description,
"__PORT__": String(options.port),
"__DATABASE_DEPENDENCY__": database.dependency,
"__DATABASE_DRIVER__": database.driver,
"__DATABASE_LOCAL_URL__": database.localUrl,
"__MYBATIS_DEPENDENCY__": mybatisDependency,
"__MYBATIS_TEST_DEPENDENCY__": mybatisTestDependency,
"__MYBATIS_CONFIG__": mybatisConfig,
"__REPO_URL__": options.repoUrl,
"__APP_ROOT__": options.appRoot,
"__SERVICE_NAME__": options.serviceName,
"__BRANCH__": options.branch,
"__AGENT_LABEL__": options.agentLabel,
"__MAVEN_CREDENTIAL_ID__": options.mavenCredentialId,
});
if (!options.build) {
console.log("[SKIP] Gradle build");
return;
}
console.log("\n[1/1] Gradle clean build 검증");
if (process.platform === "win32") {
await run("gradlew.bat", ["clean", "build"], options.targetDir);
} else {
await run("./gradlew", ["clean", "build"], options.targetDir);
}
}

96
src/files.ts Normal file
View File

@@ -0,0 +1,96 @@
import { cp, mkdir, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
import path from "node:path";
const ROOT_RENAMES: Record<string, string> = {
"_gitignore": ".gitignore",
"_gitattributes": ".gitattributes",
"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(ROOT_RENAMES)) {
const source = path.join(targetDir, sourceName);
try {
await stat(source);
await rename(source, path.join(targetDir, targetName));
} catch {
// 선택 파일은 없을 수 있습니다.
}
}
}
export async function movePackageDirectories(
targetDir: string,
basePackage: string,
applicationClass: string,
): Promise<void> {
const packageSegments = basePackage.split(".");
for (const sourceRoot of ["main", "test"]) {
const javaRoot = path.join(targetDir, "src", sourceRoot, "java");
const source = path.join(javaRoot, "__BASE_PACKAGE_PATH__");
const destination = path.join(javaRoot, ...packageSegments);
await mkdir(path.dirname(destination), { recursive: true });
await rename(source, destination);
const applicationTemplate = path.join(destination, "Application.java.template");
try {
await stat(applicationTemplate);
await rename(applicationTemplate, path.join(destination, `${applicationClass}.java`));
} catch {
// test 패키지에는 Application 템플릿이 없습니다.
}
}
}
export async function removeMyBatisFiles(targetDir: string, basePackage: string): Promise<void> {
const packagePath = path.join(...basePackage.split("."));
await rm(path.join(targetDir, "src", "main", "java", packagePath, "persistence", "mapper"), {
recursive: true,
force: true,
});
await rm(path.join(targetDir, "src", "main", "resources", "mybatis"), {
recursive: true,
force: true,
});
}
export async function removeJenkinsFiles(targetDir: string): Promise<void> {
await rm(path.join(targetDir, "Jenkinsfile"), { force: true });
await rm(path.join(targetDir, "deploy"), { recursive: true, 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() || /\.(jar|png|ico|jpg|jpeg|gif|webp|gz|zip)$/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);
}

30
src/process.ts Normal file
View File

@@ -0,0 +1,30 @@
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, ...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 === "예";
}

43
src/types.ts Normal file
View File

@@ -0,0 +1,43 @@
export type DatabaseType = "mysql" | "mssql";
export interface CliOptions {
projectName: string;
targetDir: string;
basePackage: string;
applicationClass: string;
description: string;
port: number;
database: DatabaseType;
mybatis: boolean;
repoUrl: string;
appRoot: string;
serviceName: string;
branch: string;
agentLabel: string;
mavenCredentialId: string;
yes: boolean;
build: boolean;
jenkins: boolean;
force: boolean;
}
export interface ParsedArguments {
projectName?: string;
targetDir?: string;
basePackage?: string;
description?: string;
port?: number;
database?: DatabaseType;
mybatis: boolean;
repoUrl?: string;
appRoot?: string;
serviceName?: string;
branch?: string;
agentLabel?: string;
mavenCredentialId?: string;
yes: boolean;
build: boolean;
jenkins: boolean;
force: boolean;
help: boolean;
}