Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace String#substring() with String#startsWith() or String#endsWith() #3124

Merged
merged 10 commits into from
May 5, 2018
6 changes: 3 additions & 3 deletions lib/box/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ function Box(ctx, base, options) {
persistent: true
}, options);

if (base.substring(base.length - 1) !== sep) {
if (!base.endsWith(sep)) {
base += sep;
}

Expand Down Expand Up @@ -158,11 +158,11 @@ Box.prototype.process = function(callback) {

// Check existing files in cache
const relativeBase = escapeBackslash(base.substring(ctx.base_dir.length));
const cacheFiles = Cache.filter(item => item._id.substring(0, relativeBase.length) === relativeBase).map(item => item._id.substring(relativeBase.length));
const cacheFiles = Cache.filter(item => item._id.startsWith(relativeBase)).map(item => item._id.substring(relativeBase.length));

// Read files from directory
return self._readDir(base, file => self._processFile(file.type, file.path)).map(file => file.path).then(files => // Handle deleted files
Promise.filter(cacheFiles, path => !~files.indexOf(path)).map(path => self._processFile(File.TYPE_DELETE, path)));
Promise.filter(cacheFiles, path => !files.includes(path)).map(path => self._processFile(File.TYPE_DELETE, path)));
}).catch(err => {
if (err.cause && err.cause.code !== 'ENOENT') throw err;
}).asCallback(callback);
Expand Down
17 changes: 4 additions & 13 deletions lib/extend/tag.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,21 +55,12 @@ Tag.prototype.render = function(str, options, callback) {

const cache = [];

function escapeContent(str) {
return `<!--${placeholder}${cache.push(str) - 1}-->`;
}
const escapeContent = str => `<!--${placeholder}${cache.push(str) - 1}-->`;

const env = this.env;
str = str.replace(/<pre><code.*>[\s\S]*?<\/code><\/pre>/gm, escapeContent);

return new Promise((resolve, reject) => {
str = str.replace(/<pre><code.*>[\s\S]*?<\/code><\/pre>/gm, escapeContent);
env.renderString(str, options, (err, result) => {
if (err) return reject(err);
resolve(result.replace(rPlaceholder, function(...args) {
return cache[args[1]];
}));
});
});
return Promise.fromCallback(cb => { this.env.renderString(str, options, cb); })
.then(result => result.replace(rPlaceholder, (_, index) => cache[index]));
};

