-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
359 lines (308 loc) · 10.1 KB
/
index.js
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
#!/usr/bin/env node
import inquirer from "inquirer";
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
import { execSync } from "child_process";
import chalk from "chalk";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const CHOICES = fs.readdirSync(path.join(__dirname, "templates"));
const QUESTIONS = [
{
name: "project-choice",
type: "list",
message: "What project template would you like to generate?",
choices: CHOICES,
},
{
name: "project-name",
type: "input",
message: "Project name:",
validate: function (input) {
if (/^([A-Za-z\-\_\d])+$/.test(input)) return true;
else
return "Project name may only include letters, numbers, underscores and hashes.";
},
},
];
const CURR_DIR = process.cwd();
let nodeFlag = false; // Set nodeFlag as a global variable with a default value of false
// Command line arguments
const [, , condition, folderPath, nodeFlagParam] = process.argv;
const [, , ...args] = process.argv;
const options = {
condition: null,
folderPathOrNameOrLink: null,
nodeFlagParam: "",
};
// Parse command line arguments
for (let i = 0; i < args.length; i++) {
const arg = args[i];
switch (arg) {
case "-a":
case "-r":
case "-c":
options.condition = arg;
break;
case "-h":
options.condition = arg;
options.folderPathOrNameOrLink = "";
break;
case "-y":
// Check if the previous option was '-a'
if (options.condition === "-a") {
options.nodeFlagParam = arg;
} else {
console.error(`Invalid usage of '-y' flag.`);
process.exit(1);
}
break;
default:
if (arg.startsWith("-")) {
console.error(`Invalid option: ${arg}`);
process.exit(1);
} else {
options.folderPathOrNameOrLink = arg;
}
break;
}
}
if (!args.length) {
options.condition = "";
options.folderPathOrNameOrLink = "";
}
// Check for unsupported or invalid options
if (Object.values(options).some((value) => value === null)) {
console.error(`Missing required option or invalid usage.`);
process.exit(1);
}
// Update the value of nodeFlag based on the command line argument
if (nodeFlagParam === "-y") {
nodeFlag = true;
}
function createDirectoryContents(templatePath, newProjectPath) {
const filesToCreate = fs.readdirSync(templatePath);
filesToCreate.forEach((file) => {
const origFilePath = path.join(templatePath, file);
// get stats about the current file
const stats = fs.statSync(origFilePath);
if (stats.isFile()) {
const contents = fs.readFileSync(origFilePath, "utf8");
// Rename
if (file === ".npmignore") file = ".gitignore";
if (condition === "-a") {
fs.writeFileSync(
path.join(__dirname, "templates", newProjectPath, file),
contents,
"utf8"
);
} else {
fs.writeFileSync(
path.join(CURR_DIR, newProjectPath, file),
contents,
"utf8"
);
}
} else if (stats.isDirectory()) {
if (condition === "-a") {
if (file === "node_modules" && !nodeFlag) {
return;
} else {
fs.mkdirSync(path.join(__dirname, "templates", newProjectPath, file));
}
} else {
fs.mkdirSync(path.join(CURR_DIR, newProjectPath, file));
}
// Then recursively copy contents
createDirectoryContents(
path.join(templatePath, file),
path.join(newProjectPath, file)
);
}
});
}
if (!condition) {
inquirer.prompt(QUESTIONS).then((answers) => {
const projectChoice = answers["project-choice"];
const projectName = answers["project-name"];
const templatePath = path.join(__dirname, "templates", projectChoice);
const projectPath = path.join(CURR_DIR, projectName);
// Create project directory if it doesn't exist
if (!fs.existsSync(projectPath)) {
fs.mkdirSync(projectPath);
} else {
console.log(`\nProject directory '${projectName}' already exists.`);
{
process.exit(1);
}
}
createDirectoryContents(templatePath, projectName);
console.log("\nTemplate successfully created.");
});
} else if (condition === "-a") {
// Validate folder path
if (!folderPath) {
console.error("\nError: provide a folder path.");
{
process.exit(1);
}
}
// Validate folder existence
if (!fs.existsSync(folderPath)) {
console.error("\nError: Folder does not exist.");
{
process.exit(1);
}
}
// Create project name from folder path
const projectName = path.basename(folderPath);
// Create directory for new project if it doesn't exist
const templateFolderPath = path.join(__dirname, "templates", projectName);
if (!fs.existsSync(templateFolderPath)) {
fs.mkdirSync(templateFolderPath);
} else {
console.log(`\nFolder '${templateFolderPath}' already exists.`);
{
process.exit(1);
}
}
// Copy contents from folderPath to projectName/template
createDirectoryContents(folderPath, projectName);
// InformSync user about successful operation
if (nodeFlag) {
console.log("\nTemplate successfully created with node_modules.");
} else {
console.log("\nTemplate successfully created.");
}
} else if (condition === "-r") {
const templateToRemove = process.argv[3];
// Validate if the template exists
const templatePathToRemove = path.join(
__dirname,
"templates",
templateToRemove
);
if (!fs.existsSync(templatePathToRemove)) {
console.error(`\nError: Template '${templateToRemove}' does not exist.`);
{
process.exit(1);
}
}
// Remove the template directory
fs.rmSync(templatePathToRemove, { recursive: true });
// InformSync user about successful operation
console.log(`\nTemplate '${templateToRemove}' was successfully removed.`);
} else if (condition === "-c") {
const runCommand = (command) => {
return new Promise((resolve, reject) => {
try {
execSync(command, { stdio: "inherit" });
resolve(); // Resolve the promise when the command completes successfully
} catch (error) {
console.error(`Failed to Execute ${command}`, error);
reject(error); // Reject the promise with the error if the command fails
}
});
};
const urlRegex =
/^(https?|ftp):\/\/(([a-z\d]([a-z\d-]*[a-z\d])?\.)+[a-z]{2,}|localhost)(\/[-a-z\d%_.~+]*)*(\?[;&a-z\d%_.~+=-]*)?(\#[-a-z\d_]*)?$/i;
const repoLink = process.argv[3];
if (!urlRegex.test(repoLink)) {
console.log("Invalid repository link provided.");
process.exit(1);
} else {
console.log("Repository link is valid.");
}
const gitCommand = `git clone --depth 1 ${repoLink}`;
let projectName;
// Check if a changed name is provided in the clone command
if (repoLink.includes(" ")) {
// Extract the project name from the clone command
const cloneCommandParts = repoLink.split(" "); // Split the clone command by whitespace
projectName = cloneCommandParts[cloneCommandParts.length - 1]; // Get the last part as the project name
} else {
// Extract the project name from the repository link
projectName = path.basename(repoLink, ".git");
}
runCommand(gitCommand)
.then(async () => {
console.log("\nRepository Cloned");
// Remove the .git folder
const clonedFolderPath = path.join(CURR_DIR, projectName);
const gitFolderPath = path.join(clonedFolderPath, ".git");
if (fs.existsSync(gitFolderPath)) {
await fs.promises.rm(gitFolderPath, { recursive: true });
}
// Run the 'init -a' command with the cloned folder path
const initCommand = `init -a "${clonedFolderPath}"`;
await runCommand(initCommand);
// Remove the cloned project folder asynchronously
try {
await fs.promises.rm(clonedFolderPath, { recursive: true });
} catch (error) {
console.error(`Failed to remove cloned folder: ${error}`);
}
})
.catch((error) => {
console.error("Error cloning repository:", error);
process.exit(1); // Exit the script with an error status code
});
} else if (condition === "-h") {
// Clear the terminal by printing ANSI escape codes
process.stdout.write("\u001b[2J\u001b[0;0H");
const message = `
${chalk.bold.underline.white("Package Commands:")}
${chalk.green("Create a New Template:")}
- Type ${chalk.cyan("'init'")} and press Enter at your desired location.
${chalk.green("Add a Template:")}
- Use the ${chalk.cyan(
"-a"
)} flag followed by the path in quotes. By default it skips the node_modules folder.
${chalk.yellow("Example:")} ${chalk.cyan("init -a")} ${chalk.yellow(
'"C:\\Users\\{User}\\Desktop\\Projects\\Ongoing Projects"'
)}
- But if you want to add node_modules folder with the template you are creating then ${chalk.cyan(
"-y"
)} flag after the command.
${chalk.yellow("Example:")} ${chalk.cyan("init -a")} ${chalk.yellow(
'"C:\\Users\\{User}\\Desktop\\Projects\\Ongoing Projects"'
)} ${chalk.cyan("-y")}
${chalk.green("Clone a Repository and Add as a Template:")}
- Use the ${chalk.cyan(
"-c"
)} flag followed by the repository link in quotes.
${chalk.yellow("Example:")} ${chalk.cyan("init -c")} ${chalk.yellow(
'"https://github.com/user/repoitoryName"'
)}
${chalk.green("Remove a Template:")}
- Use the ${chalk.cyan(
"-r"
)} flag followed by the exact name of the template in quotes.
${chalk.yellow("Example:")} ${chalk.cyan("init -r")} ${chalk.yellow(
'"Template Name"'
)}
${chalk.green("Help:")}
- Use ${chalk.cyan("init -h")} to see help.
Made By Sooraj Gupta
Email : [email protected]
Github Repository : https://github.com/s54a/s54a-init
`;
console.log(message);
} else if (condition) {
console.log(
chalk.red(
`
Invalid command: "${condition}".
Please use one of the supported commands.
Run ${chalk.yellow("init -h")} to see help.
`
)
);
} else {
console.log(
chalk.red(
`An error occurred or an invalid command was provided.
Run ${chalk.yellow("init -h")} to see help.`
)
);
}