Skip to content

Conversation

@zardoy
Copy link

@zardoy zardoy commented Jun 26, 2025

for pnpm/pnpm#5503

so in patching/apply-patch/src/index.ts we can do this:

const patchLogger = logger('patch')
//...

export function applyPatchToDir (opts: ApplyPatchToDirOpts): boolean {
  // Ideally, we would just run "patch" or "git apply".
  // However, "patch" is not available on Windows and "git apply" is hard to execute on a subdirectory of an existing repository
  const cwd = process.cwd()
  process.chdir(opts.patchedDir)
  patchLogger.debug({ message: 'Applying patch to directory', patchFilePath: opts.patchFilePath, patchedDir: opts.patchedDir, cwd })
  let success = false
  let applyPatchError: Error | undefined
  try {
    success = applyPatch({
      patchFilePath: opts.patchFilePath,
      onPatchError: (err: Error, context: { phase: 'apply' | 'reverse-dry-run' }) => {
        if (context.phase === 'apply') {
          applyPatchError = err
          patchLogger.debug({ message: 'Patch application error', error: err.message, phase: context.phase })
        }
      },
    })
  } catch (err: any) { // eslint-disable-line
    if (err.code === 'ENOENT') {
      throw new PnpmError('PATCH_NOT_FOUND', `Patch file not found: ${opts.patchFilePath}`)
    }
    throw new PnpmError('INVALID_PATCH', `Applying patch "${opts.patchFilePath}" failed: ${err.message as string}`)
  } finally {
    process.chdir(cwd)
  }
  if (!success) {
    const message = `Could not apply patch ${opts.patchFilePath} to ${opts.patchedDir}: ${applyPatchError?.message ?? 'Unknown error'}`
    if (opts.allowFailure) {
      globalWarn(message)
    } else {
      throw new PnpmError('PATCH_FAILED', message)
    }
  }
  return success
}

@dschmidt
Copy link

I'm trying to debug a patch applying issue, it would be nice to have this - is anything holding this back?

@zardoy
Copy link
Author

zardoy commented Aug 19, 2025

I think it will never get merged because this is not pnpm repository…
You might want to check bun, they have a well maintained version of the patch functionality… (shrug)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants