Debian Codegraph @

lib/bundler/source/git/git_proxy.rb

raw
1 # frozen_string_literal: true
2
3 module Bundler
4 class Source
5 class Git
6 class GitNotInstalledError < GitError
7 def initialize
8 msg = String.new
9 msg << "You need to install git to be able to use gems from git repositories. "
10 msg << "For help installing git, please refer to GitHub's tutorial at https://help.github.com/articles/set-up-git"
11 super msg
12 end
13 end
14
15 class GitNotAllowedError < GitError
16 def initialize(command)
17 msg = String.new
18 msg << "Bundler is trying to run `#{command}` at runtime. You probably need to run `bundle install`. However, "
19 msg << "this error message could probably be more useful. Please submit a ticket at https://github.com/rubygems/rubygems/issues/new?labels=Bundler&template=bundler-related-issue.md "
20 msg << "with steps to reproduce as well as the following\n\nCALLER: #{caller.join("\n")}"
21 super msg
22 end
23 end
24
25 class GitCommandError < GitError
26 attr_reader :command
27
28 def initialize(command, path, extra_info = nil)
29 @command = command
30
31 msg = String.new("Git error: command `#{command}`")
32 msg << " in directory #{path}" if path
33 msg << " has failed."
34 msg << "\n#{extra_info}" if extra_info
35 super msg
36 end
37 end
38
39 class MissingGitRevisionError < GitCommandError
40 def initialize(command, destination_path, ref, repo)
41 msg = "Revision #{ref} does not exist in the repository #{repo}. Maybe you misspelled it?"
42 super command, destination_path, msg
43 end
44 end
45
46 class AmbiguousGitReference < GitError
47 def initialize(options)
48 msg = "Specification of branch or ref with tag is ambiguous. You specified #{options.inspect}"
49 super msg
50 end
51 end
52
53 # The GitProxy is responsible to interact with git repositories.
54 # All actions required by the Git source is encapsulated in this
55 # object.
56 class GitProxy
57 attr_accessor :path, :uri, :branch, :tag, :ref, :explicit_ref
58 attr_writer :revision
59
60 def initialize(path, uri, options = {}, revision = nil, git = nil)
61 @path = path
62 @uri = uri
63 @tag = options["tag"]
64 @branch = options["branch"]
65 @ref = options["ref"]
66 if @tag
67 raise AmbiguousGitReference.new(options) if @branch || @ref
68 @explicit_ref = @tag
69 else
70 @explicit_ref = @ref || @branch
71 end
72 @revision = revision
73 @git = git
74 @commit_ref = nil
75 end
76
77 def revision
78 @revision ||= allowed_with_path { find_local_revision }
79 end
80
81 def current_branch
82 @current_branch ||= with_path do
83 git_local("rev-parse", "--abbrev-ref", "HEAD", dir: path).strip
84 end
85 end
86
87 def not_a_repository?
88 _, status = git_null("rev-parse", "--resolve-git-dir", path.to_s, dir: path)
89
90 !status.success?
91 end
92
93 def contains?(commit)
94 allowed_with_path do
95 result, status = git_null("branch", "--contains", commit, dir: path)
96 status.success? && result.match?(/^\* (.*)$/)
97 end
98 end
99
100 def version
101 @version ||= full_version.match(/((\.?\d+)+).*/)[1]
102 end
103
104 def full_version
105 @full_version ||= git_local("--version").sub(/git version\s*/, "").strip
106 end
107
108 def checkout
109 return if has_revision_cached?
110
111 Bundler.ui.info "Fetching #{credential_filtered_uri}"
112
113 extra_fetch_needed = clone_needs_extra_fetch?
114 unshallow_needed = clone_needs_unshallow?
115 return unless extra_fetch_needed || unshallow_needed
116
117 git_remote_fetch(unshallow_needed ? ["--unshallow"] : depth_args)
118 end
119
120 def copy_to(destination, submodules = false)
121 unless File.exist?(destination.join(".git"))
122 begin
123 SharedHelpers.filesystem_access(destination.dirname) do |p|
124 FileUtils.mkdir_p(p)
125 end
126 SharedHelpers.filesystem_access(destination) do |p|
127 FileUtils.rm_rf(p)
128 end
129 git "clone", "--no-checkout", "--quiet", path.to_s, destination.to_s
130 File.chmod(((File.stat(destination).mode | 0o777) & ~File.umask), destination)
131 rescue Errno::EEXIST => e
132 file_path = e.message[%r{.*?((?:[a-zA-Z]:)?/.*)}, 1]
133 raise GitError, "Bundler could not install a gem because it needs to " \
134 "create a directory, but a file exists - #{file_path}. Please delete " \
135 "this file and try again."
136 end
137 end
138
139 ref = @commit_ref || (locked_to_full_sha? && @revision)
140 if ref
141 git "config", "uploadpack.allowAnySHA1InWant", "true", dir: path.to_s if @commit_ref.nil? && needs_allow_any_sha1_in_want?
142
143 git "fetch", "--force", "--quiet", *extra_fetch_args(ref), dir: destination
144 end
145
146 git "reset", "--hard", @revision, dir: destination
147
148 if submodules
149 git_retry "submodule", "update", "--init", "--recursive", dir: destination
150 elsif Gem::Version.create(version) >= Gem::Version.create("2.9.0")
151 inner_command = "git -C $toplevel submodule deinit --force $sm_path"
152 git_retry "submodule", "foreach", "--quiet", inner_command, dir: destination
153 end
154 end
155
156 private
157
158 def git_remote_fetch(args)
159 command = ["fetch", "--force", "--quiet", "--no-tags", *args, "--", configured_uri, refspec].compact
160 command_with_no_credentials = check_allowed(command)
161
162 Bundler::Retry.new("`#{command_with_no_credentials}` at #{path}", [MissingGitRevisionError]).attempts do
163 out, err, status = capture(command, path)
164 return out if status.success?
165
166 if err.include?("couldn't find remote ref") || err.include?("not our ref")
167 raise MissingGitRevisionError.new(command_with_no_credentials, path, commit || explicit_ref, credential_filtered_uri)
168 else
169 raise GitCommandError.new(command_with_no_credentials, path, err)
170 end
171 end
172 end
173
174 def clone_needs_extra_fetch?
175 return true if path.exist?
176
177 SharedHelpers.filesystem_access(path.dirname) do |p|
178 FileUtils.mkdir_p(p)
179 end
180
181 command = ["clone", "--bare", "--no-hardlinks", "--quiet", *extra_clone_args, "--", configured_uri, path.to_s]
182 command_with_no_credentials = check_allowed(command)
183
184 Bundler::Retry.new("`#{command_with_no_credentials}`", [MissingGitRevisionError]).attempts do
185 _, err, status = capture(command, nil)
186 return extra_ref if status.success?
187
188 if err.include?("Could not find remote branch") || # git up to 2.49
189 err.include?("Remote branch #{branch_option} not found") # git 2.49 or higher
190 raise MissingGitRevisionError.new(command_with_no_credentials, nil, explicit_ref, credential_filtered_uri)
191 else
192 idx = command.index("--depth")
193 if idx
194 command.delete_at(idx)
195 command.delete_at(idx)
196 command_with_no_credentials = check_allowed(command)
197
198 err += "Retrying without --depth argument."
199 end
200 raise GitCommandError.new(command_with_no_credentials, path, err)
201 end
202 end
203 end
204
205 def clone_needs_unshallow?
206 return false unless path.join("shallow").exist?
207 return true if full_clone?
208
209 @revision && @revision != head_revision
210 end
211
212 def extra_ref
213 return false if not_pinned?
214 return true unless full_clone?
215
216 ref.start_with?("refs/")
217 end
218
219 def depth
220 return @depth if defined?(@depth)
221
222 @depth = if !supports_fetching_unreachable_refs?
223 nil
224 elsif not_pinned? || pinned_to_full_sha?
225 1
226 elsif ref.include?("~")
227 parsed_depth = ref.split("~").last
228 parsed_depth.to_i + 1
229 end
230 end
231
232 def refspec
233 if commit
234 @commit_ref = "refs/#{commit}-sha"
235 return "#{commit}:#{@commit_ref}"
236 end
237
238 reference = fully_qualified_ref
239
240 reference ||= if ref.include?("~")
241 ref.split("~").first
242 elsif ref.start_with?("refs/")
243 ref
244 else
245 "refs/*"
246 end
247
248 "#{reference}:#{reference}"
249 end
250
251 def commit
252 @commit ||= pinned_to_full_sha? ? ref : @revision
253 end
254
255 def fully_qualified_ref
256 if branch
257 "refs/heads/#{branch}"
258 elsif tag
259 "refs/tags/#{tag}"
260 elsif ref.nil?
261 "refs/heads/#{current_branch}"
262 end
263 end
264
265 def not_pinned?
266 branch_option || ref.nil?
267 end
268
269 def pinned_to_full_sha?
270 full_sha_revision?(ref)
271 end
272
273 def locked_to_full_sha?
274 full_sha_revision?(@revision)
275 end
276
277 def full_sha_revision?(ref)
278 ref&.match?(/\A\h{40}\z/)
279 end
280
281 def git_null(*command, dir: nil)
282 check_allowed(command)
283
284 capture(command, dir, ignore_err: true)
285 end
286
287 def git_retry(*command, dir: nil)
288 command_with_no_credentials = check_allowed(command)
289
290 Bundler::Retry.new("`#{command_with_no_credentials}` at #{dir || SharedHelpers.pwd}").attempts do
291 git(*command, dir: dir)
292 end
293 end
294
295 def git(*command, dir: nil)
296 run_command(*command, dir: dir) do |unredacted_command|
297 check_allowed(unredacted_command)
298 end
299 end
300
301 def git_local(*command, dir: nil)
302 run_command(*command, dir: dir) do |unredacted_command|
303 redact_and_check_presence(unredacted_command)
304 end
305 end
306
307 def has_revision_cached?
308 return unless @revision && path.exist?
309 git("cat-file", "-e", @revision, dir: path)
310 true
311 rescue GitError
312 false
313 end
314
315 def find_local_revision
316 return head_revision if explicit_ref.nil?
317
318 find_revision_for(explicit_ref)
319 end
320
321 def head_revision
322 verify("HEAD")
323 end
324
325 def find_revision_for(reference)
326 verify(reference)
327 rescue GitCommandError => e
328 raise MissingGitRevisionError.new(e.command, path, reference, credential_filtered_uri)
329 end
330
331 def verify(reference)
332 git("rev-parse", "--verify", reference, dir: path).strip
333 end
334
335 # Adds credentials to the URI
336 def configured_uri
337 if /https?:/.match?(uri)
338 remote = Gem::URI(uri)
339 config_auth = Bundler.settings[remote.to_s] || Bundler.settings[remote.host]
340 remote.userinfo ||= config_auth
341 remote.to_s
342 else
343 uri.to_s
344 end
345 end
346
347 # Removes credentials from the URI
348 def credential_filtered_uri
349 URICredentialsFilter.credential_filtered_uri(uri)
350 end
351
352 def allow?
353 allowed = @git ? @git.allow_git_ops? : true
354
355 raise GitNotInstalledError.new if allowed && !Bundler.git_present?
356
357 allowed
358 end
359
360 def with_path(&blk)
361 checkout unless path.exist?
362 blk.call
363 end
364
365 def allowed_with_path
366 return with_path { yield } if allow?
367 raise GitError, "The git source #{uri} is not yet checked out. Please run `bundle install` before trying to start your application"
368 end
369
370 def check_allowed(command)
371 command_with_no_credentials = redact_and_check_presence(command)
372 raise GitNotAllowedError.new(command_with_no_credentials) unless allow?
373 command_with_no_credentials
374 end
375
376 def redact_and_check_presence(command)
377 raise GitNotInstalledError.new unless Bundler.git_present?
378
379 require "shellwords"
380 URICredentialsFilter.credential_filtered_string("git #{command.shelljoin}", uri)
381 end
382
383 def run_command(*command, dir: nil)
384 command_with_no_credentials = yield(command)
385
386 out, err, status = capture(command, dir)
387
388 raise GitCommandError.new(command_with_no_credentials, dir || SharedHelpers.pwd, err) unless status.success?
389
390 Bundler.ui.warn err unless err.empty?
391
392 out
393 end
394
395 def capture(cmd, dir, ignore_err: false)
396 SharedHelpers.with_clean_git_env do
397 require "open3"
398 out, err, status = Open3.capture3(*capture3_args_for(cmd, dir))
399
400 filtered_out = URICredentialsFilter.credential_filtered_string(out, uri)
401 return [filtered_out, status] if ignore_err
402
403 filtered_err = URICredentialsFilter.credential_filtered_string(err, uri)
404 [filtered_out, filtered_err, status]
405 end
406 end
407
408 def capture3_args_for(cmd, dir)
409 return ["git", *cmd] unless dir
410
411 if Bundler.feature_flag.bundler_3_mode? || supports_minus_c?
412 ["git", "-C", dir.to_s, *cmd]
413 else
414 ["git", *cmd, { chdir: dir.to_s }]
415 end
416 end
417
418 def extra_clone_args
419 args = depth_args
420 return [] if args.empty?
421
422 args += ["--single-branch"]
423 args.unshift("--no-tags") if supports_cloning_with_no_tags?
424
425 # If there's a locked revision, no need to clone any specific branch
426 # or tag, since we will end up checking out that locked revision
427 # anyways.
428 return args if @revision
429
430 args += ["--branch", branch_option] if branch_option
431 args
432 end
433
434 def depth_args
435 return [] if full_clone?
436
437 ["--depth", depth.to_s]
438 end
439
440 def extra_fetch_args(ref)
441 extra_args = [path.to_s, *depth_args]
442 extra_args.push(ref)
443 extra_args
444 end
445
446 def branch_option
447 branch || tag
448 end
449
450 def full_clone?
451 depth.nil?
452 end
453
454 def supports_minus_c?
455 @supports_minus_c ||= Gem::Version.new(version) >= Gem::Version.new("1.8.5")
456 end
457
458 def needs_allow_any_sha1_in_want?
459 @needs_allow_any_sha1_in_want ||= Gem::Version.new(version) <= Gem::Version.new("2.13.7")
460 end
461
462 def supports_fetching_unreachable_refs?
463 @supports_fetching_unreachable_refs ||= Gem::Version.new(version) >= Gem::Version.new("2.5.0")
464 end
465
466 def supports_cloning_with_no_tags?
467 @supports_cloning_with_no_tags ||= Gem::Version.new(version) >= Gem::Version.new("2.14.0-rc0")
468 end
469 end
470 end
471 end
472 end