|
1 | | -import { copyFile } from 'fs'; |
| 1 | +import * as fs from 'fs'; |
2 | 2 | import path from 'path'; |
| 3 | +import { createHashedFile } from './fileUtils'; |
3 | 4 | import { Task, TaskOutput } from './Task'; |
4 | 5 |
|
| 6 | +const base = process.env.BUILD_BASE_PATH || ''; |
| 7 | + |
5 | 8 | export interface AboutTaskOutput extends TaskOutput { |
6 | 9 | taskName: 'ConvertAbout'; |
7 | 10 | } |
| 11 | + |
| 12 | +// Function to check if an image is missing |
| 13 | +function isImageMissing(imageSource: string, dataDir: string): boolean { |
| 14 | + return !fs.existsSync(path.join(dataDir, 'illustrations', imageSource)); |
| 15 | +} |
| 16 | + |
| 17 | +function updateImgTags(text: string, dataDir: string, verbose: number): string { |
| 18 | + return text.replace( |
| 19 | + /<img\b[^>]*\bsrc=["']([^"']*\/)?([^"']*)["'][^>]*>/gi, |
| 20 | + (_match, _path, fileName) => { |
| 21 | + // If the image is missing in the "illustrations" folder, filter out the entire tag |
| 22 | + if (isImageMissing(fileName, dataDir)) { |
| 23 | + return ''; |
| 24 | + } else { |
| 25 | + fs.mkdirSync(path.join('static', 'illustrations'), { recursive: true }); |
| 26 | + const imagePath = createHashedFile(dataDir, `illustrations/${fileName}`, verbose); |
| 27 | + |
| 28 | + return `<img src="${base}/${imagePath}">`; |
| 29 | + } |
| 30 | + } |
| 31 | + ); |
| 32 | +} |
| 33 | + |
8 | 34 | /** |
9 | | - * Copies about.partial.html to static folder |
| 35 | + * Copies about.partial.html to static folder with image tag processing |
10 | 36 | */ |
11 | 37 | export function convertAbout(dataDir: string, verbose: number) { |
12 | 38 | const srcFile = path.join(dataDir, 'about.partial.html'); |
13 | 39 | const dstFile = path.join('src/gen-assets', 'about.partial.html'); |
14 | | - copyFile(srcFile, dstFile, function (err: any) { |
15 | | - if (err) throw err; |
16 | | - if (verbose) console.log(`copied ${srcFile} to ${dstFile}`); |
17 | | - }); |
| 40 | + |
| 41 | + // Read the file content |
| 42 | + const content = fs.readFileSync(srcFile, 'utf8'); |
| 43 | + |
| 44 | + // Apply the updateImgTags filter |
| 45 | + const processedContent = updateImgTags(content, dataDir, verbose); |
| 46 | + |
| 47 | + // Write the processed content to the destination |
| 48 | + fs.writeFileSync(dstFile, processedContent, 'utf8'); |
| 49 | + |
| 50 | + if (verbose) console.log(`copied and processed ${srcFile} to ${dstFile}`); |
18 | 51 | } |
19 | 52 | export class ConvertAbout extends Task { |
20 | 53 | public triggerFiles: string[] = ['about.partial.html']; |
|
0 commit comments