1import fs from 'fs-extra'; 2import path from 'path'; 3 4import { findFiles } from '../utils'; 5import { Task } from './Task'; 6 7export type PrefixHeadersSettings = { 8 source?: string; 9 subPath: string; 10 prefix: string; 11 filePattern: string; 12 debug?: boolean; 13}; 14 15export class PrefixHeaders extends Task { 16 protected readonly source?: string; 17 protected readonly subPath: string; 18 protected readonly prefix: string; 19 protected readonly filePattern: string; 20 protected readonly debug: boolean; 21 22 constructor({ source, subPath, prefix, filePattern, debug }: PrefixHeadersSettings) { 23 super(); 24 this.source = source; 25 this.subPath = subPath; 26 this.prefix = prefix; 27 this.filePattern = filePattern; 28 this.debug = debug || false; 29 } 30 31 protected overrideWorkingDirectory(): string { 32 return this.source || '<workingDirectory>'; 33 } 34 35 async execute() { 36 const workDirectory = this.getWorkingDirectory(); 37 38 this.logSubStep(` prefix headers`); 39 40 const headersPath = await findFiles(path.join(workDirectory, this.subPath), '**/*.@(h|hpp)'); 41 if (this.debug) { 42 this.logDebugInfo('Headers: ' + headersPath.join('\n')); 43 } 44 45 const headers = headersPath.map((x) => path.parse(x)); 46 await Promise.all( 47 headers.map((header) => { 48 const fileName = this.prefix + header.base; 49 const parent = header.dir; 50 return fs.rename(path.join(header.dir, header.base), path.join(parent, fileName)); 51 }) 52 ); 53 54 const files = await findFiles(workDirectory, this.filePattern); 55 if (this.debug) { 56 this.logDebugInfo('Files: ' + files.join('\n')); 57 } 58 59 await Promise.all( 60 files.map(async (file) => { 61 const content = await fs.readFile(file, 'utf8'); 62 const transformedContent = headers.reduce((acc, header) => { 63 const regex = `(#include.*)${header.base}"`; 64 return acc.replace(new RegExp(regex, 'g'), `$1${this.prefix}${header.base}"`); 65 }, content); 66 return await fs.writeFile(file, transformedContent, 'utf8'); 67 }) 68 ); 69 } 70} 71