Class: Chef::Provider::Git

Inherits:
Chef::Provider show all
Includes:
Mixin::ShellOut
Defined in:
lib/chef/provider/git.rb

Constant Summary

Constants included from Mixin::ShellOut

Mixin::ShellOut::DEPRECATED_OPTIONS

Instance Attribute Summary

Attributes inherited from Chef::Provider

#action, #cookbook_name, #current_resource, #new_resource, #recipe_name, #run_context

Instance Method Summary collapse

Methods included from Mixin::ShellOut

#run_command_compatible_options, #shell_out, #shell_out!

Methods inherited from Chef::Provider

#action_nothing, #cleanup_after_converge, #converge_by, #events, #initialize, #node, #process_resource_requirements, #requirements, #resource_collection, #resource_updated?, #run_action, #set_updated_status, #whyrun_mode?

Methods included from DSL::Recipe

#build_resource, #declare_resource, #describe_self_for_error, #evaluate_resource_definition, #has_resource_definition?, #have_resource_class_for?, #method_missing, #resource_class_for

Methods included from Mixin::ConvertToClassName

#convert_to_class_name, #convert_to_snake_case, #filename_to_qualified_string, #snake_case_basename

Constructor Details

This class inherits a constructor from Chef::Provider

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Chef::DSL::Recipe

Instance Method Details

#action_checkoutObject



76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/chef/provider/git.rb', line 76

def action_checkout
  if target_dir_non_existent_or_empty?
    clone
    if @new_resource.enable_checkout
      checkout
    end
    enable_submodules
    add_remotes
  else
    Chef::Log.debug "#{@new_resource} checkout destination #{@new_resource.destination} already exists or is a non-empty directory"
  end
end

#action_exportObject



89
90
91
92
93
94
# File 'lib/chef/provider/git.rb', line 89

def action_export
  action_checkout
  converge_by("complete the export by removing #{@new_resource.destination}.git after checkout") do
    FileUtils.rm_rf(::File.join(@new_resource.destination,".git"))
  end
end

#action_syncObject



96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/chef/provider/git.rb', line 96

def action_sync
  if existing_git_clone?
    Chef::Log.debug "#{@new_resource} current revision: #{@current_resource.revision} target revision: #{target_revision}"
    unless current_revision_matches_target_revision?
      fetch_updates
      enable_submodules
      Chef::Log.info "#{@new_resource} updated to revision #{target_revision}"
    end
    add_remotes
  else
    action_checkout
  end
end

#add_remotesObject



128
129
130
131
132
133
134
135
136
137
# File 'lib/chef/provider/git.rb', line 128

def add_remotes
  if (@new_resource.additional_remotes.length > 0)
    @new_resource.additional_remotes.each_pair do |remote_name, remote_url|
      converge_by("add remote #{remote_name} from #{remote_url}") do
        Chef::Log.info "#{@new_resource} adding git remote #{remote_name} = #{remote_url}"
        setup_remote_tracking_branches(remote_name, remote_url)
      end
    end
  end
end

#checkoutObject



154
155
156
157
158
159
160
161
162
# File 'lib/chef/provider/git.rb', line 154

def checkout
  sha_ref = target_revision

  converge_by("checkout ref #{sha_ref} branch #{@new_resource.revision}") do
    # checkout into a local branch rather than a detached HEAD
    shell_out!("git checkout -b #{@new_resource.checkout_branch} #{sha_ref}", run_options(:cwd => @new_resource.destination))
    Chef::Log.info "#{@new_resource} checked out branch: #{@new_resource.revision} onto: #{@new_resource.checkout_branch} reference: #{sha_ref}"
  end
end

#cloneObject



139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/chef/provider/git.rb', line 139

def clone
  converge_by("clone from #{@new_resource.repository} into #{@new_resource.destination}") do
    remote = @new_resource.remote

    args = []
    args << "-o #{remote}" unless remote == 'origin'
    args << "--depth #{@new_resource.depth}" if @new_resource.depth

    Chef::Log.info "#{@new_resource} cloning repo #{@new_resource.repository} to #{@new_resource.destination}"

    clone_cmd = "git clone #{args.join(' ')} \"#{@new_resource.repository}\" \"#{@new_resource.destination}\""
    shell_out!(clone_cmd, run_options)
  end
end

#current_revision_matches_target_revision?Boolean

Returns:

  • (Boolean)


