Skip to content

Commit

Permalink
cleanup(wip): remove bluebird
Browse files Browse the repository at this point in the history
  • Loading branch information
talentlessguy committed Jun 30, 2024
1 parent a3f27b8 commit 43bf980
Show file tree
Hide file tree
Showing 63 changed files with 328 additions and 232 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,4 @@ coverage/
.tmp*
.vscode
dist/
bun.lockb
1 change: 0 additions & 1 deletion lib/box/file.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import type Promise from 'bluebird';
import { readFile, readFileSync, stat, statSync, type ReadFileOptions } from 'hexo-fs';
import type fs from 'fs';

Expand Down
96 changes: 55 additions & 41 deletions lib/box/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { join, sep } from 'path';
import BlueBirdPromise from 'bluebird';
import File from './file';
import { Pattern, createSha1Hash } from 'hexo-util';
import { createReadStream, readdir, stat, watch } from 'hexo-fs';
Expand Down Expand Up @@ -99,7 +98,7 @@ class Box extends EventEmitter {
});
}

_readDir(base: string, prefix = ''): BlueBirdPromise<any> {
_readDir(base: string, prefix = ''): Promise<any> {
const { context: ctx } = this;
const results = [];
return readDirWalker(ctx, base, results, this.ignore, prefix)
Expand All @@ -122,7 +121,7 @@ class Box extends EventEmitter {
}));
}

process(callback?: NodeJSLikeCallback<any>): BlueBirdPromise<any> {
process(callback?: NodeJSLikeCallback<any>): Promise<any> {
const { base, Cache, context: ctx } = this;

return stat(base).then(stats => {
Expand All @@ -141,9 +140,9 @@ class Box extends EventEmitter {
}).asCallback(callback);
}

_processFile(type: string, path: string): BlueBirdPromise<void> | BlueBirdPromise<string> {
async _processFile(type: string, path: string): Promise<void | string> {
if (this._processingFiles[path]) {
return BlueBirdPromise.resolve();
return Promise.resolve();
}

this._processingFiles[path] = true;
Expand All @@ -155,45 +154,55 @@ class Box extends EventEmitter {
path
});

return BlueBirdPromise.reduce(this.processors, (count, processor) => {
const params = processor.pattern.match(path);
if (!params) return count;

const file = new File({
// source is used for filesystem path, keep backslashes on Windows
source: join(base, path),
// path is used for URL path, replace backslashes on Windows
path: escapeBackslash(path),
params,
type
});

return Reflect.apply(BlueBirdPromise.method(processor.process), ctx, [file])
.thenReturn(count + 1);
}, 0).then(count => {
if (count) {
ctx.log.debug('Processed: %s', magenta(path));
try {
try {
const count_1 = await this.processors.reduce((promise, processor) => {
return promise.then(count => {
const params = processor.pattern.match(path);
if (!params) return count;

const file = new File({
// source is used for filesystem path, keep backslashes on Windows
source: join(base, path),
// path is used for URL path, replace backslashes on Windows
path: escapeBackslash(path),
params,
type
});

return Promise.resolve(processor.process.call(ctx, file))
.then(() => count + 1);
});
}, Promise.resolve(0));
if (count_1) {
ctx.log.debug('Processed: %s', magenta(path));
}

this.emit('processAfter', {
type,
path
});
} catch (err) {
ctx.log.error({ err }, 'Process failed: %s', magenta(path));
}

this.emit('processAfter', {
type,
path
});
}).catch(err => {
ctx.log.error({ err }, 'Process failed: %s', magenta(path));
}).finally(() => {
} finally {
this._processingFiles[path] = false;
}).thenReturn(path);
}
return path;
}

watch(callback?: NodeJSLikeCallback<never>): BlueBirdPromise<void> {
watch(callback?: NodeJSLikeCallback<never>): Promise<void> {
if (this.isWatching()) {
return BlueBirdPromise.reject(new Error('Watcher has already started.')).asCallback(callback);
const error = new Error('Watcher has already started.');
if (callback) {
return Promise.reject(error).catch(callback);
}
return Promise.reject(error);
}

const { base } = this;

function getPath(path) {
function getPath(path: string) {
return escapeBackslash(path.substring(base.length));
}

Expand All @@ -218,7 +227,12 @@ class Box extends EventEmitter {

this._readDir(path, prefix);
});
}).asCallback(callback);
}).then(() => {
if (callback) callback(null);
}).catch(err => {
if (callback) callback(err);
else throw err;
});
}

