style: auto fix.

This commit is contained in:
2022-10-17 15:37:01 +00:00
parent 10f64a9ba4
commit c081d55a32
68 changed files with 1403 additions and 1114 deletions

View File

@@ -1,36 +1,39 @@
const fs = require('fs')
const path = require('path')
const inquirer = require('inquirer')
const dedent = require('dedent')
const fs = require('fs');
const path = require('path');
const inquirer = require('inquirer');
const dedent = require('dedent');
const root = process.cwd()
const root = process.cwd();
const getAuthors = () => {
const authorPath = path.join(root, 'data', 'authors')
const authorList = fs.readdirSync(authorPath).map((filename) => path.parse(filename).name)
return authorList
}
const authorPath = path.join(root, 'data', 'authors');
const authorList = fs
.readdirSync(authorPath)
.map((filename) => path.parse(filename).name);
return authorList;
};
const getLayouts = () => {
const layoutPath = path.join(root, 'layouts')
const layoutPath = path.join(root, 'layouts');
const layoutList = fs
.readdirSync(layoutPath)
.map((filename) => path.parse(filename).name)
.filter((file) => file.toLowerCase().includes('post'))
return layoutList
}
.filter((file) => file.toLowerCase().includes('post'));
return layoutList;
};
const genFrontMatter = (answers) => {
let d = new Date()
let d = new Date();
const date = [
d.getFullYear(),
('0' + (d.getMonth() + 1)).slice(-2),
('0' + d.getDate()).slice(-2),
].join('-')
const tagArray = answers.tags.split(',')
tagArray.forEach((tag, index) => (tagArray[index] = tag.trim()))
const tags = "'" + tagArray.join("','") + "'"
const authorArray = answers.authors.length > 0 ? "'" + answers.authors.join("','") + "'" : ''
].join('-');
const tagArray = answers.tags.split(',');
tagArray.forEach((tag, index) => (tagArray[index] = tag.trim()));
const tags = "'" + tagArray.join("','") + "'";
const authorArray =
answers.authors.length > 0 ? "'" + answers.authors.join("','") + "'" : '';
let frontMatter = dedent`---
title: ${answers.title ? answers.title : 'Untitled'}
@@ -41,16 +44,16 @@ const genFrontMatter = (answers) => {
images: []
layout: ${answers.layout}
canonicalUrl: ${answers.canonicalUrl}
`
`;
if (answers.authors.length > 0) {
frontMatter = frontMatter + '\n' + `authors: [${authorArray}]`
frontMatter = frontMatter + '\n' + `authors: [${authorArray}]`;
}
frontMatter = frontMatter + '\n---'
frontMatter = frontMatter + '\n---';
return frontMatter
}
return frontMatter;
};
inquirer
.prompt([
@@ -105,24 +108,25 @@ inquirer
.toLowerCase()
.replace(/[^a-zA-Z0-9 ]/g, '')
.replace(/ /g, '-')
.replace(/-+/g, '-')
const frontMatter = genFrontMatter(answers)
if (!fs.existsSync('data/blog')) fs.mkdirSync('data/blog', { recursive: true })
.replace(/-+/g, '-');
const frontMatter = genFrontMatter(answers);
if (!fs.existsSync('data/blog'))
fs.mkdirSync('data/blog', { recursive: true });
const filePath = `data/blog/${fileName ? fileName : 'untitled'}.${
answers.extension ? answers.extension : 'md'
}`
}`;
fs.writeFile(filePath, frontMatter, { flag: 'wx' }, (err) => {
if (err) {
throw err
throw err;
} else {
console.log(`Blog post generated successfully at ${filePath}`)
console.log(`Blog post generated successfully at ${filePath}`);
}
})
});
})
.catch((error) => {
if (error.isTtyError) {
console.log("Prompt couldn't be rendered in the current environment")
console.log("Prompt couldn't be rendered in the current environment");
} else {
console.log('Something went wrong, sorry!')
console.log('Something went wrong, sorry!');
}
})
});

