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).keys.sort.each do |remote_name|
146 remote_url = @resource.value(:source)[remote_name]
147 at_path { do_update |= update_remote_url(remote_name, remote_url) }
150 at_path { do_update |= update_remote_url(@resource.value(:remote), @resource.value(:source)) }
153 # If at least one remote was added or updated, then we must
154 # call the 'git remote update' command
156 at_path { git_with_identity('remote','update') }
161 def update_references
164 git_with_identity('fetch', @resource.value(:remote))
165 git_with_identity('fetch', '--tags', @resource.value(:remote))
166 update_owner_and_excludes
172 # @!visibility private
173 def bare_git_config_exists?
174 File.exist?(File.join(@resource.value(:path), 'config'))
177 # @!visibility private
178 def clone_repository(source, path)
181 if @resource.value(:depth) and @resource.value(:depth).to_i > 0
182 args.push('--depth', @resource.value(:depth).to_s)
184 if @resource.value(:ensure) == :bare
187 if @resource.value(:remote) != 'origin'
188 args.push('--origin', @resource.value(:remote))
190 if !working_copy_exists?
191 args.push(source, path)
193 git_with_identity(*args)
196 notice "Repo has already been cloned"
200 # @!visibility private
202 if path_exists? and not path_empty?
203 if @resource.value(:force)
204 notice "Removing %s to replace with vcsrepo." % @resource.value(:path)
207 raise Puppet::Error, "Could not create repository (non-repository at path)"
212 # @!visibility private
213 def init_repository(path)
215 if @resource.value(:ensure) == :bare && working_copy_exists?
216 convert_working_copy_to_bare
217 elsif @resource.value(:ensure) == :present && bare_exists?
218 convert_bare_to_working_copy
221 FileUtils.mkdir(@resource.value(:path))
222 FileUtils.chown(@resource.value(:user), nil, @resource.value(:path)) if @resource.value(:user)
224 if @resource.value(:ensure) == :bare
228 git_with_identity(*args)
233 # Convert working copy to bare
239 # @!visibility private
240 def convert_working_copy_to_bare
241 notice "Converting working copy repository to bare repository"
242 FileUtils.mv(File.join(@resource.value(:path), '.git'), tempdir)
243 FileUtils.rm_rf(@resource.value(:path))
244 FileUtils.mv(tempdir, @resource.value(:path))
247 # Convert bare to working copy
253 # @!visibility private
254 def convert_bare_to_working_copy
255 notice "Converting bare repository to working copy repository"
256 FileUtils.mv(@resource.value(:path), tempdir)
257 FileUtils.mkdir(@resource.value(:path))
258 FileUtils.mv(tempdir, File.join(@resource.value(:path), '.git'))
259 if commits_in?(File.join(@resource.value(:path), '.git'))
261 git_with_identity('checkout', '--force')
262 update_owner_and_excludes
266 # @!visibility private
267 def commits_in?(dot_git)
268 Dir.glob(File.join(dot_git, 'objects/info/*'), File::FNM_DOTMATCH) do |e|
269 return true unless %w(. ..).include?(File::basename(e))
274 # Will checkout a rev/branch/tag using the locally cached versions. Does not
275 # handle upstream branch changes
276 # @!visibility private
277 def checkout(revision = @resource.value(:revision))
278 if !local_branch_revision? && remote_branch_revision?
279 #non-locally existant branches (perhaps switching to a branch that has never been checked out)
280 at_path { git_with_identity('checkout', '--force', '-b', revision, '--track', "#{@resource.value(:remote)}/#{revision}") }
282 #tags, locally existant branches (perhaps outdated), and shas
283 at_path { git_with_identity('checkout', '--force', revision) }
287 # @!visibility private
290 git_with_identity('reset', '--hard', desired)
294 # @!visibility private
295 def update_submodules
297 git_with_identity('submodule', 'update', '--init', '--recursive')
301 # Determins if the branch exists at the upstream but has not yet been locally committed
302 # @!visibility private
303 def remote_branch_revision?(revision = @resource.value(:revision))
304 # git < 1.6 returns '#{@resource.value(:remote)}/#{revision}'
305 # git 1.6+ returns 'remotes/#{@resource.value(:remote)}/#{revision}'
306 branch = at_path { branches.grep /(remotes\/)?#{@resource.value(:remote)}\/#{revision}/ }
307 branch unless branch.empty?
310 # Determins if the branch is already cached locally
311 # @!visibility private
312 def local_branch_revision?(revision = @resource.value(:revision))
313 at_path { branches.include?(revision) }
316 # @!visibility private
317 def tag_revision?(revision = @resource.value(:revision))
318 at_path { tags.include?(revision) }
321 # @!visibility private
323 at_path { git_with_identity('branch', '-a') }.gsub('*', ' ').split(/\n/).map { |line| line.strip }
326 # @!visibility private
329 matches = git_with_identity('branch', '-a').match /\*\s+(.*)/
330 matches[1] unless matches[1].match /(\(detached from|\(no branch)/
334 # @!visibility private
336 at_path { git_with_identity('tag', '-l') }.split(/\n/).map { |line| line.strip }
339 # @!visibility private
341 # Excludes may be an Array or a String.
343 open('.git/info/exclude', 'w') do |f|
344 if @resource.value(:excludes).respond_to?(:each)
345 @resource.value(:excludes).each { |ex| f.puts ex }
347 f.puts @resource.value(:excludes)
353 # Finds the latest revision or sha of the current branch if on a branch, or
355 # @note Calls create which can forcibly destroy and re-clone the repo if
359 # @!visibility private
360 # @return [String] Returns the output of get_revision
362 #TODO Why is create called here anyway?
363 create if @resource.value(:force) && working_copy_exists?
364 create if !working_copy_exists?
366 if branch = on_branch?
367 return get_revision("#{@resource.value(:remote)}/#{branch}")
373 # Returns the current revision given if the revision is a tag or branch and
374 # matches the current sha. If the current sha does not match the sha of a tag
375 # or branch, then it will just return the sha (ie, is not in sync)
377 # @!visibility private
379 # @param [String] rev The revision of which to check if it is current
380 # @return [String] Returns the tag/branch of the current repo if it's up to
381 # date; otherwise returns the sha of the requested revision.
382 def get_revision(rev = 'HEAD')
384 current = at_path { git_with_identity('rev-parse', rev).strip }
385 if @resource.value(:revision)
387 # git-rev-parse will give you the hash of the tag object itself rather
388 # than the commit it points to by default. Using tag^0 will return the
390 canonical = at_path { git_with_identity('rev-parse', "#{@resource.value(:revision)}^0").strip }
391 elsif local_branch_revision?
392 canonical = at_path { git_with_identity('rev-parse', @resource.value(:revision)).strip }
393 elsif remote_branch_revision?
394 canonical = at_path { git_with_identity('rev-parse', "#{@resource.value(:remote)}/#{@resource.value(:revision)}").strip }
396 #look for a sha (could match invalid shas)
397 canonical = at_path { git_with_identity('rev-parse', '--revs-only', @resource.value(:revision)).strip }
399 fail("#{@resource.value(:revision)} is not a local or remote ref") if canonical.nil? or canonical.empty?
400 current = @resource.value(:revision) if current == canonical
405 # @!visibility private
406 def update_owner_and_excludes
407 if @resource.value(:owner) or @resource.value(:group)
410 if @resource.value(:excludes)
415 # @!visibility private
416 def git_with_identity(*args)
417 if @resource.value(:identity)
418 Tempfile.open('git-helper') do |f|
420 f.puts "exec ssh -oStrictHostKeyChecking=no -oPasswordAuthentication=no -oKbdInteractiveAuthentication=no -oChallengeResponseAuthentication=no -oConnectTimeout=120 -i #{@resource.value(:identity)} $*"
423 FileUtils.chmod(0755, f.path)
424 env_save = ENV['GIT_SSH']
425 ENV['GIT_SSH'] = f.path
429 ENV['GIT_SSH'] = env_save
433 elsif @resource.value(:user) and @resource.value(:user) != Facter['id'].value
434 Puppet::Util::Execution.execute("git #{args.join(' ')}", :uid => @resource.value(:user), :failonfail => true)