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, :branch, :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(:branch)
185 args.push('--branch', @resource.value(:branch).to_s)
187 if @resource.value(:ensure) == :bare
190 if @resource.value(:remote) != 'origin'
191 args.push('--origin', @resource.value(:remote))
193 if !working_copy_exists?
194 args.push(source, path)
196 git_with_identity(*args)
199 notice "Repo has already been cloned"
203 # @!visibility private
205 if path_exists? and not path_empty?
206 if @resource.value(:force)
207 notice "Removing %s to replace with vcsrepo." % @resource.value(:path)
210 raise Puppet::Error, "Could not create repository (non-repository at path)"
215 # @!visibility private
216 def init_repository(path)
218 if @resource.value(:ensure) == :bare && working_copy_exists?
219 convert_working_copy_to_bare
220 elsif @resource.value(:ensure) == :present && bare_exists?
221 convert_bare_to_working_copy
224 FileUtils.mkdir(@resource.value(:path))
225 FileUtils.chown(@resource.value(:user), nil, @resource.value(:path)) if @resource.value(:user)
227 if @resource.value(:ensure) == :bare
231 git_with_identity(*args)
236 # Convert working copy to bare
242 # @!visibility private
243 def convert_working_copy_to_bare
244 notice "Converting working copy repository to bare repository"
245 FileUtils.mv(File.join(@resource.value(:path), '.git'), tempdir)
246 FileUtils.rm_rf(@resource.value(:path))
247 FileUtils.mv(tempdir, @resource.value(:path))
250 # Convert bare to working copy
256 # @!visibility private
257 def convert_bare_to_working_copy
258 notice "Converting bare repository to working copy repository"
259 FileUtils.mv(@resource.value(:path), tempdir)
260 FileUtils.mkdir(@resource.value(:path))
261 FileUtils.mv(tempdir, File.join(@resource.value(:path), '.git'))
262 if commits_in?(File.join(@resource.value(:path), '.git'))
264 git_with_identity('checkout', '--force')
265 update_owner_and_excludes
269 # @!visibility private
270 def commits_in?(dot_git)
271 Dir.glob(File.join(dot_git, 'objects/info/*'), File::FNM_DOTMATCH) do |e|
272 return true unless %w(. ..).include?(File::basename(e))
277 # Will checkout a rev/branch/tag using the locally cached versions. Does not
278 # handle upstream branch changes
279 # @!visibility private
280 def checkout(revision = @resource.value(:revision))
281 if !local_branch_revision? && remote_branch_revision?
282 #non-locally existant branches (perhaps switching to a branch that has never been checked out)
283 at_path { git_with_identity('checkout', '--force', '-b', revision, '--track', "#{@resource.value(:remote)}/#{revision}") }
285 #tags, locally existant branches (perhaps outdated), and shas
286 at_path { git_with_identity('checkout', '--force', revision) }
290 # @!visibility private
293 git_with_identity('reset', '--hard', desired)
297 # @!visibility private
298 def update_submodules
300 git_with_identity('submodule', 'update', '--init', '--recursive')
304 # Determins if the branch exists at the upstream but has not yet been locally committed
305 # @!visibility private
306 def remote_branch_revision?(revision = @resource.value(:revision))
307 # git < 1.6 returns '#{@resource.value(:remote)}/#{revision}'
308 # git 1.6+ returns 'remotes/#{@resource.value(:remote)}/#{revision}'
309 branch = at_path { branches.grep /(remotes\/)?#{@resource.value(:remote)}\/#{revision}/ }
310 branch unless branch.empty?
313 # Determins if the branch is already cached locally
314 # @!visibility private
315 def local_branch_revision?(revision = @resource.value(:revision))
316 at_path { branches.include?(revision) }
319 # @!visibility private
320 def tag_revision?(revision = @resource.value(:revision))
321 at_path { tags.include?(revision) }
324 # @!visibility private
326 at_path { git_with_identity('branch', '-a') }.gsub('*', ' ').split(/\n/).map { |line| line.strip }
329 # @!visibility private
332 matches = git_with_identity('branch', '-a').match /\*\s+(.*)/
333 matches[1] unless matches[1].match /(\(detached from|\(no branch)/
337 # @!visibility private
339 at_path { git_with_identity('tag', '-l') }.split(/\n/).map { |line| line.strip }
342 # @!visibility private
344 # Excludes may be an Array or a String.
346 open('.git/info/exclude', 'w') do |f|
347 if @resource.value(:excludes).respond_to?(:each)
348 @resource.value(:excludes).each { |ex| f.puts ex }
350 f.puts @resource.value(:excludes)
356 # Finds the latest revision or sha of the current branch if on a branch, or
358 # @note Calls create which can forcibly destroy and re-clone the repo if
362 # @!visibility private
363 # @return [String] Returns the output of get_revision
365 #TODO Why is create called here anyway?
366 create if @resource.value(:force) && working_copy_exists?
367 create if !working_copy_exists?
369 if branch = on_branch?
370 return get_revision("#{@resource.value(:remote)}/#{branch}")
376 # Returns the current revision given if the revision is a tag or branch and
377 # matches the current sha. If the current sha does not match the sha of a tag
378 # or branch, then it will just return the sha (ie, is not in sync)
380 # @!visibility private
382 # @param [String] rev The revision of which to check if it is current
383 # @return [String] Returns the tag/branch of the current repo if it's up to
384 # date; otherwise returns the sha of the requested revision.
385 def get_revision(rev = 'HEAD')
387 current = at_path { git_with_identity('rev-parse', rev).strip }
388 if @resource.value(:revision)
390 # git-rev-parse will give you the hash of the tag object itself rather
391 # than the commit it points to by default. Using tag^0 will return the
393 canonical = at_path { git_with_identity('rev-parse', "#{@resource.value(:revision)}^0").strip }
394 elsif local_branch_revision?
395 canonical = at_path { git_with_identity('rev-parse', @resource.value(:revision)).strip }
396 elsif remote_branch_revision?
397 canonical = at_path { git_with_identity('rev-parse', "#{@resource.value(:remote)}/#{@resource.value(:revision)}").strip }
399 #look for a sha (could match invalid shas)
400 canonical = at_path { git_with_identity('rev-parse', '--revs-only', @resource.value(:revision)).strip }
402 fail("#{@resource.value(:revision)} is not a local or remote ref") if canonical.nil? or canonical.empty?
403 current = @resource.value(:revision) if current == canonical
408 # @!visibility private
409 def update_owner_and_excludes
410 if @resource.value(:owner) or @resource.value(:group)
413 if @resource.value(:excludes)
418 # @!visibility private
419 def git_with_identity(*args)
420 if @resource.value(:identity)
421 Tempfile.open('git-helper') do |f|
423 f.puts "exec ssh -oStrictHostKeyChecking=no -oPasswordAuthentication=no -oKbdInteractiveAuthentication=no -oChallengeResponseAuthentication=no -oConnectTimeout=120 -i #{@resource.value(:identity)} $*"
426 FileUtils.chmod(0755, f.path)
427 env_save = ENV['GIT_SSH']
428 ENV['GIT_SSH'] = f.path
432 ENV['GIT_SSH'] = env_save
436 elsif @resource.value(:user) and @resource.value(:user) != Facter['id'].value
437 Puppet::Util::Execution.execute("git #{args.join(' ')}", :uid => @resource.value(:user), :failonfail => true)