-
-
Notifications
You must be signed in to change notification settings - Fork 668
Expand file tree
/
Copy pathgenerate-files.ts
More file actions
276 lines (239 loc) · 8.73 KB
/
generate-files.ts
File metadata and controls
276 lines (239 loc) · 8.73 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
import * as fs from "node:fs/promises";
import * as path from "node:path";
import { fileURLToPath } from "node:url";
import expand from "@inquirer/expand";
import { spawn, sync } from "cross-spawn";
import ejs from "ejs";
import { type NodePlopAPI } from "node-plop";
import { type Answers } from "../types.js";
import { logger } from "./logger.js";
export interface AddConfig {
type: string; // Type of action
path: string;
fileType: "text" | "binary";
template?: string;
templateFile?: string;
skipIfExists?: boolean;
transform?: (content: string, data: Answers | undefined) => string | Promise<string>; // transforms rendered string before writing to file
skip?: (data: Answers | undefined) => string | Promise<string>; // skips the action and logs the reason returned by the function
force?: boolean; // Force overwrite
data?: Answers; // Data for EJS template rendering
abortOnFail?: boolean; // Abort on failure
}
export type Content = string | Buffer;
export interface Result {
status: "create" | "skip" | "overwrite" | "error" | "identical";
content: Content;
}
export interface GlobalConfig {
overwriteAll: boolean;
}
const globalConfig: GlobalConfig = { overwriteAll: false };
async function doesFileExists(filePath: string): Promise<boolean> {
try {
await fs.access(filePath);
return true;
} catch {
return false;
}
}
function checkIfCodeInstalled(): boolean {
try {
const result = sync("code", ["--version"], { stdio: "ignore" });
return result.status === 0;
} catch {
return false;
}
}
function getDiff(filePath: string, tempFilePath: string): Promise<void> {
return new Promise((resolve, reject) => {
const { platform } = process;
let editor = "";
// Determine the editor based on platform and availability of VS Code
if (platform === "win32") {
if (checkIfCodeInstalled()) {
editor = "code";
} else {
reject(
new Error("Visual Studio Code is not installed. Please install VS Code to continue."),
);
return;
}
} else if (platform === "darwin" || platform === "linux") {
editor = checkIfCodeInstalled() ? "code" : "vim";
} else {
reject(new Error(`Unsupported platform: ${platform}`));
return;
}
// Construct the appropriate diff command
let diffCommand = "";
if (editor === "code") {
diffCommand = `${editor} --diff ${filePath} ${tempFilePath}`;
} else if (editor === "vim") {
diffCommand = `${editor} -d ${filePath} ${tempFilePath}`;
}
// Execute the diff command
const diffProcess = spawn(diffCommand, { shell: true, stdio: "inherit" });
diffProcess.on("exit", (code) => {
if (code !== 0) {
reject(new Error("Error opening diff in editor"));
} else {
resolve();
}
});
});
}
async function renderTemplate(
template: string | undefined,
templateFile: string | undefined,
data: Answers | undefined,
): Promise<Content> {
if (template) {
return ejs.render(template, data || {}, { async: true });
}
if (templateFile) {
const templateContent = await fs.readFile(templateFile, "utf8");
return ejs.render(templateContent, data || {}, { async: true });
}
throw new Error("Template or templateFile is required");
}
async function checkAndPrepareContent(config: AddConfig, isTemplate: boolean): Promise<Result> {
const fileExists = await doesFileExists(config.path);
let existingFileContent: Content = "";
let newContent: Content = "";
// Handle template or binary content
if (isTemplate) {
// Template rendering for non-binary files
newContent = await renderTemplate(config.template, config.templateFile, config.data);
if (config.transform && typeof config.transform === "function") {
newContent = await config.transform(newContent as string, config.data);
}
} else {
// Read binary content for binary files
newContent = await fs.readFile(config.templateFile as string);
}
// Check if overwriteAll is set globally
if (globalConfig.overwriteAll) {
return { status: "overwrite", content: newContent };
}
// Check if skip condition exists
if (config.skip && typeof config.skip === "function") {
const skipReason = await config.skip(config.data);
logger.info(` - ${skipReason}`);
return { status: "skip", content: existingFileContent || newContent };
}
// Read existing content if the file exists
if (fileExists) {
existingFileContent = await fs.readFile(config.path);
// If skipIfExists is set, skip writing the file
if (config.skipIfExists) {
return { status: "skip", content: existingFileContent };
}
// If force is set, overwrite the file
if (config.force) {
return { status: "overwrite", content: newContent };
}
// If the contents are identical (text or binary), return identical status
if (existingFileContent === newContent) {
return { status: "identical", content: existingFileContent };
}
let userChoice: Result | undefined;
while (!userChoice) {
const action = await expand({
message: `File conflict at ${path.basename(config.path)}?`,
choices: [
{ key: "y", name: "overwrite", value: "overwrite" },
{ key: "n", name: "do not overwrite", value: "skip" },
{ key: "a", name: "overwrite this and all others", value: "overwrite_all" },
{
key: "d",
name: `Show the difference${!isTemplate ? " (size/modified date)" : ""}`,
value: "diff",
},
{ key: "x", name: "abort", value: "abort" },
],
expanded: false,
});
switch (action) {
case "overwrite":
userChoice = { status: "overwrite", content: newContent };
break;
case "skip":
userChoice = { status: "skip", content: existingFileContent };
break;
case "overwrite_all":
globalConfig.overwriteAll = true;
return { status: "overwrite", content: newContent };
case "diff": {
// Prompt for conflict resolution
const tempFilePath = path.join(
config.data!.projectPath as string,
`.temp_${path.basename(config.path)}`,
);
await fs.writeFile(tempFilePath, newContent || "");
if (!isTemplate && Buffer.isBuffer(existingFileContent)) {
const existingStats = await fs.stat(config.path);
const newStats = await fs.stat(tempFilePath);
const headers = `| ${"File".padEnd(15)} | ${"Size (bytes)".padEnd(
15,
)} | ${"Last Modified".padEnd(25)} |`;
const separator = "-".repeat(headers.length);
const existingRow = `| ${"Existing File".padEnd(15)} | ${existingStats.size
.toString()
.padEnd(15)} | ${existingStats.mtime.toISOString().padEnd(25)} |`;
const newRow = `| ${"New File".padEnd(15)} | ${newStats.size
.toString()
.padEnd(15)} | ${newStats.mtime.toISOString().padEnd(25)} |`;
logger.info(separator);
logger.info(headers);
logger.info(separator);
logger.info(existingRow);
logger.info(newRow);
logger.info(separator);
} else {
await getDiff(config.path, tempFilePath);
}
await fs.unlink(tempFilePath).catch(() => {
logger.warn(`Failed to delete temporary file: ${tempFilePath}`);
});
break;
}
case "abort":
logger.error("Aborting process...");
process.exit(1);
}
}
return userChoice;
}
// If the file doesn't exist, create it
return { status: "create", content: newContent };
}
export default async function generateFiles(plop: NodePlopAPI) {
const __dirname = path.dirname(fileURLToPath(import.meta.url));
plop.setPlopfilePath(path.resolve(__dirname, "../plopfile.js"));
plop.setDefaultInclude({ actions: true });
plop.setActionType("generate-files", async (answers, config) => {
const isTemplate = config.fileType === "text";
const result = await checkAndPrepareContent(
{ ...config, data: answers } as AddConfig,
isTemplate,
);
let returnString = "";
switch (result.status) {
case "create":
case "overwrite":
// Write the content to the file (handle text or binary)
await fs.mkdir(path.dirname(config.path), { recursive: true });
await fs.writeFile(config.path, result.content);
returnString = `${result.status}|${config.path}`;
break;
case "skip":
returnString = `${result.status}|${config.path}`;
break;
case "identical":
returnString = `${result.status}|${config.path}`;
break;
}
return returnString;
});
}