Skip to content

Commit

Permalink
fix(eslint): update settings and fix source code
Browse files Browse the repository at this point in the history
  • Loading branch information
ybiquitous committed Jun 26, 2018
1 parent 46e8086 commit a236089
Show file tree
Hide file tree
Showing 12 changed files with 227 additions and 222 deletions.
36 changes: 18 additions & 18 deletions .commitlintrc.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,26 @@
module.exports = {
extends: ['@commitlint/config-conventional'],
extends: ["@commitlint/config-conventional"],

rules: {
'scope-enum': [
"scope-enum": [
2,
'always',
"always",
[
'',
'deps',
'package',
'readme',
'eslint',
'editorconfig',
'commitlint',
'coverage',
'release',
'init',
'api',
'markdownlint',
'travis',
'prettier',
"",
"deps",
"package",
"readme",
"eslint",
"editorconfig",
"commitlint",
"coverage",
"release",
"init",
"api",
"markdownlint",
"travis",
"prettier",
],
],
},
}
};
9 changes: 5 additions & 4 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
module.exports = {
root: true,

extends: ['ybiquitous'],
extends: ["ybiquitous/node"],

overrides: [
{
files: ['**/test/**/*.js'],
files: ["**/test/**/*.js"],
rules: {
'no-shadow': ['error', { allow: ['t'] }],
"no-shadow": ["error", { allow: ["t"] }],
"import/no-internal-modules": "off",
},
},
],
}
};
4 changes: 2 additions & 2 deletions bin/cli.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#!/usr/bin/env node
const cli = require(`../lib/cli`)
const cli = require(`../lib/cli`);

cli()
cli();
4 changes: 2 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
const init = require(`./lib/init`)
const init = require(`./lib/init`);

module.exports = { init }
module.exports = { init };
14 changes: 7 additions & 7 deletions lib/cli.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
const yargs = require('yargs')
const init = require('./init')
const yargs = require("yargs");
const init = require("./init");

module.exports = function cli() {
// eslint-disable-next-line no-unused-expressions
yargs
.usage('$0 <command>')
.command('init', init.desc, {}, init)
.usage("$0 <command>")
.command("init", init.desc, {}, init)
.demandCommand(1)
.strict()
.alias('help', 'h')
.alias('version', 'v').argv
}
.alias("help", "h")
.alias("version", "v").argv;
};
89 changes: 45 additions & 44 deletions lib/init.js
Original file line number Diff line number Diff line change
@@ -1,95 +1,96 @@
const path = require('path')
const { EOL } = require('os')
const fs = require('fs-extra')
const originalPackage = require('../package.json')
const path = require("path");
const { EOL } = require("os");
const fs = require("fs-extra");
const originalPackage = require("../package.json");

const packagePath = (...pathElements) =>
path.join(...[__dirname, '..', ...pathElements])
path.join(...[__dirname, "..", ...pathElements]);

const template = name => path.join(__dirname, '..', 'templates', name)
const template = name => path.join(__dirname, "..", "templates", name);

class Init {
constructor(baseDir, logger) {
this.baseDir = baseDir
this.logger = logger
this.baseDir = baseDir;
this.logger = logger;
}

async copyFile(src, dest) {
await fs.copy(src, dest)
this.logger(`${dest} was updated.`)
await fs.copy(src, dest);
this.logger(`${dest} was updated.`);
}

currentPath(...pathElements) {
return path.join(...[this.baseDir, ...pathElements])
return path.join(...[this.baseDir, ...pathElements]);
}

async writeFile(fileName, fileContent) {
const file = this.currentPath(fileName)
await fs.writeFile(file, `${fileContent}\n`)
this.logger(`${file} was updated.`)
const file = this.currentPath(fileName);
await fs.writeFile(file, `${fileContent}\n`);
this.logger(`${file} was updated.`);
}

async readFile(fileName) {
return fs.readFile(this.currentPath(fileName), 'utf8')
readFile(fileName) {
return fs.readFile(this.currentPath(fileName), "utf8");
}

// eslint-disable-next-line max-statements
async updatePackageFile() {
const packageInfo = JSON.parse(await this.readFile('package.json'))
const packageInfo = JSON.parse(await this.readFile("package.json"));

// update 'scripts'
if (!('scripts' in packageInfo)) {
packageInfo.scripts = {}
if (!("scripts" in packageInfo)) {
packageInfo.scripts = {};
}
const { scripts } = packageInfo
if (!('test' in scripts)) {
scripts.test = 'test'
const { scripts } = packageInfo;
if (!("test" in scripts)) {
scripts.test = "test";
}
scripts['test:watch'] = `${scripts.test} --watch`
scripts['test:coverage'] = 'echo "unsupported." && exit 1'
scripts["test:watch"] = `${scripts.test} --watch`;
scripts["test:coverage"] = 'echo "unsupported." && exit 1';
Object.keys(originalPackage.scripts)
.filter(key => !(key === 'test' || key.startsWith('test:')))
.filter(key => !(key === "test" || key.startsWith("test:")))
.forEach(key => {
scripts[key] = originalPackage.scripts[key]
})
scripts[key] = originalPackage.scripts[key];
});

// update other keys
const keys = ['lint-staged']
const keys = ["lint-staged"];
keys.forEach(key => {
if (!(key in packageInfo)) {
packageInfo[key] = {}
packageInfo[key] = {};
}
Object.assign(packageInfo[key], originalPackage[key])
})
Object.assign(packageInfo[key], originalPackage[key]);
});

await this.writeFile('package.json', JSON.stringify(packageInfo, null, 2))
await this.writeFile("package.json", JSON.stringify(packageInfo, null, 2));
}

