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

WIP: refactor: refactor types #5483

Draft
wants to merge 8 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 24 additions & 2 deletions lib/box/file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,38 @@ import { readFile, readFileSync, stat, statSync, type ReadFileOptions } from 'he
import type fs from 'fs';

class File {

/**
* Full path of the file
*/
public source: string;

/**
* Relative path to the box of the file
*/
public path: string;

/**
* The information from path matching.
*/
public params: any;
public type: string;

/**
* File type. The value can be create, update, skip, delete.
*/
// eslint-disable-next-line no-use-before-define
public type: typeof File.TYPE_CREATE | typeof File.TYPE_UPDATE | typeof File.TYPE_SKIP | typeof File.TYPE_DELETE;
static TYPE_CREATE: 'create';
static TYPE_UPDATE: 'update';
static TYPE_SKIP: 'skip';
static TYPE_DELETE: 'delete';

constructor({ source, path, params, type }) {
constructor({ source, path, params, type }: {
source: string;
path: string;
params: any;
type: typeof File.TYPE_CREATE | typeof File.TYPE_UPDATE | typeof File.TYPE_SKIP | typeof File.TYPE_DELETE;
SukkaW marked this conversation as resolved.
Show resolved Hide resolved
}) {
this.source = source;
this.path = path;
this.params = params;
Expand Down
19 changes: 10 additions & 9 deletions lib/box/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { EventEmitter } from 'events';
import { isMatch, makeRe } from 'micromatch';
import type Hexo from '../hexo';
import type { NodeJSLikeCallback } from '../types';
import type fs from 'fs';

const defaultPattern = new Pattern(() => ({}));

Expand Down Expand Up @@ -101,7 +102,7 @@ class Box extends EventEmitter {

_readDir(base: string, prefix = ''): BlueBirdPromise<any> {
const { context: ctx } = this;
const results = [];
const results: string[] = [];
return readDirWalker(ctx, base, results, this.ignore, prefix)
.return(results)
.map(path => this._checkFileStatus(path))
Expand Down Expand Up @@ -267,30 +268,30 @@ function toRegExp(ctx: Hexo, arg: string): RegExp | null {
return result;
}

function isIgnoreMatch(path: string, ignore: string | any[]): boolean {
function isIgnoreMatch(path: string, ignore: string | string[]): boolean {
return path && ignore && ignore.length && isMatch(path, ignore);
}

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

return BlueBirdPromise.map(readdir(base).catch(err => {
ctx.log.error({ err }, 'Failed to read directory: %s', base);
if (err && err.code === 'ENOENT') return [];
throw err;
}), async path => {
const fullpath = join(base, path);
const stats = await stat(fullpath).catch(err => {
ctx.log.error({ err }, 'Failed to stat file: %s', fullpath);
}), async (path: string) => {
const fullPath = join(base, path);
const stats: fs.Stats = await stat(fullPath).catch(err => {
ctx.log.error({ err }, 'Failed to stat file: %s', fullPath);
if (err && err.code === 'ENOENT') return null;
throw err;
});
const prefixPath = `${prefix}${path}`;
if (stats) {
if (stats.isDirectory()) {
return readDirWalker(ctx, fullpath, results, ignore, prefixPath + sep);
return readDirWalker(ctx, fullPath, results, ignore, prefixPath + sep);
}
if (!isIgnoreMatch(fullpath, ignore)) {
if (!isIgnoreMatch(fullPath, ignore)) {
results.push(prefixPath);
}
}
Expand Down
3 changes: 2 additions & 1 deletion lib/models/asset.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import warehouse from 'warehouse';
import { join } from 'path';
import type Hexo from '../hexo';
import type { AssetSchema } from '../types';

export = (ctx: Hexo) => {
const Asset = new warehouse.Schema({
Expand All @@ -10,7 +11,7 @@ export = (ctx: Hexo) => {
renderable: {type: Boolean, default: true}
});

Asset.virtual('source').get(function() {
Asset.virtual('source').get(function(this: AssetSchema) {
Copy link
Member

Choose a reason for hiding this comment

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

Let's improve the warehouse's virtual type to infer this here.

return join(ctx.base_dir, this._id);
});

Expand Down
21 changes: 15 additions & 6 deletions lib/models/cache.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,27 @@
import warehouse from 'warehouse';
import Promise from 'bluebird';
import type Hexo from '../hexo';
import type fs from 'fs';
import type Model from 'warehouse/dist/model';
import type Document from 'warehouse/dist/document';
import type { CacheSchema } from '../types';

export = (ctx: Hexo) => {

Check warning on line 9 in lib/models/cache.ts

View workflow job for this annotation

GitHub Actions / linter

'ctx' is defined but never used
const Cache = new warehouse.Schema({
_id: {type: String, required: true},
hash: {type: String, default: ''},
modified: {type: Number, default: Date.now() } // UnixTime
});

Cache.static('compareFile', function(id, hashFn, statFn) {
const cache = this.findById(id);
Cache.static('compareFile', function(this: Model<CacheSchema>, id: string,
hashFn: (id: string) => Promise<string>,
statFn: (id: string) => Promise<fs.Stats>): Promise<{ type: string }> {
const cache = this.findById(id) as Document<CacheSchema>;

// If cache does not exist, then it must be a new file. We have to get both
// file hash and stats.
if (!cache) {
return Promise.all([hashFn(id), statFn(id)]).spread((hash, stats) => this.insert({
return Promise.all([hashFn(id), statFn(id)]).spread((hash: string, stats: fs.Stats) => this.insert({
_id: id,
hash,
modified: stats.mtime.getTime()
Expand All @@ -24,10 +30,10 @@
});
}

let mtime;
let mtime: number;

// Get file stats
return statFn(id).then(stats => {
return statFn(id).then<any>(stats => {
mtime = stats.mtime.getTime();

// Skip the file if the modified time is unchanged
Expand All @@ -39,7 +45,7 @@

// Get file hash
return hashFn(id);
}).then(result => {
}).then((result: string | object) => {
// If the result is an object, skip the following steps because it's an
// unchanged file
if (typeof result === 'object') return result;
Expand All @@ -57,6 +63,9 @@
cache.hash = hash;
cache.modified = mtime;

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
// waiting warehouse v5.0.2
return cache.save().thenReturn({
type: 'update'
});
Expand Down
15 changes: 8 additions & 7 deletions lib/models/category.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import warehouse from 'warehouse';
import { slugize, full_url_for } from 'hexo-util';
import type Hexo from '../hexo';
import type { CategorySchema } from '../types';

export = (ctx: Hexo) => {
const Category = new warehouse.Schema({
name: {type: String, required: true},
parent: { type: warehouse.Schema.Types.CUID, ref: 'Category'}
});

Category.virtual('slug').get(function() {
Category.virtual('slug').get(function(this: CategorySchema) {
let name = this.name;

if (!name) return;
Expand All @@ -28,19 +29,19 @@ export = (ctx: Hexo) => {
return str;
});

Category.virtual('path').get(function() {
Category.virtual('path').get(function(this: CategorySchema) {
let catDir = ctx.config.category_dir;
if (catDir === '/') catDir = '';
if (!catDir.endsWith('/')) catDir += '/';

return `${catDir + this.slug}/`;
});

Category.virtual('permalink').get(function() {
Category.virtual('permalink').get(function(this: CategorySchema) {
return full_url_for.call(ctx, this.path);
});

Category.virtual('posts').get(function() {
Category.virtual('posts').get(function(this: CategorySchema) {
const PostCategory = ctx.model('PostCategory');

const ids = PostCategory.find({category_id: this._id}).map(item => item.post_id);
Expand All @@ -50,14 +51,14 @@ export = (ctx: Hexo) => {
});
});

Category.virtual('length').get(function() {
Category.virtual('length').get(function(this: CategorySchema) {
const PostCategory = ctx.model('PostCategory');

return PostCategory.find({category_id: this._id}).length;
});

// Check whether a category exists
Category.pre('save', data => {
Category.pre('save', (data: CategorySchema) => {
const { name, parent } = data;
if (!name) return;

Expand All @@ -73,7 +74,7 @@ export = (ctx: Hexo) => {
});

// Remove PostCategory references
Category.pre('remove', data => {
Category.pre('remove', (data: CategorySchema) => {
const PostCategory = ctx.model('PostCategory');
return PostCategory.remove({category_id: data._id});
});
Expand Down
5 changes: 3 additions & 2 deletions lib/models/page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import Moment from './types/moment';
import moment from 'moment';
import { full_url_for } from 'hexo-util';
import type Hexo from '../hexo';
import type { PageSchema } from '../types';

export = (ctx: Hexo) => {
const Page = new warehouse.Schema({
Expand All @@ -30,11 +31,11 @@ export = (ctx: Hexo) => {
more: {type: String}
});

Page.virtual('permalink').get(function() {
Page.virtual('permalink').get(function(this: PageSchema) {
return full_url_for.call(ctx, this.path);
});

Page.virtual('full_source').get(function() {
Page.virtual('full_source').get(function(this: PageSchema) {
return join(ctx.source_dir, this.source || '');
});

Expand Down
Loading
Loading