|
1 | 1 | import { toDate, timezone, isExcludedFile, isTmpFile, isHiddenFile, isMatch } from './common'; |
2 | 2 | import Promise from 'bluebird'; |
3 | 3 | import { parse as yfm } from 'hexo-front-matter'; |
4 | | -import { extname, join } from 'path'; |
| 4 | +import { extname, join, posix, sep } from 'path'; |
5 | 5 | import { stat, listDir } from 'hexo-fs'; |
6 | 6 | import { slugize, Pattern, Permalink } from 'hexo-util'; |
7 | 7 | import { magenta } from 'picocolors'; |
8 | 8 | import type { _File } from '../../box'; |
9 | 9 | import type Hexo from '../../hexo'; |
10 | 10 | import type { Stats } from 'fs'; |
| 11 | +import { PostSchema } from '../../types'; |
11 | 12 |
|
12 | 13 | const postDir = '_posts/'; |
13 | 14 | const draftDir = '_drafts/'; |
@@ -268,29 +269,41 @@ function processAsset(ctx: Hexo, file: _File) { |
268 | 269 | const PostAsset = ctx.model('PostAsset'); |
269 | 270 | const Post = ctx.model('Post'); |
270 | 271 | const id = file.source.substring(ctx.base_dir.length); |
271 | | - const doc = PostAsset.findById(id); |
| 272 | + const postAsset = PostAsset.findById(id); |
272 | 273 |
|
273 | | - if (file.type === 'delete') { |
274 | | - if (doc) { |
275 | | - return doc.remove(); |
| 274 | + if (file.type === 'delete' || Post.length === 0) { |
| 275 | + if (postAsset) { |
| 276 | + return postAsset.remove(); |
276 | 277 | } |
277 | | - |
278 | 278 | return; |
279 | 279 | } |
280 | 280 |
|
281 | | - // TODO: Better post searching |
282 | | - const post = Post.toArray().find(post => file.source.startsWith(post.asset_dir)); |
283 | | - if (post != null && (post.published || ctx._showDrafts())) { |
| 281 | + const savePostAsset = (post: PostSchema) => { |
284 | 282 | return PostAsset.save({ |
285 | 283 | _id: id, |
286 | 284 | slug: file.source.substring(post.asset_dir.length), |
287 | 285 | post: post._id, |
288 | 286 | modified: file.type !== 'skip', |
289 | 287 | renderable: file.params.renderable |
290 | 288 | }); |
| 289 | + }; |
| 290 | + |
| 291 | + if (postAsset) { |
| 292 | + // `postAsset.post` is `Post.id`. |
| 293 | + const post = Post.findById(postAsset.post); |
| 294 | + if (post != null && (post.published || ctx._showDrafts())) { |
| 295 | + return savePostAsset(post); |
| 296 | + } |
| 297 | + } |
| 298 | + |
| 299 | + const assetDir = id.slice(0, id.lastIndexOf(sep)); |
| 300 | + const post = Post.findOne(p => p.asset_dir.endsWith(posix.join(assetDir, '/'))); |
| 301 | + if (post != null && (post.published || ctx._showDrafts())) { |
| 302 | + return savePostAsset(post); |
291 | 303 | } |
292 | 304 |
|
293 | | - if (doc) { |
294 | | - return doc.remove(); |
| 305 | + // NOTE: Probably, unreachable. |
| 306 | + if (postAsset) { |
| 307 | + return postAsset.remove(); |
295 | 308 | } |
296 | 309 | } |
0 commit comments