John Watson

Hello! My name is Watson and I’m a freelance web developer. I create web sites using the latest tech for clients of all sizes. Contact me and I’ll help you build your dream project.

Using git to build CSS files for deployment

Lots of stuff going on here lately. I converted a store from osCommerce to Magento. I’m building the hosted bug tracking app I’ve always wanted. And I switched from svn to git. Converting svn repos to git repos and keeping all of the history is pretty easy. I’ll do a post about it soon. Basically, I followed the excellent instructions here but I automated it because I had a lot of repos.

Now that I’ve switched to git, you may commence moving to the next much better thing that I haven’t heard of yet.

But, to the point…

Part of the deployment process for Caravela is to create a compressed build of the CSS using yuiccompressor and save it under a new name. That new version of the CSS file is then referenced in the site header. I do this because I want the CSS to be aggressively cached by browsers to save on bandwidth and improve page load times; but I also want new CSS to take effect without waiting for caches to expire. Generating a new name for the CSS file whenever it changes solves that problem neatly.

So my deployment script does this automatically:

  • Get the latest commit ID of the main.css file
  • Look for a version of the css with that commit ID: e.g. main_v12345.css
  • If that file doesn’t exist, build it using yuicompressor
  • Store the commit ID in a file you deploy so the site knows which CSS file to serve
The key component of this is getting a commit ID. I do it by getting the output of this shell command:
git log –abbrev-commit -1 assets/css/main.css | head -1 | cut -d\  -f2
What I end up with is a unique, 7 digit version identifier based on my latest commit on that file.

Then you just need to build a new CSS file and save it using that identifier (e.g. main_v12345) (if it hasn’t already been built for a previous deployment) and teach your header file/template/view to reference the current version of the CSS file.

This works with Javascript, too, or any other file that you are both caching and versioning in git. And it isn’t important that you use yuicompressor. Your build process could just be a simple copy. The important thing is that the file has a new name so that the updated version will be loaded and cached by the user’s web browsers on their very next visit.