|
| 1 | +import { execSync as exec } from "child_process" |
| 2 | +import * as fs from "fs" |
| 3 | +import * as path from "path" |
| 4 | +import * as shellEscape from "shell-escape" |
| 5 | +import * as tmp from "tmp" |
| 6 | +import Npm from "./Npm" |
| 7 | +import { PackageManager } from "./PackageManager" |
| 8 | +import Yarn from "./Yarn" |
| 9 | + |
| 10 | +export default function makePatch(packageName: string, appPath: string) { |
| 11 | + const packagePath = path.join(appPath, "node_modules", packageName) |
| 12 | + const packageJsonPath = path.join(packagePath, "package.json") |
| 13 | + if (!fs.existsSync(packageJsonPath)) { |
| 14 | + throw new Error(`Unable to find local ${packageName} package.json at ${packageJsonPath}`) |
| 15 | + } |
| 16 | + |
| 17 | + const packageVersion = require(packageJsonPath).version |
| 18 | + |
| 19 | + const tmpDir = tmp.dirSync({ unsafeCleanup: true }) |
| 20 | + |
| 21 | + try { |
| 22 | + const packageManager = getPackageManager(tmpDir.name) |
| 23 | + |
| 24 | + packageManager.add(packageName, packageVersion) |
| 25 | + |
| 26 | + exec(`git init`, { cwd: tmpDir.name }) |
| 27 | + exec(shellEscape(["git", "add", "-f", path.join("node_modules", packageName)]), { cwd: tmpDir.name }) |
| 28 | + exec(shellEscape(["cp", "-RL", packagePath, path.join(tmpDir.name, "node_modules")])) |
| 29 | + const patch = exec(`git diff`, { cwd: tmpDir.name }).toString() |
| 30 | + |
| 31 | + const patchesDir = path.join(appPath, "patches") |
| 32 | + if (!fs.existsSync(patchesDir)) { |
| 33 | + fs.mkdirSync(patchesDir) |
| 34 | + } |
| 35 | + |
| 36 | + const patchFileName = `${packageName}:${packageVersion}.patch` |
| 37 | + console.log(`Creating patch file ${patchFileName}`) |
| 38 | + fs.writeFileSync(path.join(patchesDir, patchFileName), patch) |
| 39 | + } finally { |
| 40 | + tmpDir.removeCallback() |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +function getPackageManager(cwd: string): PackageManager { |
| 45 | + try { |
| 46 | + exec("which yarn") |
| 47 | + return new Yarn(cwd) |
| 48 | + } catch (e) { |
| 49 | + return new Npm(cwd) |
| 50 | + } |
| 51 | +} |
0 commit comments