-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
326 lines (292 loc) · 10.7 KB
/
index.js
File metadata and controls
326 lines (292 loc) · 10.7 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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
#!/usr/bin/env node
const { Command } = require("commander");
const chalk = require("chalk");
const inquirer = require("inquirer");
const fs = require("fs");
const path = require("path");
const crypto = require("crypto");
const program = new Command();
program
.name("mycli")
.description("My first Node.js CLI - A practical command-line tool")
.version("1.0.0");
// Greet command
program
.command("greet <name>")
.description("Greet a user with a friendly message")
.option("-u, --uppercase", "Display name in uppercase")
.action((name, options) => {
const displayName = options.uppercase ? name.toUpperCase() : name;
console.log(chalk.green(`Hello, ${displayName}! 👋`));
});
// Interactive prompt command
program
.command("intro")
.description("Interactive introduction")
.action(async () => {
const answers = await inquirer.prompt([
{
type: "input",
name: "username",
message: "What is your name?",
},
{
type: "list",
name: "role",
message: "What is your role?",
choices: ["Full Stack Developer", "Frontend Developer", "Backend Developer", "DevOps Engineer", "Other"],
},
]);
console.log(chalk.cyan(`\n👤 Welcome ${chalk.bold(answers.username)}!`));
console.log(chalk.cyan(`💼 Role: ${chalk.bold(answers.role)}`));
console.log(chalk.yellow("✨ Happy coding! ✨\n"));
});
// Info command
program
.command("info")
.description("Display system information")
.action(() => {
console.log(chalk.blue("\n📊 System Information:"));
console.log(chalk.white(` Node.js version: ${process.version}`));
console.log(chalk.white(` Platform: ${process.platform}`));
console.log(chalk.white(` Architecture: ${process.arch}`));
console.log(chalk.white(` Current directory: ${process.cwd()}\n`));
});
// Echo command
program
.command("echo <message...>")
.description("Echo back a message")
.option("-c, --color <color>", "Color for the message (red, green, blue, yellow)", "white")
.action((message, options) => {
const text = message.join(" ");
const colorFn = chalk[options.color] || chalk.white;
console.log(colorFn(text));
});
// Password generator
program
.command("genpass")
.description("Generate a secure random password")
.option("-l, --length <number>", "Password length", "16")
.option("-n, --no-symbols", "Exclude special symbols")
.action((options) => {
const length = parseInt(options.length);
const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
const symbols = "!@#$%^&*()_+-=[]{}|;:,.<>?";
const charSet = options.symbols ? chars + symbols : chars;
let password = "";
for (let i = 0; i < length; i++) {
password += charSet.charAt(Math.floor(Math.random() * charSet.length));
}
console.log(chalk.green("\n🔒 Generated Password:"));
console.log(chalk.bold.yellow(password));
console.log(chalk.gray(`Length: ${password.length} characters\n`));
});
// Hash generator
program
.command("hash <text>")
.description("Generate hash of text (MD5, SHA256, SHA512)")
.option("-a, --algorithm <type>", "Hash algorithm (md5, sha256, sha512)", "sha256")
.action((text, options) => {
const hash = crypto.createHash(options.algorithm).update(text).digest("hex");
console.log(chalk.blue(`\n${options.algorithm.toUpperCase()} Hash:`));
console.log(chalk.yellow(hash + "\n"));
});
// Base64 encode/decode
program
.command("base64 <text>")
.description("Encode or decode Base64")
.option("-d, --decode", "Decode from Base64")
.action((text, options) => {
if (options.decode) {
const decoded = Buffer.from(text, "base64").toString("utf-8");
console.log(chalk.green("\n📤 Decoded:"));
console.log(chalk.white(decoded + "\n"));
} else {
const encoded = Buffer.from(text).toString("base64");
console.log(chalk.green("\n📥 Encoded:"));
console.log(chalk.white(encoded + "\n"));
}
});
// Calculator
program
.command("calc <expression>")
.description("Simple calculator (e.g., '10 + 20' or '5 * 8')")
.action((expression) => {
try {
// Basic sanitization - only allow numbers and basic operators
const sanitized = expression.replace(/[^0-9+\-*/().\s]/g, "");
const result = eval(sanitized);
console.log(chalk.cyan("\n🧮 Result:"));
console.log(chalk.bold.green(`${expression} = ${result}\n`));
} catch (error) {
console.log(chalk.red("❌ Invalid expression\n"));
}
});
// File operations - List files
program
.command("ls [directory]")
.description("List files and directories")
.option("-a, --all", "Show hidden files")
.action((directory, options) => {
const dir = directory || ".";
try {
const files = fs.readdirSync(dir);
console.log(chalk.blue(`\n📁 Contents of ${path.resolve(dir)}:\n`));
files.forEach((file) => {
if (!options.all && file.startsWith(".")) return;
const filePath = path.join(dir, file);
const stats = fs.statSync(filePath);
if (stats.isDirectory()) {
console.log(chalk.cyan(` 📂 ${file}/`));
} else {
const size = (stats.size / 1024).toFixed(2);
console.log(chalk.white(` 📄 ${file} ${chalk.gray(`(${size} KB)`)}`));
}
});
console.log();
} catch (error) {
console.log(chalk.red(`❌ Error: ${error.message}\n`));
}
});
// Create directory
program
.command("mkdir <dirname>")
.description("Create a new directory")
.action((dirname) => {
try {
fs.mkdirSync(dirname, { recursive: true });
console.log(chalk.green(`✅ Directory created: ${dirname}\n`));
} catch (error) {
console.log(chalk.red(`❌ Error: ${error.message}\n`));
}
});
// Random quote
program
.command("quote")
.description("Display a random motivational quote")
.action(() => {
const quotes = [
{ text: "The best way to predict the future is to invent it.", author: "Alan Kay" },
{ text: "Code is like humor. When you have to explain it, it's bad.", author: "Cory House" },
{ text: "First, solve the problem. Then, write the code.", author: "John Johnson" },
{ text: "Any fool can write code that a computer can understand. Good programmers write code that humans can understand.", author: "Martin Fowler" },
{ text: "Experience is the name everyone gives to their mistakes.", author: "Oscar Wilde" },
{ text: "Make it work, make it right, make it fast.", author: "Kent Beck" },
{ text: "Talk is cheap. Show me the code.", author: "Linus Torvalds" },
{ text: "The only way to learn a new programming language is by writing programs in it.", author: "Dennis Ritchie" },
{ text: "Simplicity is the soul of efficiency.", author: "Austin Freeman" },
{ text: "Code never lies, comments sometimes do.", author: "Ron Jeffries" },
];
const quote = quotes[Math.floor(Math.random() * quotes.length)];
console.log(chalk.yellow("\n💭 Random Quote:\n"));
console.log(chalk.white(` "${quote.text}"`));
console.log(chalk.gray(` - ${quote.author}\n`));
});
// JSON formatter
program
.command("json <file>")
.description("Format and validate JSON file")
.option("-m, --minify", "Minify JSON instead of formatting")
.action((file, options) => {
try {
const content = fs.readFileSync(file, "utf-8");
const parsed = JSON.parse(content);
const formatted = options.minify
? JSON.stringify(parsed)
: JSON.stringify(parsed, null, 2);
console.log(chalk.green("✅ Valid JSON\n"));
console.log(formatted);
console.log();
// Optionally save formatted version
inquirer.prompt([{
type: "confirm",
name: "save",
message: "Save formatted version?",
default: false
}]).then(answer => {
if (answer.save) {
fs.writeFileSync(file, formatted);
console.log(chalk.green(`✅ File updated: ${file}\n`));
}
});
} catch (error) {
console.log(chalk.red(`❌ Error: ${error.message}\n`));
}
});
// Project initializer
program
.command("init")
.description("Initialize a new project with template")
.action(async () => {
const answers = await inquirer.prompt([
{
type: "input",
name: "projectName",
message: "Project name:",
default: "my-project"
},
{
type: "list",
name: "projectType",
message: "Project type:",
choices: ["Node.js", "React", "Express API", "HTML/CSS/JS"]
},
{
type: "confirm",
name: "gitInit",
message: "Initialize git repository?",
default: true
}
]);
const projectPath = path.join(process.cwd(), answers.projectName);
try {
// Create project directory
fs.mkdirSync(projectPath, { recursive: true });
// Create package.json for Node projects
if (["Node.js", "React", "Express API"].includes(answers.projectType)) {
const packageJson = {
name: answers.projectName,
version: "1.0.0",
description: "",
main: "index.js",
scripts: {
start: "node index.js"
},
keywords: [],
author: "",
license: "ISC"
};
fs.writeFileSync(
path.join(projectPath, "package.json"),
JSON.stringify(packageJson, null, 2)
);
}
// Create README
fs.writeFileSync(
path.join(projectPath, "README.md"),
`# ${answers.projectName}\n\nProject created with mycli\n`
);
// Create .gitignore
const gitignore = answers.projectType.includes("Node") || answers.projectType.includes("Express")
? "node_modules/\n.env\n*.log\n"
: "*.log\n";
fs.writeFileSync(path.join(projectPath, ".gitignore"), gitignore);
console.log(chalk.green(`\n✅ Project created: ${answers.projectName}`));
console.log(chalk.cyan("\n📁 Project structure:"));
console.log(chalk.white(` ${answers.projectName}/`));
console.log(chalk.white(` ├── README.md`));
console.log(chalk.white(` ├── .gitignore`));
if (["Node.js", "React", "Express API"].includes(answers.projectType)) {
console.log(chalk.white(` └── package.json`));
}
console.log(chalk.yellow(`\n💡 Next steps:`));
console.log(chalk.white(` cd ${answers.projectName}`));
if (answers.gitInit) {
console.log(chalk.white(` git init`));
}
console.log();
} catch (error) {
console.log(chalk.red(`❌ Error: ${error.message}\n`));
}
});
program.parse();