View File

@@ -1,11 +1,11 @@
const fs = require('fs')
const globby = require('globby')
const matter = require('gray-matter')
const prettier = require('prettier')
const siteMetadata = require('../data/siteMetadata')
const fs = require('fs');
const globby = require('globby');
const matter = require('gray-matter');
const prettier = require('prettier');
const siteMetadata = require('../data/siteMetadata');
;(async () => {
const prettierConfig = await prettier.resolveConfig('./.prettierrc.js')
(async () => {
const prettierConfig = await prettier.resolveConfig('./.prettierrc.js');
const pages = await globby([
'pages/*.js',
'pages/*.tsx',
@@ -15,7 +15,7 @@ const siteMetadata = require('../data/siteMetadata')
'!pages/_*.js',
'!pages/_*.tsx',
'!pages/api',
])
]);
const sitemap = `
<?xml version="1.0" encoding="UTF-8"?>
@@ -24,13 +24,13 @@ const siteMetadata = require('../data/siteMetadata')
.map((page) => {
// Exclude drafts from the sitemap
if (page.search('.md') >= 1 && fs.existsSync(page)) {
const source = fs.readFileSync(page, 'utf8')
const fm = matter(source)
const source = fs.readFileSync(page, 'utf8');
const fm = matter(source);
if (fm.data.draft) {
return
return;
}
if (fm.data.canonicalUrl) {
return
return;
}
}
const path = page
@@ -41,26 +41,29 @@ const siteMetadata = require('../data/siteMetadata')
.replace('.tsx', '')
.replace('.mdx', '')
.replace('.md', '')
.replace('/feed.xml', '')
const route = path === '/index' ? '' : path
if (page.search('pages/404.') > -1 || page.search(`pages/blog/[...slug].`) > -1) {
return
.replace('/feed.xml', '');
const route = path === '/index' ? '' : path;
if (
page.search('pages/404.') > -1 ||
page.search(`pages/blog/[...slug].`) > -1
) {
return;
}
return `
<url>
<loc>${siteMetadata.siteUrl}${route}</loc>
</url>
`
`;
})
.join('')}
</urlset>
`
`;
const formatted = prettier.format(sitemap, {
...prettierConfig,
parser: 'html',
})
});
// eslint-disable-next-line no-sync
fs.writeFileSync('public/sitemap.xml', formatted)
})()
fs.writeFileSync('public/sitemap.xml', formatted);
})();

View File

