Skip to content

Instantly share code, notes, and snippets.

@karmi
Created June 3, 2010 10:58
Show Gist options
  • Save karmi/423746 to your computer and use it in GitHub Desktop.
Save karmi/423746 to your computer and use it in GitHub Desktop.
GitInfo: Rack middleware example
.DS_Store
*.log
require 'rubygems'
require 'sinatra'
# LET'S USE OUT MIDDLEWARE ---------------------------------------------->
require 'rack/gitinfo'
use Rack::GitInfo
# use Rack::GitInfo, :path => '/Users/karmi/Playground/Rails/rails'
# <-----------------------------------------------------------------------
get '/' do
erb :index
end
__END__
@@ layout
<!DOCTYPE html>
<html>
<head>
<title>Rack::GitInfo Example</title>
<meta charset="utf-8">
<style>body { font-family: sans-serif; margin: 4em; } small { color: #333; }</style>
</head>
<body>
<%= yield %>
</body>
</html>
@@index
<p>Hey, am I in Git?</p>
# = Rack::GitInfo
#
# Example Rack middleware to show revision info from Git
#
# For a more advanced library have a look at http://github.com/sickill/rack-revision-info
module Rack
class GitInfo
def initialize(app, options={})
@app = app
@path = options[:path] || ::File.expand_path('../', $0)
end
def call(env)
status, headers, body = @app.call(env)
if headers['Content-Type'].to_s.include?('text/html') # Only update HTML bodies
body = (body << message).to_a.join("\n")
headers['Content-Length'] = Rack::Utils.bytesize(body.to_s).to_s
headers['X-Git-Revision-ID'] = @sha
end
[status, headers, body]
end
private
def git_revision_info
output = %x[( GIT_DIR=#{@path}/.git git log -1 --no-color --pretty=format:'%H~~~%ai~~~%an~~~%s' 2>&1)]
output =~ /(fatal)|(no such file)/i ? nil : output
end
def message
@sha, date, author, message = git_revision_info.split('~~~')
"<p><small>Revision info: #{@sha} from #{date} by #{author} : #{message}</small></p>"
rescue
@sha = 'N/A'
"<p><small>Cannot get Git revision info</small></p>"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment