Skip to content

Commit

Permalink
Refactor(es2015) (#65)
Browse files Browse the repository at this point in the history
* Refactor(es2015): Run lebab

* Refactor: es2015

* Refactor printList
  • Loading branch information
segayuu authored and JLHwung committed May 9, 2019
1 parent cac3c9e commit 6dc001f
Show file tree
Hide file tree
Showing 8 changed files with 68 additions and 105 deletions.
44 changes: 21 additions & 23 deletions lib/console/help.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,13 @@ function helpConsole(args) {
}

function printHelpForCommand(command, data) {
const options = data.options;
const { options } = data;

const desc = options.description || options.desc || data.description || data.desc;

console.log('Usage: hexo', command, options.usage || '');
console.log('\nDescription:');
console.log((options.description || options.desc || data.description || data.desc) + '\n');
console.log(`${desc}\n`);

if (options.arguments) printList('Arguments', options.arguments);
if (options.commands) printList('Commands', options.commands);
Expand All @@ -43,10 +45,10 @@ function printHelpForCommand(command, data) {
function printAllHelp(list) {
const keys = Object.keys(list);
const commands = [];
let key = '';
const { length } = keys;

for (let i = 0, len = keys.length; i < len; i++) {
key = keys[i];
for (let i = 0; i < length; i++) {
const key = keys[i];

commands.push({
name: key,
Expand Down Expand Up @@ -74,31 +76,27 @@ function printAllHelp(list) {
}

function printList(title, list) {
let length = 0;
let str = title + ':\n';

list.forEach(function(item) {
length = Math.max(length, item.name.length);
});

list.sort(function(a, b) {
list.sort((a, b) => {
const nameA = a.name;
const nameB = b.name;

if (nameA < nameB) return -1;
else if (nameA > nameB) return 1;
if (nameA > nameB) return 1;

return 0;
}).forEach(function(item) {
let padding = length - item.name.length + 2;
str += ' ' + chalk.bold(item.name);
});

while (padding--) {
str += ' ';
}
const lengths = list.map(item => item.name.length);
const maxLen = lengths.reduce((prev, current) => Math.max(prev, current));

str += (item.description || item.desc) + '\n';
});
let str = `${title}:\n`;
const { length } = list;

for (let i = 0; i < length; i++) {
const { description = list[i].desc } = list[i];
const pad = ' '.repeat(maxLen - lengths[i] + 2);
str += ` ${chalk.bold(list[i].name)}${pad}${description}`;
}

console.log(str);

Expand All @@ -112,7 +110,7 @@ function printConsoleList(list) {
}

function printCompletion(type) {
return fs.readFile(pathFn.join(COMPLETION_DIR, type)).then(function(content) {
return fs.readFile(pathFn.join(COMPLETION_DIR, type)).then(content => {
console.log(content);
});
}
Expand Down
2 changes: 1 addition & 1 deletion lib/console/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
'use strict';

module.exports = function(ctx) {
const console = ctx.extend.console;
const { console } = ctx.extend;

console.register('help', 'Get help on a command.', {}, require('./help'));

Expand Down
58 changes: 19 additions & 39 deletions lib/console/init.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,24 +12,21 @@ const ASSET_DIR = pathFn.join(__dirname, '../../assets');
const GIT_REPO_URL = 'https:/hexojs/hexo-starter.git';

function initConsole(args) {
args = Object.assign({
install: true,
clone: true
}, args);
args = Object.assign({ install: true, clone: true }, args);

const baseDir = this.base_dir;
const target = args._[0] ? pathFn.resolve(baseDir, String(args._[0])) : baseDir;
const log = this.log;
let promise, npmCommand;
const { log } = this;

if (fs.existsSync(target) && fs.readdirSync(target).length !== 0) {
log.fatal(chalk.magenta(tildify(target))
+ ' not empty, please run `hexo init` on an empty folder and then copy your files into it');
log.fatal(`${chalk.magenta(tildify(target))} not empty, please run \`hexo init\` on an empty folder and then copy your files into it`);
return Promise.reject(new Error('target not empty'));
}

log.info('Cloning hexo-starter', GIT_REPO_URL);

let promise;

if (args.clone) {
promise = spawn('git', ['clone', '--recursive', GIT_REPO_URL, target], {
stdio: 'inherit'
Expand All @@ -38,67 +35,50 @@ function initConsole(args) {
promise = copyAsset(target);
}

return promise.catch(function() {
return promise.catch(() => {
log.warn('git clone failed. Copying data instead');

return copyAsset(target);
}).then(function() {
return Promise.all([
removeGitDir(target),
removeGitModules(target)
]);
}).then(function() {
}).then(() => Promise.all([
removeGitDir(target),
removeGitModules(target)
])).then(() => {
if (!args.install) return;

log.info('Install dependencies');

if (commandExistsSync('yarn')) {
npmCommand = 'yarn';
} else {
npmCommand = 'npm';
}
const npmCommand = commandExistsSync('yarn') ? 'yarn' : 'npm';

return spawn(npmCommand, ['install', '--production'], {
cwd: target,
stdio: 'inherit'
});
}).then(function() {
}).then(() => {
log.info('Start blogging with Hexo!');
}).catch(function() {
}).catch(() => {
log.warn('Failed to install dependencies. Please run \'npm install\' manually!');
});
}

function copyAsset(target) {
return fs.copyDir(ASSET_DIR, target, {
ignoreHidden: false
});
return fs.copyDir(ASSET_DIR, target, { ignoreHidden: false });
}

function removeGitDir(target) {
const gitDir = pathFn.join(target, '.git');

return fs.stat(gitDir).catch(function(err) {
return fs.stat(gitDir).catch(err => {
if (err.cause && err.cause.code === 'ENOENT') return;
throw err;
}).then(function(stats) {
}).then(stats => {
if (stats) {
if (stats.isDirectory()) return fs.rmdir(gitDir);
return fs.unlink(gitDir);
return stats.isDirectory() ? fs.rmdir(gitDir) : fs.unlink(gitDir);
}
}).then(function() {
return fs.readdir(target);
}).map(function(path) {
return pathFn.join(target, path);
}).filter(function(path) {
return fs.stat(path).then(function(stats) {
return stats.isDirectory();
});
}).each(removeGitDir);
}).then(() => fs.readdir(target)).map(path => pathFn.join(target, path)).filter(path => fs.stat(path).then(stats => stats.isDirectory())).each(removeGitDir);
}

function removeGitModules(target) {
return fs.unlink(pathFn.join(target, '.gitmodules')).catch(function(err) {
return fs.unlink(pathFn.join(target, '.gitmodules')).catch(err => {
if (err.cause && err.cause.code === 'ENOENT') return;
throw err;
});
Expand Down
3 changes: 1 addition & 2 deletions lib/console/version.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ const Promise = require('bluebird');
function versionConsole(args) {
const versions = process.versions;
const keys = Object.keys(versions);
let key = '';

if (this.version) {
console.log('hexo:', this.version);
Expand All @@ -17,7 +16,7 @@ function versionConsole(args) {
console.log('os:', os.type(), os.release(), os.platform(), os.arch());

for (let i = 0, len = keys.length; i < len; i++) {
key = keys[i];
const key = keys[i];
console.log('%s: %s', key, versions[key]);
}

Expand Down
23 changes: 9 additions & 14 deletions lib/context.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,14 @@

const logger = require('hexo-log');
const chalk = require('chalk');
const EventEmitter = require('events').EventEmitter;
const { EventEmitter } = require('events');
const Promise = require('bluebird');
const ConsoleExtend = require('./extend/console');

// a stub Hexo object
// see `hexojs/hexo/lib/hexo/index.js`

function Context(base, args) {
base = base || process.cwd();
args = args || {};

function Context(base = process.cwd(), args = {}) {
EventEmitter.call(this);

this.base_dir = base;
Expand All @@ -25,7 +22,7 @@ function Context(base, args) {

require('util').inherits(Context, EventEmitter);

Context.prototype.init = function() {
Context.prototype.init = () => {
// Do nothing
};

Expand All @@ -35,23 +32,21 @@ Context.prototype.call = function(name, args, callback) {
args = {};
}

const self = this;

return new Promise(function(resolve, reject) {
const c = self.extend.console.get(name);
return new Promise((resolve, reject) => {
const c = this.extend.console.get(name);

if (c) {
c.call(self, args).then(resolve, reject);
c.call(this, args).then(resolve, reject);
} else {
reject(new Error('Console `' + name + '` has not been registered yet!'));
reject(new Error(`Console \`${name}\` has not been registered yet!`));
}
}).asCallback(callback);
};

Context.prototype.exit = function(err) {
if (err) {
this.log.fatal(
{err: err},
{err},
'Something\'s wrong. Maybe you can find the solution here: %s',
chalk.underline('http://hexo.io/docs/troubleshooting.html')
);
Expand All @@ -60,7 +55,7 @@ Context.prototype.exit = function(err) {
return Promise.resolve();
};

Context.prototype.unwatch = function() {
Context.prototype.unwatch = () => {
// Do nothing
};

Expand Down
8 changes: 3 additions & 5 deletions lib/find_pkg.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@
const pathFn = require('path');
const fs = require('hexo-fs');

function findPkg(cwd, args) {
args = args || {};

function findPkg(cwd, args = {}) {
if (args.cwd) {
cwd = pathFn.resolve(cwd, args.cwd);
}
Expand All @@ -16,10 +14,10 @@ function findPkg(cwd, args) {
function checkPkg(path) {
const pkgPath = pathFn.join(path, 'package.json');

return fs.readFile(pkgPath).then(function(content) {
return fs.readFile(pkgPath).then(content => {
const json = JSON.parse(content);
if (typeof json.hexo === 'object') return path;
}).catch(function(err) {
}).catch(err => {
if (err && err.cause.code === 'ENOENT') {
const parent = pathFn.dirname(path);

Expand Down
4 changes: 1 addition & 3 deletions lib/goodbye.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,4 @@ const byeWords = [
'Catch you later'
];

module.exports = function() {
return byeWords[(Math.random() * byeWords.length) | 0];
};
module.exports = () => byeWords[(Math.random() * byeWords.length) | 0];
Loading

0 comments on commit 6dc001f

Please sign in to comment.