105 lines
2.2 KiB
TypeScript
105 lines
2.2 KiB
TypeScript
import arg from "arg";
|
|
import paths from "node:path";
|
|
import fs from "node:fs/promises";
|
|
|
|
const globalArgs = arg(
|
|
{
|
|
"--help": Boolean,
|
|
},
|
|
{ argv: process.argv.slice(2), stopAtPositional: true },
|
|
);
|
|
|
|
if (globalArgs["--help"] || globalArgs._.length === 0) {
|
|
process.stdout.write(`postman.ts [...options] <command>
|
|
|
|
COMMANDS
|
|
|
|
new - Create new post
|
|
|
|
OPTIONS
|
|
--help - Print this message and exit
|
|
`);
|
|
|
|
process.exit();
|
|
}
|
|
|
|
const command = globalArgs._[0];
|
|
let rest = globalArgs._.slice(1);
|
|
|
|
function parseNewPostArgsPartial(rest: string[]) {
|
|
return arg(
|
|
{
|
|
"--draft": Boolean,
|
|
"--overwrite": Boolean,
|
|
"--help": Boolean,
|
|
},
|
|
{ stopAtPositional: true, argv: rest },
|
|
);
|
|
}
|
|
|
|
const postRoot = paths.resolve(import.meta.dir, "..", "src", "posts");
|
|
|
|
if (command === "new") {
|
|
const cfg = parseNewPostArgsPartial(rest);
|
|
rest = cfg._.slice(1);
|
|
const postId: string = cfg._[0];
|
|
|
|
const hasAdditionalArgs = cfg._.length > 0;
|
|
|
|
const partialCfg = parseNewPostArgsPartial(rest);
|
|
Object.assign(cfg, partialCfg);
|
|
|
|
if (cfg["--help"] || !hasAdditionalArgs) {
|
|
process.stdout.write(`postman.ts new <postId> [...options]
|
|
|
|
Create a new post with default content.
|
|
|
|
OPTIONS
|
|
|
|
--draft - Create the post as a draft
|
|
--overwrite - Overwrite existing file
|
|
--help - Print this message and exit
|
|
`);
|
|
|
|
process.exit();
|
|
}
|
|
|
|
if (partialCfg._.length > 0) {
|
|
throw new TypeError(`unexpected positional argument "${partialCfg._[0]}"`);
|
|
}
|
|
|
|
const thisPostRoot = paths.join(postRoot, postId);
|
|
|
|
await fs.mkdir(thisPostRoot);
|
|
|
|
const postContent = `---
|
|
title: ${postId}
|
|
${cfg["--draft"] ? "visibility: draft" : ""}
|
|
---
|
|
import More from "~/components/More.astro";
|
|
|
|
<More />
|
|
`;
|
|
|
|
const thisPostFilename = paths.join(thisPostRoot, "index.mdx");
|
|
|
|
const file = await fs.open(
|
|
thisPostFilename,
|
|
(cfg["--overwrite"]
|
|
? fs.constants.O_TRUNC
|
|
: fs.constants.O_CREAT | fs.constants.O_EXCL) | fs.constants.O_WRONLY,
|
|
);
|
|
|
|
try {
|
|
await fs.writeFile(file, postContent, {
|
|
encoding: "utf-8",
|
|
});
|
|
} finally {
|
|
await file.close();
|
|
}
|
|
|
|
const displayedPath = paths.relative(process.cwd(), thisPostFilename);
|
|
process.stdout.write(displayedPath);
|
|
} else {
|
|
throw new TypeError(`unknown command ${command}`);
|
|
}
|