1
0
mirror of https://github.com/kremalicious/blog.git synced 2024-11-15 17:45:31 +01:00
blog/scripts/new.js

73 lines
2.0 KiB
JavaScript
Raw Normal View History

2018-11-01 19:35:18 +01:00
import fs from 'fs-extra'
2018-09-24 01:09:50 +02:00
import path from 'path'
import slugify from 'slugify'
import ora from 'ora'
const templatePath = path.join(__dirname, 'new.md')
2018-11-05 23:32:02 +01:00
const templatePathPhoto = path.join(__dirname, 'new-photo.md')
2018-09-24 01:09:50 +02:00
const template = fs.readFileSync(templatePath).toString()
2018-11-05 23:32:02 +01:00
const templatePhoto = fs.readFileSync(templatePathPhoto).toString()
2018-09-24 01:09:50 +02:00
2018-11-05 23:32:02 +01:00
const spinner = ora('Adding new post').start()
2018-09-24 01:09:50 +02:00
if (!process.argv[2]) {
2018-09-29 23:05:14 +02:00
spinner.fail('Use the format `npm run new "Title of post"`')
2018-09-24 01:09:50 +02:00
}
const title = process.argv[2]
2018-11-05 23:32:02 +01:00
const isPhoto = process.argv[3] === 'photo'
2018-09-24 01:09:50 +02:00
spinner.text = `Adding '${title}'.`
const titleSlug = slugify(title, { lower: true })
2018-09-29 23:05:14 +02:00
const postsPath = path.join('.', 'content', 'posts')
2018-11-05 23:32:02 +01:00
const photosPath = path.join('.', 'content', 'photos')
2018-11-06 00:28:52 +01:00
let date = new Date().toISOString()
2018-09-29 23:05:14 +02:00
2018-11-05 23:32:02 +01:00
if (isPhoto) {
2018-11-06 00:28:52 +01:00
if (process.argv[4]) {
date = new Date(process.argv[4]).toISOString()
}
const dateShort = date.slice(0, 10)
const filePhoto = `${photosPath}/${dateShort}-${titleSlug}.md`
const newContentsPhoto = templatePhoto
.split('TITLE')
.join(title)
.split('SLUG')
.join(titleSlug)
.split('DATE_LONG')
.join(date)
.split('DATE_SHORT')
.join(dateShort)
2018-11-05 23:32:02 +01:00
fs.appendFile(filePhoto, newContentsPhoto, err => {
if (err) spinner.fail(`Error creating photo post: ${err}`)
2019-02-11 20:57:26 +01:00
spinner.succeed(
`New photo post '${title}' created.\n\n Use ${dateShort}-${titleSlug}.jpg as the photo file name.`
)
2018-11-01 19:35:18 +01:00
})
2018-11-05 23:32:02 +01:00
} else {
2018-11-06 00:28:52 +01:00
if (process.argv[3]) {
date = new Date(process.argv[3]).toISOString()
}
const dateShort = date.slice(0, 10)
const file = `${postsPath}/${dateShort}-${titleSlug}/index.md`
const newContents = template
.split('TITLE')
.join(title)
.split('SLUG')
.join(titleSlug)
.split('DATE')
.join(date)
2018-11-05 23:32:02 +01:00
fs.outputFile(file, newContents)
.then(() => fs.readFile(file, 'utf8'))
.then(() => spinner.succeed(`New post '${title}' created.`))
.catch(err => spinner.fail(`Error creating post: ${err}`))
}