220
221
222
# File 'lib/chef/provider/git.rb', line 220

def current_revision_matches_target_revision?
  (!@current_resource.revision.nil?) && (target_revision.strip.to_i(16) == @current_resource.revision.strip.to_i(16))
end

#define_resource_requirementsObject



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
# File 'lib/chef/provider/git.rb', line 44

def define_resource_requirements
  # Parent directory of the target must exist.
  requirements.assert(:checkout, :sync) do |a|
    dirname = ::File.dirname(@new_resource.destination)
    a.assertion { ::File.directory?(dirname) }
    a.whyrun("Directory #{dirname} does not exist, this run will fail unless it has been previously created. Assuming it would have been created.")
    a.failure_message(Chef::Exceptions::MissingParentDirectory,
      "Cannot clone #{@new_resource} to #{@new_resource.destination}, the enclosing directory #{dirname} does not exist")
  end


  requirements.assert(:all_actions) do |a|
    a.assertion { !(@new_resource.revision =~ /^origin\//) }
    a.failure_message Chef::Exceptions::InvalidRemoteGitReference,
       "Deploying remote branches is not supported. " +
       "Specify the remote branch as a local branch for " +
       "the git repository you're deploying from " +
       "(ie: '#{@new_resource.revision.gsub('origin/', '')}' rather than '#{@new_resource.revision}')."
  end

  requirements.assert(:all_actions) do |a|
    # this can't be recovered from in why-run mode, because nothing that
    # we do in the course of a run is likely to create a valid target_revision
    # if we can't resolve it up front.
    a.assertion { target_revision != nil }
    a.failure_message Chef::Exceptions::UnresolvableGitReference,
      "Unable to parse SHA reference for '#{@new_resource.revision}' in repository '#{@new_resource.repository}'. " +
      "Verify your (case-sensitive) repository URL and revision.\n" +
      "`git ls-remote` output: #{@resolved_reference}"
  end
end

#enable_submodulesObject



164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'lib/chef/provider/git.rb', line 164

def enable_submodules
  if @new_resource.enable_submodules
    converge_by("enable git submodules for #{@new_resource}") do
      Chef::Log.info "#{@new_resource} synchronizing git submodules"
      command = "git submodule sync"
      shell_out!(command, run_options(:cwd => @new_resource.destination))
      Chef::Log.info "#{@new_resource} enabling git submodules"
      # the --recursive flag means we require git 1.6.5+ now, see CHEF-1827
      command = "git submodule update --init --recursive"
      shell_out!(command, run_options(:cwd => @new_resource.destination))
    end
  end
end

#existing_git_clone?Boolean

Returns:

  • (Boolean)


111
112
113
# File 'lib/chef/provider/git.rb', line 111

def existing_git_clone?
  ::File.exist?(::File.join(@new_resource.destination, ".git"))
end

#fetch_updatesObject



178
179
180
181
182
183
184
185
186
# File 'lib/chef/provider/git.rb', line 178

def fetch_updates
  setup_remote_tracking_branches(@new_resource.remote, @new_resource.repository)
  converge_by("fetch updates for #{@new_resource.remote}") do
    # since we're in a local branch already, just reset to specified revision rather than merge
    fetch_command = "git fetch #{@new_resource.remote} && git fetch #{@new_resource.remote} --tags && git reset --hard #{target_revision}"
    Chef::Log.debug "Fetching updates from #{new_resource.remote} and resetting to revision #{target_revision}"
    shell_out!(fetch_command, run_options(:cwd => @new_resource.destination))
  end
end

#find_current_revisionObject



119
120
121
122
123
124
125
126
# File 'lib/chef/provider/git.rb', line 119

def find_current_revision
  Chef::Log.debug("#{@new_resource} finding current git revision")
  if ::File.exist?(::File.join(cwd, ".git"))
    # 128 is returned when we're not in a git repo. this is fine
    result = shell_out!('git rev-parse HEAD', :cwd => cwd, :returns => [0,128]).stdout.strip
  end
  sha_hash?(result) ? result : nil
end

#load_current_resourceObject



36
37
38
39
40
41
42
# File 'lib/chef/provider/git.rb', line 36

def load_current_resource
  @resolved_reference = nil
  @current_resource = Chef::Resource::Git.new(@new_resource.name)
  if current_revision = find_current_revision
    @current_resource.revision current_revision
  end
end

#multiple_remotes?(check_remote_command_result) ⇒ Boolean

Returns:

  • (Boolean)


212
213
214
# File 'lib/chef/provider/git.rb', line 212

def multiple_remotes?(check_remote_command_result)
  check_remote_command_result.exitstatus == 2
end

#remote_matches?(remote_url, check_remote_command_result) ⇒ Boolean

Returns:

  • (Boolean)


216
217
218
# File 'lib/chef/provider/git.rb', line 216

def remote_matches?(remote_url, check_remote_command_result)
  check_remote_command_result.stdout.strip.eql?(remote_url)
end

#remote_resolve_referenceObject



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
# File 'lib/chef/provider/git.rb', line 236

def remote_resolve_reference
  Chef::Log.debug("#{@new_resource} resolving remote reference")
  # The sha pointed to by an annotated tag is identified by the
  # '^{}' suffix appended to the tag. In order to resolve
  # annotated tags, we have to search for "revision*" and
  # post-process. Special handling for 'HEAD' to ignore a tag
  # named 'HEAD'.
  rev_pattern = case @new_resource.revision
                when '', 'HEAD'
                  'HEAD'
                else
                  @new_resource.revision + '*'
                end
  command = git("ls-remote \"#{@new_resource.repository}\" \"#{rev_pattern}\"")
  @resolved_reference = shell_out!(command, run_options).stdout
  ref_lines = @resolved_reference.split("\n")
  refs = ref_lines.map { |line| line.split("\t") }
  # first try for ^{} indicating the commit pointed to by an
  # annotated tag
  tagged_commit = refs.find { |m| m[1].end_with?("#{@new_resource.revision}^{}") }
  # It is possible for a user to create a tag named 'HEAD'.
  # Using such a degenerate annotated tag would be very
  # confusing. We avoid the issue by disallowing the use of
  # annotated tags named 'HEAD'.
  if tagged_commit && rev_pattern != 'HEAD'
    tagged_commit[0]
  else
    found = refs.find { |m| m[1].end_with?(@new_resource.revision) }
    if found
      found[0]
    else
      nil
    end
  end
end

#setup_remote_tracking_branches(remote_name, remote_url) ⇒ Object



188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
# File 'lib/chef/provider/git.rb', line 188

def setup_remote_tracking_branches(remote_name, remote_url)
  converge_by("set up remote tracking branches for #{remote_url} at #{remote_name}") do
    Chef::Log.debug "#{@new_resource} configuring remote tracking branches for repository #{remote_url} "+
      "at remote #{remote_name}"
    check_remote_command = "git config --get remote.#{remote_name}.url"
    remote_status = shell_out!(check_remote_command, run_options(:cwd => @new_resource.destination, :returns => [0,1,2]))
    case remote_status.exitstatus
    when 0, 2
      # * Status 0 means that we already have a remote with this name, so we should update the url
      #   if it doesn't match the url we want.
      # * Status 2 means that we have multiple urls assigned to the same remote (not a good idea)
      #   which we can fix by replacing them all with our target url (hence the --replace-all option)

      if multiple_remotes?(remote_status) || !remote_matches?(remote_url,remote_status)
        update_remote_url_command = "git config --replace-all remote.#{remote_name}.url #{remote_url}"
        shell_out!(update_remote_url_command, run_options(:cwd => @new_resource.destination))
      end
    when 1
      add_remote_command = "git remote add #{remote_name} #{remote_url}"
      shell_out!(add_remote_command, run_options(:cwd => @new_resource.destination))
    end
  end
end

#target_dir_non_existent_or_empty?Boolean

Returns:

  • (Boolean)


115
116
117
# File 'lib/chef/provider/git.rb', line 115

def target_dir_non_existent_or_empty?
  !::File.exist?(@new_resource.destination) || Dir.entries(@new_resource.destination).sort == ['.','..']
end

#target_revisionObject Also known as: revision_slug



224
225
226
227
228
229
230
231
232
# File 'lib/chef/provider/git.rb', line 224

def target_revision
  @target_revision ||= begin
    if sha_hash?(@new_resource.revision)
      @target_revision = @new_resource.revision
    else
      @target_revision = remote_resolve_reference
    end
  end
end

#whyrun_supported?Boolean

Returns:

  • (Boolean)


32
33
34
# File 'lib/chef/provider/git.rb', line 32

def whyrun_supported?
  true
end