unwatch(): void {
Expand All @@ -238,11 +252,11 @@ function escapeBackslash(path: string): string {
return path.replace(/\\/g, '/');
}

function getHash(path: string): BlueBirdPromise<string> {
function getHash(path: string): Promise<string> {
const src = createReadStream(path);
const hasher = createSha1Hash();

const finishedPromise = new BlueBirdPromise((resolve, reject) => {
const finishedPromise = new Promise((resolve, reject) => {
src.once('error', reject);
src.once('end', resolve);
});
Expand Down Expand Up @@ -270,10 +284,10 @@ function isIgnoreMatch(path: string, ignore: string | any[]): boolean {
return path && ignore && ignore.length && isMatch(path, ignore);
}

function readDirWalker(ctx: Hexo, base: string, results: any[], ignore: any, prefix: string): BlueBirdPromise<any> {
if (isIgnoreMatch(base, ignore)) return BlueBirdPromise.resolve();
function readDirWalker(ctx: Hexo, base: string, results: any[], ignore: any, prefix: string): Promise<any> {
if (isIgnoreMatch(base, ignore)) return Promise.resolve();

return BlueBirdPromise.map(readdir(base).catch(err => {
return Promise.map(readdir(base).catch(err => {
ctx.log.error({ err }, 'Failed to read directory: %s', base);
if (err && err.code === 'ENOENT') return [];
throw err;
Expand Down
2 changes: 1 addition & 1 deletion lib/extend/console.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import Promise from 'bluebird';

import abbrev from 'abbrev';
import type { NodeJSLikeCallback } from '../types';

Expand Down
2 changes: 1 addition & 1 deletion lib/extend/deployer.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import Promise from 'bluebird';

import type { NodeJSLikeCallback } from '../types';

interface StoreFunction {
Expand Down
2 changes: 1 addition & 1 deletion lib/extend/filter.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import Promise from 'bluebird';


const typeAlias = {
pre: 'before_post_render',
Expand Down
2 changes: 1 addition & 1 deletion lib/extend/generator.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import Promise from 'bluebird';

import type { NodeJSLikeCallback } from '../types';

interface BaseObj {
Expand Down
2 changes: 1 addition & 1 deletion lib/extend/migrator.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import Promise from 'bluebird';

import type { NodeJSLikeCallback } from '../types';

interface StoreFunction {
Expand Down
2 changes: 1 addition & 1 deletion lib/extend/processor.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import Promise from 'bluebird';

import { Pattern } from 'hexo-util';
import type File from '../box/file';

Expand Down
6 changes: 3 additions & 3 deletions lib/extend/renderer.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { extname } from 'path';
import Promise from 'bluebird';
import { promisify } from 'util';
import type { NodeJSLikeCallback } from '../types';

const getExtname = (str: string) => {
Expand Down Expand Up @@ -98,10 +98,10 @@ class Renderer {
this.storeSync[name] = fn;
this.storeSync[name].output = output;

this.store[name] = Promise.method(fn);
this.store[name] = promisify(fn);
this.store[name].disableNunjucks = (fn as StoreFunction).disableNunjucks;
} else {
if (fn.length > 2) fn = Promise.promisify(fn);
if (fn.length > 2) fn = promisify(fn);
this.store[name] = fn;
}

Expand Down
2 changes: 1 addition & 1 deletion lib/extend/tag.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { stripIndent } from 'hexo-util';
import { cyan, magenta, red, bold } from 'picocolors';
import { Environment } from 'nunjucks';
import Promise from 'bluebird';

import type { NodeJSLikeCallback } from '../types';

const rSwigRawFullBlock = /{% *raw *%}/;
Expand Down
2 changes: 1 addition & 1 deletion lib/hexo/default_config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export = {
category_dir: 'categories',
code_dir: 'downloads/code',
i18n_dir: ':lang',
skip_render: [],
skip_render: [] as string[],
// Writing
new_post_name: ':title.md',
default_layout: 'post',
Expand Down
62 changes: 37 additions & 25 deletions lib/hexo/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import Promise from 'bluebird';
import { sep, join, dirname } from 'path';
import tildify from 'tildify';
import Database from 'warehouse';
Expand Down Expand Up @@ -86,13 +85,17 @@ const createLoadThemeRoute = function(generatorResult: NormalPageGenerator | Nor
context: ctx,
args: [locals]
}))
.tap(result => {
.then(result => {
if (useCache) {
routeCache.set(generatorResult, result);
}
}).tapCatch(err => {
return result;
})
.catch(err => {
log.error({ err }, `Render HTML failed: ${magenta(path)}`);
throw err;
});

}
}

Expand Down Expand Up @@ -423,15 +426,17 @@ class Hexo extends EventEmitter {
require('../plugins/tag').default(this);

// Load config
return Promise.each([
return Promise.all([
'update_package', // Update package.json
'load_config', // Load config
'load_theme_config', // Load alternate theme config
'load_plugins' // Load external plugins & scripts
], name => require(`./${name}`)(this)).then(() => this.execFilter('after_init', null, { context: this })).then(() => {
].map(name => require(`./${name}`)(this)))
.then(() => this.execFilter('after_init', null, { context: this }))
.then(() => {
// Ready to go!
this.emit('ready');
});
this.emit('ready');
});
}

call(name: string, callback?: NodeJSLikeCallback<any>): Promise<any>;
Expand Down Expand Up @@ -600,14 +605,16 @@ class Hexo extends EventEmitter {
const { log } = this;

// Run generators
return Promise.map(Object.keys(generators), key => {
return Promise.all(Object.keys(generators).map(key => {
const generator = generators[key];

log.debug('Generator: %s', magenta(key));
return Reflect.apply(generator, this, [siteLocals]);
}).reduce((result, data) => {
return data ? result.concat(data) : result;
}, []);
}))
.then((results: any[]) => results.reduce((result: any[], data: any) => {
return data ? result.concat(data) : result;
}, []));

}

_routerRefresh(runningGenerators: Promise<(AssetGenerator | PostGenerator | PageGenerator)[]>, useCache: boolean): Promise<void> {
Expand All @@ -616,23 +623,27 @@ class Hexo extends EventEmitter {
const Locals = this._generateLocals();
Locals.prototype.cache = useCache;

return runningGenerators.map((generatorResult: AssetGenerator | PostGenerator | PageGenerator) => {
if (typeof generatorResult !== 'object' || generatorResult.path == null) return undefined;
return runningGenerators.then(generators => {
return Promise.all(generators.map(generatorResult => {
if (typeof generatorResult !== 'object' || generatorResult.path == null) return undefined;

// add Route
const path = route.format(generatorResult.path);
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const { data, layout } = generatorResult;
// add Route
const path = route.format(generatorResult.path);
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const { data, layout } = generatorResult;

if (!layout) {
route.set(path, data);
return path;
}
if (!layout) {
route.set(path, data);
return path;
}

return this.execFilter('template_locals', new Locals(path, data as unknown as NormalPageGenerator | NormalPostGenerator), { context: this })
.then(locals => { route.set(path, createLoadThemeRoute(generatorResult as NormalPageGenerator | NormalPostGenerator, locals, this)); })
.thenReturn(path);
return this.execFilter('template_locals', new Locals(path, data as unknown as NormalPageGenerator | NormalPostGenerator), { context: this })
.then(locals => {
route.set(path, createLoadThemeRoute(generatorResult as NormalPageGenerator | NormalPostGenerator, locals, this));
return path;
});
}));
}).then(newRouteList => {
// Remove old routes
for (let i = 0, len = routeList.length; i < len; i++) {
Expand All @@ -645,6 +656,7 @@ class Hexo extends EventEmitter {
});
}


_generate(options: { cache?: boolean } = {}): Promise<any> {
if (this._isGenerating) return;

Expand Down
2 changes: 1 addition & 1 deletion lib/hexo/load_database.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { exists, unlink } from 'hexo-fs';
import Promise from 'bluebird';

import type Hexo from './index';

export = (ctx: Hexo): Promise<void> => {
Expand Down
2 changes: 1 addition & 1 deletion lib/hexo/load_plugins.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { join } from 'path';
import { exists, readFile, listDir } from 'hexo-fs';
import Promise from 'bluebird';

import { magenta } from 'picocolors';
import type Hexo from './index';

Expand Down
1 change: 0 additions & 1 deletion lib/hexo/load_theme_config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { exists, readdir } from 'hexo-fs';
import { magenta } from 'picocolors';
import { deepMerge } from 'hexo-util';
import type Hexo from './index';
import type Promise from 'bluebird';

export = (ctx: Hexo): Promise<void> => {
if (!ctx.env.init) return;
Expand Down
2 changes: 1 addition & 1 deletion lib/hexo/post.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import assert from 'assert';
import moment from 'moment';
import Promise from 'bluebird';

import { join, extname, basename } from 'path';
import { magenta } from 'picocolors';
import { load } from 'js-yaml';
Expand Down
Loading

0 comments on commit 43bf980

Please sign in to comment.