-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathutils.js
More file actions
223 lines (195 loc) · 5.48 KB
/
Copy pathutils.js
File metadata and controls
223 lines (195 loc) · 5.48 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
import arg from 'arg';
import chalk from 'chalk';
import fs from 'fs';
import fse from 'fs-extra';
import inquirer from 'inquirer';
import path from 'path';
import { Listr } from 'listr2';
import { fileURLToPath } from 'url';
import { execa } from 'execa';
import Handlebars from 'handlebars';
import { resolveAdminforthVersionRange } from '../cli.js';
export function parseArgumentsIntoOptions(rawArgs) {
const args = arg(
{
"--plugin-name": String,
// you can add more flags here if needed
},
{
argv: rawArgs.slice(1), // skip "create-plugin"
}
);
return {
pluginName: args["--plugin-name"],
};
}
export async function promptForMissingOptions(options) {
const questions = [];
if (!options.pluginName) {
questions.push({
type: "input",
name: "pluginName",
message: "Please specify the name of the plugin >",
default: "adminforth-plugin",
});
}
const answers = await inquirer.prompt(questions);
return {
...options,
pluginName: options.pluginName || answers.pluginName,
};
}
function checkNodeVersion(minRequiredVersion = 20) {
const current = process.versions.node.split(".");
const major = parseInt(current[0], 10);
if (isNaN(major) || major < minRequiredVersion) {
throw new Error(
`Node.js v${minRequiredVersion}+ is required. You have ${process.versions.node}. ` +
`Please upgrade Node.js. We recommend using nvm for managing multiple Node.js versions.`
);
}
}
function checkForExistingPackageJson() {
if (fs.existsSync(path.join(process.cwd(), "package.json"))) {
throw new Error(
`A package.json already exists in this directory.\n` +
`Please remove it or use an empty directory.`
);
}
}
function initialChecks() {
return [
{
title: "👀 Checking Node.js version...",
task: () => checkNodeVersion(20),
},
{
title: "👀 Validating current working directory...",
task: () => checkForExistingPackageJson(),
},
];
}
function renderHBSTemplate(templatePath, data) {
const template = fs.readFileSync(templatePath, "utf-8");
const compiled = Handlebars.compile(template);
return compiled(data);
}
async function scaffoldProject(ctx, options, cwd) {
const pluginName = options.pluginName;
const filename = fileURLToPath(import.meta.url);
const dirname = path.dirname(filename);
// Prepare directories
ctx.customDir = path.join(cwd, "custom");
await fse.ensureDir(ctx.customDir);
// Write templated files
await writeTemplateFiles(dirname, cwd, {
pluginName,
});
}
async function writeTemplateFiles(dirname, cwd, options) {
const { pluginName } = options;
const adminforthVersion = await resolveAdminforthVersionRange();
// Build a list of files to generate
const templateTasks = [
{
src: "tsconfig.json.hbs",
dest: "tsconfig.json",
data: {},
},
{
src: "package.json.hbs",
dest: "package.json",
data: { pluginName, adminforthVersion },
},
{
src: "index.ts.hbs",
dest: "index.ts",
data: {},
},
{
src: ".gitignore.hbs",
dest: ".gitignore",
data: {},
},
{
src: "types.ts.hbs",
dest: "types.ts",
data: {},
},
{
src: "custom/tsconfig.json.hbs",
dest: "custom/tsconfig.json",
data: {},
},
];
for (const task of templateTasks) {
// If a condition is specified and false, skip this file
if (task.condition === false) continue;
const destPath = path.join(cwd, task.dest);
fse.ensureDirSync(path.dirname(destPath));
if (task.empty) {
fs.writeFileSync(destPath, "");
} else {
const templatePath = path.join(dirname, "templates", task.src);
const compiled = renderHBSTemplate(templatePath, task.data);
fs.writeFileSync(destPath, compiled);
}
}
}
async function installDependencies(ctx, cwd) {
const customDir = ctx.customDir;
await Promise.all([
await execa("pnpm", ["install"], { cwd }),
await execa("pnpm", ["install"], { cwd: customDir }),
]);
}
function generateFinalInstructions() {
let instruction = "⏭️ Your plugin is ready! Next steps:\n";
instruction += `
${chalk.dim("// Build your plugin")}
${chalk.cyan("$ pnpm build")}\n`;
instruction += `
${chalk.dim("// To test your plugin locally")}
${chalk.cyan("$ pnpm link")}\n`;
instruction += `
${chalk.dim("// In your AdminForth project")}
${chalk.cyan("$ pnpm link " + chalk.italic("your-plugin-name"))}\n`;
instruction += "\n😉 Happy coding!";
return instruction;
}
export function prepareWorkflow(options) {
const cwd = process.cwd();
const tasks = new Listr(
[
{
title: "🔍 Initial checks...",
task: (_, task) => task.newListr(initialChecks(), { concurrent: true }),
},
{
title: "🚀 Scaffolding your plugin...",
task: async (ctx) => scaffoldProject(ctx, options, cwd),
},
{
title: "📦 Installing dependencies...",
task: async (ctx) => installDependencies(ctx, cwd),
},
{
title: "📝 Preparing final instructions...",
task: (ctx) => {
console.log(
chalk.green(`✅ Successfully created your new AdminForth plugin!\n`)
);
console.log(generateFinalInstructions());
console.log("\n\n");
},
},
],
{
rendererOptions: { collapseSubtasks: false },
concurrent: false,
exitOnError: true,
collectErrors: true,
}
);
return tasks;
}