1 require File.join(File.dirname(__FILE__), '..', 'vcsrepo')
3 Puppet::Type.type(:vcsrepo).provide(:git, :parent => Puppet::Provider::Vcsrepo) do
4 desc "Supports Git repositories"
6 has_command(:git, 'git') do
7 environment({ 'HOME' => ENV['HOME'] })
10 has_features :bare_repositories, :reference_tracking, :ssh_identity, :multiple_remotes, :user, :depth, :branch, :submodules
13 if @resource.value(:revision) and ensure_bare_or_mirror?
14 fail("Cannot set a revision (#{@resource.value(:revision)}) on a bare repository")
16 if !@resource.value(:source)
17 if @resource.value(:ensure) == :mirror
18 fail("Cannot init repository with mirror option, try bare instead")
21 init_repository(@resource.value(:path))
23 clone_repository(default_url, @resource.value(:path))
26 if @resource.value(:revision)
29 if !ensure_bare_or_mirror? && @resource.value(:submodules) == :true
34 update_owner_and_excludes
38 FileUtils.rm_rf(@resource.value(:path))
41 # Checks to see if the current revision is equal to the revision on the
42 # remote (whether on a branch, tag, or reference)
44 # @return [Boolean] Returns true if the repo is on the latest revision
46 return revision == latest_revision
49 # Just gives the `should` value that we should be setting the repo to if
50 # latest? returns false
52 # @return [String] Returns the target sha/tag/branch
54 if not @resource.value(:revision) and branch = on_branch?
57 return @resource.value(:revision)
61 # Get the current revision of the repo (tag/branch/sha)
63 # @return [String] Returns the branch/tag if the current sha matches the
64 # remote; otherwise returns the current sha.
66 #HEAD is the default, but lets just be explicit here.
70 # Is passed the desired reference, whether a tag, rev, or branch. Should
71 # handle transitions from a rev/branch/tag to a rev/branch/tag. Detached
72 # heads should be treated like bare revisions.
74 # @param [String] desired The desired revision to which the repo should be
76 def revision=(desired)
77 #just checkout tags and shas; fetch has already happened so they should be updated.
79 #branches require more work.
80 if local_branch_revision?(desired)
81 #reset instead of pull to avoid merge conflicts. assuming remote is
82 #updated and authoritative.
83 #TODO might be worthwhile to have an allow_local_changes param to decide
84 #whether to reset or pull when we're ensuring latest.
85 if @resource.value(:source)
86 at_path { git_with_identity('reset', '--hard', "#{@resource.value(:remote)}/#{desired}") }
88 at_path { git_with_identity('reset', '--hard', "#{desired}") }
91 #TODO Would this ever reach here if it is bare?
92 if !ensure_bare_or_mirror? && @resource.value(:submodules) == :true
95 update_owner_and_excludes
99 bare_git_config_exists? && !working_copy_exists?
102 def ensure_bare_or_mirror?
103 [:bare, :mirror].include? @resource.value(:ensure)
106 # If :source is set to a hash (for supporting multiple remotes),
107 # we search for the URL for :remote. If it doesn't exist,
108 # we throw an error. If :source is just a string, we use that
109 # value for the default URL.
111 if @resource.value(:source).is_a?(Hash)
112 if @resource.value(:source).has_key?(@resource.value(:remote))
113 @resource.value(:source)[@resource.value(:remote)]
115 fail("You must specify the URL for #{@resource.value(:remote)} in the :source hash")
118 @resource.value(:source)
122 def working_copy_exists?
123 if @resource.value(:source) and File.exists?(File.join(@resource.value(:path), '.git', 'config'))
124 File.readlines(File.join(@resource.value(:path), '.git', 'config')).grep(/#{Regexp.escape(default_url)}/).any?
126 File.directory?(File.join(@resource.value(:path), '.git'))
131 working_copy_exists? || bare_exists?
134 def update_remote_url(remote_name, remote_url)
136 current = git_with_identity('config', '-l')
138 unless remote_url.nil?
139 # Check if remote exists at all, regardless of URL.
140 # If remote doesn't exist, add it
141 if not current.include? "remote.#{remote_name}.url"
142 git_with_identity('remote','add', remote_name, remote_url)
145 # If remote exists, but URL doesn't match, update URL
146 elsif not current.include? "remote.#{remote_name}.url=#{remote_url}"
147 git_with_identity('remote','set-url', remote_name, remote_url)
159 # If supplied source is a hash of remote name and remote url pairs, then
160 # we loop around the hash. Otherwise, we assume single url specified
162 if @resource.value(:source).is_a?(Hash)
163 @resource.value(:source).keys.sort.each do |remote_name|
164 remote_url = @resource.value(:source)[remote_name]
165 at_path { do_update |= update_remote_url(remote_name, remote_url) }
168 at_path { do_update |= update_remote_url(@resource.value(:remote), @resource.value(:source)) }
171 # If at least one remote was added or updated, then we must
172 # call the 'git remote update' command
174 at_path { git_with_identity('remote','update') }
179 def update_references
182 git_with_identity('fetch', @resource.value(:remote))
183 git_with_identity('fetch', '--tags', @resource.value(:remote))
184 update_owner_and_excludes
191 Dir.chdir(@resource.value(:path)){ system('git rev-parse > /dev/null 2>&1')}
194 def bare_git_config_exists?
195 File.exist?(File.join(@resource.value(:path), 'config')) && valid_repo?
198 # @!visibility private
199 def clone_repository(source, path)
202 if @resource.value(:depth) and @resource.value(:depth).to_i > 0
203 args.push('--depth', @resource.value(:depth).to_s)
204 if @resource.value(:revision)
205 args.push('--branch', @resource.value(:revision).to_s)
208 if @resource.value(:branch)
209 args.push('--branch', @resource.value(:branch).to_s)
212 case @resource.value(:ensure)
213 when :bare then args << '--bare'
214 when :mirror then args << '--mirror'
217 if @resource.value(:remote) != 'origin'
218 args.push('--origin', @resource.value(:remote))
220 if !working_copy_exists?
221 args.push(source, path)
223 git_with_identity(*args)
226 notice "Repo has already been cloned"
230 # @!visibility private
232 if path_exists? and not path_empty?
233 if @resource.value(:force) && !valid_repo?
234 notice "Removing %s to replace with vcsrepo." % @resource.value(:path)
237 raise Puppet::Error, "Could not create repository (non-repository at path)"
242 # @!visibility private
243 def init_repository(path)
245 if @resource.value(:ensure) == :bare && working_copy_exists?
246 convert_working_copy_to_bare
247 elsif @resource.value(:ensure) == :present && bare_exists?
248 convert_bare_to_working_copy
251 FileUtils.mkdir(@resource.value(:path))
252 FileUtils.chown(@resource.value(:user), nil, @resource.value(:path)) if @resource.value(:user)
254 if @resource.value(:ensure) == :bare
258 git_with_identity(*args)
263 # Convert working copy to bare
269 # @!visibility private
270 def convert_working_copy_to_bare
271 notice "Converting working copy repository to bare repository"
272 FileUtils.mv(File.join(@resource.value(:path), '.git'), tempdir)
273 FileUtils.rm_rf(@resource.value(:path))
274 FileUtils.mv(tempdir, @resource.value(:path))
277 # Convert bare to working copy
283 # @!visibility private
284 def convert_bare_to_working_copy
285 notice "Converting bare repository to working copy repository"
286 FileUtils.mv(@resource.value(:path), tempdir)
287 FileUtils.mkdir(@resource.value(:path))
288 FileUtils.mv(tempdir, File.join(@resource.value(:path), '.git'))
289 if commits_in?(File.join(@resource.value(:path), '.git'))
291 git_with_identity('checkout', '--force')
292 update_owner_and_excludes
296 # @!visibility private
297 def commits_in?(dot_git)
298 Dir.glob(File.join(dot_git, 'objects/info/*'), File::FNM_DOTMATCH) do |e|
299 return true unless %w(. ..).include?(File::basename(e))
304 # Will checkout a rev/branch/tag using the locally cached versions. Does not
305 # handle upstream branch changes
306 # @!visibility private
307 def checkout(revision = @resource.value(:revision))
308 if !local_branch_revision?(revision) && remote_branch_revision?(revision)
309 #non-locally existant branches (perhaps switching to a branch that has never been checked out)
310 at_path { git_with_identity('checkout', '--force', '-b', revision, '--track', "#{@resource.value(:remote)}/#{revision}") }
312 #tags, locally existant branches (perhaps outdated), and shas
313 at_path { git_with_identity('checkout', '--force', revision) }
317 # @!visibility private
320 git_with_identity('reset', '--hard', desired)
324 # @!visibility private
325 def update_submodules
327 git_with_identity('submodule', 'update', '--init', '--recursive')
331 # Determins if the branch exists at the upstream but has not yet been locally committed
332 # @!visibility private
333 def remote_branch_revision?(revision = @resource.value(:revision))
334 # git < 1.6 returns '#{@resource.value(:remote)}/#{revision}'
335 # git 1.6+ returns 'remotes/#{@resource.value(:remote)}/#{revision}'
336 branch = at_path { branches.grep /(remotes\/)?#{@resource.value(:remote)}\/#{revision}$/ }
337 branch unless branch.empty?
340 # Determins if the branch is already cached locally
341 # @!visibility private
342 def local_branch_revision?(revision = @resource.value(:revision))
343 at_path { branches.include?(revision) }
346 # @!visibility private
347 def tag_revision?(revision = @resource.value(:revision))
348 at_path { tags.include?(revision) }
351 # @!visibility private
353 at_path { git_with_identity('branch', '-a') }.gsub('*', ' ').split(/\n/).map { |line| line.strip }
356 # git < 2.4 returns 'detached from'
357 # git 2.4+ returns 'HEAD detached at'
358 # @!visibility private
361 matches = git_with_identity('branch', '-a').match /\*\s+(.*)/
362 matches[1] unless matches[1].match /(\(detached from|\(HEAD detached at|\(no branch)/
366 # @!visibility private
368 at_path { git_with_identity('tag', '-l') }.split(/\n/).map { |line| line.strip }
371 # @!visibility private
373 # Excludes may be an Array or a String.
375 open('.git/info/exclude', 'w') do |f|
376 if @resource.value(:excludes).respond_to?(:each)
377 @resource.value(:excludes).each { |ex| f.puts ex }
379 f.puts @resource.value(:excludes)
385 # Finds the latest revision or sha of the current branch if on a branch, or
387 # @note Calls create which can forcibly destroy and re-clone the repo if
391 # @!visibility private
392 # @return [String] Returns the output of get_revision
394 #TODO Why is create called here anyway?
395 create if @resource.value(:force) && working_copy_exists?
396 create if !working_copy_exists?
398 if branch = on_branch?
399 return get_revision("#{@resource.value(:remote)}/#{branch}")
405 # Returns the current revision given if the revision is a tag or branch and
406 # matches the current sha. If the current sha does not match the sha of a tag
407 # or branch, then it will just return the sha (ie, is not in sync)
409 # @!visibility private
411 # @param [String] rev The revision of which to check if it is current
412 # @return [String] Returns the tag/branch of the current repo if it's up to
413 # date; otherwise returns the sha of the requested revision.
414 def get_revision(rev = 'HEAD')
415 if @resource.value(:source)
418 status = at_path { git_with_identity('status')}
419 is_it_new = status =~ /Initial commit/
421 status =~ /On branch (.*)/
426 current = at_path { git_with_identity('rev-parse', rev).strip }
427 if @resource.value(:revision)
429 # git-rev-parse will give you the hash of the tag object itself rather
430 # than the commit it points to by default. Using tag^0 will return the
432 canonical = at_path { git_with_identity('rev-parse', "#{@resource.value(:revision)}^0").strip }
433 elsif local_branch_revision?
434 canonical = at_path { git_with_identity('rev-parse', @resource.value(:revision)).strip }
435 elsif remote_branch_revision?
436 canonical = at_path { git_with_identity('rev-parse', "#{@resource.value(:remote)}/#{@resource.value(:revision)}").strip }
438 #look for a sha (could match invalid shas)
439 canonical = at_path { git_with_identity('rev-parse', '--revs-only', @resource.value(:revision)).strip }
441 fail("#{@resource.value(:revision)} is not a local or remote ref") if canonical.nil? or canonical.empty?
442 current = @resource.value(:revision) if current == canonical
447 # @!visibility private
448 def update_owner_and_excludes
449 if @resource.value(:owner) or @resource.value(:group)
452 if @resource.value(:excludes)
457 # @!visibility private
458 def git_with_identity(*args)
459 if @resource.value(:identity)
460 Tempfile.open('git-helper', Puppet[:statedir]) do |f|
462 f.puts 'export SSH_AUTH_SOCKET='
463 f.puts "exec ssh -oStrictHostKeyChecking=no -oPasswordAuthentication=no -oKbdInteractiveAuthentication=no -oChallengeResponseAuthentication=no -oConnectTimeout=120 -i #{@resource.value(:identity)} $*"
466 FileUtils.chmod(0755, f.path)
467 env_save = ENV['GIT_SSH']
468 ENV['GIT_SSH'] = f.path
472 ENV['GIT_SSH'] = env_save
476 elsif @resource.value(:user) and @resource.value(:user) != Facter['id'].value
477 env = Etc.getpwnam(@resource.value(:user))
478 Puppet::Util::Execution.execute("git #{args.join(' ')}", :uid => @resource.value(:user), :failonfail => true, :custom_environment => {'HOME' => env['dir']}, :combine => true)