|
| 1 | +const { cp, stat } = require('fs/promises') |
| 2 | +const { join, dirname, sep } = require('path') |
| 3 | +const Settings = require('../../../../settings') |
| 4 | +const { contentRoot, getSlug } = require('../../../../helpers') |
| 5 | +const { debugLog } = require('../../../../debug') |
| 6 | + |
| 7 | +const all = Promise.all.bind(Promise) |
| 8 | + |
| 9 | +const withBasePath = (basePath) => (asset) => ({ ...asset, basePath }) |
| 10 | + |
| 11 | +const copyAsset = async ({ basePath, destPath, path, name, isFolder }) => { |
| 12 | + const { out } = Settings.getSettings() |
| 13 | + const outputDir = dirname(destPath || path) |
| 14 | + const dirnameSlug = outputDir === '.' ? |
| 15 | + outputDir : |
| 16 | + outputDir.split(sep).map(getSlug).join(sep) |
| 17 | + const outPath = join(out, join(dirnameSlug, name)) |
| 18 | + debugLog('copying:', path) |
| 19 | + try { |
| 20 | + return await cp(join(basePath, path), outPath, { recursive: !!isFolder }) |
| 21 | + } catch (e) { |
| 22 | + if (e.code === 'ENOENT') { |
| 23 | + debugLog('failed copying asset that no longer exists', e) |
| 24 | + } else { |
| 25 | + debugLog('failed copying asset', e) |
| 26 | + } |
| 27 | + return Promise.resolve() |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +const copyLocalAssets = async (contentModel) => { |
| 32 | + const { rootDirectory, contentDirectory, pagesDirectory } = Settings.getSettings() |
| 33 | + const basePath = await contentRoot(rootDirectory, contentDirectory) |
| 34 | + const { localAssets, homepage, posts, subpages, categories } = contentModel |
| 35 | + |
| 36 | + console.log('copyLocalAssets CM', contentModel) |
| 37 | + |
| 38 | + const copyRootAssets = all( |
| 39 | + localAssets |
| 40 | + .map(withBasePath(basePath)) |
| 41 | + .map(copyAsset) |
| 42 | + ) |
| 43 | + |
| 44 | + const copyHomepageAssets = all( |
| 45 | + (homepage.localAssets || []).map((localAsset) => { |
| 46 | + const assetWithBasePath = withBasePath(basePath)(localAsset) |
| 47 | + return copyAsset({ |
| 48 | + ...assetWithBasePath, |
| 49 | + destPath: '.' |
| 50 | + }) |
| 51 | + }) |
| 52 | + ) |
| 53 | + |
| 54 | + const copySubpageAssets = all( |
| 55 | + (subpages || []).map(({ localAssets = [] }) => { |
| 56 | + return all( |
| 57 | + localAssets |
| 58 | + .map(withBasePath(basePath)) |
| 59 | + .map(a => ({ |
| 60 | + ...a, |
| 61 | + destPath: a.path.replace(new RegExp('^' + pagesDirectory), '') |
| 62 | + })) |
| 63 | + .map(copyAsset) |
| 64 | + ) |
| 65 | + }) |
| 66 | + ) |
| 67 | + |
| 68 | + return all([ |
| 69 | + copyRootAssets, |
| 70 | + copyHomepageAssets, |
| 71 | + copySubpageAssets |
| 72 | + ]) |
| 73 | +} |
| 74 | + |
| 75 | +const renderLocalAssets = (renderer, contentModel) => { |
| 76 | + return copyLocalAssets(contentModel) |
| 77 | +} |
| 78 | + |
| 79 | +module.exports = renderLocalAssets |
0 commit comments