-
Notifications
You must be signed in to change notification settings - Fork 0
/
cli.js
executable file
·56 lines (50 loc) · 1.66 KB
/
cli.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
#!/usr/bin/env node
// packages/libraries
const fs = require("fs");
const argv = require("yargs").usage(
`Flags:
-t ["template" | String | either "page" or "post"]
-m ["mdx file" | n/a | if present file will be .mdx, else .js]
-f ["file name" | String | e.g. "how-to-build-a-nextjs-app"]`
).argv;
// terminal output color functions
const { green, red, highlight } = require("./utils-cli/cli-colors.js");
// CLI flag vars
const templateType = argv.t === "page" ? argv.t : "post";
const ext = argv.m ? "mdx" : "js";
let fileName = argv.f
? `${argv.f}.${ext}`
: `new-${argv.t}-${Date.now()}.${ext}`;
// template function, and pass in the argv properties as arguments
const template = require(`./utils-cli/cli-template`)(argv.m, argv.t);
const BLOG_DIR_PATH = templateType === "post" ? "./pages/blog" : "./pages";
const pathToFile = `${BLOG_DIR_PATH}/${fileName}`;
// script logic
try {
// Abort if the blog directory does not exist.
fs.accessSync(BLOG_DIR_PATH, fs.F_OK);
} catch (error) {
console.log(
`\n${red(
"Error:"
)} Could not find blog directory: ${BLOG_DIR_PATH}\n${error}\n`
);
}
try {
// Abort if file name is already being used.
if (fs.existsSync(`${pathToFile}`)) {
console.log(
`\n${red("Operation aborted")}. The file ${BLOG_DIR_PATH}/${highlight(
fileName
)} already exists.\n`
);
process.exit(1);
}
// If file doesn't already exit, create it.
fs.writeFileSync(`${pathToFile}`, template);
console.log(
`\n${green("Success!")} Created ${BLOG_DIR_PATH}/${highlight(fileName)}\n`
);
} catch (error) {
console.log(`\n${red("Error:")} creating new post.\n${error}\n`);
}