Syncing Updates from Upstream Repository#
I created my own repository using a Github Template and need to sync some patch updates; I can't just rewrite it by hand, so I searched for a solution.
Here's a record.
Adding Upstream Repository#
Give the upstream repository a name. If named upstream
, you can run the following command in your local repository:
git remote add upstream https://github.com/$<upstream-repo>.git
Fetching Changes from Upstream Repository#
Run the following command to fetch all branches and commits from the upstream repository:
git fetch upstream
Merging Upstream Changes#
Now, merge the changes from the upstream main branch into your local main branch:
git merge upstream/main --allow-unrelated-histories
If you only need to merge a specific commit:
git cherry-pick <commit-hash>
You can also use
gcp <commit-hash>
The commit-hash can be copied directly from the GitHub webpage.
At this point, the author of the commit is the author of the source repository. Vercel prompts me that the Build failed and I need to upgrade to Pro; I can modify a file and add a commit myself.
Of course, this is not very elegant. You can use the following command to get changes to the file without committing:
git cherry-pick <commit-hash> --no-commit
Then manually commit:
git commit -m "commit information"
Resolving Conflicts#
If you have already modified the source code, conflicts may occur during the merge process, and you need to resolve them manually.
Git will also provide prompts; manually edit the conflict files and save them, then commit the changes.
Batch Commit#
git cherry-pick <start-commit>^..<end-commit>
If there are conflicts, they will be processed in order, then execute continue
until finished:
git cherry-pick --continue
-
<start-commit>
: The starting point of the range (not including this commit unless using<start-commit>~
or<start-commit>^
). -
<end-commit>
: The ending point of the range (including this commit). -
^
is Git's syntax for specifying "the previous commit." -
..
indicates the range.
Pushing#
git push origin main
Of course, by default, it will not push to the newly added upstream
; just git push
will suffice.
If you no longer need to sync, you can remove the upstream repository:
git remote remove upstream