-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLumenNewPost.js
105 lines (94 loc) · 2.77 KB
/
LumenNewPost.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
#! /usr/bin/env node
const fs = require('fs'),
path = require('path')
const articlesDir = path.join(__dirname, `../../src/pages/articles/`)
// parse commandline parameters, returning 'value' for every getParam(key)
const getParam = arg =>
(process.argv.find(param => param.split('=')[0] === arg) || '').split('=')[1]
//long or short ISO timezones
const niceNow = (short = true, now = new Date()) =>
short ? now.toISOString().split('T')[0] : now.toISOString()
// blog article directory
const getDirectory = () =>
articlesDir +
niceNow() +
'---' +
title.replace(/ /g, '-').replace(/[\/\\]/g, '-')
// parse out custom blog options
let title = ''
try {
title = getParam('title').trim()
if (title.length <= 0) throw 'title empty'
} catch (err) {
console.log(`There doesn't seem to be a valid title argument passed.`)
return
}
const category = getParam('cat') || getParam('category') || ''
const description = getParam('desc') || getParam('description') || ''
const tags = getParam('tags')
? ('\n - "' + (getParam('tags') || '').replace(/,/g, '","') + '"')
.split(',')
.join('\n - ')
: ''
// The promise land
const makeBlogDir = () => {
const dir = getDirectory()
const promise = new Promise((resolve, reject) => {
console.log(dir)
try {
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir)
resolve({ message: 'Directory Created' })
}
reject('Directory Already Exists With That Blog Title')
} catch (err) {
reject(err)
}
})
return promise
}
const readBlogTemplate = blog => {
if (blog.message) console.log(blog.message)
const promise = new Promise((resolve, reject) => {
fs.readFile(
path.join(__dirname, '/emptyBlogTemplate.md'),
'utf8',
(err, data) => {
if (err) reject(err)
const template = data
.replace(/Blog-Title/g, title.replace(/\\/g, '\\\\'))
.replace(/Blog-Category/g, category)
.replace(/Blog-Description/g, description)
.replace(/Blog-Tags/g, tags)
.replace(
/Blog-Path/g,
title
.toLowerCase()
.replace(/ /g, '-')
.replace(/[\/\\]/g, '-'),
)
.replace(/Blog-Date/g, niceNow(false))
resolve({
message: 'Template Generated\n' + template,
data: template,
})
},
)
})
return promise
}
const writeBlogTemplate = blog => {
if (blog.message) console.log(blog.message)
const promise = new Promise((resolve, reject) => {
fs.writeFile(path.join(getDirectory(), '/index.md'), blog.data, err => {
if (err) reject(err)
resolve('The file was saved!')
})
})
return promise
}
makeBlogDir()
.then(readBlogTemplate)
.then(writeBlogTemplate)
.then(console.log)
.catch(console.log)