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"
8 has_features :bare_repositories, :reference_tracking, :ssh_identity, :multiple_remotes, :user, :depth, :submodules
11 if @resource.value(:revision) and @resource.value(:ensure) == :bare
12 fail("Cannot set a revision (#{@resource.value(:revision)}) on a bare repository")
14 if !@resource.value(:source)
15 init_repository(@resource.value(:path))
17 clone_repository(default_url, @resource.value(:path))
20 if @resource.value(:revision)
23 if @resource.value(:ensure) != :bare && @resource.value(:submodules) == :true
28 update_owner_and_excludes
32 FileUtils.rm_rf(@resource.value(:path))
35 # Checks to see if the current revision is equal to the revision on the
36 # remote (whether on a branch, tag, or reference)
38 # @return [Boolean] Returns true if the repo is on the latest revision
40 return revision == latest_revision
43 # Just gives the `should` value that we should be setting the repo to if
44 # latest? returns false
46 # @return [String] Returns the target sha/tag/branch
48 @resource.value(:revision)
51 # Get the current revision of the repo (tag/branch/sha)
53 # @return [String] Returns the branch/tag if the current sha matches the
54 # remote; otherwise returns the current sha.
56 #HEAD is the default, but lets just be explicit here.
60 # Is passed the desired reference, whether a tag, rev, or branch. Should
61 # handle transitions from a rev/branch/tag to a rev/branch/tag. Detached
62 # heads should be treated like bare revisions.
64 # @param [String] desired The desired revision to which the repo should be
66 def revision=(desired)
67 #just checkout tags and shas; fetch has already happened so they should be updated.
69 #branches require more work.
70 if local_branch_revision?(desired)
71 #reset instead of pull to avoid merge conflicts. assuming remote is
72 #updated and authoritative.
73 #TODO might be worthwhile to have an allow_local_changes param to decide
74 #whether to reset or pull when we're ensuring latest.
75 at_path { git_with_identity('reset', '--hard', "#{@resource.value(:remote)}/#{desired}") }
77 #TODO Would this ever reach here if it is bare?
78 if @resource.value(:ensure) != :bare
81 update_owner_and_excludes
85 bare_git_config_exists? && !working_copy_exists?
88 # If :source is set to a hash (for supporting multiple remotes),
89 # we search for the URL for :remote. If it doesn't exist,
90 # we throw an error. If :source is just a string, we use that
91 # value for the default URL.
93 if @resource.value(:source).is_a?(Hash)
94 if @resource.value(:source).has_key?(@resource.value(:remote))
95 @resource.value(:source)[@resource.value(:remote)]
97 fail("You must specify the URL for #{@resource.value(:remote)} in the :source hash")
100 @resource.value(:source)
104 def working_copy_exists?
105 if @resource.value(:source) and File.exists?(File.join(@resource.value(:path), '.git', 'config'))
106 File.readlines(File.join(@resource.value(:path), '.git', 'config')).grep(/#{default_url}/).any?
108 File.directory?(File.join(@resource.value(:path), '.git'))
113 working_copy_exists? || bare_exists?
116 def update_remote_url(remote_name, remote_url)
118 current = git_with_identity('config', '-l')
120 unless remote_url.nil?
121 # Check if remote exists at all, regardless of URL.
122 # If remote doesn't exist, add it
123 if not current.include? "remote.#{remote_name}.url"
124 git_with_identity('remote','add', remote_name, remote_url)
127 # If remote exists, but URL doesn't match, update URL
128 elsif not current.include? "remote.#{remote_name}.url=#{remote_url}"
129 git_with_identity('remote','set-url', remote_name, remote_url)
141 # If supplied source is a hash of remote name and remote url pairs, then
142 # we loop around the hash. Otherwise, we assume single url specified
144 if @resource.value(:source).is_a?(Hash)
145 @resource.value(:source).each do |remote_name, remote_url|
146 at_path { do_update |= update_remote_url(remote_name, remote_url) }
149 at_path { do_update |= update_remote_url(@resource.value(:remote), @resource.value(:source)) }
152 # If at least one remote was added or updated, then we must
153 # call the 'git remote update' command
155 at_path { git_with_identity('remote','update') }
160 def update_references
163 git_with_identity('fetch', @resource.value(:remote))
164 git_with_identity('fetch', '--tags', @resource.value(:remote))
165 update_owner_and_excludes
171 # @!visibility private
172 def bare_git_config_exists?
173 File.exist?(File.join(@resource.value(:path), 'config'))
176 # @!visibility private
177 def clone_repository(source, path)
180 if @resource.value(:depth) and @resource.value(:depth).to_i > 0
181 args.push('--depth', @resource.value(:depth).to_s)
183 if @resource.value(:ensure) == :bare
186 if @resource.value(:remote) != 'origin'
187 args.push('--origin', @resource.value(:remote))
189 if !working_copy_exists?
190 args.push(source, path)
192 git_with_identity(*args)
195 notice "Repo has already been cloned"
199 # @!visibility private
201 if path_exists? and not path_empty?
202 if @resource.value(:force)
203 notice "Removing %s to replace with vcsrepo." % @resource.value(:path)
206 raise Puppet::Error, "Could not create repository (non-repository at path)"
211 # @!visibility private
212 def init_repository(path)
214 if @resource.value(:ensure) == :bare && working_copy_exists?
215 convert_working_copy_to_bare
216 elsif @resource.value(:ensure) == :present && bare_exists?
217 convert_bare_to_working_copy
220 FileUtils.mkdir(@resource.value(:path))
221 FileUtils.chown(@resource.value(:user), nil, @resource.value(:path)) if @resource.value(:user)
223 if @resource.value(:ensure) == :bare
227 git_with_identity(*args)
232 # Convert working copy to bare
238 # @!visibility private
239 def convert_working_copy_to_bare
240 notice "Converting working copy repository to bare repository"
241 FileUtils.mv(File.join(@resource.value(:path), '.git'), tempdir)
242 FileUtils.rm_rf(@resource.value(:path))
243 FileUtils.mv(tempdir, @resource.value(:path))
246 # Convert bare to working copy
252 # @!visibility private
253 def convert_bare_to_working_copy
254 notice "Converting bare repository to working copy repository"
255 FileUtils.mv(@resource.value(:path), tempdir)
256 FileUtils.mkdir(@resource.value(:path))
257 FileUtils.mv(tempdir, File.join(@resource.value(:path), '.git'))
258 if commits_in?(File.join(@resource.value(:path), '.git'))
260 git_with_identity('checkout', '--force')
261 update_owner_and_excludes
265 # @!visibility private
266 def commits_in?(dot_git)
267 Dir.glob(File.join(dot_git, 'objects/info/*'), File::FNM_DOTMATCH) do |e|
268 return true unless %w(. ..).include?(File::basename(e))
273 # Will checkout a rev/branch/tag using the locally cached versions. Does not
274 # handle upstream branch changes
275 # @!visibility private
276 def checkout(revision = @resource.value(:revision))
277 if !local_branch_revision? && remote_branch_revision?
278 #non-locally existant branches (perhaps switching to a branch that has never been checked out)
279 at_path { git_with_identity('checkout', '--force', '-b', revision, '--track', "#{@resource.value(:remote)}/#{revision}") }
281 #tags, locally existant branches (perhaps outdated), and shas
282 at_path { git_with_identity('checkout', '--force', revision) }
286 # @!visibility private
289 git_with_identity('reset', '--hard', desired)
293 # @!visibility private
294 def update_submodules
296 git_with_identity('submodule', 'update', '--init', '--recursive')
300 # Determins if the branch exists at the upstream but has not yet been locally committed
301 # @!visibility private
302 def remote_branch_revision?(revision = @resource.value(:revision))
303 # git < 1.6 returns '#{@resource.value(:remote)}/#{revision}'
304 # git 1.6+ returns 'remotes/#{@resource.value(:remote)}/#{revision}'
305 branch = at_path { branches.grep /(remotes\/)?#{@resource.value(:remote)}\/#{revision}/ }
306 branch unless branch.empty?
309 # Determins if the branch is already cached locally
310 # @!visibility private
311 def local_branch_revision?(revision = @resource.value(:revision))
312 at_path { branches.include?(revision) }
315 # @!visibility private
316 def tag_revision?(revision = @resource.value(:revision))
317 at_path { tags.include?(revision) }
320 # @!visibility private
322 at_path { git_with_identity('branch', '-a') }.gsub('*', ' ').split(/\n/).map { |line| line.strip }
325 # @!visibility private
328 matches = git_with_identity('branch', '-a').match /\*\s+(.*)/
329 matches[1] unless matches[1].match /(\(detached from|\(no branch)/
333 # @!visibility private
335 at_path { git_with_identity('tag', '-l') }.split(/\n/).map { |line| line.strip }
338 # @!visibility private
340 # Excludes may be an Array or a String.
342 open('.git/info/exclude', 'w') do |f|
343 if @resource.value(:excludes).respond_to?(:each)
344 @resource.value(:excludes).each { |ex| f.puts ex }
346 f.puts @resource.value(:excludes)
352 # Finds the latest revision or sha of the current branch if on a branch, or
354 # @note Calls create which can forcibly destroy and re-clone the repo if
358 # @!visibility private
359 # @return [String] Returns the output of get_revision
361 #TODO Why is create called here anyway?
362 create if @resource.value(:force) && working_copy_exists?
363 create if !working_copy_exists?
365 if branch = on_branch?
366 return get_revision("#{@resource.value(:remote)}/#{branch}")
372 # Returns the current revision given if the revision is a tag or branch and
373 # matches the current sha. If the current sha does not match the sha of a tag
374 # or branch, then it will just return the sha (ie, is not in sync)
376 # @!visibility private
378 # @param [String] rev The revision of which to check if it is current
379 # @return [String] Returns the tag/branch of the current repo if it's up to
380 # date; otherwise returns the sha of the requested revision.
381 def get_revision(rev = 'HEAD')
383 current = at_path { git_with_identity('rev-parse', rev).strip }
384 if @resource.value(:revision)
386 # git-rev-parse will give you the hash of the tag object itself rather
387 # than the commit it points to by default. Using tag^0 will return the
389 canonical = at_path { git_with_identity('rev-parse', "#{@resource.value(:revision)}^0").strip }
390 elsif local_branch_revision?
391 canonical = at_path { git_with_identity('rev-parse', @resource.value(:revision)).strip }
392 elsif remote_branch_revision?
393 canonical = at_path { git_with_identity('rev-parse', "#{@resource.value(:remote)}/#{@resource.value(:revision)}").strip }
395 #look for a sha (could match invalid shas)
396 canonical = at_path { git_with_identity('rev-parse', '--revs-only', @resource.value(:revision)).strip }
398 fail("#{@resource.value(:revision)} is not a local or remote ref") if canonical.nil? or canonical.empty?
399 current = @resource.value(:revision) if current == canonical
404 # @!visibility private
405 def update_owner_and_excludes
406 if @resource.value(:owner) or @resource.value(:group)
409 if @resource.value(:excludes)
414 # @!visibility private
415 def git_with_identity(*args)
416 if @resource.value(:identity)
417 Tempfile.open('git-helper') do |f|
419 f.puts "exec ssh -oStrictHostKeyChecking=no -oPasswordAuthentication=no -oKbdInteractiveAuthentication=no -oChallengeResponseAuthentication=no -oConnectTimeout=120 -i #{@resource.value(:identity)} $*"
422 FileUtils.chmod(0755, f.path)
423 env_save = ENV['GIT_SSH']
424 ENV['GIT_SSH'] = f.path
428 ENV['GIT_SSH'] = env_save
432 elsif @resource.value(:user) and @resource.value(:user) != Facter['id'].value
433 Puppet::Util::Execution.execute("git #{args.join(' ')}", :uid => @resource.value(:user), :failonfail => true)