import path from 'path'; import os from 'os'; import fs from 'fs/promises'; import { TransformerPath } from '../types/runner'; import { generateUID, merge } from './helper'; /** * Filters out the list of file paths containing the given extension * @param files List of file paths * @param extensions Extensions of the file to filter out from the given list * @returns list of filtered files list */ export const filterFiles = (files: string[], extensions: string[]): string[][] => { const filtered: string[][] = []; const lastIdx = extensions.length; extensions.forEach((_, idx) => (filtered[idx] = [])); filtered[lastIdx] = []; files.forEach((file) => { const ext = file.split('.').pop() || ''; const idx = extensions.indexOf(ext); if (idx > -1) { filtered[idx].push(file); } else { filtered[lastIdx].push(file); } }); return filtered; }; /** * Returns the path to the transform file used by JSCodeshift * @param transformer Partial path to the transform file * @param ext Extension of the transform file */ export const getTransformFile = (transformer: TransformerPath, ext: 'ts' | 'js' = 'js'): string => path.resolve(__dirname, `../transformers/${transformer}.${ext}`); /** * Creates a directory in the OS temp directory where temporary files will be stored * @param prefix Prefix for the temp directory * @returns The path to the created temp directory */ export const initTempDir = async (prefix: string): Promise => fs.mkdtemp(path.join(os.tmpdir(), prefix)); /** * Saves data into a temporary file storage * @param data Data to be stored * @param dirPath Path to the temporary directory where a temp file will be created */ export const saveTempData = async (data: T, dirPath: string): Promise => { try { const tmpFilePath = path.join(dirPath, `${generateUID()}.json`); await fs.writeFile(tmpFilePath, JSON.stringify(data), { encoding: 'utf8' }); } catch (e: any) { throw new Error(e.message); } }; /** * Reads and returns the data from the temporary file storage * @param dirPath Path to temp directory * @param cleanup Should delete temp directory * @returns Data merged from all the files in the temp directory */ export const readTempData = async (dirPath: string, cleanup: boolean = true): Promise => { try { const files = await fs.readdir(dirPath); const finalResult = {} as T; for (const file of files) { const fileContent = await fs.readFile(path.resolve(dirPath, file), { encoding: 'utf8' }); const data = JSON.parse(fileContent) as T; merge(finalResult, data); } if (cleanup) { await fs.rm(dirPath, { recursive: true, force: true }); } return finalResult; } catch (e: any) { throw new Error(e.message); } };