Class: Hercules::GitHandler

Inherits:
Object
  • Object
show all
Defined in:
lib/git_handler.rb

Overview

Class that handles the git operations.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ GitHandler

We pass an options hash that should contain:

{
'target_directory' => '/home/hercules/hercules.com', 
'repository' => 'git://github.com/diogob/hercules.git',
'master' => { 'checkouts_to_keep' => 2 },
}


14
15
16
17
# File 'lib/git_handler.rb', line 14

def initialize(options)
  @options = options
  @last_commit = nil
end

Instance Attribute Details

#last_commitObject (readonly)

Returns the value of attribute last_commit.



7
8
9
# File 'lib/git_handler.rb', line 7

def last_commit
  @last_commit
end

Instance Method Details

#branches_pathObject

Returns the path to branches’ link directory.



40
41
42
# File 'lib/git_handler.rb', line 40

def branches_path
  "#{@options['target_directory']}/branches"
end

#create_branches_dirObject

Creates and then returns the path to branches’ link directory.



45
46
47
48
# File 'lib/git_handler.rb', line 45

def create_branches_dir
  FileUtils.mkdir_p branches_path
  branches_path
end

#deploy_branch(branch = 'master') {|checkout, branch| ... } ⇒ Object

Deploys the branch. This means it exports it and removes old checkouts upon a successful completion. It also creates the links’ directory and links the checkout.

  • branch is the branch name to be deployed. Defaults to master.

Yields:

  • (checkout, branch)


54
55
56
57
58
59
60
61
62
# File 'lib/git_handler.rb', line 54

def deploy_branch(branch = 'master')
  checkout = export_branch(branch)
  #@todo here we must call the before deploy script
  yield(checkout, branch) if block_given?
  remove_old_checkouts branch
  FileUtils.rm_f("#{create_branches_dir}/#{branch}")
  FileUtils.ln_sf(checkout, "#{branches_path}/#{branch}")
  self
end

#export_branch(branch = 'master') ⇒ Object

Will export the branch to @options/checkouts/ And link it in @options/branches/ It uses the commit’s sha1 as directory name.

  • branch is the branch to be deployed, defaults to master.



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/git_handler.rb', line 23

def export_branch(branch = 'master')
  tmp_dir = "#{@options['target_directory']}/checkouts/#{branch}/.tmp_#{Time.now.strftime("%Y%m%d%H%M%S")}"
  begin
    repo = Git.clone(@options['repository'], tmp_dir, {:depth => 1})
    repo.checkout("origin/#{branch}")
  rescue Exception => e
    FileUtils.rm_rf repo.dir.to_s unless repo.nil?
    raise "Error while cloning #{@options['repository']}: #{e}"
  end
  @last_commit = repo.gcommit('HEAD').sha
  commit_dir = "#{@options['target_directory']}/checkouts/#{branch}/#{@last_commit}"
  Dir.chdir(repo.dir.to_s) { FileUtils.rm_r '.git' }
  FileUtils.mv repo.dir.to_s, commit_dir
  commit_dir
end