UNPKG

2.73 kBJavaScriptView Raw
1const path = require("path");
2const { EOL } = require("os");
3const { promisify } = require("util");
4const fs = require("fs");
5const originalPackage = require("../package.json");
6
7const copy = promisify(fs.copyFile);
8const write = promisify(fs.writeFile);
9const read = promisify(fs.readFile);
10
11const packagePath = (...pathElements) => path.join(...[__dirname, "..", ...pathElements]);
12
13// eslint-disable-next-line max-lines-per-function
14const initCommand = (baseDir, logger) => {
15 const currentPath = (...pathElems) => path.join(...[baseDir, ...pathElems]);
16
17 const readFile = fileName => read(currentPath(fileName), "utf8");
18
19 const copyFile = async (src, dest) => {
20 await copy(src, dest);
21 logger(`${dest} was updated.`);
22 };
23
24 const writeFile = async (fileName, fileContent) => {
25 const file = currentPath(fileName);
26 await write(file, `${fileContent}\n`);
27 logger(`${file} was updated.`);
28 };
29
30 return {
31 // eslint-disable-next-line max-statements
32 async updatePackageFile() {
33 const packageInfo = JSON.parse(await readFile("package.json"));
34
35 // update 'scripts'
36 if (!("scripts" in packageInfo)) {
37 packageInfo.scripts = {};
38 }
39 const { scripts } = packageInfo;
40 if (!("test" in scripts)) {
41 scripts.test = "test";
42 }
43 scripts["test:watch"] = `${scripts.test} --watch`;
44 scripts["test:coverage"] = 'echo "unsupported." && exit 1';
45 Object.keys(originalPackage.scripts)
46 .filter(key => !(key === "test" || key.startsWith("test:")))
47 .forEach(key => {
48 scripts[key] = originalPackage.scripts[key];
49 });
50
51 // update other keys
52 const keys = ["husky", "lint-staged", "standard-version", "prettier", "remarkConfig"];
53 keys.forEach(key => {
54 if (!(key in packageInfo)) {
55 packageInfo[key] = {};
56 }
57 Object.assign(packageInfo[key], originalPackage[key]);
58 });
59 packageInfo.commitlint = {
60 extends: ["@commitlint/config-conventional"],
61 };
62 packageInfo.eslintConfig = {
63 extends: ["ybiquitous"],
64 };
65
66 await writeFile("package.json", JSON.stringify(packageInfo, null, 2));
67 },
68
69 async writePackageFile(name) {
70 await copyFile(packagePath(name), currentPath(name));
71 },
72 };
73};
74
75const defaultLogger = msg => process.stdout.write(`${msg}${EOL}`);
76
77module.exports = async function init({ cwd = process.cwd(), logger = defaultLogger } = {}) {
78 const cmd = initCommand(cwd, logger);
79 await cmd.updatePackageFile();
80 await cmd.writePackageFile(".editorconfig");
81 await cmd.writePackageFile(".remarkignore");
82};
83
84module.exports.desc = `Setup npm project:
85- Update 'package.json'
86- Create '.editorconfig'`;