diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 00000000..28c83c8d --- /dev/null +++ b/.prettierrc @@ -0,0 +1,5 @@ +{ + "semi": false, + "trailingComma": "all", + "printWidth": 120 +} diff --git a/.vscode/settings.json b/.vscode/settings.json index 46ca2cad..972c3ce5 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -9,8 +9,6 @@ "dist": true }, "editor.formatOnPaste": true, - "prettier.semi": false, - "prettier.trailingComma": "all", "editor.formatOnSave": true, "tslint.enable": true, "typescript.tsdk": "node_modules/typescript/lib" diff --git a/package.json b/package.json index 0519c1e7..a0094022 100644 --- a/package.json +++ b/package.json @@ -50,7 +50,7 @@ "jest": "^20.0.4", "lint-staged": "^3.4.1", "np": "^2.15.0", - "prettier": "^1.11.1", + "prettier": "^1.12.1", "randomstring": "^1.1.5", "ts-jest": "^20.0.10", "tslint": "^5.2.0", diff --git a/src/__tests__/differentGitRoot.test.ts b/src/__tests__/differentGitRoot.test.ts index da06b770..aa872d28 100644 --- a/src/__tests__/differentGitRoot.test.ts +++ b/src/__tests__/differentGitRoot.test.ts @@ -13,11 +13,10 @@ describe("patch-package", () => { // make subfolder for app const appPath = path.join(repo.name, "subproject") // create app - fs.copySync( - path.join(__dirname, "test-projects", "left-pad-breakage"), - appPath, - { recursive: true, overwrite: true }, - ) + fs.copySync(path.join(__dirname, "test-projects", "left-pad-breakage"), appPath, { + recursive: true, + overwrite: true, + }) // install pp and everything spawnSync("yarn", ["add", "file:" + patchPackageTarballPath], { cwd: appPath, @@ -25,9 +24,7 @@ describe("patch-package", () => { spawnSync("yarn", ["install"], { cwd: appPath }) // make sure file got patched - const leftPadContents = fs - .readFileSync(path.join(appPath, "node_modules/left-pad/index.js")) - .toString() + const leftPadContents = fs.readFileSync(path.join(appPath, "node_modules/left-pad/index.js")).toString() expect(leftPadContents.includes("patch-package")).toBe(true) }) diff --git a/src/__tests__/happyPath.test.ts b/src/__tests__/happyPath.test.ts index a14ca77b..c0a0c344 100644 --- a/src/__tests__/happyPath.test.ts +++ b/src/__tests__/happyPath.test.ts @@ -29,8 +29,7 @@ describe("patch-package", () => { `, ) - const tmpSpawn = (command: string, args: string[]) => - spawnSync(command, args, { cwd: tmpDir.name }) + const tmpSpawn = (command: string, args: string[]) => spawnSync(command, args, { cwd: tmpDir.name }) // install tmpSpawn("yarn", ["install"]) @@ -48,9 +47,7 @@ describe("patch-package", () => { tmpSpawn(patchPackageBin, ["left-pad"]) // snapshot it - const patchContents = fs - .readFileSync(path.join(tmpDir.name, "patches/left-pad+1.1.3.patch")) - .toString() + const patchContents = fs.readFileSync(path.join(tmpDir.name, "patches/left-pad+1.1.3.patch")).toString() expect(patchContents).toMatchSnapshot() @@ -61,9 +58,7 @@ describe("patch-package", () => { tmpSpawn("yarn", ["install"]) // check that the file was patched - expect(fs.readFileSync(leftPadPath).toString()).toEqual( - mutatedLeftPadSource, - ) + expect(fs.readFileSync(leftPadPath).toString()).toEqual(mutatedLeftPadSource) }) it("should produce patches which can be applied with npm", () => { @@ -95,8 +90,7 @@ describe("patch-package", () => { `, ) - const tmpSpawn = (command: string, args: string[]) => - spawnSync(command, args, { cwd: tmpDir.name }) + const tmpSpawn = (command: string, args: string[]) => spawnSync(command, args, { cwd: tmpDir.name }) // install tmpSpawn("npm", ["install"]) @@ -114,9 +108,7 @@ describe("patch-package", () => { tmpSpawn(patchPackageBin, ["left-pad"]) // snapshot it - const patchContents = fs - .readFileSync(path.join(tmpDir.name, "patches/left-pad+1.1.3.patch")) - .toString() + const patchContents = fs.readFileSync(path.join(tmpDir.name, "patches/left-pad+1.1.3.patch")).toString() expect(patchContents).toMatchSnapshot() @@ -127,8 +119,6 @@ describe("patch-package", () => { tmpSpawn("npm", ["install"]) // check that the file was patched - expect(fs.readFileSync(leftPadPath).toString()).toEqual( - mutatedLeftPadSource, - ) + expect(fs.readFileSync(leftPadPath).toString()).toEqual(mutatedLeftPadSource) }) }) diff --git a/src/__tests__/packageGetsUpdated.test.ts b/src/__tests__/packageGetsUpdated.test.ts index 7bdb0983..23474078 100644 --- a/src/__tests__/packageGetsUpdated.test.ts +++ b/src/__tests__/packageGetsUpdated.test.ts @@ -7,9 +7,7 @@ describe("patch-package", () => { project.install() function patchWasApplied() { - return project - .readFileSync("node_modules", "left-pad", "index.js") - .includes("patch-package") + return project.readFileSync("node_modules", "left-pad", "index.js").includes("patch-package") } // assert patch was applied to 1.1.1 @@ -18,9 +16,7 @@ describe("patch-package", () => { }) // bump version to 1.1.2 it("gives a warning when the patch is applied successfully but the version changed", () => { - expect( - project.spawnSync("yarn", ["add", "left-pad@1.1.2"]).stderr.toString(), - ).toMatchSnapshot() + expect(project.spawnSync("yarn", ["add", "left-pad@1.1.2"]).stderr.toString()).toMatchSnapshot() expect(patchWasApplied()).toBe(true) }) diff --git a/src/__tests__/propertyBasedTests.test.ts b/src/__tests__/propertyBasedTests.test.ts index f6907cdd..14c487fa 100644 --- a/src/__tests__/propertyBasedTests.test.ts +++ b/src/__tests__/propertyBasedTests.test.ts @@ -72,10 +72,7 @@ abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ["deleteLine", 10], ["insertLine", 10], ] - const liklihoodSum = mutationKindLikelihoods.reduce( - (acc, [_, n]) => acc + n, - 0, - ) + const liklihoodSum = mutationKindLikelihoods.reduce((acc, [_, n]) => acc + n, 0) function getNextMutationKind(): MutationKind { const n = Math.random() * liklihoodSum @@ -130,19 +127,13 @@ abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ break } case "deleteLine": { - const pathToDeleteFrom = selectRandomElement( - Object.keys(mutatedFiles), - ) - mutatedFiles[pathToDeleteFrom] = deleteLinesFromFile( - mutatedFiles[pathToDeleteFrom], - ) + const pathToDeleteFrom = selectRandomElement(Object.keys(mutatedFiles)) + mutatedFiles[pathToDeleteFrom] = deleteLinesFromFile(mutatedFiles[pathToDeleteFrom]) break } case "insertLine": const pathToInsertTo = selectRandomElement(Object.keys(mutatedFiles)) - mutatedFiles[pathToInsertTo] = insertLinesIntoFile( - mutatedFiles[pathToInsertTo], - ) + mutatedFiles[pathToInsertTo] = insertLinesIntoFile(mutatedFiles[pathToInsertTo]) // select a file at random and insert some text in there break } @@ -186,9 +177,7 @@ abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ beforeEach(() => { ;(fs as any).readFileSync = jest.fn(path => getWorkingFiles()[path]) - ;(fs as any).writeFileSync = jest.fn( - (path, data) => (getWorkingFiles()[path] = data), - ) + ;(fs as any).writeFileSync = jest.fn((path, data) => (getWorkingFiles()[path] = data)) ;(fs as any).unlinkSync = jest.fn(path => delete getWorkingFiles()[path]) ;(fs as any).moveSync = jest.fn((from, to) => { getWorkingFiles()[to] = getWorkingFiles()[from] @@ -260,15 +249,11 @@ index 2de83dd..842652c 100644 writeFiles(tmpDir.name, testCase.modifiedFiles) spawnSafeSync("git", ["add", "-A"], { cwd: tmpDir.name }) - const patchResult = spawnSafeSync( - "git", - ["diff", "--color=never", "--cached"], - { - cwd: tmpDir.name, - logStdErrOnError: true, - throwOnError: true, - }, - ) + const patchResult = spawnSafeSync("git", ["diff", "--color=never", "--cached"], { + cwd: tmpDir.name, + logStdErrOnError: true, + throwOnError: true, + }) const patchFileContents = patchResult.stdout.toString() @@ -276,9 +261,7 @@ index 2de83dd..842652c 100644 it("looks the same whether parsed with blank lines or not", () => { reportingFailures(() => { - expect(parsePatch(patchFileContents)).toEqual( - parsePatch(patchFileContentsWithBlankLines), - ) + expect(parsePatch(patchFileContents)).toEqual(parsePatch(patchFileContentsWithBlankLines)) }) }) diff --git a/src/__tests__/resolveRelativeFileDependencies.test.ts b/src/__tests__/resolveRelativeFileDependencies.test.ts index 53d52a29..1a2ff8ab 100644 --- a/src/__tests__/resolveRelativeFileDependencies.test.ts +++ b/src/__tests__/resolveRelativeFileDependencies.test.ts @@ -37,12 +37,9 @@ describe("resolveRelativeFileDependencies", () => { }, } - expect( - resolveRelativeFileDependenciesInPackageJson( - appRootPath, - JSON.parse(JSON.stringify(packageJson)), - ), - ).toEqual(expected) + expect(resolveRelativeFileDependenciesInPackageJson(appRootPath, JSON.parse(JSON.stringify(packageJson)))).toEqual( + expected, + ) }) it("works for package-lock.json", () => { const appRootPath = "/bloo/far" @@ -70,8 +67,6 @@ describe("resolveRelativeFileDependencies", () => { }, } - expect( - resolveRelativeFileDependenciesInPackageLock(appRootPath, packageLock), - ).toEqual(expected) + expect(resolveRelativeFileDependenciesInPackageLock(appRootPath, packageLock)).toEqual(expected) }) }) diff --git a/src/__tests__/scopedPackage.test.ts b/src/__tests__/scopedPackage.test.ts index 21a1a826..ff411c9e 100644 --- a/src/__tests__/scopedPackage.test.ts +++ b/src/__tests__/scopedPackage.test.ts @@ -5,12 +5,7 @@ describe("patch-package", () => { project.install() it("applies patches to scoped packages", () => { - const typingsContent = project.readFileSync( - "node_modules", - "@types", - "left-pad", - "index.d.ts", - ) + const typingsContent = project.readFileSync("node_modules", "@types", "left-pad", "index.d.ts") expect(typingsContent.includes("patch-package")).toBe(true) }) diff --git a/src/__tests__/shellTests.ts b/src/__tests__/shellTests.ts index 1d23f740..878eee62 100644 --- a/src/__tests__/shellTests.ts +++ b/src/__tests__/shellTests.ts @@ -4,10 +4,7 @@ import * as path from "../path" import * as tmp from "tmp" import spawnSync from "../spawnSafe" -export function runShellTest( - projectName: string, - shouldProduceSnapshots: boolean = true, -) { +export function runShellTest(projectName: string, shouldProduceSnapshots: boolean = true) { describe(`Test ${projectName}:`, () => { const tmpDir = tmp.dirSync({ unsafeCleanup: true }) fs.copySync(path.join("test", projectName), tmpDir.name, { diff --git a/src/__tests__/shrinkwrap.test.ts b/src/__tests__/shrinkwrap.test.ts index 7b546a4b..63dbe1a2 100644 --- a/src/__tests__/shrinkwrap.test.ts +++ b/src/__tests__/shrinkwrap.test.ts @@ -5,11 +5,7 @@ describe("patch-package", () => { project.install() it("works with npm shrinkwrap", () => { - const leftPadSource = project.readFileSync( - "node_modules", - "left-pad", - "index.js", - ) + const leftPadSource = project.readFileSync("node_modules", "left-pad", "index.js") expect(leftPadSource.includes("patch-package")).toBe(true) }) diff --git a/src/__tests__/testProjects.ts b/src/__tests__/testProjects.ts index 785febbd..32d2df78 100644 --- a/src/__tests__/testProjects.ts +++ b/src/__tests__/testProjects.ts @@ -6,15 +6,10 @@ import * as path from "../path" import spawnSafe, { SpawnSafeOptions } from "../spawnSafe" export const patchPackageTarballPath = path.resolve( - fs - .readdirSync(".") - .filter(nm => nm.match(/^patch-package\.test\.\d+\.tgz$/))[0], + fs.readdirSync(".").filter(nm => nm.match(/^patch-package\.test\.\d+\.tgz$/))[0], ) -export function initTestProject( - testProjectName: string, - packageManager: "yarn" | "npm" = "yarn", -) { +export function initTestProject(testProjectName: string, packageManager: "yarn" | "npm" = "yarn") { // copy left-pad-breakage repo to temp folder const tmpDir = tmp.dirSync({ unsafeCleanup: true, @@ -37,13 +32,7 @@ export function initTestProject( return fs.readFileSync(path.join(tmpDir.name, ...parts)).toString() }, writeFileSync(filePath: string[] | string, data: string) { - fs.writeFileSync( - path.join( - tmpDir.name, - Array.isArray(filePath) ? path.join(...filePath) : filePath, - ), - data, - ) + fs.writeFileSync(path.join(tmpDir.name, Array.isArray(filePath) ? path.join(...filePath) : filePath), data) }, runPatchPackage(options?: SpawnSafeOptions) { if (packageManager === "yarn") { @@ -58,11 +47,7 @@ export function initTestProject( return spawnSync("yarn", ["install"], options) } else { spawnSync("npm", ["i"], options) - return spawnSync( - "npm", - ["i", "file:" + patchPackageTarballPath], - options, - ) + return spawnSync("npm", ["i", "file:" + patchPackageTarballPath], options) } }, } diff --git a/src/applyPatches.ts b/src/applyPatches.ts index 4a956dd2..7ea950b3 100644 --- a/src/applyPatches.ts +++ b/src/applyPatches.ts @@ -33,23 +33,18 @@ function getPatchDetailsFromFilename(filename: FileName) { } } -function getInstalledPackageVersion( - appPath: AppPath, - packageName: PackageName, -) { +function getInstalledPackageVersion(appPath: AppPath, packageName: PackageName) { const packageDir = path.join(appPath, "node_modules", packageName) if (!fs.existsSync(packageDir)) { console.warn( - `${red("Warning:")} Patch file found for package ${path.posix.basename( - packageDir, - )}` + ` which is not present at ${packageDir}`, + `${red("Warning:")} Patch file found for package ${path.posix.basename(packageDir)}` + + ` which is not present at ${packageDir}`, ) return null } - return require(path.join(packageDir, "package.json")) - .version as PackageVersion + return require(path.join(packageDir, "package.json")).version as PackageVersion } export function applyPatchesForApp(appPath: AppPath, reverse: boolean): void { @@ -63,26 +58,17 @@ export function applyPatchesForApp(appPath: AppPath, reverse: boolean): void { files.forEach(filename => { const { packageName, version } = getPatchDetailsFromFilename(filename) - const installedPackageVersion = getInstalledPackageVersion( - appPath, - packageName, - ) + const installedPackageVersion = getInstalledPackageVersion(appPath, packageName) if (!installedPackageVersion) { return } - if ( - applyPatch(path.resolve(patchesDirectory, filename) as FileName, reverse) - ) { + if (applyPatch(path.resolve(patchesDirectory, filename) as FileName, reverse)) { // yay patch was applied successfully // print warning if version mismatch if (installedPackageVersion !== version) { - printVersionMismatchWarning( - packageName, - installedPackageVersion, - version, - ) + printVersionMismatchWarning(packageName, installedPackageVersion, version) } else { console.log(`${bold(packageName)}@${version} ${green("✔")}`) } @@ -92,12 +78,7 @@ export function applyPatchesForApp(appPath: AppPath, reverse: boolean): void { if (installedPackageVersion === version) { printBrokenPatchFileError(packageName, filename) } else { - printPatchApplictionFailureError( - packageName, - installedPackageVersion, - version, - filename, - ) + printPatchApplictionFailureError(packageName, installedPackageVersion, version, filename) } process.exit(1) } @@ -151,14 +132,9 @@ ${red("Warning:")} patch-package detected a patch file version mismatch `) } -function printBrokenPatchFileError( - packageName: PackageName, - patchFileName: FileName, -) { +function printBrokenPatchFileError(packageName: PackageName, patchFileName: FileName) { console.error(` -${red.bold("**ERROR**")} ${red( - `Failed to apply patch for package ${bold(packageName)}`, - )} +${red.bold("**ERROR**")} ${red(`Failed to apply patch for package ${bold(packageName)}`)} This error was caused because patch-package cannot apply the following patch file: @@ -180,9 +156,7 @@ function printPatchApplictionFailureError( patchFileName: FileName, ) { console.error(` -${red.bold("**ERROR**")} ${red( - `Failed to apply patch for package ${bold(packageName)}`, - )} +${red.bold("**ERROR**")} ${red(`Failed to apply patch for package ${bold(packageName)}`)} This error was caused because ${bold(packageName)} has changed since you made the patch file for it. This introduced conflicts with your patch, @@ -219,8 +193,6 @@ ${red.bold("**ERROR**")} ${red( Info: Patch was made for version ${green.bold(originalVersion)} - Meanwhile node_modules/${bold(packageName)} is version ${red.bold( - actualVersion, - )} + Meanwhile node_modules/${bold(packageName)} is version ${red.bold(actualVersion)} `) } diff --git a/src/detectPackageManager.ts b/src/detectPackageManager.ts index 36c80822..c2d39004 100644 --- a/src/detectPackageManager.ts +++ b/src/detectPackageManager.ts @@ -9,12 +9,8 @@ export default function detectPackageManager( appRootPath: string, overridePackageManager: PackageManager | null, ): PackageManager { - const packageLockExists = fs.existsSync( - path.join(appRootPath, "package-lock.json"), - ) - const shrinkWrapExists = fs.existsSync( - path.join(appRootPath, "npm-shrinkwrap.json"), - ) + const packageLockExists = fs.existsSync(path.join(appRootPath, "package-lock.json")) + const shrinkWrapExists = fs.existsSync(path.join(appRootPath, "npm-shrinkwrap.json")) const yarnLockExists = fs.existsSync(path.join(appRootPath, "yarn.lock")) if ((packageLockExists || shrinkWrapExists) && yarnLockExists) { if (overridePackageManager) { @@ -41,9 +37,7 @@ export default function detectPackageManager( function printNoYarnLockfileError() { console.error(` -${chalk.red.bold("**ERROR**")} ${chalk.red( - `The --use-yarn option was specified but there is no yarn.lock file`, - )} +${chalk.red.bold("**ERROR**")} ${chalk.red(`The --use-yarn option was specified but there is no yarn.lock file`)} `) } @@ -60,9 +54,7 @@ dependencies.`, function printSelectingDefaultMessage() { console.info( - `${chalk.bold( - "patch-package", - )}: you have both yarn.lock and package-lock.json + `${chalk.bold("patch-package")}: you have both yarn.lock and package-lock.json Defaulting to using ${chalk.bold("npm")} You can override this setting by passing --use-yarn or deleting package-lock.json if you don't need it diff --git a/src/index.ts b/src/index.ts index 293077c6..ff03bb6b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -18,26 +18,10 @@ if (argv.help || argv.h) { printHelp() } else { if (packageNames.length) { - const include = makeRegExp( - argv.include, - "include", - /.*/, - argv["case-sensitive-path-filtering"], - ) - const exclude = makeRegExp( - argv.exclude, - "exclude", - /package\.json$/, - argv["case-sensitive-path-filtering"], - ) + const include = makeRegExp(argv.include, "include", /.*/, argv["case-sensitive-path-filtering"]) + const exclude = makeRegExp(argv.exclude, "exclude", /package\.json$/, argv["case-sensitive-path-filtering"]) packageNames.forEach((packageName: string) => { - makePatch( - packageName, - appPath, - detectPackageManager(appPath, argv["use-yarn"] ? "yarn" : null), - include, - exclude, - ) + makePatch(packageName, appPath, detectPackageManager(appPath, argv["use-yarn"] ? "yarn" : null), include, exclude) }) } else { console.log("patch-package: Applying patches...") @@ -54,9 +38,7 @@ Usage: ${bold("patch-package")} - Without arguments, the ${bold( - "patch-package", - )} command will attempt to find and apply + Without arguments, the ${bold("patch-package")} command will attempt to find and apply patch files to your project. It looks for files named like ./patches/+.patch diff --git a/src/makePatch.ts b/src/makePatch.ts index 81125f30..97a251fc 100644 --- a/src/makePatch.ts +++ b/src/makePatch.ts @@ -48,15 +48,8 @@ export default function makePatch( } else { // remove exsiting patch for this package, if any getPatchFiles(patchesDir).forEach(fileName => { - if ( - fileName.startsWith(packageName + ":") || - fileName.startsWith(packageName + "+") - ) { - console.info( - green("☑"), - "Removing existing", - path.relative(process.cwd(), path.join(patchesDir, fileName)), - ) + if (fileName.startsWith(packageName + ":") || fileName.startsWith(packageName + "+")) { + console.info(green("☑"), "Removing existing", path.relative(process.cwd(), path.join(patchesDir, fileName))) fs.unlinkSync(path.join(patchesDir, fileName)) } }) @@ -64,66 +57,38 @@ export default function makePatch( console.info(green("☑"), "Creating temporary folder") - const tmpExec = (command: string, args?: string[]) => - spawnSafeSync(command, args, { cwd: tmpRepo.name }) + const tmpExec = (command: string, args?: string[]) => spawnSafeSync(command, args, { cwd: tmpRepo.name }) // reinstall a clean version of the user's node_modules in our tmp location - fsExtra.copySync( - path.join(appPath, "package.json"), - path.join(tmpRepo.name, "package.json"), - ) + fsExtra.copySync(path.join(appPath, "package.json"), path.join(tmpRepo.name, "package.json")) // resolve relative file paths in package.json // also delete scripts fs.writeFileSync( tmpRepoPackageJsonPath, JSON.stringify( - deleteScripts( - resolveRelativeFileDependenciesInPackageJson( - appPath, - require(tmpRepoPackageJsonPath), - ), - ), + deleteScripts(resolveRelativeFileDependenciesInPackageJson(appPath, require(tmpRepoPackageJsonPath))), ), ) if (packageManager === "yarn") { - fsExtra.copySync( - path.join(appPath, "yarn.lock"), - path.join(tmpRepo.name, "yarn.lock"), - ) + fsExtra.copySync(path.join(appPath, "yarn.lock"), path.join(tmpRepo.name, "yarn.lock")) console.info(green("☑"), "Building clean node_modules with yarn") tmpExec(`yarn`) } else { - const lockFileName = - packageManager === "npm-shrinkwrap" - ? "npm-shrinkwrap.json" - : "package-lock.json" - - const lockFileContents = JSON.parse( - fsExtra.readFileSync(path.join(appPath, lockFileName)).toString(), - ) - const resolvedLockFileContents = resolveRelativeFileDependenciesInPackageLock( - appPath, - lockFileContents, - ) - fs.writeFileSync( - path.join(tmpRepo.name, lockFileName), - JSON.stringify(resolvedLockFileContents), - ) + const lockFileName = packageManager === "npm-shrinkwrap" ? "npm-shrinkwrap.json" : "package-lock.json" + + const lockFileContents = JSON.parse(fsExtra.readFileSync(path.join(appPath, lockFileName)).toString()) + const resolvedLockFileContents = resolveRelativeFileDependenciesInPackageLock(appPath, lockFileContents) + fs.writeFileSync(path.join(tmpRepo.name, lockFileName), JSON.stringify(resolvedLockFileContents)) console.info(green("☑"), "Building clean node_modules with npm") tmpExec("npm", ["i"]) } // commit the package console.info(green("☑"), "Diffing your files with clean files") - fs.writeFileSync( - path.join(tmpRepo.name, ".gitignore"), - "!/node_modules\n\n", - ) + fs.writeFileSync(path.join(tmpRepo.name, ".gitignore"), "!/node_modules\n\n") tmpExec("git", ["init"]) // don't commit package.json though - fs.unlinkSync( - path.join(tmpRepo.name, "node_modules", packageName, "package.json"), - ) + fs.unlinkSync(path.join(tmpRepo.name, "node_modules", packageName, "package.json")) tmpExec("git", ["add", "-f", slash(path.join("node_modules", packageName))]) tmpExec("git", ["commit", "-m", "init"]) @@ -133,9 +98,7 @@ export default function makePatch( fsExtra.copySync(packagePath, tmpRepoPackagePath, { recursive: true }) // remove package.json again - fs.unlinkSync( - path.join(tmpRepo.name, "node_modules", packageName, "package.json"), - ) + fs.unlinkSync(path.join(tmpRepo.name, "node_modules", packageName, "package.json")) // stage all files tmpExec("git", ["add", "-f", slash(path.join("node_modules", packageName))]) @@ -152,12 +115,7 @@ export default function makePatch( }) // get diff of changes - const patch = tmpExec("git", [ - "diff", - "--cached", - "--no-color", - "--ignore-space-at-eol", - ]).stdout.toString() + const patch = tmpExec("git", ["diff", "--cached", "--no-color", "--ignore-space-at-eol"]).stdout.toString() if (patch.trim() === "") { console.warn(`⁉️ Not creating patch file for package '${packageName}'`) @@ -181,10 +139,7 @@ export default function makePatch( } } -function printNoPackageFoundError( - packageName: string, - packageJsonPath: string, -) { +function printNoPackageFoundError(packageName: string, packageJsonPath: string) { console.error( `No such package ${packageName} diff --git a/src/makeRegExp.ts b/src/makeRegExp.ts index d548a42a..e14b729b 100644 --- a/src/makeRegExp.ts +++ b/src/makeRegExp.ts @@ -15,9 +15,7 @@ export default function makeRegExp( console.error(`${red.bold("***ERROR***")} Invalid format for option --${name} - Unable to convert the string ${JSON.stringify( - reString, - )} to a regular expression. + Unable to convert the string ${JSON.stringify(reString)} to a regular expression. `) process.exit(1) diff --git a/src/patch/apply.ts b/src/patch/apply.ts index 7129e8a1..f1569bba 100644 --- a/src/patch/apply.ts +++ b/src/patch/apply.ts @@ -38,17 +38,10 @@ export function executeEffects(effects: Effect[]) { fs.moveSync(eff.fromPath, eff.toPath) break case "file creation": - fs.writeFileSync( - eff.path, - eff.lines.join("\n") + (eff.noNewlineAtEndOfFile ? "" : "\n"), - { mode: eff.mode }, - ) + fs.writeFileSync(eff.path, eff.lines.join("\n") + (eff.noNewlineAtEndOfFile ? "" : "\n"), { mode: eff.mode }) break case "replace": - fs.writeFileSync( - eff.path, - eff.lines.join("\n") + (eff.noNewlineAtEndOfFile ? "" : "\n"), - ) + fs.writeFileSync(eff.path, eff.lines.join("\n") + (eff.noNewlineAtEndOfFile ? "" : "\n")) break } }) @@ -116,18 +109,14 @@ function applyPatch({ parts, path }: FilePatch): Effect { // contextIndex - part.lines.length, // part.lines.length, // ) - fileLines.splice( - contextIndex - part.lines.length, - part.lines.length, - ) + fileLines.splice(contextIndex - part.lines.length, part.lines.length) contextIndex -= part.lines.length if (contextIndex >= fileLines.length) { if ( (hunkHeader.patched.length > 0 && part.noNewlineAtEndOfFile) || (parts[i - 2] && - (parts[i - 2].type === "insertion" || - parts[i - 2].type === "context") && + (parts[i - 2].type === "insertion" || parts[i - 2].type === "context") && !(parts[i - 2] as any).noNewlineAtEndOfFile) ) { // delete the fact that there was no newline at the end of the file diff --git a/src/patch/parse.ts b/src/patch/parse.ts index 2011da59..4c035b9a 100644 --- a/src/patch/parse.ts +++ b/src/patch/parse.ts @@ -11,9 +11,7 @@ interface HunkHeader { } export function parseHunkHeaderLine(headerLine: string): HunkHeader { - const match = headerLine - .trim() - .match(/^@@ -(\d+)(,(\d+))? \+(\d+)(,(\d+))? @@.*/) + const match = headerLine.trim().match(/^@@ -(\d+)(,(\d+))? \+(\d+)(,(\d+))? @@.*/) if (!match) { throw new Error(`Bad header line: '${headerLine}'`) } @@ -138,9 +136,7 @@ class PatchParser { } if (this.currentLine.startsWith("deleted file mode")) { - this._fileMode = this.currentLine - .slice("deleted file mode ".length) - .trim() + this._fileMode = this.currentLine.slice("deleted file mode ".length).trim() this.nextLine() continue } @@ -154,13 +150,8 @@ class PatchParser { // That's no longer needed but this should still support those old files // unless the file created is empty, in which case the normal patch // parsing bits below don't work and we need this special case - if ( - !this.lines[this.i].startsWith("--- /dev/null") && - !this.lines[this.i + 1].startsWith("--- /dev/null") - ) { - const match = this.lines[this.i - 2].match( - /^diff --git a\/(.+) b\/(.+)$/, - ) + if (!this.lines[this.i].startsWith("--- /dev/null") && !this.lines[this.i + 1].startsWith("--- /dev/null")) { + const match = this.lines[this.i - 2].match(/^diff --git a\/(.+) b\/(.+)$/) if (!match) { console.error(this.lines, this.i) throw new Error("Creating new empty file but found no diff header.") @@ -235,10 +226,7 @@ class PatchParser { ) let noNewlineAtEndOfFile = false - if ( - !this.isEOF && - this.currentLine.startsWith("\\ No newline at end of file") - ) { + if (!this.isEOF && this.currentLine.startsWith("\\ No newline at end of file")) { noNewlineAtEndOfFile = true this.nextLine() } @@ -282,9 +270,7 @@ class PatchParser { const deletion: PatchMutationPart = this.parsePatchMutationPart() if (header.original.length !== deletion.lines.length) { - throw new Error( - "hunk header integrity check failed when parsing file deletion", - ) + throw new Error("hunk header integrity check failed when parsing file deletion") } this.result.push({ @@ -304,9 +290,7 @@ class PatchParser { const addition: PatchMutationPart = this.parsePatchMutationPart() if (header.patched.length !== addition.lines.length) { - throw new Error( - "hunk header integrity check failed when parsing file addition", - ) + throw new Error("hunk header integrity check failed when parsing file addition") } this.result.push({ @@ -332,20 +316,14 @@ class PatchParser { this.nextLine() - while ( - this.currentLineIsPartOfHunk() && - !(this.isOneLineLeft && this.currentLine === "") - ) { + while (this.currentLineIsPartOfHunk() && !(this.isOneLineLeft && this.currentLine === "")) { const mutations = this.parsePatchMutationPart() hunkParts.push(mutations) } // verify hunk integrity const endSize = hunkParts.reduce( - ( - { originalLength, patchedLength }, - { type, lines }: PatchMutationPart, - ) => { + ({ originalLength, patchedLength }, { type, lines }: PatchMutationPart) => { switch (type) { case "insertion": return { @@ -367,13 +345,8 @@ class PatchParser { { originalLength: 0, patchedLength: 0 }, ) - if ( - endSize.originalLength !== header.original.length || - endSize.patchedLength !== header.patched.length - ) { - throw new Error( - "hunk header integrity check failed when parsing file addition", - ) + if (endSize.originalLength !== header.original.length || endSize.patchedLength !== header.patched.length) { + throw new Error("hunk header integrity check failed when parsing file addition") } filePatch.parts.push(header) diff --git a/src/patchFs.ts b/src/patchFs.ts index b6a2ec97..02550e0a 100644 --- a/src/patchFs.ts +++ b/src/patchFs.ts @@ -1,18 +1,11 @@ import * as fs from "fs-extra" import * as path from "./path" -function _getPatchFiles( - rootPatchesDir: string, - scopedDir: string = "", - acc: string[] = [], -) { +function _getPatchFiles(rootPatchesDir: string, scopedDir: string = "", acc: string[] = []) { fs.readdirSync(path.join(rootPatchesDir, scopedDir)).forEach(filename => { if (filename.endsWith(".patch")) { acc.push(path.join(scopedDir, filename)) - } else if ( - filename.startsWith("@") && - fs.statSync(path.join(rootPatchesDir, filename)).isDirectory() - ) { + } else if (filename.startsWith("@") && fs.statSync(path.join(rootPatchesDir, filename)).isDirectory()) { _getPatchFiles(rootPatchesDir, filename, acc) } }) @@ -20,7 +13,5 @@ function _getPatchFiles( } export function getPatchFiles(patchesDir: string) { - return _getPatchFiles(patchesDir).filter(filename => - filename.match(/^.+(:|\+).+\.patch$/), - ) + return _getPatchFiles(patchesDir).filter(filename => filename.match(/^.+(:|\+).+\.patch$/)) } diff --git a/src/resolveRelativeFileDependencies.ts b/src/resolveRelativeFileDependencies.ts index 6bec04be..161fd631 100644 --- a/src/resolveRelativeFileDependencies.ts +++ b/src/resolveRelativeFileDependencies.ts @@ -17,22 +17,21 @@ interface PackageLock { } } -export function resolveRelativeFileDependenciesInPackageJson< - T extends PackageJson ->(appRootPath: string, pkg: T): PackageJson { +export function resolveRelativeFileDependenciesInPackageJson( + appRootPath: string, + pkg: T, +): PackageJson { _resolveRelativeFileDependencies(appRootPath, pkg.dependencies) _resolveRelativeFileDependencies(appRootPath, pkg.devDependencies) return pkg } -export function resolveRelativeFileDependenciesInPackageLock< - T extends PackageLock ->(appRootPath: string, pkg: T): PackageLock { +export function resolveRelativeFileDependenciesInPackageLock( + appRootPath: string, + pkg: T, +): PackageLock { for (const packageName of Object.keys(pkg.dependencies)) { - pkg.dependencies[packageName].version = transformVersionString( - pkg.dependencies[packageName].version, - appRootPath, - ) + pkg.dependencies[packageName].version = transformVersionString(pkg.dependencies[packageName].version, appRootPath) } return pkg } @@ -45,16 +44,10 @@ function transformVersionString(version: string, appRootPath: string) { } } -function _resolveRelativeFileDependencies( - appRootPath: string, - dependencies?: { [packageName: string]: string }, -) { +function _resolveRelativeFileDependencies(appRootPath: string, dependencies?: { [packageName: string]: string }) { if (dependencies) { for (const packageName of Object.keys(dependencies)) { - dependencies[packageName] = transformVersionString( - dependencies[packageName], - appRootPath, - ) + dependencies[packageName] = transformVersionString(dependencies[packageName], appRootPath) } } } diff --git a/src/spawnSafe.ts b/src/spawnSafe.ts index bf7d927c..fb0ba624 100644 --- a/src/spawnSafe.ts +++ b/src/spawnSafe.ts @@ -12,11 +12,7 @@ const defaultOptions: SpawnSafeOptions = { throwOnError: true, } -export default function spawnSafeSync( - command: string, - args?: string[], - options?: SpawnSafeOptions, -) { +export default function spawnSafeSync(command: string, args?: string[], options?: SpawnSafeOptions) { const mergedOptions = Object.assign({}, defaultOptions, options) const result = spawnSync(command, args, options) if (result.error || result.status !== 0) { diff --git a/yarn.lock b/yarn.lock index 71348ef9..6f151779 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2507,9 +2507,9 @@ preserve@^0.2.0: version "0.2.0" resolved "https://registry.yarnpkg.com/preserve/-/preserve-0.2.0.tgz#815ed1f6ebc65926f865b310c0713bcb3315ce4b" -prettier@^1.11.1: - version "1.11.1" - resolved "https://registry.yarnpkg.com/prettier/-/prettier-1.11.1.tgz#61e43fc4cd44e68f2b0dfc2c38cd4bb0fccdcc75" +prettier@^1.12.1: + version "1.12.1" + resolved "https://nexus.elder.org/content/groups/npm-all/prettier/-/prettier-1.12.1.tgz#c1ad20e803e7749faf905a409d2367e06bbe7325" pretty-format@^20.0.0: version "20.0.0"