-
Notifications
You must be signed in to change notification settings - Fork 4
/
add-article.js
113 lines (96 loc) · 2.36 KB
/
add-article.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
const path = require("path");
const readline = require("readline");
const fs = require("fs");
const POSTS_DIR = "./content/posts/";
const args = process.argv.reduce((obj, arg) => {
const match = arg.match(/^--(.+)="?(.+)"?$/);
if (match) {
obj[match[1]] = match[2];
}
return obj;
}, {});
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const question = (argument, sample) =>
new Promise(resolve => {
rl.question(`Specify ${argument} (i.e. ${sample}): `, answer => {
console.log(`You can also type the article name as an argument: --${argument}="${sample}"`);
resolve(answer);
});
});
const getDate = () => {
const date = new Date();
let month = (date.getMonth() + 1).toString();
if (month.length === 1) {
month = "0" + month;
}
let day = date.getDate().toString();
if (day.length === 1) {
day = "0" + day;
}
return date.getFullYear() + "-" + month + "-" + day;
};
const getSlug = name =>
getDate() +
"_" +
name
.trim()
.toLowerCase()
.replace(/[!@#$%^&*()_+\-=\\/ ]/g, "-");
const main = async () => {
// Gather data
let { name, subtitle, tags, author } = args;
if (!name) {
name = await question("name", "My new article");
if (!name) {
console.log("Name is required to correctly generate the article");
process.exit(1);
}
}
if (!subtitle) {
subtitle = await question("subtitle", "A slightly more detailed topic description.");
}
if (!tags) {
tags = await question("tags", "javascript, react, nodejs");
}
tags = `"${tags
.split(",")
.map(tag => tag.trim())
.join(`", "`)}"`;
if (!author) {
author = await question("author", "John Doe");
}
rl.close();
// Prepare location
const slug = getSlug(name);
const location = path.join(POSTS_DIR, `${slug}.md`);
console.log("Location: " + location);
// Check for conflicts
if (fs.existsSync(location)) {
console.log("Article already exists");
process.exit(2);
}
// Prepare template
const template = `\
---
title: ${name}
subTitle: ${subtitle}
tags: [${tags}]
cover:
postAuthor: ${author}
---
- [Section 1](#section1)
- ...
## <a name="section1"></a>Section 1
`;
// Write template
fs.writeFileSync(location, template, "utf8");
};
main()
.then(() => process.exit(0))
.catch(error => {
console.error(error);
process.exit(1);
});