Generic-user-small Daniel Bullok 1 post

Hi.
I just bought the beta book this week. It’s very good. I’ve been hoping to find out how to move code between two repositories, which doesn’t seem to be covered in the book yet (or I somehow missed it). In subversion, I put all of my code in one repository. While working on a project, I very frequently end up writing some code that I’ll eventually use elsewhere. I almost never pull this code out of the project and into a library until I need it for a second project. Subversion makes this quite easy if your project and the library are in the same repository (svn move). You can accomplish the same thing in git if your code is in the same repository, but using a single git repository for all your code isn’t such a good idea. So is there an easy way to move or copy code from one git repository into another while still retaining the history?
Thanks.
-Dan

 
Me-square_small Travis Swice... 13 posts

Hey Daniel;

That’s a work-flow I haven’t covered in the book yet. It’s kind of specific, but could definitely be useful. Maybe I’ll add it to the Recipes appendix.

You are definitely right, though. Keeping a bunch of different projects in one big Git repository isn’t the best of way to handle this situation. You can do it, but you don’t have as much flexibility as having smaller, more focused repositories.

So here’s what I would do. Create a clone of the repository that has the code you want to extract into its own repository. Let’s call them repo A and repo B, respectively. The cloned copy will become your repo B. Just run git rebase -i and erase all of the commits that you’re not interested in keeping around. When you finish, your repository will have just has the history related to parts of the code you want to keep around. Change the remote repository to the remote you want to use to share this repository with others, and you’re set.

To make your job a bit easier, you can generate the list of commits you want to pull out for your rebase instead of manually going over every commit. To do that, run git log --pretty=format:"pick %h %s" path/to/pull. That assumes all of your files exist in the same path. You could also provide it with a list of all of the individual files you want to keep around. The format that the log output is in is the same format that git rebase -i uses, so just copy-and-paste that into your editor when setting up the rebase and you’re set.

Hope that helps!
-T

2 posts, 2 voices