Git and Perforce Integration

I’m an avid fan of git, a great open-source version control system. I wrote a little bit about how I use my website as a private repository before. Now, I’m going to show you how to  integrate it with Perforce.

Working with Perforce as a remote repository functions in a similar way to using svn or cvs as a remote repository. And, for that matterm semantics are pretty much the same when git itself is the remote repository (such as github.org). I’ll assume you’re already familiar with Perforce and the directions that follow are specific to Linux, work on the Mac, and I imagine minor tweaks would be necessary for Windows.

Start off with your default p4 depot on your local drive. When working in git, you won’t be working in that folder on your OS mount. Rather, you’ll work in a clone repository.

On my linux box, my depot is at ~/sandbox/nick. My perforce client-spec is defined as: //depot/sandbox/nick/… //nick-machine06/sandbox/nick/… . Next, the command I will show you will also import revision history from Perforce. To do this, you need to create a clone of this repository that git will interact with. Simple:

[nick@machine06 ~]$ git p4 clone //depot/sandbox/nick@all sandbox.git

I believe the @all instructs the git-p4 commant to import all history for the imported files. This command creates a new directory on my root alongside my p4 depot:

~/sandbox (p4 depot)
~/sandbox.git #git's repository

When making changes via git, you work in ~/sandbox.git and submit to ~/sandbox. Here is a set of operations that edit a file and submit to the master branch:

vi ~/sandbox/nick/python/delempty.py
# make a change
# save the file
# notice I didn't "open" the file for edit. It's just a file, edit it. Git will detect changes when you submit.
git commit -a
# this will commit change to git repository

Then, the git p4 command submits the latest batch of changes to Perforce. It opens the files for editing in the P4 depot, creates a changelist, and submits.

git p4 submit

This will push it to perforce. It knows to do this because the “remote repository” (~/sandbox) is known to this git repository as it’s configured in hidden config files. Same works for cvs, subversion, and other git remote repositories.

Much of what I wrote here was learned from a thread over at kerneltrap.org. A colleague at work helped me work out the remaining bits. Thanks Dan! At some point, I’ll write about how developers can submit batches of code seamlessly using git and reviewers can view them in a lightweight branch. Of course, I need to figure all that out first!