function NunjucksTag(name, fn) {
Expand Down
14 changes: 10 additions & 4 deletions lib/hexo/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,6 @@ const sep = pathFn.sep;
const dbVersion = 1;

function Hexo(base = process.cwd(), args = {}) {
const mcp = multiConfigPath(this);

EventEmitter.call(this);

this.base_dir = base + sep;
Expand Down Expand Up @@ -82,12 +80,20 @@ function Hexo(base = process.cwd(), args = {}) {

this._isGenerating = false;

// If `output` is provided, use that as the
// root for saving the db. Otherwise default to `base`.
const dbPath = args.output || base;

this.log.d(`Writing database to ${dbPath}/db.json`);

this.database = new Database({
version: dbVersion,
path: pathFn.join(base, 'db.json')
path: pathFn.join(dbPath, 'db.json')
});

this.config_path = args.config ? mcp(base, args.config) :
const mcp = multiConfigPath(this);

this.config_path = args.config ? mcp(base, args.config, args.output) :
pathFn.join(base, '_config.yml');

registerModels(this);
Expand Down
4 changes: 2 additions & 2 deletions lib/hexo/load_config.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,12 @@ function findConfigPath(path) {
const basename = pathFn.basename(path, extname);

return fs.readdir(dirname).then(files => {
let item = '';
let item;

for (let i = 0, len = files.length; i < len; i++) {
item = files[i];

if (item.substring(0, basename.length) === basename) {
if (item.startsWith(basename)) {
return pathFn.join(dirname, item);
}
}
Expand Down
31 changes: 22 additions & 9 deletions lib/hexo/multi_config_path.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const fs = require('hexo-fs');
const _ = require('lodash');
const yml = require('js-yaml');

module.exports = ctx => function multiConfigPath(base, configPaths) {
module.exports = ctx => function multiConfigPath(base, configPaths, outputDir) {
const log = ctx.log;

const defaultPath = pathFn.join(base, '_config.yml');
Expand All @@ -17,17 +17,18 @@ module.exports = ctx => function multiConfigPath(base, configPaths) {
}

// determine if comma or space separated
if (configPaths.indexOf(',') > -1) {
if (configPaths.includes(',')) {
paths = configPaths.replace(' ', '').split(',');

} else {
// only one config
if (!fs.existsSync(pathFn.join(base, configPaths))) {
let configPath = pathFn.isAbsolute(configPaths) ? configPaths : pathFn.resolve(base, configPaths);

if (!fs.existsSync(configPath)) {
log.w(`Config file ${configPaths} not found, using default.`);
return defaultPath;
configPath = defaultPath;
}

return pathFn.resolve(base, configPaths);
return configPath;
}

const numPaths = paths.length;
Expand All @@ -36,13 +37,21 @@ module.exports = ctx => function multiConfigPath(base, configPaths) {
const combinedConfig = {};
let count = 0;
for (let i = 0; i < numPaths; i++) {
if (!fs.existsSync(pathFn.join(base, paths[i]))) {
let configPath = '';

if (pathFn.isAbsolute(paths[i])) {
configPath = paths[i];
} else {
configPath = pathFn.join(base, paths[i]);
}

if (!fs.existsSync(configPath)) {
log.w(`Config file ${paths[i]} not found.`);
continue;
}

// files read synchronously to ensure proper overwrite order
const file = fs.readFileSync(pathFn.join(base, paths[i]));
const file = fs.readFileSync(configPath);
const ext = pathFn.extname(paths[i]).toLowerCase();

if (ext === '.yml') {
Expand All @@ -63,7 +72,11 @@ module.exports = ctx => function multiConfigPath(base, configPaths) {

log.i('Config based on', count, 'files');

const outputPath = pathFn.join(base, '_multiconfig.yml');
const multiconfigRoot = outputDir || base;
const outputPath = pathFn.join(multiconfigRoot, '_multiconfig.yml');

log.d(`Writing _multiconfig.yml to ${outputPath}`);

fs.writeFileSync(outputPath, yml.dump(combinedConfig));

// write file and return path
Expand Down
4 changes: 2 additions & 2 deletions lib/plugins/console/generate.js
Original file line number Diff line number Diff line change
Expand Up @@ -123,14 +123,14 @@ function generateConsole(args = {}) {
throw err;
}).then(() => {
const routeList = route.list();
const publicFiles = Cache.filter(item => item._id.substring(0, 7) === 'public/').map(item => item._id.substring(7));
const publicFiles = Cache.filter(item => item._id.startsWith('public/')).map(item => item._id.substring(7));

return Promise.all([
// Generate files
Promise.map(routeList, generateFile),

// Clean files
Promise.filter(publicFiles, path => !~routeList.indexOf(path)).map(deleteFile)
Promise.filter(publicFiles, path => !routeList.includes(path)).map(deleteFile)
]);
}).spread(result => {
const interval = prettyHrtime(process.hrtime(start));
Expand Down
1 change: 1 addition & 0 deletions lib/plugins/filter/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,5 @@ module.exports = ctx => {

filter.register('new_post_path', require('./new_post_path'));
filter.register('post_permalink', require('./post_permalink'));
filter.register('after_render:html', require('./meta_generator'));
};
17 changes: 17 additions & 0 deletions lib/plugins/filter/meta_generator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
'use strict';

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, it seems new filter added here. But in pull readme there is nothing about this.

Copy link
Contributor Author

@segayuu segayuu May 1, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That change is the result of #3129 being resolved by running git rebase.


let cheerio;
const hexoGeneratorTag = '<meta name="generator" content="Hexo %s" />';

function hexoMetaGeneratorInject(data) {
if (!cheerio) cheerio = require('cheerio');
const $ = cheerio.load(data, {decodeEntities: false});

if (!($('meta[name="generator"]').length > 0)) {
$('head').prepend(hexoGeneratorTag.replace('%s', this.version));

return $.html();
}
}

module.exports = hexoMetaGeneratorInject;
2 changes: 1 addition & 1 deletion lib/plugins/filter/template_locals/i18n.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ function i18nLocalsFilter(locals) {
const pattern = new Pattern(`${i18nDir}/*path`);
const data = pattern.match(locals.path);

if (data && data.lang && ~i18nLanguages.indexOf(data.lang)) {
if (data && data.lang && i18nLanguages.includes(data.lang)) {
lang = data.lang;
page.canonical_path = data.path;
} else {
Expand Down
2 changes: 1 addition & 1 deletion lib/plugins/helper/css.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ function cssHelper(...args) {
if (Array.isArray(path)) {
result += cssHelper.apply(this, path);
} else {
if (path.indexOf('?') < 0 && path.substring(path.length - 4, path.length) !== '.css') path += '.css';
if (!path.includes('?') && !path.endsWith('.css')) path += '.css';
result += `<link rel="stylesheet" href="${this.url_for(path)}">`;
}
}
Expand Down
11 changes: 4 additions & 7 deletions lib/plugins/helper/is.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
'use strict';

function isCurrentHelper(path = '/', strict) {
const currentPath = this.path.replace(/^[^\/].*/, _ => // eslint-disable-line no-useless-escape
`/${_}`);
const currentPath = this.path.replace(/^[^/].*/, '/$&');

if (strict) {
if (path[path.length - 1] === '/') path += 'index.html';
path = path.replace(/^[^\/].*/, _ => // eslint-disable-line no-useless-escape
`/${_}`);
path = path.replace(/^[^/].*/, '/$&');

return currentPath === path;
}
Expand All @@ -16,10 +14,9 @@ function isCurrentHelper(path = '/', strict) {

if (path === '/') return currentPath === '/index.html';

path = path.replace(/^[^\/].*/, _ => // eslint-disable-line no-useless-escape
`/${_}`);
path = path.replace(/^[^/].*/, '/$&');

return currentPath.substring(0, path.length) === path;
return currentPath.startsWith(path);
}

function isHomeHelper() {
Expand Down
2 changes: 1 addition & 1 deletion lib/plugins/helper/js.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ function jsHelper(...args) {
if (Array.isArray(path)) {
result += jsHelper.apply(this, path);
} else {
if (path.indexOf('?') < 0 && path.substring(path.length - 3, path.length) !== '.js') path += '.js';
if (!path.includes('?') && !path.endsWith('.js')) path += '.js';
result += `<script src="${this.url_for(path)}"></script>`;
}
}
Expand Down
2 changes: 1 addition & 1 deletion lib/plugins/helper/list_categories.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ function listCategoriesHelper(categories, options) {

// special case: category page
if (!isCurrent && self.page.base) {
if (self.page.base.indexOf(cat.path) === 0) {
if (self.page.base.startsWith(cat.path)) {
isCurrent = true;
}
}
Expand Down
2 changes: 1 addition & 1 deletion lib/plugins/helper/tagcloud.js
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ function tagcloudHelper(tags, options) {

tags.sort('length').forEach(tag => {
const length = tag.length;
if (~sizes.indexOf(length)) return;
if (sizes.includes(length)) return;

sizes.push(length);
});
Expand Down
2 changes: 1 addition & 1 deletion lib/plugins/helper/url_for.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const url = require('url');
const _ = require('lodash');

function urlForHelper(path = '/', options) {
if (path[0] === '#' || path.substring(0, 2) === '//') {
if (path[0] === '#' || path.startsWith('//')) {
return path;
}

Expand Down
2 changes: 1 addition & 1 deletion lib/plugins/tag/img.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ module.exports = ctx => {
const config = ctx.config;

function makeUrl(path) {
if (path[0] === '#' || path.substring(0, 2) === '//') {
if (path[0] === '#' || path.startsWith('//')) {
return path;
}

Expand Down
2 changes: 1 addition & 1 deletion lib/theme/processors/source.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ exports.pattern = new Pattern(path => {
if (!_.startsWith(path, 'source/')) return false;

path = path.substring(7);
if (common.isHiddenFile(path) || common.isTmpFile(path) || ~path.indexOf('node_modules')) return false;
if (common.isHiddenFile(path) || common.isTmpFile(path) || path.includes('node_modules')) return false;

return {path};
});
Loading