Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: e9f6b19aca
Fetching contributors…

Cannot retrieve contributors at this time

file 308 lines (254 sloc) 8.799 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
require 'rubygems'
require 'sinatra'
require 'yaml'
require 'logger'

# = Pushr
# Deploy Rails applications by Github Post-Receive URLs launching Capistrano's commands

CONFIG = YAML.load_file( File.join(File.dirname(__FILE__), 'config.yml') ) unless defined? CONFIG

class String
  # http://github.com/rails/rails/blob/master/activesupport/lib/active_support/core_ext/string/inflections.rb#L44-49
  def camelize
    self.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase }
  end
end

module Pushr

  # == Shared logger
  module Logger
    unless defined? LOGGER
      LOGGER = ::Logger.new(File.join(File.dirname(__FILE__), 'deploy.log'), 'weekly')
      LOGGER.level = ::Logger::INFO
    end
    def log; LOGGER; end
  end

  # == Wrapping notifications
  # Inspired by http://github.com/foca/integrity
  class Notifier

    # Inherit from this class in your notifiers
    # See eg. http://github.com/karmi/pushr_notifiers/blob/master/irc.rb
    class Base

      include Pushr::Logger

      attr_reader :config

      def initialize(config={})
        @config = config
        log.fatal("#{self.class.name}") { "Notifier not configured!" } unless configured?
      end

      # Implement this method for your particular notification method
      def deliver!
        raise NoMethodError, "You need to implement 'deliver!' method in your notifier"
      end

      private

      # Over-ride this method to send diferent message
      def message(notification)
        if notification.success
          "Deployed #{notification.application} with revision #{notification.repository.info.revision}#{notification.repository.info.message.slice(0, 100)}"
        else
          "FAIL! Deploying #{notification.application} failed. Check deploy.log for details."
        end
      end

      # Implement this method to check for notifier configuration
      def configured?
        raise NoMethodError, "You need to implement 'configured?' method in your notifier"
      end

    end

    # Twitter notifications (default)
    class Twitter < Base

      def deliver!(notification)
        return unless configured?
        %x[curl --silent --data status='#{message(notification)}' http://#{config['username']}:#{config['password']}@twitter.com/statuses/update.json]
      end

      private

      def configured?
        !config['username'].nil? && !config['password'].nil?
      end
    end

  end # end Notifier

  # == Wrapping Git stuff
  class Repository

    include Logger

    Struct.new('Info', :revision, :message, :author, :when, :datetime) unless defined? Struct::Info

    def initialize(path)
      @path = path
    end

    def info
      info = `cd #{@path}/current; git log --pretty=format:'%h --|-- %s --|-- %an --|-- %ar --|-- %ci' -n 1`
      @info ||= Struct::Info.new( *info.split(/\s{1}--\|--\s{1}/) )
    end

    def reload!
      @info = nil
      info
    end

    def uptodate?
      log.info('Pushr') { "Fetching new revisions from remote..." }
      info = `cd #{@path}/shared/cached-copy; git fetch -q origin 2>&1`
      log.fatal('git fetch -q origin') { "Error while checking if app up-to-date: #{info}" } and return false unless $?.success?
      return info.strip == '' # Blank output => No updates from git remote
    end

  end # end Repository

  # == Wrapping application logic
  class Application

    include Logger

    attr_reader :path, :application, :repository, :success, :cap_output

    def initialize(path)
      log.fatal('Pushr.new') { "Path not valid: #{path}" } and raise ArgumentError, "File not found: #{path}" unless File.exists?(path)
      @path = path
      @application = ::CONFIG['application'] || "You really should set this to something"
      @repository = Repository.new(path)
      load_notifiers
    end

    def deploy!(force=false)
      if repository.uptodate? # Do not deploy if up-to-date (eg. push was to other branch) ...
        log.info('Pushr') { "No updates for application found" } and return {:@success => false, :output => 'Application is uptodate'}
      end unless force == 'true' # ... unless forced from web GUI
      cap_command = CONFIG['cap_command'] || 'deploy:migrations'
      log.info(application) { "Deployment #{"(force) " if force == 'true' }starting..." }
      @cap_output = %x[cd #{path}/shared/cached-copy; cap #{cap_command} 2>&1]
      @success = $?.success?
      @repository.reload! # Update repository info (after deploy)
      log_deploy_result
      send_notifications
    end

    private

    def log_deploy_result
      if @success
        log.info('[SUCCESS]') { "Successfuly deployed application with revision #{repository.info.revision} (#{repository.info.message}). Capistrano output:" }
        log.info('Capistrano') { @cap_output.to_s }
      else
        log.warn('[FAILURE]') { "Error when deploying application! Check Capistrano output below:" }
        log.warn('Capistrano') { @cap_output.to_s }
      end
    end

    def load_notifiers
      @notifiers_path = CONFIG['notifiers_path'] || '../pushr_notifiers'
      @notifiers = []
      CONFIG['notifiers'].each do |notifier|
        notifier_name, notifier_config = notifier.to_a.flatten
        unless Pushr::Notifier::const_defined?(notifier_name.to_s.camelize)
          begin
            require File.join( File.dirname(__FILE__), @notifiers_path, notifier_name )
          rescue Exception => e
            raise LoadError, "Notifier #{notifier_name} not found! (#{e.message})"
          end
        end
        @notifiers << Pushr::Notifier::const_get( notifier_name.to_s.camelize ).new(notifier_config)
      end
    end

    def send_notifications
      @notifiers.each { |n| n.deliver!(self) }
    end

  end # end Application

end # end Pushr

# ------- Sinatra gets on stage here --------------------------------------------------

# -- Authorize all requests with username/password set in <tt>config.yml</tt>
before do
  halt [404, "Not configured\n"] and return unless configured?
  response['WWW-Authenticate'] = %(Basic realm="[pushr] #{CONFIG['application']}") and \
  halt([401, "Not authorized\n"]) and \
  return unless authorized?
end

# -- Helpers
helpers do

  def authorized?
    @auth ||= Rack::Auth::Basic::Request.new(request.env)
    @auth.provided? && @auth.basic? && @auth.credentials && @auth.credentials.first == CONFIG['username'] && @auth.credentials.last == CONFIG['password']
  end

  def configured?
    CONFIG['username'] && !CONFIG['username'].nil? && CONFIG['password'] && !CONFIG['password'].nil?
  end

end

# == Get info
get '/' do
  @pushr = Pushr::Application.new(CONFIG['path'])
  haml :info
end

# == Deploy!
post '/' do
  @pushr = Pushr::Application.new(CONFIG['path'])
  @pushr.deploy!(params[:force])
  haml :deployed
end

# == Look nice
get '/style.css' do
  content_type 'text/css', :charset => 'utf-8'
  sass :style
end
get( '/favicon.ico' ) { content_type 'image/gif' }

__END__

@@ layout
%html
%head
%title= "[pushr] #{@pushr.application}"
%meta{ 'http-equiv' => 'Content-Type', :content => 'text/html;charset=utf-8' }
%link{ :rel => 'stylesheet', :type => 'text/css', :href => "/style.css" }
%body
= yield

@@ info
%div.info
%p
Last deployed revision of
%strong
%em
= @pushr.application
is
%strong
= @pushr.repository.info.revision
\:
%strong
%em
= @pushr.repository.info.message
committed
%strong
= @pushr.repository.info.when
by
= @pushr.repository.info.author
%p
%form{ :action => "/", :method => 'post', :onsubmit => "this.submit.disabled='true'" }
%input{ 'type' => 'hidden', 'name' => 'force', 'value' => 'true' }
%input{ 'type' => 'submit', 'value' => 'Deploy!', 'name' => 'submit', :id => 'submit' }


@@ deployed
- if @pushr.success
%div.success
%h2
Application deployed successfully.
%form{ 'action' => "", :method => 'get' }
%p
%input{ 'type' => 'submit', 'value' => 'Return to index' }
%pre
= @pushr.cap_output
- else
%div.failure
%h2
There were errors when deploying the application!
%form{ 'action' => "", :method => 'get' }
%p
%input{ 'type' => 'submit', 'value' => 'Return to index' }
%pre
= @pushr.cap_output

@@ style
body
:color #000
:background #f8f8f8
:font-size 90%
:font-family Helvetica, Tahoma, sans-serif
:line-height 1.5
:padding 10%
:text-align center
div
:border 4px solid #ccc
:padding 3em
div h2
:margin-bottom 1em
a
:color #000
div.success h2
:color #128B45
div.failure h2
:color #E21F3A
pre
:color #444
:font-size 95%
:text-align left
:word-wrap break-word
:white-space pre
:white-space pre-wrap
:white-space -moz-pre-wrap
:white-space -o-pre-wrap
Something went wrong with that request. Please try again.