|
| 1 | +import path from 'path' |
| 2 | +import { fs } from './util/fs' |
| 3 | + |
| 4 | +export async function readFile (projectRoot: string, options: { file: string, encoding?: string } = { file: '', encoding: 'utf8' }) { |
| 5 | + const filePath = path.resolve(projectRoot, options.file) |
| 6 | + const readFn = (path.extname(filePath) === '.json' && options.encoding !== null) ? fs.readJsonAsync : fs.readFileAsync |
| 7 | + |
| 8 | + // https://github.com/cypress-io/cypress/issues/1558 |
| 9 | + // If no encoding is specified, then Cypress has historically defaulted |
| 10 | + // to `utf8`, because of it's focus on text files. This is in contrast to |
| 11 | + // NodeJs, which defaults to binary. We allow users to pass in `null` |
| 12 | + // to restore the default node behavior. |
| 13 | + try { |
| 14 | + // @ts-ignore as we are mixing types with fs |
| 15 | + const contents = await readFn(filePath, options.encoding === undefined ? 'utf8' : options.encoding) |
| 16 | + |
| 17 | + return { |
| 18 | + contents, |
| 19 | + filePath, |
| 20 | + } |
| 21 | + } catch (err) { |
| 22 | + err.originalFilePath = options.file |
| 23 | + err.filePath = filePath |
| 24 | + throw err |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +export async function readFiles (projectRoot: string, options: { files: { path: string, encoding?: string }[] } = { files: [] }) { |
| 29 | + const files = await Promise.all(options.files.map(async (file) => { |
| 30 | + const { contents, filePath } = await readFile(projectRoot, { |
| 31 | + file: file.path, |
| 32 | + encoding: file.encoding, |
| 33 | + }) |
| 34 | + |
| 35 | + return { |
| 36 | + ...file, |
| 37 | + filePath, |
| 38 | + contents, |
| 39 | + } |
| 40 | + })) |
| 41 | + |
| 42 | + return files |
| 43 | +} |
| 44 | + |
| 45 | +export async function writeFile (projectRoot: string, options: { fileName: string, contents: string, encoding?: string, flag?: string } = { fileName: '', contents: '', encoding: 'utf8', flag: 'w' }) { |
| 46 | + const filePath = path.resolve(projectRoot, options.fileName) |
| 47 | + const writeOptions = { |
| 48 | + encoding: options.encoding === undefined ? 'utf8' : options.encoding, |
| 49 | + flag: options.flag || 'w', |
| 50 | + } |
| 51 | + |
| 52 | + try { |
| 53 | + await fs.outputFile(filePath, options.contents, writeOptions) |
| 54 | + |
| 55 | + return { |
| 56 | + contents: options.contents, |
| 57 | + filePath, |
| 58 | + } |
| 59 | + } catch (err) { |
| 60 | + err.filePath = filePath |
| 61 | + throw err |
| 62 | + } |
| 63 | +} |
0 commit comments