260703_01_FST: First Commit
This commit is contained in:
6
.gitignore
vendored
Normal file
6
.gitignore
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
node_modules/
|
||||
dist/
|
||||
*.tgz
|
||||
.idea/
|
||||
*.iml
|
||||
.DS_Store
|
||||
3
.npmrc
Normal file
3
.npmrc
Normal file
@@ -0,0 +1,3 @@
|
||||
registry=https://registry.npmjs.org/
|
||||
@kri:registry=https://gitea.kric.com/api/packages/KRi/npm/
|
||||
//gitea.kric.com/api/packages/KRi/npm/:_authToken=${GITEA_NPM_TOKEN}
|
||||
81
README.md
Normal file
81
README.md
Normal file
@@ -0,0 +1,81 @@
|
||||
# @kri/create-spring-app
|
||||
|
||||
KRI 표준 Spring Boot 프로젝트 생성 CLI입니다.
|
||||
|
||||
## 기본 구성
|
||||
|
||||
- Java 17
|
||||
- Spring Boot 3.5.7
|
||||
- Gradle Groovy DSL / Gradle Wrapper 8.14.3
|
||||
- `com.kri.common:starter:latest.release`
|
||||
- JPA + QueryDSL + JdbcTemplate 벌크 처리 예제
|
||||
- EmbeddedId 복합키 예제
|
||||
- MyBatis 선택 설치
|
||||
- MySQL 또는 MSSQL 선택
|
||||
- JWT/Security와 API Key는 공용 Starter 설정으로 활성화
|
||||
- Scheduler, 파일 저장소, 정적 리소스 설정 예제
|
||||
- Jenkinsfile 및 systemd 서비스 예제
|
||||
|
||||
## 개발
|
||||
|
||||
```powershell
|
||||
npm install
|
||||
npm run typecheck
|
||||
npm run build
|
||||
```
|
||||
|
||||
## 로컬 실행 테스트
|
||||
|
||||
```powershell
|
||||
node .\dist\cli.js sample-server --yes --skip-build
|
||||
```
|
||||
|
||||
전체 생성 및 Gradle 빌드:
|
||||
|
||||
```powershell
|
||||
node .\dist\cli.js sample-server --yes
|
||||
```
|
||||
|
||||
## 배포 후 사용
|
||||
|
||||
```powershell
|
||||
npx @kri/create-spring-app sample-server
|
||||
```
|
||||
|
||||
## 옵션
|
||||
|
||||
```text
|
||||
--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 도움말
|
||||
```
|
||||
|
||||
## Gitea Maven 인증
|
||||
|
||||
개발자 PC의 `%USERPROFILE%\.gradle\gradle.properties`:
|
||||
|
||||
```properties
|
||||
giteaUser=사용자명
|
||||
giteaToken=Gitea토큰
|
||||
```
|
||||
|
||||
또는 환경변수:
|
||||
|
||||
```text
|
||||
GITEA_MAVEN_USER
|
||||
GITEA_MAVEN_TOKEN
|
||||
```
|
||||
176
package-lock.json
generated
Normal file
176
package-lock.json
generated
Normal file
@@ -0,0 +1,176 @@
|
||||
{
|
||||
"name": "@kri/create-spring-app",
|
||||
"version": "0.1.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@kri/create-spring-app",
|
||||
"version": "0.1.0",
|
||||
"license": "UNLICENSED",
|
||||
"bin": {
|
||||
"kri-create-spring-app": "dist/cli.js"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "latest",
|
||||
"rimraf": "latest",
|
||||
"typescript": "^5"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/node": {
|
||||
"version": "26.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.1.0.tgz",
|
||||
"integrity": "sha512-O0A1G3xPGy4w7AgQdAQYUlQ+BKk2Oovw8eRpofyp5KdBZULnbe+WqaOVNrm705SHphCiG4XHsACrSmPu1f+Kgw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"undici-types": "~8.3.0"
|
||||
}
|
||||
},
|
||||
"node_modules/balanced-match": {
|
||||
"version": "4.0.4",
|
||||
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz",
|
||||
"integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": "18 || 20 || >=22"
|
||||
}
|
||||
},
|
||||
"node_modules/brace-expansion": {
|
||||
"version": "5.0.7",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.7.tgz",
|
||||
"integrity": "sha512-7oFy703dxfY3/NLxC1fh2SUCQ0H9rmAY+5EpDVfXjUTTs+HEwR2nYaqLv+GWcTsumwxPfiz6CzCNkwXwBUwqCA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"balanced-match": "^4.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": "18 || 20 || >=22"
|
||||
}
|
||||
},
|
||||
"node_modules/glob": {
|
||||
"version": "13.0.6",
|
||||
"resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz",
|
||||
"integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==",
|
||||
"dev": true,
|
||||
"license": "BlueOak-1.0.0",
|
||||
"dependencies": {
|
||||
"minimatch": "^10.2.2",
|
||||
"minipass": "^7.1.3",
|
||||
"path-scurry": "^2.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": "18 || 20 || >=22"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/isaacs"
|
||||
}
|
||||
},
|
||||
"node_modules/lru-cache": {
|
||||
"version": "11.5.1",
|
||||
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.1.tgz",
|
||||
"integrity": "sha512-RPimw/7aMdv2oqRrxKwvZXcPfwBrn/JZ2xYcY9Hus/6LaS3VOAKVWKWgNLCFSiOm1ESXinjsDlidVU7JlnCN2A==",
|
||||
"dev": true,
|
||||
"license": "BlueOak-1.0.0",
|
||||
"engines": {
|
||||
"node": "20 || >=22"
|
||||
}
|
||||
},
|
||||
"node_modules/minimatch": {
|
||||
"version": "10.2.5",
|
||||
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz",
|
||||
"integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==",
|
||||
"dev": true,
|
||||
"license": "BlueOak-1.0.0",
|
||||
"dependencies": {
|
||||
"brace-expansion": "^5.0.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": "18 || 20 || >=22"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/isaacs"
|
||||
}
|
||||
},
|
||||
"node_modules/minipass": {
|
||||
"version": "7.1.3",
|
||||
"resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz",
|
||||
"integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==",
|
||||
"dev": true,
|
||||
"license": "BlueOak-1.0.0",
|
||||
"engines": {
|
||||
"node": ">=16 || 14 >=14.17"
|
||||
}
|
||||
},
|
||||
"node_modules/package-json-from-dist": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz",
|
||||
"integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==",
|
||||
"dev": true,
|
||||
"license": "BlueOak-1.0.0"
|
||||
},
|
||||
"node_modules/path-scurry": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz",
|
||||
"integrity": "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==",
|
||||
"dev": true,
|
||||
"license": "BlueOak-1.0.0",
|
||||
"dependencies": {
|
||||
"lru-cache": "^11.0.0",
|
||||
"minipass": "^7.1.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": "18 || 20 || >=22"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/isaacs"
|
||||
}
|
||||
},
|
||||
"node_modules/rimraf": {
|
||||
"version": "6.1.3",
|
||||
"resolved": "https://registry.npmjs.org/rimraf/-/rimraf-6.1.3.tgz",
|
||||
"integrity": "sha512-LKg+Cr2ZF61fkcaK1UdkH2yEBBKnYjTyWzTJT6KNPcSPaiT7HSdhtMXQuN5wkTX0Xu72KQ1l8S42rlmexS2hSA==",
|
||||
"dev": true,
|
||||
"license": "BlueOak-1.0.0",
|
||||
"dependencies": {
|
||||
"glob": "^13.0.3",
|
||||
"package-json-from-dist": "^1.0.1"
|
||||
},
|
||||
"bin": {
|
||||
"rimraf": "dist/esm/bin.mjs"
|
||||
},
|
||||
"engines": {
|
||||
"node": "20 || >=22"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/isaacs"
|
||||
}
|
||||
},
|
||||
"node_modules/typescript": {
|
||||
"version": "5.9.3",
|
||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
|
||||
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
"tsserver": "bin/tsserver"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14.17"
|
||||
}
|
||||
},
|
||||
"node_modules/undici-types": {
|
||||
"version": "8.3.0",
|
||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz",
|
||||
"integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
}
|
||||
}
|
||||
}
|
||||
33
package.json
Normal file
33
package.json
Normal file
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"name": "@kri/create-spring-app",
|
||||
"version": "0.1.0",
|
||||
"description": "Create a KRI standard Spring Boot application",
|
||||
"type": "module",
|
||||
"bin": {
|
||||
"kri-create-spring-app": "./dist/cli.js"
|
||||
},
|
||||
"files": [
|
||||
"dist",
|
||||
"templates",
|
||||
"README.md"
|
||||
],
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"build": "npm run clean && tsc -p tsconfig.json",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||
"prepack": "npm run build"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "latest",
|
||||
"rimraf": "latest",
|
||||
"typescript": "^5"
|
||||
},
|
||||
"publishConfig": {
|
||||
"registry": "https://gitea.kric.com/api/packages/KRi/npm/",
|
||||
"access": "restricted"
|
||||
},
|
||||
"license": "UNLICENSED"
|
||||
}
|
||||
138
src/args.ts
Normal file
138
src/args.ts
Normal 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
145
src/cli.ts
Normal 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
87
src/create-project.ts
Normal 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
96
src/files.ts
Normal 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
30
src/process.ts
Normal 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
20
src/prompts.ts
Normal 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
43
src/types.ts
Normal 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;
|
||||
}
|
||||
103
templates/base/Jenkinsfile.template
Normal file
103
templates/base/Jenkinsfile.template
Normal file
@@ -0,0 +1,103 @@
|
||||
pipeline {
|
||||
agent none
|
||||
|
||||
options {
|
||||
disableConcurrentBuilds()
|
||||
timestamps()
|
||||
}
|
||||
|
||||
environment {
|
||||
AGENT_LABEL = '__AGENT_LABEL__'
|
||||
REPO_URL = '__REPO_URL__'
|
||||
BRANCH = '__BRANCH__'
|
||||
SERVICE_NAME = '__SERVICE_NAME__'
|
||||
APP_ROOT = '__APP_ROOT__'
|
||||
}
|
||||
|
||||
stages {
|
||||
stage('Git Pull') {
|
||||
agent { label "${env.AGENT_LABEL}" }
|
||||
steps {
|
||||
deleteDir()
|
||||
dir('src') {
|
||||
git branch: env.BRANCH, url: env.REPO_URL
|
||||
sh '''#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
echo "[INFO] branch=$(git rev-parse --abbrev-ref HEAD)"
|
||||
echo "[INFO] commit=$(git rev-parse --short HEAD)"
|
||||
'''
|
||||
}
|
||||
stash name: 'src', includes: 'src/**,src/.*,src/**/.*', excludes: 'src/.git/**'
|
||||
}
|
||||
}
|
||||
|
||||
stage('Build') {
|
||||
agent { label "${env.AGENT_LABEL}" }
|
||||
steps {
|
||||
deleteDir()
|
||||
unstash 'src'
|
||||
dir('src') {
|
||||
withCredentials([
|
||||
usernamePassword(
|
||||
credentialsId: '__MAVEN_CREDENTIAL_ID__',
|
||||
usernameVariable: 'GITEA_MAVEN_USER',
|
||||
passwordVariable: 'GITEA_MAVEN_TOKEN'
|
||||
)
|
||||
]) {
|
||||
sh '''#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
chmod +x gradlew
|
||||
./gradlew clean bootJar
|
||||
|
||||
JAR_FILE="$(find build/libs -maxdepth 1 -type f -name '*.jar' ! -name '*-plain.jar' -print -quit)"
|
||||
test -n "${JAR_FILE}"
|
||||
cp "${JAR_FILE}" artifact.jar
|
||||
ls -lh artifact.jar
|
||||
'''
|
||||
}
|
||||
stash name: 'artifact', includes: 'artifact.jar'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stage('Deploy') {
|
||||
agent { label "${env.AGENT_LABEL}" }
|
||||
steps {
|
||||
deleteDir()
|
||||
unstash 'artifact'
|
||||
sh '''#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
mkdir -p "${APP_ROOT}/releases"
|
||||
TS="$(date +%Y%m%d_%H%M%S)"
|
||||
RELEASE_DIR="${APP_ROOT}/releases/${TS}"
|
||||
mkdir -p "${RELEASE_DIR}"
|
||||
cp artifact.jar "${RELEASE_DIR}/app.jar"
|
||||
ln -sfn "${RELEASE_DIR}" "${APP_ROOT}/current"
|
||||
test -f "${APP_ROOT}/current/app.jar"
|
||||
ls -1dt "${APP_ROOT}"/releases/* 2>/dev/null | tail -n +6 | xargs -r rm -rf
|
||||
echo "[INFO] deployed release=${RELEASE_DIR}"
|
||||
'''
|
||||
}
|
||||
}
|
||||
|
||||
stage('Service Restart') {
|
||||
agent { label "${env.AGENT_LABEL}" }
|
||||
steps {
|
||||
sh '''#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
sudo -n /usr/bin/systemctl restart "${SERVICE_NAME}"
|
||||
sudo -n /usr/bin/systemctl status "${SERVICE_NAME}" --no-pager -l | head -n 80
|
||||
'''
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
post {
|
||||
success {
|
||||
echo '__PROJECT_NAME__ deployment completed successfully.'
|
||||
}
|
||||
failure {
|
||||
echo '__PROJECT_NAME__ deployment failed.'
|
||||
}
|
||||
}
|
||||
}
|
||||
73
templates/base/README.md.template
Normal file
73
templates/base/README.md.template
Normal file
@@ -0,0 +1,73 @@
|
||||
# __PROJECT_NAME__
|
||||
|
||||
__DESCRIPTION__
|
||||
|
||||
## 기술 구성
|
||||
|
||||
- Java 17
|
||||
- Spring Boot 3.5.7
|
||||
- `com.kri.common:starter:latest.release`
|
||||
- JPA + QueryDSL + JdbcTemplate
|
||||
- EmbeddedId 예제
|
||||
- MyBatis는 생성 옵션에 따라 포함
|
||||
|
||||
## Gitea Maven 인증
|
||||
|
||||
Windows 사용자 Gradle 설정:
|
||||
|
||||
```text
|
||||
%USERPROFILE%\.gradle\gradle.properties
|
||||
```
|
||||
|
||||
```properties
|
||||
giteaUser=사용자명
|
||||
giteaToken=Gitea토큰
|
||||
```
|
||||
|
||||
또는 다음 환경변수를 사용할 수 있습니다.
|
||||
|
||||
```text
|
||||
GITEA_MAVEN_USER
|
||||
GITEA_MAVEN_TOKEN
|
||||
```
|
||||
|
||||
## 실행
|
||||
|
||||
Windows:
|
||||
|
||||
```powershell
|
||||
.\gradlew.bat bootRun
|
||||
```
|
||||
|
||||
Linux/macOS:
|
||||
|
||||
```bash
|
||||
./gradlew bootRun
|
||||
```
|
||||
|
||||
프로필 지정:
|
||||
|
||||
```powershell
|
||||
.\gradlew.bat bootRun --args="--spring.profiles.active=local"
|
||||
```
|
||||
|
||||
## 빌드
|
||||
|
||||
```powershell
|
||||
.\gradlew.bat clean build
|
||||
```
|
||||
|
||||
## 인증 설정
|
||||
|
||||
공용 Starter 설정으로 제어합니다.
|
||||
|
||||
```yaml
|
||||
kri:
|
||||
security:
|
||||
enabled: true
|
||||
auth:
|
||||
apikey:
|
||||
enabled: false
|
||||
```
|
||||
|
||||
프로젝트 내부에 JWT/API Key 필터를 중복 구현하지 않습니다.
|
||||
3
templates/base/_gitattributes
Normal file
3
templates/base/_gitattributes
Normal file
@@ -0,0 +1,3 @@
|
||||
/gradlew text eol=lf
|
||||
*.bat text eol=crlf
|
||||
*.jar binary
|
||||
24
templates/base/_gitignore
Normal file
24
templates/base/_gitignore
Normal file
@@ -0,0 +1,24 @@
|
||||
.gradle/
|
||||
build/
|
||||
!gradle/wrapper/gradle-wrapper.jar
|
||||
!**/src/main/**/build/
|
||||
!**/src/test/**/build/
|
||||
|
||||
### IntelliJ IDEA ###
|
||||
.idea/
|
||||
*.iws
|
||||
*.iml
|
||||
*.ipr
|
||||
out/
|
||||
|
||||
### VS Code ###
|
||||
.vscode/
|
||||
|
||||
### Logs / runtime files ###
|
||||
logs/
|
||||
upload-file/
|
||||
*.log
|
||||
|
||||
### OS ###
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
95
templates/base/build.gradle
Normal file
95
templates/base/build.gradle
Normal file
@@ -0,0 +1,95 @@
|
||||
plugins {
|
||||
id 'java'
|
||||
id 'org.springframework.boot' version '3.5.7'
|
||||
id 'io.spring.dependency-management' version '1.1.7'
|
||||
}
|
||||
|
||||
group = '__BASE_PACKAGE__'
|
||||
version = '0.0.1-SNAPSHOT'
|
||||
description = '__DESCRIPTION__'
|
||||
|
||||
java {
|
||||
toolchain {
|
||||
languageVersion = JavaLanguageVersion.of(17)
|
||||
}
|
||||
}
|
||||
|
||||
configurations {
|
||||
compileOnly {
|
||||
extendsFrom annotationProcessor
|
||||
}
|
||||
}
|
||||
|
||||
def giteaUser = findProperty('giteaUser')
|
||||
?: System.getenv('GITEA_MAVEN_USER')
|
||||
?: ''
|
||||
def giteaToken = findProperty('giteaToken')
|
||||
?: System.getenv('GITEA_MAVEN_TOKEN')
|
||||
?: ''
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
|
||||
maven {
|
||||
name = 'gitea'
|
||||
url = uri('https://gitea.kric.com/api/packages/KRi/maven')
|
||||
credentials {
|
||||
username = giteaUser
|
||||
password = giteaToken
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
configurations.configureEach {
|
||||
resolutionStrategy.cacheDynamicVersionsFor 0, 'seconds'
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation 'com.kri.common:starter:latest.release'
|
||||
|
||||
implementation 'org.springframework.boot:spring-boot-starter-web'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-security'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-validation'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-jdbc'
|
||||
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.8.11'
|
||||
|
||||
implementation 'io.github.openfeign.querydsl:querydsl-jpa:7.1'
|
||||
annotationProcessor 'com.querydsl:querydsl-apt:5.0.0:jakarta'
|
||||
annotationProcessor 'jakarta.annotation:jakarta.annotation-api'
|
||||
annotationProcessor 'jakarta.persistence:jakarta.persistence-api'
|
||||
|
||||
__DATABASE_DEPENDENCY__
|
||||
__MYBATIS_DEPENDENCY__
|
||||
|
||||
compileOnly 'org.projectlombok:lombok'
|
||||
annotationProcessor 'org.projectlombok:lombok'
|
||||
|
||||
developmentOnly 'org.springframework.boot:spring-boot-devtools'
|
||||
|
||||
testImplementation 'org.springframework.boot:spring-boot-starter-test'
|
||||
testImplementation 'org.springframework.security:spring-security-test'
|
||||
__MYBATIS_TEST_DEPENDENCY__
|
||||
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
|
||||
}
|
||||
|
||||
def querydslDir = layout.buildDirectory.dir('generated/querydsl').get().asFile
|
||||
|
||||
sourceSets {
|
||||
main.java.srcDirs += [querydslDir]
|
||||
}
|
||||
|
||||
tasks.withType(JavaCompile).configureEach {
|
||||
options.encoding = 'UTF-8'
|
||||
options.generatedSourceOutputDirectory.set(file(querydslDir))
|
||||
}
|
||||
|
||||
tasks.named('test') {
|
||||
useJUnitPlatform()
|
||||
}
|
||||
|
||||
tasks.named('clean') {
|
||||
doLast {
|
||||
delete querydslDir
|
||||
}
|
||||
}
|
||||
16
templates/base/deploy/systemd.service.example
Normal file
16
templates/base/deploy/systemd.service.example
Normal file
@@ -0,0 +1,16 @@
|
||||
[Unit]
|
||||
Description=__PROJECT_NAME__
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=jenkins
|
||||
WorkingDirectory=__APP_ROOT__/current
|
||||
Environment=SPRING_PROFILES_ACTIVE=prod
|
||||
ExecStart=/usr/bin/java -jar __APP_ROOT__/current/app.jar
|
||||
Restart=always
|
||||
RestartSec=5
|
||||
SuccessExitStatus=143
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
3
templates/base/gradle.properties
Normal file
3
templates/base/gradle.properties
Normal file
@@ -0,0 +1,3 @@
|
||||
org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8
|
||||
org.gradle.parallel=true
|
||||
org.gradle.caching=true
|
||||
BIN
templates/base/gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
BIN
templates/base/gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
Binary file not shown.
7
templates/base/gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
7
templates/base/gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
251
templates/base/gradlew
vendored
Normal file
251
templates/base/gradlew
vendored
Normal file
@@ -0,0 +1,251 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015-2021 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# This is normally unused
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH="\\\"\\\""
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
if ! command -v java >/dev/null 2>&1
|
||||
then
|
||||
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Collect all arguments for the java command:
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# and any embedded shellness will be escaped.
|
||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||
# treated as '${Hostname}' itself on the command line.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
if ! command -v xargs >/dev/null 2>&1
|
||||
then
|
||||
die "xargs is not available"
|
||||
fi
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
#
|
||||
# In Bash we could simply go:
|
||||
#
|
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||
# set -- "${ARGS[@]}" "$@"
|
||||
#
|
||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||
# character that might be a shell metacharacter, then use eval to reverse
|
||||
# that process (while maintaining the separation between arguments), and wrap
|
||||
# the whole thing up as a single "set" statement.
|
||||
#
|
||||
# This will of course break if any of these variables contains a newline or
|
||||
# an unmatched quote.
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
94
templates/base/gradlew.bat
vendored
Normal file
94
templates/base/gradlew.bat
vendored
Normal file
@@ -0,0 +1,94 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
@rem SPDX-License-Identifier: Apache-2.0
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%"=="" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%"=="" set DIRNAME=.
|
||||
@rem This is normally unused
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if %ERRORLEVEL% equ 0 goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
set EXIT_CODE=%ERRORLEVEL%
|
||||
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||
exit /b %EXIT_CODE%
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
1
templates/base/settings.gradle
Normal file
1
templates/base/settings.gradle
Normal file
@@ -0,0 +1 @@
|
||||
rootProject.name = '__PROJECT_NAME__'
|
||||
@@ -0,0 +1,14 @@
|
||||
package __BASE_PACKAGE__;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
|
||||
|
||||
@SpringBootApplication
|
||||
@ConfigurationPropertiesScan
|
||||
public class __APPLICATION_CLASS__ {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(__APPLICATION_CLASS__.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package __BASE_PACKAGE__.common.consts;
|
||||
|
||||
public final class ExampleConstant {
|
||||
|
||||
public static final int DEFAULT_BATCH_SIZE = 1_000;
|
||||
|
||||
private ExampleConstant() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package __BASE_PACKAGE__.common.enums;
|
||||
|
||||
public enum ExampleStatus {
|
||||
ACTIVE,
|
||||
INACTIVE
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package __BASE_PACKAGE__.common.util;
|
||||
|
||||
public final class StringNormalizer {
|
||||
|
||||
private StringNormalizer() {
|
||||
}
|
||||
|
||||
public static String trimToNull(String value) {
|
||||
if (value == null) return null;
|
||||
String normalized = value.trim();
|
||||
return normalized.isEmpty() ? null : normalized;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
/**
|
||||
* 프로젝트 전용 Bean Validation annotation과 validator를 배치합니다.
|
||||
*/
|
||||
package __BASE_PACKAGE__.common.validation;
|
||||
@@ -0,0 +1,14 @@
|
||||
package __BASE_PACKAGE__.config;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@ConfigurationProperties(prefix = "kri.file")
|
||||
public class FileStorageProperties {
|
||||
|
||||
private String baseDir = "./upload-file";
|
||||
private String resourcePattern = "/files/**";
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package __BASE_PACKAGE__.config;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
|
||||
@Configuration
|
||||
public class JdbcConfig {
|
||||
|
||||
@Bean
|
||||
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
|
||||
return new JdbcTemplate(dataSource);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package __BASE_PACKAGE__.config;
|
||||
|
||||
import com.querydsl.jpa.impl.JPAQueryFactory;
|
||||
import jakarta.persistence.EntityManager;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@RequiredArgsConstructor
|
||||
public class QueryDSLConfig {
|
||||
|
||||
private final EntityManager entityManager;
|
||||
|
||||
@Bean
|
||||
public JPAQueryFactory jpaQueryFactory() {
|
||||
return new JPAQueryFactory(entityManager);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package __BASE_PACKAGE__.config;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@Configuration
|
||||
@RequiredArgsConstructor
|
||||
public class WebResourceConfig implements WebMvcConfigurer {
|
||||
|
||||
private final FileStorageProperties fileStorageProperties;
|
||||
|
||||
@Override
|
||||
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||
String location = Path.of(fileStorageProperties.getBaseDir())
|
||||
.toAbsolutePath()
|
||||
.normalize()
|
||||
.toUri()
|
||||
.toString();
|
||||
|
||||
registry.addResourceHandler(fileStorageProperties.getResourcePattern())
|
||||
.addResourceLocations(location.endsWith("/") ? location : location + "/");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package __BASE_PACKAGE__.controller;
|
||||
|
||||
import __BASE_PACKAGE__.dto.request.CreateExampleRequest;
|
||||
import __BASE_PACKAGE__.dto.response.ExampleResponse;
|
||||
import __BASE_PACKAGE__.service.ExampleService;
|
||||
import jakarta.validation.Valid;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/api/v1/examples")
|
||||
public class ExampleController {
|
||||
|
||||
private final ExampleService exampleService;
|
||||
|
||||
@GetMapping
|
||||
public List<ExampleResponse> search(
|
||||
@RequestParam(defaultValue = "") String keyword,
|
||||
@RequestParam(defaultValue = "20") int limit
|
||||
) {
|
||||
return exampleService.search(keyword, limit);
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
public ExampleResponse create(@Valid @RequestBody CreateExampleRequest request) {
|
||||
return exampleService.create(request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package __BASE_PACKAGE__.controller;
|
||||
|
||||
import java.util.Map;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
public class PingController {
|
||||
|
||||
@GetMapping("/ping")
|
||||
public Map<String, String> ping() {
|
||||
return Map.of("status", "ok");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package __BASE_PACKAGE__.dto.request;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Positive;
|
||||
|
||||
public record CreateExampleRequest(
|
||||
@NotNull @Positive Long groupId,
|
||||
@NotNull @Positive Integer sequence,
|
||||
@NotBlank String name
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package __BASE_PACKAGE__.dto.response;
|
||||
|
||||
import __BASE_PACKAGE__.persistence.entity.ExampleEntity;
|
||||
|
||||
public record ExampleResponse(
|
||||
Long groupId,
|
||||
Integer sequence,
|
||||
String name,
|
||||
String status
|
||||
) {
|
||||
public static ExampleResponse from(ExampleEntity entity) {
|
||||
return new ExampleResponse(
|
||||
entity.getId().getGroupId(),
|
||||
entity.getId().getSequence(),
|
||||
entity.getName(),
|
||||
entity.getStatus().name()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package __BASE_PACKAGE__.persistence.entity;
|
||||
|
||||
import __BASE_PACKAGE__.common.enums.ExampleStatus;
|
||||
import __BASE_PACKAGE__.persistence.entity.id.ExampleEntityId;
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.EmbeddedId;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.EnumType;
|
||||
import jakarta.persistence.Enumerated;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Getter
|
||||
@Entity
|
||||
@Table(name = "t_example")
|
||||
@NoArgsConstructor(access = AccessLevel.PROTECTED)
|
||||
public class ExampleEntity {
|
||||
|
||||
@EmbeddedId
|
||||
private ExampleEntityId id;
|
||||
|
||||
@Column(name = "name", nullable = false, length = 100)
|
||||
private String name;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(name = "status", nullable = false, length = 20)
|
||||
private ExampleStatus status;
|
||||
|
||||
@Builder
|
||||
public ExampleEntity(ExampleEntityId id, String name, ExampleStatus status) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.status = status == null ? ExampleStatus.ACTIVE : status;
|
||||
}
|
||||
|
||||
public void changeName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package __BASE_PACKAGE__.persistence.entity.id;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Embeddable;
|
||||
import java.io.Serial;
|
||||
import java.io.Serializable;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Getter
|
||||
@Embeddable
|
||||
@EqualsAndHashCode
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor(access = AccessLevel.PROTECTED)
|
||||
public class ExampleEntityId implements Serializable {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Column(name = "group_id", nullable = false)
|
||||
private Long groupId;
|
||||
|
||||
@Column(name = "sequence", nullable = false)
|
||||
private Integer sequence;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package __BASE_PACKAGE__.persistence.jdbc;
|
||||
|
||||
public record ExampleBulkItem(
|
||||
Long groupId,
|
||||
Integer sequence,
|
||||
String name,
|
||||
String status
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package __BASE_PACKAGE__.persistence.jdbc;
|
||||
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
public class ExampleBulkJdbcRepository {
|
||||
|
||||
private final JdbcTemplate jdbcTemplate;
|
||||
|
||||
public void insertAll(List<ExampleBulkItem> items, int batchSize) {
|
||||
if (items == null || items.isEmpty()) return;
|
||||
|
||||
String sql = """
|
||||
insert into t_example (group_id, sequence, name, status)
|
||||
values (?, ?, ?, ?)
|
||||
""";
|
||||
|
||||
int safeBatchSize = Math.max(batchSize, 1);
|
||||
for (int from = 0; from < items.size(); from += safeBatchSize) {
|
||||
int to = Math.min(from + safeBatchSize, items.size());
|
||||
List<ExampleBulkItem> batch = items.subList(from, to);
|
||||
|
||||
jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
|
||||
@Override
|
||||
public void setValues(PreparedStatement statement, int index) throws SQLException {
|
||||
ExampleBulkItem item = batch.get(index);
|
||||
statement.setLong(1, item.groupId());
|
||||
statement.setInt(2, item.sequence());
|
||||
statement.setString(3, item.name());
|
||||
statement.setString(4, item.status());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getBatchSize() {
|
||||
return batch.size();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package __BASE_PACKAGE__.persistence.mapper;
|
||||
|
||||
import __BASE_PACKAGE__.dto.response.ExampleResponse;
|
||||
import java.util.List;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
@Mapper
|
||||
public interface ExampleMapper {
|
||||
List<ExampleResponse> findByName(@Param("keyword") String keyword);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package __BASE_PACKAGE__.persistence.query;
|
||||
|
||||
import __BASE_PACKAGE__.persistence.entity.QExampleEntity;
|
||||
import com.querydsl.core.types.dsl.BooleanExpression;
|
||||
|
||||
public final class ExamplePredicates {
|
||||
|
||||
private ExamplePredicates() {
|
||||
}
|
||||
|
||||
public static BooleanExpression nameContains(QExampleEntity example, String keyword) {
|
||||
if (keyword == null || keyword.isBlank()) return null;
|
||||
return example.name.containsIgnoreCase(keyword.trim());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package __BASE_PACKAGE__.persistence.repository;
|
||||
|
||||
import __BASE_PACKAGE__.persistence.entity.ExampleEntity;
|
||||
import java.util.List;
|
||||
|
||||
public interface ExampleQueryRepository {
|
||||
List<ExampleEntity> findByNameContains(String keyword, int limit);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package __BASE_PACKAGE__.persistence.repository;
|
||||
|
||||
import static __BASE_PACKAGE__.persistence.entity.QExampleEntity.exampleEntity;
|
||||
|
||||
import __BASE_PACKAGE__.persistence.entity.ExampleEntity;
|
||||
import __BASE_PACKAGE__.persistence.query.ExamplePredicates;
|
||||
import com.querydsl.jpa.impl.JPAQueryFactory;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
@RequiredArgsConstructor
|
||||
public class ExampleQueryRepositoryImpl implements ExampleQueryRepository {
|
||||
|
||||
private final JPAQueryFactory jpaQueryFactory;
|
||||
|
||||
@Override
|
||||
public List<ExampleEntity> findByNameContains(String keyword, int limit) {
|
||||
return jpaQueryFactory
|
||||
.selectFrom(exampleEntity)
|
||||
.where(ExamplePredicates.nameContains(exampleEntity, keyword))
|
||||
.orderBy(exampleEntity.id.groupId.asc(), exampleEntity.id.sequence.asc())
|
||||
.limit(Math.max(limit, 1))
|
||||
.fetch();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package __BASE_PACKAGE__.persistence.repository;
|
||||
|
||||
import __BASE_PACKAGE__.persistence.entity.ExampleEntity;
|
||||
import __BASE_PACKAGE__.persistence.entity.id.ExampleEntityId;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface ExampleRepository
|
||||
extends JpaRepository<ExampleEntity, ExampleEntityId>, ExampleQueryRepository {
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package __BASE_PACKAGE__.scheduler;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@ConditionalOnProperty(
|
||||
prefix = "app.scheduler.example",
|
||||
name = "enabled",
|
||||
havingValue = "true"
|
||||
)
|
||||
public class ExampleScheduler {
|
||||
|
||||
@Scheduled(cron = "${app.scheduler.example.cron:0 0 1 * * *}")
|
||||
public void execute() {
|
||||
log.info("Example scheduler executed");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package __BASE_PACKAGE__.service;
|
||||
|
||||
import __BASE_PACKAGE__.common.enums.ExampleStatus;
|
||||
import __BASE_PACKAGE__.dto.request.CreateExampleRequest;
|
||||
import __BASE_PACKAGE__.dto.response.ExampleResponse;
|
||||
import __BASE_PACKAGE__.persistence.entity.ExampleEntity;
|
||||
import __BASE_PACKAGE__.persistence.entity.id.ExampleEntityId;
|
||||
import __BASE_PACKAGE__.persistence.repository.ExampleRepository;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Transactional(readOnly = true)
|
||||
public class ExampleService {
|
||||
|
||||
private final ExampleRepository exampleRepository;
|
||||
|
||||
@Transactional
|
||||
public ExampleResponse create(CreateExampleRequest request) {
|
||||
ExampleEntity entity = ExampleEntity.builder()
|
||||
.id(new ExampleEntityId(request.groupId(), request.sequence()))
|
||||
.name(request.name())
|
||||
.status(ExampleStatus.ACTIVE)
|
||||
.build();
|
||||
return ExampleResponse.from(exampleRepository.save(entity));
|
||||
}
|
||||
|
||||
public List<ExampleResponse> search(String keyword, int limit) {
|
||||
return exampleRepository.findByNameContains(keyword == null ? "" : keyword, limit)
|
||||
.stream()
|
||||
.map(ExampleResponse::from)
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
10
templates/base/src/main/resources/application-dev.yml
Normal file
10
templates/base/src/main/resources/application-dev.yml
Normal file
@@ -0,0 +1,10 @@
|
||||
spring:
|
||||
datasource:
|
||||
url: "${DB_URL}"
|
||||
username: "${DB_USERNAME}"
|
||||
password: "${DB_PASSWORD}"
|
||||
driver-class-name: __DATABASE_DRIVER__
|
||||
|
||||
logging:
|
||||
level:
|
||||
org.hibernate.SQL: DEBUG
|
||||
6
templates/base/src/main/resources/application-local.yml
Normal file
6
templates/base/src/main/resources/application-local.yml
Normal file
@@ -0,0 +1,6 @@
|
||||
spring:
|
||||
datasource:
|
||||
url: "${DB_URL:__DATABASE_LOCAL_URL__}"
|
||||
username: "${DB_USERNAME:sample}"
|
||||
password: "${DB_PASSWORD:sample}"
|
||||
driver-class-name: __DATABASE_DRIVER__
|
||||
10
templates/base/src/main/resources/application-prod.yml
Normal file
10
templates/base/src/main/resources/application-prod.yml
Normal file
@@ -0,0 +1,10 @@
|
||||
spring:
|
||||
datasource:
|
||||
url: "${DB_URL}"
|
||||
username: "${DB_USERNAME}"
|
||||
password: "${DB_PASSWORD}"
|
||||
driver-class-name: __DATABASE_DRIVER__
|
||||
|
||||
kri:
|
||||
swagger:
|
||||
enabled: ${KRI_SWAGGER_ENABLED:false}
|
||||
71
templates/base/src/main/resources/application.yml
Normal file
71
templates/base/src/main/resources/application.yml
Normal file
@@ -0,0 +1,71 @@
|
||||
server:
|
||||
port: __PORT__
|
||||
forward-headers-strategy: framework
|
||||
|
||||
spring:
|
||||
application:
|
||||
name: __PROJECT_NAME__
|
||||
profiles:
|
||||
default: local
|
||||
jpa:
|
||||
open-in-view: false
|
||||
hibernate:
|
||||
ddl-auto: none
|
||||
properties:
|
||||
hibernate:
|
||||
jdbc:
|
||||
batch_size: 1000
|
||||
order_inserts: true
|
||||
order_updates: true
|
||||
format_sql: true
|
||||
servlet:
|
||||
multipart:
|
||||
max-file-size: 20MB
|
||||
max-request-size: 20MB
|
||||
|
||||
logging:
|
||||
file:
|
||||
path: ./logs
|
||||
|
||||
kri:
|
||||
auth:
|
||||
apikey:
|
||||
enabled: ${KRI_API_KEY_ENABLED:false}
|
||||
key: ${KRI_API_KEY:}
|
||||
header-name: ${KRI_API_KEY_HEADER_NAME:X-API-Key}
|
||||
service-code: ${KRI_API_KEY_SERVICE_CODE:__PROJECT_NAME__}
|
||||
preload-on-startup: ${KRI_API_KEY_PRELOAD_ON_STARTUP:false}
|
||||
admin-api-enabled: ${KRI_API_KEY_ADMIN_ENABLED:false}
|
||||
admin-allow-ips: []
|
||||
security:
|
||||
enabled: ${KRI_SECURITY_ENABLED:true}
|
||||
public-paths:
|
||||
- /v3/api-docs/**
|
||||
- /swagger-ui.html
|
||||
- /swagger-ui/**
|
||||
- /ping
|
||||
- /files/**
|
||||
swagger:
|
||||
enabled: ${KRI_SWAGGER_ENABLED:true}
|
||||
title: "__PROJECT_NAME__ API"
|
||||
description: "__DESCRIPTION__"
|
||||
version: "v1.0.0"
|
||||
base-package: "__BASE_PACKAGE__"
|
||||
allowed-ips: []
|
||||
file:
|
||||
base-dir: ${FILE_STORAGE_BASE_DIR:./upload-file}
|
||||
resource-pattern: /files/**
|
||||
web:
|
||||
enabled: true
|
||||
redis:
|
||||
enabled: false
|
||||
scheduling:
|
||||
enabled: true
|
||||
|
||||
app:
|
||||
scheduler:
|
||||
example:
|
||||
enabled: ${EXAMPLE_SCHEDULER_ENABLED:false}
|
||||
cron: ${EXAMPLE_SCHEDULER_CRON:0 0 1 * * *}
|
||||
|
||||
__MYBATIS_CONFIG__
|
||||
@@ -0,0 +1,16 @@
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<!DOCTYPE mapper
|
||||
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="__BASE_PACKAGE__.persistence.mapper.ExampleMapper">
|
||||
<select id="findByName" resultType="__BASE_PACKAGE__.dto.response.ExampleResponse">
|
||||
select
|
||||
group_id as groupId,
|
||||
sequence,
|
||||
name,
|
||||
status
|
||||
from t_example
|
||||
where name like concat('%', #{keyword}, '%')
|
||||
order by group_id, sequence
|
||||
</select>
|
||||
</mapper>
|
||||
@@ -0,0 +1,13 @@
|
||||
package __BASE_PACKAGE__;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class PackageStructureTest {
|
||||
|
||||
@Test
|
||||
void templateIsGenerated() {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
18
tsconfig.json
Normal file
18
tsconfig.json
Normal file
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"lib": ["ES2022"],
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"rootDir": "src",
|
||||
"outDir": "dist",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"declaration": true,
|
||||
"sourceMap": true,
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src/**/*.ts"]
|
||||
}
|
||||
Reference in New Issue
Block a user