@simplix-boot/cli 0.0.0-stage → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/LICENSE +25 -0
  2. package/LICENSE_KO +28 -0
  3. package/README.md +146 -2
  4. package/bin/simplix-boot.js +6 -0
  5. package/package.json +45 -4
  6. package/src/cli.js +103 -0
  7. package/src/commands/config.js +129 -0
  8. package/src/commands/generate.js +291 -0
  9. package/src/commands/generated.js +125 -0
  10. package/src/commands/init.js +41 -0
  11. package/src/commands/promote.js +172 -0
  12. package/src/commands/templates.js +100 -0
  13. package/src/commands/version.js +134 -0
  14. package/src/lib/analysis/fields.js +217 -0
  15. package/src/lib/analysis/imports.js +76 -0
  16. package/src/lib/analysis/structure.js +193 -0
  17. package/src/lib/analysis/types.js +94 -0
  18. package/src/lib/args.js +69 -0
  19. package/src/lib/comment-extractor.js +141 -0
  20. package/src/lib/config/fields.js +321 -0
  21. package/src/lib/config/parents.js +108 -0
  22. package/src/lib/config/paths.js +156 -0
  23. package/src/lib/config/yml.js +61 -0
  24. package/src/lib/console.js +83 -0
  25. package/src/lib/controller-name.js +33 -0
  26. package/src/lib/entity-analyzer.js +49 -0
  27. package/src/lib/entity-type-resolver.js +80 -0
  28. package/src/lib/entity-type.js +35 -0
  29. package/src/lib/errors.js +17 -0
  30. package/src/lib/export-config.js +74 -0
  31. package/src/lib/file-utils.js +77 -0
  32. package/src/lib/generate/file-plan.js +155 -0
  33. package/src/lib/generate/search-fields.js +111 -0
  34. package/src/lib/generate/settings.js +111 -0
  35. package/src/lib/generate/support-classes.js +47 -0
  36. package/src/lib/generate/template-vars.js +183 -0
  37. package/src/lib/git-utils.js +18 -0
  38. package/src/lib/name-field.js +42 -0
  39. package/src/lib/project.js +121 -0
  40. package/src/lib/promote-files.js +132 -0
  41. package/src/lib/rendered-output.js +13 -0
  42. package/src/lib/search-operators.js +87 -0
  43. package/src/lib/templates.js +50 -0
  44. package/src/lib/tracked-render.js +200 -0
  45. package/src/lib/version-check.js +195 -0
  46. package/src/lib/version-utils.js +97 -0
  47. package/templates/controller/rest/EntityRestController.java.template +517 -0
  48. package/templates/controller/web/EntityWebController.java.template +211 -0
  49. package/templates/dto/EntityDTOs.java.template +981 -0
  50. package/templates/repository/EntityRepository.java.template +78 -0
  51. package/templates/service/EntityService.java.template +790 -0
  52. package/templates/service/EntityTreeService.java.template +352 -0
  53. package/templates/test/EntityServiceTest.java.template +937 -0
  54. package/templates/test/EntityTreeServiceTest.java.template +842 -0