@@ -5,116 +5,130 @@
// The app listens to the event and triggers a client-side router refresh
// see components/ClientReload.js
const chalk = require('chalk')
const chokidar = require('chokidar')
const program = require('commander')
const http = require('http')
const SocketIO = require('socket.io')
const express = require('express')
const spawn = require('child_process').spawn
const next = require('next')
const path = require('path')
const { parse } = require('url')
const chalk = require('chalk');
const chokidar = require('chokidar');
const program = require('commander');
const http = require('http');
const SocketIO = require('socket.io');
const express = require('express');
const spawn = require('child_process').spawn;
const next = require('next');
const path = require('path');
const { parse } = require('url');
const pkg = require('../package.json')
const pkg = require('../package.json');
const defaultWatchEvent = 'change'
const defaultWatchEvent = 'change';
program.storeOptionsAsProperties().version(pkg.version)
program.storeOptionsAsProperties().version(pkg.version);
program
.option('-r, --root [dir]', 'root directory of your nextjs app')
.option('-s, --script [path]', 'path to the script you want to trigger on a watcher event', false)
.option(
'-s, --script [path]',
'path to the script you want to trigger on a watcher event',
false
)
.option('-c, --command [cmd]', 'command to execute on a watcher event', false)
.option(
'-e, --event [name]',
`name of event to watch, defaults to ${defaultWatchEvent}`,
defaultWatchEvent
)
.option('-p, --polling [name]', `use polling for the watcher, defaults to false`, false)
.parse(process.argv)
.option(
'-p, --polling [name]',
`use polling for the watcher, defaults to false`,
false
)
.parse(process.argv);
const shell = process.env.SHELL
const app = next({ dev: true, dir: program.root || process.cwd() })
const port = parseInt(process.env.PORT, 10) || 3000
const handle = app.getRequestHandler()
const shell = process.env.SHELL;
const app = next({ dev: true, dir: program.root || process.cwd() });
const port = parseInt(process.env.PORT, 10) || 3000;
const handle = app.getRequestHandler();
app.prepare().then(() => {
// if directories are provided, watch them for changes and trigger reload
if (program.args.length > 0) {
chokidar
.watch(program.args, { usePolling: Boolean(program.polling) })
.on(program.event, async (filePathContext, eventContext = defaultWatchEvent) => {
// Emit changes via socketio
io.sockets.emit('reload', filePathContext)
app.server.hotReloader.send('building')
.on(
program.event,
async (filePathContext, eventContext = defaultWatchEvent) => {
// Emit changes via socketio
io.sockets.emit('reload', filePathContext);
app.server.hotReloader.send('building');
if (program.command) {
// Use spawn here so that we can pipe stdio from the command without buffering
spawn(
shell,
[
'-c',
program.command
.replace(/\{event\}/gi, filePathContext)
.replace(/\{path\}/gi, eventContext),
],
{
stdio: 'inherit',
}
)
}
if (program.script) {
try {
// find the path of your --script script
const scriptPath = path.join(process.cwd(), program.script.toString())
// require your --script script
const executeFile = require(scriptPath)
// run the exported function from your --script script
executeFile(filePathContext, eventContext)
} catch (e) {
console.error('Remote script failed')
console.error(e)
return e
if (program.command) {
// Use spawn here so that we can pipe stdio from the command without buffering
spawn(
shell,
[
'-c',
program.command
.replace(/\{event\}/gi, filePathContext)
.replace(/\{path\}/gi, eventContext),
],
{
stdio: 'inherit',
}
);
}
}
app.server.hotReloader.send('reloadPage')
})
if (program.script) {
try {
// find the path of your --script script
const scriptPath = path.join(
process.cwd(),
program.script.toString()
);
// require your --script script
const executeFile = require(scriptPath);
// run the exported function from your --script script
executeFile(filePathContext, eventContext);
} catch (e) {
console.error('Remote script failed');
console.error(e);
return e;
}
}
app.server.hotReloader.send('reloadPage');
}
);
}
// create an express server
const expressApp = express()
const server = http.createServer(expressApp)
const expressApp = express();
const server = http.createServer(expressApp);
// watch files with socketIO
const io = SocketIO(server)
const io = SocketIO(server);
// special handling for mdx reload route
const reloadRoute = express.Router()
reloadRoute.use(express.json())
const reloadRoute = express.Router();
reloadRoute.use(express.json());
reloadRoute.all('/', (req, res) => {
// log message if present
const msg = req.body.message
const color = req.body.color
msg && console.log(color ? chalk[color](msg) : msg)
const msg = req.body.message;
const color = req.body.color;
msg && console.log(color ? chalk[color](msg) : msg);
// reload the nextjs app
app.server.hotReloader.send('building')
app.server.hotReloader.send('reloadPage')
res.end('Reload initiated')
})
app.server.hotReloader.send('building');
app.server.hotReloader.send('reloadPage');
res.end('Reload initiated');
});
expressApp.use('/__next_reload', reloadRoute)
expressApp.use('/__next_reload', reloadRoute);
// handle all other routes with next.js
expressApp.all('*', (req, res) => handle(req, res, parse(req.url, true)))
expressApp.all('*', (req, res) => handle(req, res, parse(req.url, true)));
// fire it up
server.listen(port, (err) => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
})
})
if (err) throw err;
console.log(`> Ready on http://localhost:${port}`);
});
});