async writeTemplateFile(name) {
await this.copyFile(template(name), this.currentPath(name))
await this.copyFile(template(name), this.currentPath(name));
}

async writePackageFile(name) {
await this.copyFile(packagePath(name), this.currentPath(name))
await this.copyFile(packagePath(name), this.currentPath(name));
}
}

const defaultLogger = msg => process.stdout.write(`${msg}${EOL}`)
const defaultLogger = msg => process.stdout.write(`${msg}${EOL}`);

module.exports = async function init({
cwd = process.cwd(),
logger = defaultLogger,
} = {}) {
const cmd = new Init(cwd, logger)
await cmd.updatePackageFile()
await cmd.writePackageFile('.editorconfig')
await cmd.writePackageFile('.prettierignore')
await cmd.writePackageFile('.markdownlint.json')
await cmd.writeTemplateFile('.eslintrc.js')
await cmd.writeTemplateFile('.commitlintrc.js')
}
const cmd = new Init(cwd, logger);
await cmd.updatePackageFile();
await cmd.writePackageFile(".editorconfig");
await cmd.writePackageFile(".prettierignore");
await cmd.writePackageFile(".markdownlint.json");
await cmd.writeTemplateFile(".eslintrc.js");
await cmd.writeTemplateFile(".commitlintrc.js");
};

module.exports.desc = `Setup npm project:
- Update 'package.json'
- Create '.commitlintrc.js'
- Create '.editorconfig'
- Create '.eslintrc.js'`
- Create '.eslintrc.js'`;
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
".markdownlint.json"
],
"engines": {
"node": ">=8"
"node": ">=8.3.0"
},
"dependencies": {
"@commitlint/cli": "^7.0.0",
Expand Down Expand Up @@ -76,6 +76,9 @@
"CHANGELOG.md"
]
},
"prettier": {
"trailingComma": "es5"
},
"browserslist": [
"> 1%",
"not ie 11",
Expand Down
46 changes: 23 additions & 23 deletions test/help.test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const test = require('tape')
const exec = require('./helpers/exec')
const test = require("tape");
const exec = require("./helpers/exec");

const HELP = `
cli.js <command>
Expand All @@ -14,26 +14,26 @@ Commands:
Options:
--help, -h Show help [boolean]
--version, -v Show version number [boolean]
`.trim()
`.trim();

test('help', t => {
;[[], ['unknown'], ['unknown', 'xyz']].forEach(args => {
t.test(`with arguments [${args.join(', ')}]`, async t => {
const error = await exec(...args).catch(err => err)
const { code, stdout, stderr } = error
t.ok(error instanceof Error)
t.is(code, 1)
t.is(stdout, '')
t.ok(stderr.includes(HELP))
t.end()
})
})
;['--help', '-h'].forEach(option => {
test("help", t => {
[[], ["unknown"], ["unknown", "xyz"]].forEach(args => {
t.test(`with arguments [${args.join(", ")}]`, async t => {
const error = await exec(...args).catch(err => err);
const { code, stdout, stderr } = error;
t.ok(error instanceof Error);
t.is(code, 1);
t.is(stdout, "");
t.ok(stderr.includes(HELP));
t.end();
});
});
["--help", "-h"].forEach(option => {
t.test(`with "${option}" option`, async t => {
const { stdout, stderr } = await exec(option)
t.ok(stdout.includes(HELP))
t.is(stderr, '')
t.end()
})
})
})
const { stdout, stderr } = await exec(option);
t.ok(stdout.includes(HELP));
t.is(stderr, "");
t.end();
});
});
});
30 changes: 15 additions & 15 deletions test/helpers/exec.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,27 @@
const path = require('path')
const cp = require('child_process')
const path = require("path");
const cp = require("child_process");

const tested = path.join(process.cwd(), 'bin', 'cli.js')
const tested = path.join(process.cwd(), "bin", "cli.js");

module.exports = function exec(...args) {
const options = {
env: { ...process.env, LANG: 'C' },
}
const lastArg = args[args.length - 1]
if (lastArg && typeof lastArg === 'object') {
options.cwd = lastArg.cwd
env: { ...process.env, LANG: "C" },
};
const lastArg = args[args.length - 1];
if (lastArg && typeof lastArg === "object") {
options.cwd = lastArg.cwd;
}
return new Promise((resolve, reject) => {
cp.execFile(tested, args, options, (error, stdout, stderr) => {
if (error) {
/* eslint-disable no-param-reassign */
error.stdout = stdout
error.stderr = stderr
error.stdout = stdout;
error.stderr = stderr;
/* eslint-enable no-param-reassign */
reject(error)
reject(error);
} else {
resolve({ stdout, stderr })
resolve({ stdout, stderr });
}
})
})
}
});
});
};
Loading

0 comments on commit a236089

Please sign in to comment.