-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.ts
More file actions
298 lines (257 loc) · 8.01 KB
/
Copy pathcli.ts
File metadata and controls
298 lines (257 loc) · 8.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
import {existsSync} from 'fs';
import {mkdir, writeFile} from 'fs/promises';
import {join} from 'path';
import prompts from 'prompts';
import {postProcessFile, type PostProcessOptions} from './postProcess.js';
import {TemplateEngine, type TemplateContext} from './templateEngine.js';
export function detectPackageManager(): string {
const userAgent = process.env.npm_config_user_agent || '';
if (userAgent.includes('pnpm')) return 'pnpm';
if (userAgent.includes('bun')) return 'bun';
if (userAgent.includes('yarn')) return 'yarn';
return 'npm';
}
export interface Question {
type:
| 'text'
| 'select'
| 'confirm'
| ((
prev: unknown,
answers: Record<string, unknown>,
) => 'text' | 'select' | 'confirm' | null);
name: string;
message: string;
initial?: string | number | boolean;
choices?: Array<{title: string; value: string | boolean}>;
validate?: (value: string) => boolean | string;
}
export interface FileConfig {
template: string;
output: string;
prettier?: boolean;
transpile?: boolean;
processedContent?: string;
}
export interface ProjectConfig {
welcomeMessage?: string;
questions: Question[];
createContext: (answers: Record<string, unknown>) => TemplateContext;
getFiles: (context: TemplateContext) => FileConfig[] | Promise<FileConfig[]>;
processIncludedFile?: (
file: FileConfig,
context: TemplateContext,
) => FileConfig;
templateRoot: string;
createDirectories?: (
targetDir: string,
context: TemplateContext,
) => Promise<void>;
installCommand?: string;
devCommand?: string;
workingDirectory?: string | ((context: TemplateContext) => string);
onSuccess?: (
projectName: string,
context: TemplateContext,
) => void | Promise<void>;
}
export interface CLIOptions {
nonInteractive?: boolean;
args?: string[];
}
export async function createCLI(
config: ProjectConfig,
options: CLIOptions = {},
): Promise<void> {
const args = options.args || process.argv.slice(2);
const nonInteractive =
options.nonInteractive || args.includes('--non-interactive');
if (!nonInteractive && config.welcomeMessage) {
console.log(config.welcomeMessage);
}
let answers: Record<string, unknown>;
if (nonInteractive) {
answers = {};
for (const question of config.questions) {
const argName = `--${question.name}`;
const argIndex = args.indexOf(argName);
if (argIndex !== -1 && argIndex + 1 < args.length) {
const value = args[argIndex + 1];
if (question.type === 'confirm') {
answers[question.name] = value === 'true';
} else {
answers[question.name] = value;
}
} else if (question.initial !== undefined) {
answers[question.name] = question.initial;
}
}
} else {
answers = await prompts(config.questions, {
onCancel: () => {
console.log('\n❌ Cancelled');
process.exit(0);
},
});
}
const context = config.createContext(answers);
const projectName =
(answers.projectName as string) || (context.projectName as string);
const projectPath = join(process.cwd(), projectName);
if (existsSync(projectPath)) {
console.error(
`❌ Error: Directory "${
projectName
}" already exists. Please choose a different name.`,
);
process.exit(1);
}
if (!nonInteractive) {
console.log(`\n📦 Creating your project...\n`);
}
try {
await mkdir(projectPath, {recursive: true});
if (config.createDirectories) {
await config.createDirectories(projectPath, context);
}
await generateProject(projectPath, context, config);
if (!nonInteractive) {
console.log('✅ Done!\n');
if (config.installCommand && config.devCommand && context.installAndRun) {
await handleInstallAndRun(
projectName,
projectPath,
config.installCommand,
config.devCommand,
config.workingDirectory,
context,
);
} else if (config.onSuccess) {
await config.onSuccess(projectName, context);
}
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
console.error('❌ Error creating project:', errorMessage);
process.exit(1);
}
}
async function handleInstallAndRun(
projectName: string,
projectPath: string,
installCommand: string,
devCommand: string,
workingDirectory?: string | ((context: TemplateContext) => string),
context?: TemplateContext,
): Promise<void> {
const {spawn} = await import('child_process');
const {join} = await import('path');
const pm = detectPackageManager();
const install = installCommand.replace(/{pm}/g, pm);
const dev = devCommand.replace(/{pm}/g, pm);
const workDir =
typeof workingDirectory === 'function'
? workingDirectory(context!)
: workingDirectory;
const cwd = workDir ? join(projectPath, workDir) : projectPath;
console.log(`📦 Installing dependencies with ${pm}...\n`);
const installProcess = spawn(install, [], {
cwd,
stdio: 'inherit',
shell: true,
});
installProcess.on('close', (code) => {
if (code !== 0) {
console.error('\n❌ Failed to install dependencies');
console.log('\nNext steps:');
console.log(` cd ${projectName}`);
console.log(` ${install}`);
console.log(` ${dev}`);
return;
}
console.log('\n✅ Dependencies installed!\n');
console.log('🚀 Starting development server...\n');
const devProcess = spawn(dev, [], {
cwd,
stdio: 'inherit',
shell: true,
});
devProcess.on('error', (error) => {
console.error('\n❌ Failed to start dev server:', error.message);
});
});
installProcess.on('error', (error) => {
console.error('\n❌ Failed to install dependencies:', error.message);
console.log('\nNext steps:');
console.log(` cd ${projectName}`);
console.log(` ${install}`);
console.log(` ${dev}`);
});
}
async function generateProject(
targetDir: string,
context: TemplateContext,
config: ProjectConfig,
): Promise<void> {
const engine = new TemplateEngine(context, config.templateRoot);
const files = await config.getFiles(context);
const allFiles = [...files];
const processedTemplates = new Set<string>();
for (const file of files) {
const {content, includedFiles} = await engine.processTemplate(
file.template,
);
file.processedContent = content;
processedTemplates.add(file.template);
for (const included of includedFiles) {
if (!processedTemplates.has(included.template)) {
const processedIncluded = config.processIncludedFile
? config.processIncludedFile(included, context)
: included;
allFiles.push({
...processedIncluded,
processedContent: '',
});
}
}
}
let i = files.length;
while (i < allFiles.length) {
const file = allFiles[i];
const {content, includedFiles} = await engine.processTemplate(
file.template,
);
file.processedContent = content;
processedTemplates.add(file.template);
for (const included of includedFiles) {
if (!processedTemplates.has(included.template)) {
const processedIncluded = config.processIncludedFile
? config.processIncludedFile(included, context)
: included;
allFiles.push({
...processedIncluded,
processedContent: '',
});
}
}
i++;
}
for (const file of allFiles) {
if (!file.processedContent) {
throw new Error(`File ${file.output} was not processed`);
}
const postProcessOptions: PostProcessOptions = {
prettier: file.prettier ?? false,
transpileToJS: file.transpile && !context.isTypescript,
};
const {content, filePath} = await postProcessFile(
file.output,
file.processedContent,
postProcessOptions,
);
const fullPath = join(targetDir, filePath);
const {dirname} = await import('path');
await mkdir(dirname(fullPath), {recursive: true});
await writeFile(fullPath, content);
}
}