> ## Documentation Index
> Fetch the complete documentation index at: https://aspect.build/llms.txt
> Use this file to discover all available pages before exploring further.

# Patching external libraries and Bazel modules

> Apply Bazel's patch-and-PR workflow to fix external libraries and Bazel modules without forking, using patch files attached to module dependency declarations.

* Forks considered dangerous
* Method for creating patch files
* Applying the patch
* Recommendation: “patch and PR”

You'll often find that some upstream code needs some minor fixes to work for your use case.
The naive thing is to fork that upstream repository, either explicitly by creating a GitHub repository in your org which copies all the files, or implicitly by vendoring files into your monorepo.
Forking is very easy to perform, but it adds a constant maintenance burden to your team.
You now own a copy of that project, along with the need to test changes to it.
Your copy will diverge over time, so the ability to rebase or cherry-pick changes from the upstream will rot.

A better approach is to use Bazel's ubiquitous support for applying patches to dependencies as they
are fetched. A nice workflow is:

1. Clone the dependency locally. If it's a Bazel module, use `--override_repository` to point to your
   local copy without having to change any files in the monorepo. If it's a library, use whatever
   mechanism exists in the language's package manager. For example, pnpm has [https://pnpm.io/cli/patch](https://pnpm.io/cli/patch)
2. Make edits like print-debugging in the dependency.
3. When you get to a working state, you commit your changes with a good commit message.
4. Make a PR to the upstream with your commit (unless it's confidential internal-only code).
   Do this even if you don't really care whether they accept your PR!!
   This way you'll share your solution with others, and get comments from the project maintainers that
   might help you improve your patch or even discover it's not needed.
   Furthermore, if the PR is eventually merged, you'll be able to remove the patch from your repository
   which lowers your maintenance burden and "complexity budget".
5. Run `git show > /[path/to/monorepo]/[some/bazel]/rule.pr123.patch` to make a copy of your commit in the monorepo.
   You should have some convention for where your Bazel setup belongs, these patches can just go there.
   By including the PR number in the patch file name, you make it possible for someone browsing the repository
   to discover the comment thread from upstream maintainers about the patch.
6. Add the `patch_args=["-p1"]` and `patches=["//some/bazel:rule.pr123.patch"]` attributes to whatever
   spot is fetching the dependency.
