|
| 1 | +import fs from 'fs-extra'; |
| 2 | +import path from 'path'; |
| 3 | +import type { Root, RootContent } from 'hast'; |
| 4 | +import * as log from './log.js'; |
| 5 | +import { Options } from './create.js'; |
| 6 | + |
| 7 | +export function copyied(fromPath: string, toPath: string) { |
| 8 | + const stat = fs.statSync(fromPath); |
| 9 | + if (!stat.isFile()) { |
| 10 | + return; |
| 11 | + } |
| 12 | + fs.ensureDir(path.dirname(toPath), (err) => { |
| 13 | + if (err) { |
| 14 | + console.log(` \x1b[31midoc:copy:\x1b[0m`, err); |
| 15 | + return; |
| 16 | + } |
| 17 | + fs.copyFile(decodeURIComponent(fromPath), decodeURIComponent(toPath)) |
| 18 | + .then((result) => { |
| 19 | + log.output('\x1b[35;1mcopy\x1b[0m')(decodeURIComponent(fromPath), decodeURIComponent(toPath)); |
| 20 | + }) |
| 21 | + .catch((err) => { |
| 22 | + console.log(` \x1b[31midoc:asset:copy:\x1b[0m`, err); |
| 23 | + }); |
| 24 | + }); |
| 25 | +} |
| 26 | + |
| 27 | +export function copyAsset(node: Root | RootContent, options: Options = {}) { |
| 28 | + let mdpath = options.fromPath || ''; |
| 29 | + |
| 30 | + if (node.type !== 'element' || !/^(img|a|video|source|audio)$/.test(node.tagName)) return; |
| 31 | + let src = node.properties.src as string; |
| 32 | + if (typeof src !== 'string' || /^https?:\/\//.test(src) || !src || /^data:/.test(src)) return; |
| 33 | + let outputHTMLPath = options.outputHTMLPath || ''; |
| 34 | + const assetFromPath = path.resolve(path.dirname(mdpath), decodeURIComponent(src)).replace(/[?#].*$/, ''); |
| 35 | + const assetToPath = path.resolve(path.dirname(outputHTMLPath), decodeURIComponent(src)).replace(/[?#].*$/, ''); |
| 36 | + copyied(assetFromPath, assetToPath); |
| 37 | +} |
0 commit comments