How can I transfer a series of Git commits between two local copies of the repository?

Viewed 95

I currently have two copies of the same Git project checked out on my machine. I'm aware that traditionally one would not do that; it's more typical to have the project checked out once and switch branches as needed. The primary reason I have the second copy so that I can review merge requests locally — within my IDE, as well as by running the code — without having to context switch out of whatever work I might be in the middle of. That work might not be in a state where it's convenient for me to stash, or commit, or stop running a long running process.

I accidentally made some changes to the wrong copy of my project locally, and want to move them to the correct copy.

I know that I can create a branch, push them to the server, check them out on the other branch, and then delete the remote branch. This isn't too terribly onerous.

cd /path/to/source-project

git switch -c myTempBranch
git push -u origin myTempBranch

cd /path/to/other-project

git pull
git merge myTempBranch
git push -d origin myTempBranch

That being said, the changes aren't ready for anyone else's consumption quite yet, and it would be nice if I could do this all locally without having to get the remote server involved.

Is there a way to apply a series of commits from one checked out get project to a different copy of that project without pushing it?

2 Answers

You can add a local repository as a remote and fetch it to get the changes. E.g.

git remote add repoWithChanges file:///<path_to_remote>

git fetch repoWithChanges

Now after the other repository's changes are fetched you can cherry-pick, merge, and so on.

PS: If you need a second worktree for the pull requests you can just use

 git worktree add /some/path/to/checkout someBranch

This doesn't help when already in the described situation, but a different approach to checking out the repository twice is to create a second working tree. With this setup, different branches the same project are checked out in two different locations on the filesystem, and changes to branches in either working tree are visible to the other.

# Create a new worktree
git worktree add /path/to/other-worktree

With a multiple working tree setup such as this, it doesn't matter which working tree the changes were made on, as they're visible to all the other working trees. The branch with the desired changes just needs to be checked out in the second working tree, and the changes will be present in the desired location.

cd /path/to/other-worktree
git switch branchWithChanges

Note that the one main limitation to this workflow is that the same branch cannot be checked out in both locations, though a copy of the branch or detatched head could be if the same code needs to be checked out in both places.

Related