Skip to content

feat: add detailed error handling for patch failures #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

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
}

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.

1 participant