IAmTheRockstar

Yes. Yes I am.
Examples in bzrlib
January 18 2009

So while I've spent my fair share of time hacking with Bazaar, I'm ashamed to say I hadn't done a lot of hacking on Bazaar. I've fixed small issues in Bazaar plugins, and even written a few of my own (although Jono Lange actually released his implementation before I could get mine done). However, during Christmastime, I had the opportunity to hack on some Bazaar plugins that I will be releasing shortly. In this process, I learned a bunch about the bzrlib API, and its great ease of use. I thought I'd compile a bit of what I've found into a blog post or two.

I'd like to start the examples off with some relatively easy exercises. In order to do some of these examples, it's best to have a local bzr branch of any kind. I'll start by demonstrating how to do some of the tasks you do from the command line (or GUI of your choice) programmatically.

Getting a Branch object

In order to operate on your branch, you'll need to create a Branch object. This will be a programmatic handle to your bzr branch itself. So let's start by getting the branch itself.

from bzrlib.branch import Branch

my_branch = Branch.open('/path/to/branch')

Now we can operate on the branch with python. Let's say we want to see what config variables are set on this branch. We'll want to get the configuration of the branch, and then examine its contents. In this example, we'll check the username you'll be committing to bzr with (because you hopefully ran bzr whoami.

my_branch_config = my_branch.get_config()
print my_branch_config.username()

Simple local branching

Let's say you want to programatically create a local copy of a remote branch.

from bzrlib.branch import Branch

remote_branch_url = 'bzr+ssh://bzr.eventuallyanyway.com/code/foo-bar-baz'

remote_branch = Branch.open(remote_branch_url)
local_branch = remote_branch.bzrdir.sprout(
    '/code/foo-bar-baz').open_branch()

Getting a diff

Programmatically, I think the best use for understanding the Bazaar API is to diff the changes in your current working tree. You'll do this by creating a WorkingTree object and operating on it.

from bzrlib.workingtree import WorkingTree

tree = WorkingTree.open('/code/foo-bar-baz')

Now you've got a working tree. Let's get a diff between it's current state and its last committed state. If it's changed, commit the changes with a commit message of "Committed changes"

delta = tree.changes_from(tree.basis_tree())
if delta.has_changes:
    tree.commit('Committed changes')

All in all, I think the greatest strength of Bazaar is its easy extensibility, and easy entry into working with its API is proof.

All opinions expressed here constitute my personal opinion, and do not necessarily represent the opinion of any other organization or person, including, but not limited to, my fellow employees, my employer, its clients or their agents.