package/LICENSE ADDED
@@ -0,0 +1,25 @@
1
+ SimpleCORE License 1.0 (SCL-1.0)
2
+
3
+ Copyright (c) 2025 SimpleCORE
4
+
5
+ Permission is hereby granted, free of charge, to any individual or organization (the “Licensee”) to use, modify, and integrate this software (the “Software”) into their own internal or commercial products, subject to the following terms:
6
+
7
+ 1. **Internal and Product Use Permitted**
8
+ The Licensee may use and modify the Software internally, including incorporation into products that are developed, marketed, and sold by the Licensee. This includes the right to compile, bundle, or statically link the Software for use within their own distributed applications.
9
+
10
+ 2. **Commercial Redistribution Requires Permission**
11
+ The Licensee may **not** sell, license, lease, or otherwise redistribute this Software, in source or binary form, to third parties — whether standalone or as part of a product — without prior **written consent** from SimpleCORE.
12
+
13
+ 3. **Third-party Distribution Requires Permission**
14
+ The Licensee may **not** distribute the Software or derivative works to any third party in any form (source, binary, object code, container image, etc.) without prior **written consent** from SimpleCORE.
15
+
16
+ 4. **No SaaS / Hosted Service Offering Without Permission**
17
+ The Licensee may **not** use the Software to provide a hosted service (e.g., SaaS, PaaS, or API-based access) to third parties unless a separate commercial license is obtained from SimpleCORE.
18
+
19
+ 5. **Open Source Use Exception (Optional)**
20
+ Non-commercial open source use (e.g., academic research, nonprofit projects) is permitted, subject to compliance with this License, and with clear attribution to SimpleCORE.
21
+
22
+ 6. **No Warranty**
23
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY...
24
+
25
+ For licensing inquiries, contact: license@simplecore.kr
package/LICENSE_KO ADDED
@@ -0,0 +1,28 @@
1
+ SimpleCORE 라이선스 1.0 (SCL-1.0)
2
+ 한글 번역 — 참고용
3
+
4
+ 저작권 ⓒ 2025 SimpleCORE
5
+
6
+ 본 소프트웨어(이하 “소프트웨어”)는 다음 조건에 따라 개인 또는 조직(이하 “라이선스 사용자”)이 자유롭게 사용, 수정, 통합할 수 있습니다.
7
+
8
+ 1. **내부 사용 및 제품 통합 허용**
9
+ 라이선스 사용자는 소프트웨어를 자유롭게 사용하고 수정하여 자체 개발하는 제품에 통합할 수 있습니다. 이에는 해당 제품을 시장에 출시하거나 상업적으로 판매하는 경우도 포함됩니다. 단, 제3자 제공은 별도 조항에 따릅니다.
10
+
11
+ 2. **상업적 재배포 금지 (허가 필요)**
12
+ 라이선스 사용자는 본 소프트웨어를 단독 혹은 제품 일부로서 **판매, 라이선스, 임대, 패키징 등 상업적 목적으로 제3자에게 제공할 수 없습니다**. 이러한 사용을 원할 경우, **SimpleCORE의 서면 허가**가 필요합니다.
13
+
14
+ 3. **제3자 제공 금지 (허가 필요)**
15
+ 소프트웨어 혹은 파생물(수정본)을 제3자에게 배포하거나 공개할 수 없습니다. 여기에는 소스코드, 바이너리, 패키지, 컨테이너 이미지 등 모든 형태가 포함되며, **사전 서면 허가** 없이는 허용되지 않습니다.
16
+
17
+ 4. **SaaS/호스팅 서비스 제공 금지 (허가 필요)**
18
+ 소프트웨어를 이용한 SaaS, API 서비스, 클라우드 기반 제공 형태로 제3자에게 서비스를 제공할 수 없습니다. 이러한 사용을 원할 경우 **별도의 상용 라이선스를 SimpleCORE로부터 취득해야 합니다**.
19
+
20
+ 5. **비영리 목적의 오픈소스 사용 예외 (선택 사항)**
21
+ 학술 연구나 비영리 프로젝트에서 소프트웨어를 사용하는 경우, 본 라이선스를 준수하고 SimpleCORE를 명시하는 조건 하에 사용이 허용될 수 있습니다.
22
+
23
+ 6. **보증 없음**
24
+ 본 소프트웨어는 “있는 그대로” 제공되며, 특정 목적에의 적합성, 상품성, 권리 비침해성 등에 대한 **명시적 또는 묵시적 보증을 하지 않습니다**. 어떠한 손해에 대해서도 SimpleCORE는 책임을 지지 않습니다.
25
+
26
+ 라이선스 관련 문의: license@simplecore.kr
27
+
28
+ ※ 본 문서는 원문의 이해를 돕기 위한 비공식 번역이며, 법적 효력은 원문(SCL-1.0 영문 라이선스)에 따릅니다.
package/README.md CHANGED
@@ -1,3 +1,147 @@
1
- # Temporary Holding Version
1
+ # SimpliX CLI
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ JPA 엔티티에서 SimpliX 서비스, REST 컨트롤러, DTO, 테스트 코드를 생성하는 명령줄 도구입니다. npm 패키지 이름은 `@simplix-boot/cli`이고 실행 파일 이름은 `simplix-boot`입니다.
4
+
5
+ ## 주요 기능
6
+
7
+ - ✔ **엔티티 분석** - JPA 엔티티 소스를 읽어 필드, 식별자, 연관 관계를 담은 yml을 작성합니다.
8
+ - ✔ **코드 생성** - yml과 템플릿으로 서비스, REST 컨트롤러, DTO, 서비스 테스트를 생성합니다.
9
+ - ✔ **내장 템플릿** - 템플릿을 CLI에 포함해 배포하므로 프로젝트에 템플릿을 복사하지 않아도 생성할 수 있습니다.
10
+ - ✔ **프로젝트 템플릿 우선** - `.simplix/templates`에 같은 상대 경로의 파일을 두면 내장 템플릿 대신 그 파일로 렌더링합니다.
11
+ - ✔ **추적 렌더(tracked render)** - 모듈로 옮긴 파일에 렌더 지문(render fingerprint)을 기록하고, 템플릿이 바뀌면 직접 고친 내용에 3방향 병합으로 반영합니다.
12
+ - ✔ **버전 고정** - 프로젝트가 요구하는 CLI 버전을 설정 파일에 기록하고, 더 낮은 버전의 CLI로는 생성하지 않습니다.
13
+
14
+ ## 빠른 시작
15
+
16
+ ### 1. 실행
17
+
18
+ 설치 없이 실행하려면 `npx`를 사용하세요.
19
+
20
+ ```bash
21
+ npx @simplix-boot/cli help
22
+ ```
23
+
24
+ 자주 쓰는 환경에서는 전역으로 설치하세요.
25
+
26
+ ```bash
27
+ npm install -g @simplix-boot/cli
28
+ simplix-boot help
29
+ ```
30
+
31
+ Spring Boot 3 기반의 SimpliX 1.x 프로젝트에서는 `@simplix-boot/cli@spring-boot-3x`를 설치하세요. 릴리스 라인별 설치 방법은 [개요](docs/ko/overview.md#릴리스-라인)에 있습니다.
32
+
33
+ SimpliX 프레임워크 체크아웃이 있으면 그 안의 `simplix-cli`를 전역 명령으로 연결해 사용할 수 있습니다. 게시된 버전을 기다리지 않고 체크아웃의 현재 소스로 실행합니다. 확인과 해제 방법은 [개요](docs/ko/overview.md#설치와-실행)에 있습니다.
34
+
35
+ ```bash
36
+ cd <simplix checkout>/simplix-cli
37
+ npm ci
38
+ npm link
39
+ simplix-boot --version
40
+ ```
41
+
42
+ ### 2. 프로젝트 설정
43
+
44
+ 프로젝트 루트에서 `.simplix` 폴더를 만듭니다.
45
+
46
+ ```bash
47
+ simplix-boot init
48
+ ```
49
+
50
+ `.simplix/generator-simplix.json`을 작성합니다.
51
+
52
+ ```json
53
+ {
54
+ "entity": {
55
+ "scanPath": "src/main/java",
56
+ "basePackage": "com.example.library.domain"
57
+ },
58
+ "repository": {
59
+ "scanPath": "src/main/java",
60
+ "deriveFromEntity": true
61
+ },
62
+ "target": {
63
+ "generatedBasePath": "generated/main/java/com/example/library/web",
64
+ "basePackage": "com.example.library.web",
65
+ "targetPath": {
66
+ "service": "{modulePath}/service",
67
+ "controllerRest": "{modulePath}/controller",
68
+ "dto": "{modulePath}/dto"
69
+ },
70
+ "testGeneratedBasePath": "generated/test/java/com/example/library/web",
71
+ "testTargetPath": {
72
+ "serviceTest": "{modulePath}/service"
73
+ }
74
+ },
75
+ "promote": {
76
+ "moduleRoot": "modules"
77
+ }
78
+ }
79
+ ```
80
+
81
+ ### 3. 사용
82
+
83
+ ```bash
84
+ # Write .simplix/entity/Book.yml from the Book entity
85
+ simplix-boot config Book
86
+
87
+ # Edit the yml, then generate the code into the generated tree
88
+ simplix-boot generate Book
89
+
90
+ # Move the generated files into a module as tracked renders
91
+ simplix-boot promote Book --module catalog
92
+
93
+ # Report the state of every promoted file
94
+ simplix-boot generated
95
+ ```
96
+
97
+ ## 설정 요약
98
+
99
+ `.simplix/generator-simplix.json`의 주요 키입니다. 전체 목록은 [설정 레퍼런스](docs/ko/configuration.md)에 있습니다.
100
+
101
+ | 키 | 필수 | 설명 |
102
+ |----|------|------|
103
+ | `entity.scanPath` | 아니요 | 엔티티 소스를 찾는 경로입니다. 지정하지 않으면 `src/main/java`를 사용합니다. |
104
+ | `target.generatedBasePath` | 예 | 생성한 소스를 쓰는 경로입니다. |
105
+ | `target.basePackage` | 예 | 생성한 클래스의 기준 패키지입니다. |
106
+ | `target.targetPath` | 예 | 구성 요소별 하위 경로입니다. 경로를 지정한 구성 요소만 생성합니다. |
107
+ | `template` | 아니요 | 구성 요소별 템플릿 상대 경로입니다. |
108
+ | `supportClasses` | 아니요 | 생성 코드가 호출하는 애플리케이션 클래스의 전체 이름입니다. |
109
+ | `generator.version` | 아니요 | 프로젝트가 요구하는 CLI 버전입니다. |
110
+
111
+ ## 아키텍처
112
+
113
+ ```
114
+ simplix-cli/
115
+ +-- bin/
116
+ | +-- simplix-boot.js # Executable entry
117
+ +-- src/
118
+ | +-- cli.js # Command dispatch, help, exit codes
119
+ | +-- commands/ # init, config, generate, promote, generated, templates, version
120
+ | +-- lib/
121
+ | +-- analysis/ # JPA entity source analysis
122
+ | +-- config/ # Entity yml construction
123
+ | +-- generate/ # File plan, search fields, template variables
124
+ | +-- templates.js # Project template first, built-in template otherwise
125
+ | +-- tracked-render.js # Render fingerprint, stored base, three-way merge
126
+ +-- templates/ # Built-in templates
127
+ +-- test/ # node:test suites and the fixture project
128
+ ```
129
+
130
+ ## 문서
131
+
132
+ | 문서 | 설명 |
133
+ |------|------|
134
+ | [개요](docs/ko/overview.md) | 처리 흐름, 구성 요소, 설정 구조 |
135
+ | [명령 가이드](docs/ko/command-guide.md) | 명령별 인자, 옵션, 종료 코드 |
136
+ | [템플릿 가이드](docs/ko/template-guide.md) | 내장 템플릿, 프로젝트 템플릿, 템플릿 변수 |
137
+ | [설정 레퍼런스](docs/ko/configuration.md) | `generator-simplix.json`과 엔티티 yml의 키 |
138
+ | [전환 가이드](docs/ko/migration-guide.md) | `generator-simplix` 프로젝트에서 사용하는 방법 |
139
+
140
+ ## 요구 사항
141
+
142
+ - Node.js 20 이상
143
+ - Git (`promote`의 3방향 병합에 `git merge-file`을 사용합니다)
144
+
145
+ ## 라이선스
146
+
147
+ SimpleCORE License 1.0 (SCL-1.0)
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env node
2
+ import { main } from '../src/cli.js';
3
+ import { tolerateClosedReader } from '../src/lib/console.js';
4
+
5
+ tolerateClosedReader(process.stdout);
6
+ process.exitCode = main(process.argv.slice(2));
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "@simplix-boot/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.3.0",
4
+ "description": "Command line tool that generates SimpliX Spring Boot code (services, controllers, DTOs, tests) from JPA entities",
5
+ "type": "module",
6
+ "bin": {
7
+ "simplix-boot": "bin/simplix-boot.js"
8
+ },
9
+ "files": [
10
+ "bin",
11
+ "src",
12
+ "templates",
13
+ "LICENSE_KO"
14
+ ],
15
+ "engines": {
16
+ "node": ">=20"
17
+ },
18
+ "scripts": {
19
+ "test": "node --test test/*.test.js",
20
+ "prepack": "node scripts/license-files.mjs copy",
21
+ "postpack": "node scripts/license-files.mjs remove",
22
+ "prepublishOnly": "node scripts/assert-release-version.mjs"
23
+ },
24
+ "dependencies": {
25
+ "ejs": "^3.1.10",
26
+ "js-yaml": "^4.1.0",
27
+ "lodash": "^4.17.21"
28
+ },
29
+ "keywords": [
30
+ "simplix",
31
+ "spring-boot",
32
+ "jpa",
33
+ "crud",
34
+ "code-generator",
35
+ "cli"
36
+ ],
37
+ "repository": {
38
+ "type": "git",
39
+ "url": "git+https://github.com/simplix-framework/simplix.git",
40
+ "directory": "simplix-cli"
41
+ },
42
+ "license": "SEE LICENSE IN LICENSE",
43
+ "publishConfig": {
44
+ "access": "public",
45
+ "tag": "spring-boot-3x"
46
+ }
47
+ }
package/src/cli.js ADDED
@@ -0,0 +1,103 @@
1
+ import { parseArguments } from './lib/args.js';
2
+ import { createOutput, style, symbols } from './lib/console.js';
3
+ import { CliError } from './lib/errors.js';
4
+ import { requireProjectRoot } from './lib/project.js';
5
+ import { getGeneratorVersion } from './lib/version-utils.js';
6
+ import * as config from './commands/config.js';
7
+ import * as generate from './commands/generate.js';
8
+ import * as generated from './commands/generated.js';
9
+ import * as init from './commands/init.js';
10
+ import * as promote from './commands/promote.js';
11
+ import * as templates from './commands/templates.js';
12
+ import * as version from './commands/version.js';
13
+
14
+ /** The commands by name, in the order the help lists them. */
15
+ const COMMANDS = { init, config, generate, promote, generated, templates, version };
16
+
17
+ /** Names a command also answers to. */
18
+ const ALIASES = { entity: 'generate' };
19
+
20
+ function helpText() {
21
+ const width = Math.max(...Object.keys(COMMANDS).map(name => name.length));
22
+ const lines = [
23
+ '',
24
+ `${style.cyan('SimpliX Boot CLI')} v${getGeneratorVersion()}`,
25
+ '',
26
+ 'Generates SimpliX Spring Boot code (services, controllers, DTOs, tests) from JPA entities.',
27
+ '',
28
+ style.bold('Usage:'),
29
+ ' simplix-boot <command> [options]',
30
+ '',
31
+ style.bold('Commands:'),
32
+ ...Object.entries(COMMANDS).map(([name, command]) => ` ${name.padEnd(width)} ${command.summary}`),
33
+ '',
34
+ style.bold('Workflow:'),
35
+ ' 1. simplix-boot init Create .simplix in the project root',
36
+ ' 2. simplix-boot config <EntityName> Write the entity yml from the JPA entity',
37
+ ' 3. Edit .simplix/entity/<EntityName>.yml to match the requirements',
38
+ ' 4. simplix-boot generate <EntityName> Generate the code from the yml',
39
+ ' 5. simplix-boot promote <EntityName> --module <module>',
40
+ '',
41
+ 'Templates come with the CLI. A file of the same relative path under .simplix/templates',
42
+ 'replaces the built-in one; "simplix-boot templates" lists which is in use.',
43
+ '',
44
+ 'Run "simplix-boot <command> --help" for the options of one command.',
45
+ '',
46
+ ];
47
+
48
+ return lines.join('\n');
49
+ }
50
+
51
+ function commandHelpText(name, command) {
52
+ const options = Object.entries(command.argumentSpec.options ?? {}).map(([option, declared]) => {
53
+ if (declared.type === 'string') return ` --${option} <value>`;
54
+ return declared.default === true ? ` --no-${option}` : ` --${option}`;
55
+ });
56
+
57
+ return ['', command.summary, '', style.bold('Usage:'), ` ${command.usage}`, ...(options.length > 0 ? ['', style.bold('Options:'), ...options] : []), ''].join('\n');
58
+ }
59
+
60
+ /**
61
+ * Runs the command line.
62
+ *
63
+ * @param {string[]} argv the arguments after the executable
64
+ * @param {object} [environment]
65
+ * @param {string} [environment.cwd] the directory the command was run in
66
+ * @returns {number} the process exit code
67
+ */
68
+ export function main(argv, { cwd = process.cwd() } = {}) {
69
+ const [first, ...rest] = argv;
70
+
71
+ try {
72
+ if (first === undefined || first === 'help' || first === '--help' || first === '-h') {
73
+ process.stdout.write(`${helpText()}\n`);
74
+ return 0;
75
+ }
76
+
77
+ if (first === '--version' || first === '-v') {
78
+ process.stdout.write(`${getGeneratorVersion()}\n`);
79
+ return 0;
80
+ }
81
+
82
+ const name = ALIASES[first] ?? first;
83
+ const command = Object.hasOwn(COMMANDS, name) ? COMMANDS[name] : undefined;
84
+ if (command === undefined) {
85
+ throw new CliError(`Unknown command: ${first}\nRun "simplix-boot help" for the list of commands.`);
86
+ }
87
+
88
+ if (rest.includes('--help') || rest.includes('-h')) {
89
+ process.stdout.write(`${commandHelpText(name, command)}\n`);
90
+ return 0;
91
+ }
92
+
93
+ const { positionals, options } = parseArguments(rest, command.argumentSpec);
94
+ const output = createOutput();
95
+ const root = command.needsProject === false ? undefined : requireProjectRoot(cwd);
96
+
97
+ return command.run({ cwd, root, positionals, options, output }) ?? 0;
98
+ } catch (error) {
99
+ if (!(error instanceof CliError)) throw error;
100
+ process.stderr.write(`${symbols.error} ${error.message}\n`);
101
+ return error.exitCode;
102
+ }
103
+ }
@@ -0,0 +1,129 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { symbols } from '../lib/console.js';
4
+ import { analyzeEntity } from '../lib/entity-analyzer.js';
5
+ import { CliError } from '../lib/errors.js';
6
+ import { findEntityFile } from '../lib/file-utils.js';
7
+ import { buildFkIdFieldMap, processEmbeddedIdFields, processRegularField } from '../lib/config/fields.js';
8
+ import { analyzeParentClass, mergeFields } from '../lib/config/parents.js';
9
+ import {
10
+ entityTypeResolver,
11
+ extractModulePath,
12
+ findRepositoryModulePath,
13
+ getBaseEntityPath,
14
+ } from '../lib/config/paths.js';
15
+ import { createBaseConfig, dumpEntityConfig } from '../lib/config/yml.js';
16
+ import { findNameField } from '../lib/name-field.js';
17
+ import { entityConfigPathOf, readProjectConfig } from '../lib/project.js';
18
+ import { assertGeneratorVersion } from '../lib/version-check.js';
19
+
20
+ export const usage = 'simplix-boot config <EntityName> [--force] [--skip-version-check]';
21
+
22
+ export const summary = 'Analyze a JPA entity and write its yml under .simplix/entity';
23
+
24
+ export const argumentSpec = {
25
+ positionals: ['entityName'],
26
+ options: {
27
+ force: { type: 'boolean', default: false },
28
+ 'skip-version-check': { type: 'boolean', default: false },
29
+ },
30
+ };
31
+
32
+ /**
33
+ * Builds the yml of one entity from its Java source: its id and name fields, its module path, and
34
+ * for every field the views it appears in and the operators it is searched with.
35
+ *
36
+ * @param {object} context
37
+ * @param {string} context.root the project root
38
+ * @param {object} [context.config] the parsed project configuration
39
+ * @param {(message?: string) => void} context.log where progress goes
40
+ * @param {string} entityName the entity class name
41
+ * @returns {string} the yml text
42
+ * @throws {CliError} when the entity source is not found
43
+ */
44
+ export function buildEntityConfigYml(context, entityName) {
45
+ const baseEntityPath = getBaseEntityPath(context);
46
+ const srcPath = path.join(context.root, baseEntityPath);
47
+ const entityPath = findEntityFile(srcPath, entityName);
48
+
49
+ if (!entityPath) {
50
+ throw new CliError(`Entity file not found\nLooking for: ${entityName}.java\nSearched in: ${srcPath}`);
51
+ }
52
+
53
+ const entityContent = fs.readFileSync(entityPath, 'utf8');
54
+ const { fields, embeddedIdFields, idField, parentClass } = analyzeEntity(entityContent, {
55
+ isEntityType: entityTypeResolver(context, srcPath),
56
+ });
57
+
58
+ let finalIdField = idField;
59
+ const { parentFields, finalIdField: parentIdField } = analyzeParentClass(
60
+ context,
61
+ parentClass,
62
+ baseEntityPath,
63
+ srcPath,
64
+ new Set()
65
+ );
66
+
67
+ if (!finalIdField && parentIdField) {
68
+ finalIdField = parentIdField;
69
+ }
70
+
71
+ if (parentFields.length > 0) {
72
+ mergeFields(parentFields, fields);
73
+ }
74
+
75
+ const idFieldName = finalIdField || 'id';
76
+ const nameField = findNameField(fields, idFieldName);
77
+ const modulePath = extractModulePath(entityContent, entityName);
78
+
79
+ const repositoryModulePath = findRepositoryModulePath(context, entityName, modulePath);
80
+ if (repositoryModulePath !== null && repositoryModulePath !== modulePath) {
81
+ context.log(` Repository found at: ${repositoryModulePath || '(root)'}`);
82
+ }
83
+
84
+ const config = createBaseConfig(entityName, modulePath, idFieldName, nameField, repositoryModulePath);
85
+
86
+ if (Array.isArray(fields) && fields.some(field => field.name === 'createdAt')) {
87
+ config.defaultSortField = 'createdAt';
88
+ }
89
+
90
+ processEmbeddedIdFields(embeddedIdFields, config);
91
+
92
+ const fkIdFieldMap = buildFkIdFieldMap(fields);
93
+
94
+ if (Array.isArray(fields)) {
95
+ fields.forEach(field => {
96
+ processRegularField(context, field, config, idFieldName, embeddedIdFields, fkIdFieldMap);
97
+ });
98
+ }
99
+
100
+ return dumpEntityConfig(config);
101
+ }
102
+
103
+ /** Runs `config` from the command line. */
104
+ export function run({ root, positionals, options, output }) {
105
+ const { entityName } = positionals;
106
+ if (!entityName) {
107
+ throw new CliError(`Entity name is required\nUsage: ${usage}`);
108
+ }
109
+
110
+ const config = readProjectConfig(root);
111
+ const log = output.log;
112
+
113
+ if (config) {
114
+ assertGeneratorVersion({ config, log, skip: options['skip-version-check'] });
115
+ }
116
+
117
+ const yml = buildEntityConfigYml({ root, config, log }, entityName);
118
+ const configPath = entityConfigPathOf(root, entityName);
119
+
120
+ if (fs.existsSync(configPath) && !options.force) {
121
+ log(`\n${symbols.warning} Config file already exists: ${entityName}.yml`);
122
+ log('Use --force to overwrite');
123
+ return;
124
+ }
125
+
126
+ fs.mkdirSync(path.dirname(configPath), { recursive: true });
127
+ fs.writeFileSync(configPath, yml);
128
+ log(`\n${symbols.success} Generated config file: ${entityName}.yml`);
129
+ }