Sean’s Obsessions

Sean Walberg’s blog

Showing Git Commits in a Rails View

I have an administration panel for my Rails application that shows various information. I’ve found it helpful to show the last few commits along with a link to the repository. Here’s the code:

Controller:

1
2
3
4
5
6
7
8
9
10
11
@commits = Array.new
git = `git log -15 --abbrev-commit --pretty=format:"%H - %cr - %s - %d"`
git.split(/\n/).each do |commit|
  elements = commit.split(/ - /)
  @commits
    :hash => elements[0],
    :time => elements[1],
    :subject => elements[2],
    :refs => (elements[3] || "").match(/deploy_[^,]*/)
  }
end

The :refs never got used, I had thought that I’d tag all my deploys and be able to highlight them later, but it never ended up working out.

View: (It’s in HAML)

1
2
3
4
5
 - @commits.each do |commit|
      %li
        = link_to truncate(commit[:subject], :length => 80), "http://git.example.com/git/myapp.git/commit/#{commit[:hash]}"
        = "(#{commit[:time]})"
        %b= commit[:refs]

It’s pretty simple, it just parses the output of git log and spits it out as a list, showing the description and how long ago it was checked in. If you have gitweb or something similar installed, you get a link to the repo.

It’s helped me to find production bugs, and also when I deploy without pushing my code to the git repo, and end up forgetting some changes!

Comments

I’m trying something new here. Talk to me on Twitter with the button above, please.