UNPKG

@embrace-io/react-native

Version:
108 lines (107 loc) 3.67 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getFileContents = exports.NoopFile = exports.patchFiles = void 0; const fs = require("fs"); const patchFiles = (...files) => { return chainPromises(...files).then((patchables) => { patchables.map(p => p.patch()); }); }; exports.patchFiles = patchFiles; const chainPromises = (...promises) => promises.reduce((prev, cur) => prev.then(prevRes => cur().then(curRes => [...prevRes, curRes])), Promise.resolve([])); exports.NoopFile = { path: "", contents: "", patch: () => { }, hasLine: (_) => false, getPaddingFromString: (searchString) => "", getPaddingAfterStringToTheNextString: (searchString) => "", addBefore: (line, add) => { }, addAfter: (line, add) => { }, deleteLine: (line) => { }, }; class FileContents { constructor(path = "") { this.path = path; this.contents = fs.readFileSync(path, "utf8"); } getPaddingFromString(searchString) { const index = this.contents.indexOf(searchString); const lastLineBreakIndex = this.contents.lastIndexOf("\n", index); const start = lastLineBreakIndex === -1 ? 0 : lastLineBreakIndex + 1; const leadingWhitespace = this.contents .substring(start, index) .match(/[ \t]*$/); if (leadingWhitespace) { return leadingWhitespace[0]; } return ""; } getPaddingAfterStringToTheNextString(searchString) { const match = this.contents.match(searchString); if (!match) { return ""; } const index = match.index; const nextLineBreakIndex = this.contents.indexOf("\n", index); if (nextLineBreakIndex === -1) { return ""; } let afterLineBreakIndex = nextLineBreakIndex + 2; while (afterLineBreakIndex < this.contents.length) { if (!/[\s\n]/.test(this.contents.charAt(afterLineBreakIndex))) { break; } afterLineBreakIndex++; } const spacesBetween = this.contents .substring(nextLineBreakIndex + 1, afterLineBreakIndex) .match(/[ \t]*$/); if (spacesBetween) { return spacesBetween[0]; } return ""; } hasLine(line) { return ((line instanceof RegExp ? this.contents.search(line) : this.contents.indexOf(line)) > -1); } addBefore(line, add) { if (this.hasLine(line)) { this.contents = this.contents.replace(line, `${add}${line}`); } } addAfter(line, add) { if (this.hasLine(line)) { let replaceWith = line; let space = ""; if (line instanceof RegExp) { const matches = this.contents.match(line) || []; if (matches.length === 0) { return; } // If regex starts with space matcher, use space. if (line.toString().match(/^\/\(\\s\+\)/)) { space = matches[1]; } if (matches[0]) { replaceWith = matches[0]; } } this.contents = this.contents.replace(line, `${replaceWith}${space}${add}`); } } deleteLine(line) { if (this.hasLine(line)) { this.contents = this.contents.replace(line, ""); } } patch() { fs.writeFileSync(this.path, this.contents); } } const getFileContents = (path) => { return new FileContents(path); }; exports.getFileContents = getFileContents;