1import { Task } from './Task'; 2import path from 'path'; 3import chalk from 'chalk'; 4import fs from 'fs-extra'; 5import { findFiles } from '../utils'; 6 7export type FileContentTransformStepSettings = { 8 source?: string; 9 filePattern: string; 10 find: string; 11 replace: string; 12}; 13 14/** 15 * A task which will transformed files content. 16 * Firstly, it's searching for all files which matched the `filePattern` in the working directory. 17 * Then it'll find the provided pattern and replace it with a new value. 18 */ 19export class TransformFilesContent extends Task { 20 protected readonly source?: string; 21 protected readonly filePattern: string; 22 protected readonly find: RegExp; 23 protected readonly replace: string; 24 25 constructor({ source, filePattern, find, replace }: FileContentTransformStepSettings) { 26 super(); 27 this.source = source; 28 this.filePattern = filePattern; 29 this.find = new RegExp(find, 'gm'); 30 this.replace = replace; 31 } 32 33 protected overrideWorkingDirectory(): string | undefined { 34 return this.source; 35 } 36 37 async execute() { 38 const workDirectory = this.getWorkingDirectory(); 39 40 this.logSubStep( 41 ` find ${chalk.yellow(this.find.toString())} in ${chalk.green( 42 this.overrideWorkingDirectory() || '<workingDirectory>' 43 )}/${chalk.yellow(this.filePattern)} and replace with ${chalk.magenta(this.replace)}` 44 ); 45 46 const files = await findFiles(workDirectory, this.filePattern); 47 await Promise.all( 48 files.map(async (file) => { 49 const content = await fs.readFile(file, 'utf8'); 50 const transformedContent = content.replace(this.find, this.replace); 51 return await fs.writeFile(file, transformedContent, 'utf8'); 52 }) 53 ); 54 } 55} 56 57export const prefixPackage = ({ 58 packageName, 59 prefix, 60}: { 61 source?: string; 62 packageName: string; 63 prefix: string; 64}): TransformFilesContent => { 65 return new TransformFilesContent({ 66 filePattern: path.join('android', '**', '*.@(java|kt)'), 67 find: packageName, 68 replace: `${prefix}.${packageName}`, 69 }); 70}; 71 72export const renameIOSSymbols = (settings: { 73 find: string; 74 replace: string; 75}): TransformFilesContent => { 76 return new TransformFilesContent({ 77 ...settings, 78 filePattern: path.join('ios', '**', '*.@(h|m)'), 79 }); 80}; 81