-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcli.ts
More file actions
307 lines (273 loc) · 10.6 KB
/
cli.ts
File metadata and controls
307 lines (273 loc) · 10.6 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
299
300
301
302
303
304
305
306
307
#!/usr/bin/env node
import { program } from 'commander';
import { execa } from 'execa';
import inquirer from 'inquirer';
import fs from 'fs-extra';
import path from 'path';
import { defaultTemplates } from './templates.js';
import { mergeTemplates } from './template-loader.js';
import { offerAndCreateGitHubRepo } from './github.js';
import { runSave } from './save.js';
import { runLoad } from './load.js';
/** Project data provided by the user */
type ProjectData = {
/** Project name */
name: string,
/** Project version */
version: string,
/** Project description */
description: string,
/** Project author */
author: string
}
/** Command to create a new project */
program
.version('1.0.0')
.command('create')
.description('Create a new project from a git template')
.argument('[project-directory]', 'The directory to create the project in')
.argument('[template-name]', 'The name of the template to use')
.option('-t, --template-file <path>', 'Path to a JSON file with custom templates (same format as built-in)')
.option('--ssh', 'Use SSH URL for cloning the template repository')
.action(async (projectDirectory, templateName, options) => {
const templatesToUse = mergeTemplates(defaultTemplates, options?.templateFile);
// If project directory is not provided, prompt for it
if (!projectDirectory) {
const projectDirAnswer = await inquirer.prompt([
{
type: 'input',
name: 'projectDirectory',
message: 'Please provide the directory where you want to create the project?',
default: 'my-app',
},
]);
projectDirectory = projectDirAnswer.projectDirectory;
}
// If template name is not provided, show available templates and let user select
if (!templateName) {
console.log('\n📋 Available templates:\n');
templatesToUse.forEach(t => {
console.log(` ${t.name.padEnd(12)} - ${t.description}`);
});
console.log('');
const templateQuestion = [
{
type: 'list',
name: 'templateName',
message: 'Select a template:',
choices: templatesToUse.map(t => ({
name: `${t.name} - ${t.description}`,
value: t.name
}))
}
];
const templateAnswer = await inquirer.prompt(templateQuestion);
templateName = templateAnswer.templateName;
}
// Look up the template by name
const template = templatesToUse.find(t => t.name === templateName);
if (!template) {
console.error(`❌ Template "${templateName}" not found.\n`);
console.log('📋 Available templates:\n');
templatesToUse.forEach(t => {
console.log(` ${t.name.padEnd(12)} - ${t.description}`);
});
console.log('');
process.exit(1);
}
// If --ssh was not passed, prompt whether to use SSH
let useSSH = options?.ssh;
if (useSSH === undefined && template.repoSSH) {
const sshAnswer = await inquirer.prompt([
{
type: 'confirm',
name: 'useSSH',
message: 'Use SSH URL for cloning?',
default: false,
},
]);
useSSH = sshAnswer.useSSH;
}
const templateRepoUrl = useSSH && template.repoSSH ? template.repoSSH : template.repo;
// Define the full path for the new project
const projectPath = path.resolve(projectDirectory);
console.log(`Cloning template "${templateName}" from ${templateRepoUrl} into ${projectPath}...`);
try {
// Clone the repository
const cloneArgs = ['clone'];
if (template.options && Array.isArray(template.options)) {
cloneArgs.push(...template.options);
}
cloneArgs.push(templateRepoUrl, projectPath);
await execa('git', cloneArgs, { stdio: 'inherit' });
console.log('✅ Template cloned successfully.');
// Remove the .git folder from the *new* project
await fs.remove(path.join(projectPath, '.git'));
console.log('🧹 Cleaned up template .git directory.');
// Ask user for customization details
const questions = [
{
type: 'input',
name: 'name',
message: 'What is the project name?',
default: path.basename(projectPath),
},
{
type: 'input',
name: 'version',
message: 'What version number would you like to use?',
default: '1.0.0',
},
{
type: 'input',
name: 'description',
message: 'What is the project description?',
default: '',
},
{
type: 'input',
name: 'author',
message: 'Who is the author of the project?',
default: '',
},
];
const answers: ProjectData = await inquirer.prompt(questions);
// Update the package.json in the new project
const pkgJsonPath = path.join(projectPath, 'package.json');
if (await fs.pathExists(pkgJsonPath)) {
const pkgJson = await fs.readJson(pkgJsonPath);
// Overwrite fields with user's answers
pkgJson.name = answers.name;
pkgJson.version = answers.version;
pkgJson.description = answers.description;
pkgJson.author = answers.author;
// Write the updated package.json back
await fs.writeJson(pkgJsonPath, pkgJson, { spaces: 2 });
console.log('📝 Customized package.json.');
} else {
console.log('ℹ️ No package.json found in template, skipping customization.');
}
const packageManager = template.packageManager || "npm";
// Install dependencies
console.log('📦 Installing dependencies... (This may take a moment)');
await execa(packageManager, ['install'], { cwd: projectPath, stdio: 'inherit' });
console.log('✅ Dependencies installed.');
// Optional: Create GitHub repository
await offerAndCreateGitHubRepo(projectPath);
// Let the user know the project was created successfully
console.log('\n✨ Project created successfully! ✨\n');
console.log(`To get started:`);
console.log(` cd ${projectDirectory}`);
console.log(' Happy coding! 🚀');
} catch (error) {
console.error('❌ An error occurred:');
if (error instanceof Error) {
console.error(error.message);
} else if (error && typeof error === 'object' && 'stderr' in error) {
console.error((error as { stderr?: string }).stderr || String(error));
} else {
console.error(String(error));
}
// Clean up the created directory if an error occurred
if (await fs.pathExists(projectPath)) {
await fs.remove(projectPath);
console.log('🧹 Cleaned up failed project directory.');
}
}
});
/** Command to initialize a project and optionally create a GitHub repository */
program
.command('init')
.description('Initialize the current directory (or path) as a git repo and optionally create a GitHub repository')
.argument('[path]', 'Path to the project directory (defaults to current directory)')
.action(async (dirPath) => {
const cwd = dirPath ? path.resolve(dirPath) : process.cwd();
const gitDir = path.join(cwd, '.git');
if (!(await fs.pathExists(gitDir))) {
await execa('git', ['init'], { stdio: 'inherit', cwd });
console.log('✅ Git repository initialized.\n');
}
await offerAndCreateGitHubRepo(cwd);
});
/** Command to list all available templates */
program
.command('list')
.description('List all available templates')
.option('--verbose', 'List all available templates with verbose information')
.option('-t, --template-file <path>', 'Include templates from a JSON file (same format as built-in)')
.action((options) => {
const templatesToUse = mergeTemplates(defaultTemplates, options?.templateFile);
console.log('\n📋 Available templates:\n');
templatesToUse.forEach(template => {
console.log(` ${template.name.padEnd(20)} - ${template.description}`)
if (options.verbose) {
console.log(` Repo URL: ${template.repo}`);
if (template.options && Array.isArray(template.options)) {
console.log(` Checkout Options: ${template.options.join(', ')}`);
}
}
});
console.log('');
});
/** Command to run PatternFly codemods on a directory */
program
.command('update')
.description('Run PatternFly codemods on a directory to transform code to the latest PatternFly patterns')
.argument('[path]', 'The path to the source directory to run codemods on (defaults to "src")')
.option('--fix', 'Automatically apply fixes to files instead of just showing what would be changed')
.action(async (srcPath, options) => {
const targetPath = srcPath || 'src';
const resolvedPath = path.resolve(targetPath);
const commands = ['@patternfly/pf-codemods', '@patternfly/class-name-updater'];
console.log(`Running PatternFly updates on ${resolvedPath}...`);
for (const command of commands) {
try {
console.log(`\n📦 Running ${command}...`);
const args = [command];
if (options.fix) {
args.push('--fix');
}
args.push(resolvedPath);
await execa('npx', args, { stdio: 'inherit' });
console.log(`✅ ${command} completed successfully.`);
} catch (error) {
console.error(`❌ An error occurred while running ${command}:`);
if (error instanceof Error) {
console.error(error.message);
} else if (error && typeof error === 'object' && 'stderr' in error) {
console.error((error as { stderr?: string }).stderr || String(error));
} else {
console.error(String(error));
}
process.exit(1);
}
}
console.log('\n✨ All updates completed successfully! ✨');
});
/** Command to save changes: check for changes, prompt to commit, and push */
program
.command('save')
.description('Check for changes, optionally commit them with a message, and push to the current branch')
.argument('[path]', 'Path to the repository (defaults to current directory)')
.action(async (repoPath) => {
const cwd = repoPath ? path.resolve(repoPath) : process.cwd();
try {
await runSave(cwd);
} catch {
process.exit(1);
}
});
/** Command to load latest updates from the remote */
program
.command('load')
.description('Pull the latest updates from GitHub')
.argument('[path]', 'Path to the repository (defaults to current directory)')
.action(async (repoPath) => {
const cwd = repoPath ? path.resolve(repoPath) : process.cwd();
try {
await runLoad(cwd);
} catch {
process.exit(1);
}
});
program.parse(process.argv);