rubygems-update 4.1.0 → 4.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +46 -0
  3. data/Manifest.txt +6 -0
  4. data/bundler.gemspec +5 -3
  5. data/lib/bundler/build_metadata.rb +2 -2
  6. data/lib/bundler/checksum.rb +15 -6
  7. data/lib/bundler/cli/outdated.rb +1 -4
  8. data/lib/bundler/definition.rb +27 -4
  9. data/lib/bundler/dependency.rb +17 -2
  10. data/lib/bundler/dsl.rb +3 -0
  11. data/lib/bundler/injector.rb +1 -1
  12. data/lib/bundler/inline.rb +3 -1
  13. data/lib/bundler/lazy_specification.rb +4 -0
  14. data/lib/bundler/man/bundle-lock.1 +1 -1
  15. data/lib/bundler/man/bundle-lock.1.ronn +5 -1
  16. data/lib/bundler/match_remote_metadata.rb +6 -0
  17. data/lib/bundler/plugin/index.rb +14 -11
  18. data/lib/bundler/remote_specification.rb +5 -0
  19. data/lib/bundler/resolver/candidate.rb +5 -0
  20. data/lib/bundler/resolver.rb +87 -7
  21. data/lib/bundler/rubygems_ext.rb +13 -0
  22. data/lib/bundler/runtime.rb +5 -1
  23. data/lib/bundler/settings.rb +2 -3
  24. data/lib/bundler/spec_set.rb +28 -7
  25. data/lib/bundler/vendored_securerandom.rb +5 -2
  26. data/lib/bundler/vendored_uri.rb +18 -3
  27. data/lib/bundler/version.rb +1 -1
  28. data/lib/rubygems/commands/push_command.rb +3 -1
  29. data/lib/rubygems/core_ext/tcpsocket_init.rb +2 -2
  30. data/lib/rubygems/doctor.rb +1 -0
  31. data/lib/rubygems/installer.rb +23 -19
  32. data/lib/rubygems/package/old.rb +2 -2
  33. data/lib/rubygems/package.rb +45 -12
  34. data/lib/rubygems/request_set.rb +1 -3
  35. data/lib/rubygems/vendor/pub_grub/lib/pub_grub/term.rb +1 -1
  36. data/lib/rubygems/yaml_serializer/builder.rb +261 -0
  37. data/lib/rubygems/yaml_serializer/core.rb +41 -0
  38. data/lib/rubygems/yaml_serializer/emitter.rb +197 -0
  39. data/lib/rubygems/yaml_serializer/nodes.rb +10 -0
  40. data/lib/rubygems/yaml_serializer/parser.rb +531 -0
  41. data/lib/rubygems/yaml_serializer/psych_errors.rb +11 -0
  42. data/lib/rubygems/yaml_serializer.rb +1 -988
  43. data/lib/rubygems.rb +1 -1
  44. metadata +8 -2
@@ -395,7 +395,11 @@ module Bundler
395
395
  return unless activated_spec = Bundler.rubygems.loaded_specs(spec.name)
396
396
  return if activated_spec.version == spec.version
397
397
 
398
- suggestion = if activated_spec.default_gem?
398
+ activating_gemfile = activated_spec.bundler_activating_gemfile if activated_spec.respond_to?(:bundler_activating_gemfile)
399
+ suggestion = if @definition.gemfiles.include?(activating_gemfile)
400
+ "#{spec.name} was activated while evaluating your Gemfile. If a `require` in your Gemfile loads it, " \
401
+ "remove that call or move it outside the Gemfile, after `Bundler.setup`."
402
+ elsif activated_spec.default_gem?
399
403
  "Since #{spec.name} is a default gem, you can either remove your dependency on it" \
400
404
  " or try updating to a newer version of bundler that supports #{spec.name} as a default gem."
401
405
  else
@@ -826,9 +826,8 @@ module Bundler
826
826
  end
827
827
 
828
828
  def serializer_class
829
- # The Bundler gem ships its own copy of Gem::YAMLSerializer, so this
830
- # resolves even on RubyGems versions that predate it.
831
- require "rubygems/yaml_serializer"
829
+ # See lib/rubygems/yaml_serializer/core.rb.
830
+ require_relative "../rubygems/yaml_serializer/core"
832
831
  Gem::YAMLSerializer
833
832
  end
834
833
 
@@ -63,7 +63,7 @@ module Bundler
63
63
  invalid_platforms
64
64
  end
65
65
 
66
- def add_extra_platforms!(platforms)
66
+ def add_extra_platforms!(platforms, prefer_local: false)
67
67
  if @specs.empty?
68
68
  platforms.concat([Gem::Platform::RUBY]).uniq
69
69
  return
@@ -73,12 +73,13 @@ module Bundler
73
73
  next if platforms.include?(platform)
74
74
  next unless Gem::Platform.generic(platform) == Gem::Platform::RUBY
75
75
 
76
- complete_platform(platform)
76
+ complete_platform(platform, prefer_local: prefer_local && platform === Bundler.local_platform)
77
77
  end
78
78
  return if new_platforms.empty?
79
79
 
80
80
  platforms.concat(new_platforms)
81
81
  return if new_platforms.include?(Bundler.local_platform)
82
+ return if prefer_local && @specs.any? {|spec| spec.platform == Bundler.local_platform }
82
83
 
83
84
  less_specific_platform = new_platforms.find {|platform| platform != Gem::Platform::RUBY && Bundler.local_platform === platform && platform === Bundler.local_platform }
84
85
  platforms.delete(Bundler.local_platform) if less_specific_platform
@@ -162,14 +163,14 @@ module Bundler
162
163
  end
163
164
 
164
165
  def incomplete_for_platform?(deps, platform)
166
+ return false if @specs.empty?
167
+
165
168
  incomplete_specs_for_platform(deps, platform).any?
166
169
  end
167
170
 
168
171
  def incomplete_specs_for_platform(deps, platform)
169
- return [] if @specs.empty?
170
-
171
172
  validation_set = self.class.new(@specs)
172
- validation_set.for(deps, [platform])
173
+ validation_set.for(deps.select {|dep| dep.should_include?(platform) }, [platform])
173
174
  validation_set.incomplete_specs
174
175
  end
175
176
 
@@ -291,7 +292,7 @@ module Bundler
291
292
  @materializations.filter_map(&:materialized_spec)
292
293
  end
293
294
 
294
- def complete_platform(platform)
295
+ def complete_platform(platform, prefer_local: false)
295
296
  new_specs = []
296
297
 
297
298
  valid_platform = lookup.all? do |_, specs|
@@ -302,7 +303,7 @@ module Bundler
302
303
  # the same overrides the install/resolve path already applies.
303
304
  overrides = spec.is_a?(LazySpecification) ? Array(spec.overrides) : []
304
305
  matching_specs = spec.source.specs.search([spec.name, spec.version])
305
- platform_spec = MatchPlatform.select_best_platform_match(matching_specs, platform).find do |s|
306
+ platform_spec = find_platform_spec(matching_specs, platform, prefer_local) do |s|
306
307
  s.matches_current_metadata_with_overrides?(overrides) && validate_deps(s, overrides) == :valid
307
308
  end
308
309
 
@@ -328,6 +329,26 @@ module Bundler
328
329
  valid_platform
329
330
  end
330
331
 
332
+ def find_platform_spec(specs, platform, prefer_local, &valid)
333
+ if prefer_local
334
+ local_specs = specs.select {|s| s.is_a?(StubSpecification) || s.instance_of?(Gem::Specification) }
335
+ local_matches = local_specs.select {|s| covers_platform?(s.platform, platform) && valid.call(s) }
336
+ return MatchPlatform.select_best_platform_match(local_matches, platform).first if local_matches.any?
337
+ end
338
+
339
+ MatchPlatform.select_best_platform_match(specs, platform).find(&valid)
340
+ end
341
+
342
+ def covers_platform?(gem_platform, platform)
343
+ return true if gem_platform == Gem::Platform::RUBY
344
+ return false unless gem_platform === platform
345
+ # A versioned or CPU-specific binary cannot cover a wildcard in the lockfile.
346
+ return false if platform.version.nil? && gem_platform.version
347
+ return false if [nil, "universal"].include?(platform.cpu) && ![nil, "universal"].include?(gem_platform.cpu)
348
+
349
+ true
350
+ end
351
+
331
352
  def all_platforms
332
353
  @specs.flat_map {|spec| spec.source.specs.search([spec.name, spec.version]).map(&:platform) }.uniq
333
354
  end
@@ -3,11 +3,14 @@
3
3
  # Reuse RubyGems' vendored SecureRandom (Gem::SecureRandom). The Bundler gem
4
4
  # ships a copy under lib/rubygems/vendor, so this resolves even on RubyGems
5
5
  # versions that predate it. Fall back to the stdlib only when no vendored copy
6
- # is available at all.
6
+ # is available at all. RubyGems' own file is required by path for the reason
7
+ # given in vendored_uri.rb.
7
8
 
8
9
  unless defined?(Gem::SecureRandom)
10
+ rubygems_securerandom = File.join(Gem::RUBYGEMS_DIR, "rubygems/vendor/securerandom/lib/securerandom.rb")
11
+
9
12
  begin
10
- require "rubygems/vendor/securerandom/lib/securerandom"
13
+ require File.exist?(rubygems_securerandom) ? rubygems_securerandom : "rubygems/vendor/securerandom/lib/securerandom"
11
14
  rescue LoadError
12
15
  require "securerandom"
13
16
  Gem::SecureRandom = SecureRandom
@@ -1,12 +1,27 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  # Reuse RubyGems' vendored URI (Gem::URI). The Bundler gem ships a copy under
4
- # lib/rubygems/vendor, so this resolves even on RubyGems versions that predate
5
- # it. Fall back to the stdlib only when no vendored copy is available at all.
4
+ # lib/rubygems/vendor without its entry file, which Bundler 2.5.6 to 4.0.x
5
+ # require by name on RubyGems older than 3.5.6 (see
6
+ # lib/rubygems/yaml_serializer/core.rb), so this loads the files that entry file
7
+ # loads on RubyGems versions that predate it. Fall back to the stdlib only when
8
+ # no vendored copy is available at all.
9
+ #
10
+ # RubyGems requires its own copy with require_relative, so require that same
11
+ # file when it exists. Older RubyGems versions, whose copy has no double load
12
+ # guard, would otherwise load the library a second time.
6
13
 
7
14
  unless defined?(Gem::URI)
15
+ rubygems_uri = File.join(Gem::RUBYGEMS_DIR, "rubygems/vendor/uri/lib/uri.rb")
16
+
8
17
  begin
9
- require "rubygems/vendor/uri/lib/uri"
18
+ if File.exist?(rubygems_uri)
19
+ require rubygems_uri
20
+ else
21
+ %w[version common generic file ftp http https ldap ldaps mailto ws wss].each do |file|
22
+ require_relative "../rubygems/vendor/uri/lib/uri/#{file}"
23
+ end
24
+ end
10
25
  rescue LoadError
11
26
  require "uri"
12
27
  Gem::URI = URI
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: false
2
2
 
3
3
  module Bundler
4
- VERSION = "4.1.0".freeze
4
+ VERSION = "4.1.1".freeze
5
5
 
6
6
  def self.bundler_major_version
7
7
  @bundler_major_version ||= gem_version.segments.first
@@ -196,7 +196,9 @@ The API key to send is resolved in this order: the GEM_HOST_API_KEY environment
196
196
  return send_push_request_without_attestation(name, args)
197
197
  end
198
198
  end
199
- bundles = "[" + attestations.join(",") + "]"
199
+ # JSON.parse in json before 2.7.3 retags the attestations as UTF-8, which the
200
+ # multipart body cannot join with the binary gem.
201
+ bundles = ("[" + attestations.join(",") + "]").b
200
202
 
201
203
  rubygems_api_request(*args, scope: get_push_scope) do |request|
202
204
  request.set_form([
@@ -12,7 +12,7 @@ module CoreExtensions
12
12
  CONNECTION_TIMEOUT = 5
13
13
  IPV4_DELAY_SECONDS = 0.1
14
14
 
15
- def initialize(host, serv, *rest)
15
+ def initialize(host, serv, ...)
16
16
  mutex = Thread::Mutex.new
17
17
  addrs = []
18
18
  threads = []
@@ -45,7 +45,7 @@ module CoreExtensions
45
45
 
46
46
  threads.each {|t| t.kill.join if t.alive? }
47
47
 
48
- super(host, serv, *rest)
48
+ super(host, serv, ...)
49
49
  end
50
50
  end
51
51
  end
@@ -111,6 +111,7 @@ class Gem::Doctor
111
111
 
112
112
  basename = strip_extension File.basename(child), extensions
113
113
  next if installed_specs.include? basename
114
+ next if sub_directory == "gems" && File.fnmatch?(".*.lock", ent) && File.file?(child)
114
115
  next if /^rubygems-\d/.match?(basename)
115
116
  next if sub_directory == "specifications" && basename == "default"
116
117
  next if sub_directory == "plugins" && Gem.plugin_suffix_regexp =~ basename
@@ -280,31 +280,35 @@ class Gem::Installer
280
280
  # Set loaded_from to ensure extension_dir is correct
281
281
  spec.loaded_from = spec_file
282
282
 
283
- # Completely remove any previous gem files
284
- FileUtils.rm_rf gem_dir
285
- FileUtils.rm_rf spec.extension_dir
283
+ gems_dir = File.dirname(gem_dir)
284
+ ensure_writable_dir gems_dir
285
+ Gem.open_file_with_lock(File.join(gems_dir, ".#{spec.full_name}")) do
286
+ # Completely remove any previous gem files
287
+ FileUtils.rm_rf gem_dir
288
+ FileUtils.rm_rf spec.extension_dir
286
289
 
287
- dir_mode = options[:dir_mode]
288
- FileUtils.mkdir_p gem_dir, mode: dir_mode && 0o755
290
+ dir_mode = options[:dir_mode]
291
+ FileUtils.mkdir_p gem_dir, mode: dir_mode && 0o755
289
292
 
290
- extract_files
293
+ extract_files
291
294
 
292
- build_extensions
293
- write_build_info_file
294
- run_post_build_hooks
295
+ build_extensions
296
+ write_build_info_file
297
+ run_post_build_hooks
295
298
 
296
- generate_bin
297
- if options[:install_plugin] == false
298
- remove_stale_plugins
299
- warn_skipped_plugins
300
- else
301
- generate_plugins
302
- end
299
+ generate_bin
300
+ if options[:install_plugin] == false
301
+ remove_stale_plugins
302
+ warn_skipped_plugins
303
+ else
304
+ generate_plugins
305
+ end
303
306
 
304
- write_spec
305
- write_cache_file
307
+ write_spec
308
+ write_cache_file
306
309
 
307
- File.chmod(dir_mode, gem_dir) if dir_mode
310
+ File.chmod(dir_mode, gem_dir) if dir_mode
311
+ end
308
312
 
309
313
  say clean_text(spec.post_install_message.to_s) if options[:post_install_message] && !spec.post_install_message.nil?
310
314
 
@@ -79,10 +79,10 @@ class Gem::Package::Old < Gem::Package
79
79
  raise Gem::Package::FormatError, "#{full_name} in #{@gem} is corrupt" if
80
80
  file_data.length != entry["size"].to_i
81
81
 
82
- FileUtils.mkdir_p File.dirname(destination), mode: dir_mode && 0o755
83
-
84
82
  verify_extraction_dir File.dirname(destination), destination_dir
85
83
 
84
+ FileUtils.mkdir_p File.dirname(destination), mode: dir_mode && 0o755
85
+
86
86
  FileUtils.rm_rf destination
87
87
 
88
88
  File.open destination, "wb", file_mode(entry["mode"]) do |out|
@@ -513,6 +513,10 @@ EOM
513
513
 
514
514
  def extract_tar_gz(io, destination_dir, pattern = "*") # :nodoc:
515
515
  destination_dir = File.realpath(destination_dir)
516
+ # File.umask sets the process umask to 0 while reading it, so read it once
517
+ # instead of per file to keep other threads' files from being created
518
+ # world-writable.
519
+ umask = File.umask
516
520
 
517
521
  directories = []
518
522
  symlinks = []
@@ -536,7 +540,7 @@ EOM
536
540
  raise Gem::Package::SymlinkError.new(full_name, real_destination, destination_dir) unless
537
541
  normalize_path(real_destination).start_with? normalize_path(destination_dir + "/")
538
542
 
539
- symlinks << [full_name, link_target, destination, real_destination]
543
+ symlinks << [full_name, link_target, destination]
540
544
  end
541
545
 
542
546
  mkdir =
@@ -546,13 +550,13 @@ EOM
546
550
  File.dirname destination
547
551
  end
548
552
 
553
+ verify_extraction_dir mkdir, destination_dir
554
+
549
555
  unless directories.include?(mkdir)
550
- FileUtils.mkdir_p mkdir, mode: dir_mode ? 0o755 : (entry.header.mode & 0o777 if entry.directory?)
556
+ FileUtils.mkdir_p mkdir, mode: dir_mode ? 0o755 : (entry.header.mode & 0o777 & ~umask if entry.directory?)
551
557
  directories << mkdir
552
558
  end
553
559
 
554
- verify_extraction_dir mkdir, destination_dir
555
-
556
560
  if entry.file?
557
561
  raise Gem::Package::PathError.new(destination, destination_dir) if
558
562
  File.symlink?(destination)
@@ -563,7 +567,7 @@ EOM
563
567
  # in the IO buffer that needs to be written, and that could be
564
568
  # written after the chmod (on close) which would mess up the perms
565
569
  out.flush
566
- out.chmod file_mode(entry.header.mode) & ~File.umask
570
+ out.chmod file_mode(entry.header.mode) & ~umask
567
571
  end
568
572
  end
569
573
 
@@ -571,12 +575,21 @@ EOM
571
575
  end
572
576
  end
573
577
 
574
- symlinks.each do |name, target, destination, real_destination|
575
- if File.exist?(real_destination)
576
- create_symlink(target, destination)
577
- else
578
- alert_warning "#{@spec.full_name} ships with a dangling symlink named #{name} pointing to missing #{target} file. Ignoring"
578
+ symlinks.each do |name, target, destination|
579
+ # The check above expands ".." lexically, so a target that walks
580
+ # through another symlink in the gem is only known once resolved.
581
+ real_destination = begin
582
+ resolve_symlink_target(target, File.dirname(destination))
583
+ rescue SystemCallError
584
+ gem_name = @spec ? @spec.full_name : "unknown"
585
+ alert_warning "#{gem_name} ships with a dangling symlink named #{name} pointing to missing #{target} file. Ignoring"
586
+ next
579
587
  end
588
+
589
+ raise Gem::Package::SymlinkError.new(name, real_destination, destination_dir) unless
590
+ normalize_path(real_destination).start_with? normalize_path(destination_dir + "/")
591
+
592
+ create_symlink(target, destination)
580
593
  end
581
594
 
582
595
  if dir_mode && !directories.empty?
@@ -842,10 +855,13 @@ EOM
842
855
 
843
856
  ##
844
857
  # Raises an exception unless +dir+, with symlinks resolved, is
845
- # +destination_dir+ or a directory inside it. +destination_dir+ must
846
- # already be resolved with File.realpath by the caller.
858
+ # +destination_dir+ or a directory inside it. When +dir+ does not exist
859
+ # yet, its nearest existing ancestor is checked instead, so this can run
860
+ # before +dir+ is created. +destination_dir+ must already be resolved with
861
+ # File.realpath by the caller.
847
862
 
848
863
  def verify_extraction_dir(dir, destination_dir) # :nodoc:
864
+ dir = File.dirname(dir) until File.exist?(dir)
849
865
  real_dir = File.realpath(dir)
850
866
 
851
867
  return if real_dir == destination_dir ||
@@ -854,6 +870,23 @@ EOM
854
870
  raise Gem::Package::PathError.new(real_dir, destination_dir)
855
871
  end
856
872
 
873
+ ##
874
+ # Resolves the symlink +target+ against +dir+ one component at a time.
875
+ # File.realpath on JRuby and TruffleRuby folds ".." before following
876
+ # symlinks, so ".." is applied here to the already resolved path instead.
877
+
878
+ def resolve_symlink_target(target, dir) # :nodoc:
879
+ root = target[%r{\A(?:[A-Za-z]:)?/}] if target.start_with?("/") || File.absolute_path?(target)
880
+
881
+ target.delete_prefix(root.to_s).split("/").inject(File.realpath(File.expand_path(root || dir))) do |current, name|
882
+ case name
883
+ when "", "." then current
884
+ when ".." then File.dirname(current)
885
+ else File.realpath(name, current)
886
+ end
887
+ end
888
+ end
889
+
857
890
  ##
858
891
  # Verifies the +checksums+ against the +digests+. This check is not
859
892
  # cryptographically secure. Missing checksums are ignored.
@@ -533,9 +533,7 @@ class Gem::RequestSet
533
533
  node.spec.dependencies.each do |dep|
534
534
  next if dep.type == :development && !@development
535
535
 
536
- match = @requests.find do |r|
537
- dep.match?(r.spec.name, r.spec.version, r.spec.is_a?(Gem::Resolver::InstalledSpecification) || @prerelease)
538
- end
536
+ match = @requests.find {|r| dep.matches_spec?(r.spec) }
539
537
 
540
538
  unless match
541
539
  next if dep.type == :development && @development_shallow
@@ -95,7 +95,7 @@ module Gem::PubGrub
95
95
  end
96
96
 
97
97
  def empty?
98
- @empty ||= normalized_constraint.empty?
98
+ @empty ||= constraint.empty?
99
99
  end
100
100
 
101
101
  def inspect
@@ -0,0 +1,261 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Gem
4
+ module YAMLSerializer
5
+ class Builder
6
+ VALID_OPS = %w[= != > < >= <= ~>].freeze
7
+ ARRAY_FIELDS = %w[files test_files executables extra_rdoc_files].freeze
8
+ MAX_ALIAS_EXPANSION = 100_000
9
+
10
+ def initialize(permitted_classes: [], permitted_symbols: [], aliases: true)
11
+ @permitted_classes = permitted_classes.map {|c| "!ruby/object:#{c}" }
12
+ @permitted_symbols = permitted_symbols
13
+ @aliases = aliases
14
+ @anchor_values = {}
15
+ @anchor_sizes = {}
16
+ @expanded_size = 0
17
+ @alias_expansion = 0
18
+ end
19
+
20
+ def build(node)
21
+ return nil if node.nil?
22
+
23
+ result = build_node(node)
24
+
25
+ if result.is_a?(Hash) && result[:tag] == "!ruby/object:Gem::Specification"
26
+ build_specification(result)
27
+ else
28
+ result
29
+ end
30
+ end
31
+
32
+ private
33
+
34
+ def build_node(node)
35
+ start = @expanded_size
36
+ case node
37
+ when nil then nil
38
+ when AliasRef then resolve_alias(node)
39
+ when Scalar then store_anchor(node.anchor, node.value, start)
40
+ when Mapping then store_anchor(node.anchor, build_mapping(node), start)
41
+ when Sequence then store_anchor(node.anchor, node.items.map {|item| build_node(item) }, start)
42
+ else node # already a Ruby object
43
+ end
44
+ end
45
+
46
+ def resolve_alias(node)
47
+ raise Psych::AliasesNotEnabled unless @aliases
48
+ unless @anchor_values.key?(node.name)
49
+ raise Psych::AnchorNotDefined, node.name if defined?(Psych::AnchorNotDefined)
50
+ raise Psych::BadAlias, "An alias referenced an unknown anchor: #{node.name}"
51
+ end
52
+ # Charge the expanded size of the anchor, weighing scalars by length,
53
+ # so neither nested aliases nor aliases to a long string blow up.
54
+ size = @anchor_sizes.fetch(node.name)
55
+ @expanded_size += size
56
+ @alias_expansion += size
57
+ if @alias_expansion > MAX_ALIAS_EXPANSION
58
+ raise Psych::BadAlias, "exceeded maximum alias expansion (#{MAX_ALIAS_EXPANSION})"
59
+ end
60
+ @anchor_values.fetch(node.name)
61
+ end
62
+
63
+ def store_anchor(name, value, start)
64
+ @expanded_size += value.is_a?(String) ? 1 + value.bytesize : 1
65
+ if name
66
+ @anchor_values[name] = value
67
+ @anchor_sizes[name] = @expanded_size - start
68
+ end
69
+ value
70
+ end
71
+
72
+ def build_mapping(node)
73
+ validate_tag!(node.tag) if node.tag
74
+
75
+ result = case node.tag
76
+ when "!ruby/object:Gem::Version"
77
+ build_version(node)
78
+ when "!ruby/object:Gem::Platform"
79
+ build_platform(node)
80
+ when "!ruby/object:Gem::Requirement", "!ruby/object:Gem::Version::Requirement"
81
+ build_requirement(node)
82
+ when "!ruby/object:Gem::Dependency"
83
+ build_dependency(node)
84
+ when nil
85
+ build_hash(node)
86
+ when "!ruby/object:Gem::Specification"
87
+ hash = build_hash(node)
88
+ hash[:tag] = node.tag
89
+ hash
90
+ else
91
+ raise ArgumentError, "undefined class/module #{node.tag.sub("!ruby/object:", "")}"
92
+ end
93
+
94
+ result
95
+ end
96
+
97
+ def build_hash(node)
98
+ result = {}
99
+ each_pair(node) do |key, value_node|
100
+ value = build_node(value_node)
101
+
102
+ if ARRAY_FIELDS.include?(key)
103
+ value = normalize_array_field(value)
104
+ end
105
+
106
+ result[key] = value
107
+ end
108
+ result
109
+ end
110
+
111
+ def build_version(node)
112
+ hash = pairs_to_hash(node)
113
+ Gem::Version.new((hash["version"] || hash["value"]).to_s)
114
+ end
115
+
116
+ PLATFORM_FIELDS = %w[cpu os version].freeze
117
+ PLATFORM_ALLOWED_IVARS = %w[cpu os version value].freeze
118
+
119
+ def build_platform(node)
120
+ hash = pairs_to_hash(node)
121
+ if (hash.keys & PLATFORM_FIELDS).any?
122
+ Gem::Platform.new([hash["cpu"], hash["os"], hash["version"]])
123
+ elsif hash["value"].is_a?(Array)
124
+ # Malformed platform (e.g. sequence instead of mapping).
125
+ # Return the raw value so yaml_initialize handles it like Psych does.
126
+ hash["value"]
127
+ else
128
+ plat = Gem::Platform.allocate
129
+ hash.each do |k, v|
130
+ plat.instance_variable_set(:"@#{k}", v) if PLATFORM_ALLOWED_IVARS.include?(k)
131
+ end
132
+ plat
133
+ end
134
+ end
135
+
136
+ def build_requirement(node)
137
+ r = Gem::Requirement.allocate
138
+ hash = pairs_to_hash(node)
139
+ reqs = hash["requirements"] || hash["value"]
140
+
141
+ if reqs.is_a?(Array) && !reqs.empty?
142
+ safe_reqs = []
143
+ reqs.each do |item|
144
+ if item.is_a?(Array) && item.size == 2
145
+ op = item[0].to_s
146
+ ver = item[1]
147
+ if VALID_OPS.include?(op)
148
+ version_obj = ver.is_a?(Gem::Version) ? ver : Gem::Version.new(ver.to_s)
149
+ safe_reqs << [op, version_obj]
150
+ end
151
+ elsif item.is_a?(String)
152
+ parsed = Gem::Requirement.parse(item)
153
+ safe_reqs << parsed
154
+ end
155
+ rescue Gem::Requirement::BadRequirementError, Gem::Version::BadVersionError
156
+ # Skip malformed items silently
157
+ end
158
+ reqs = safe_reqs unless safe_reqs.empty?
159
+ end
160
+
161
+ r.instance_variable_set(:@requirements, reqs)
162
+ r
163
+ end
164
+
165
+ def build_dependency(node)
166
+ hash = pairs_to_hash(node)
167
+ d = Gem::Dependency.allocate
168
+ d.instance_variable_set(:@name, hash["name"])
169
+
170
+ d.instance_variable_set(:@requirement, hash["requirement"] || hash["version_requirements"])
171
+
172
+ raw_type = hash["type"]
173
+ if raw_type
174
+ name = raw_type.to_s.sub(/^:/, "")
175
+ validate_symbol!(name)
176
+ type = name.to_sym
177
+ else
178
+ type = :runtime
179
+ end
180
+ d.instance_variable_set(:@type, type)
181
+
182
+ d.instance_variable_set(:@prerelease, ["true", true].include?(hash["prerelease"]))
183
+ d.instance_variable_set(:@version_requirements, d.instance_variable_get(:@requirement))
184
+ d
185
+ end
186
+
187
+ def build_specification(hash)
188
+ spec = Gem::Specification.allocate
189
+
190
+ normalize_specification_version!(hash)
191
+ normalize_array_fields!(hash)
192
+
193
+ spec.yaml_initialize("!ruby/object:Gem::Specification", hash)
194
+ spec
195
+ end
196
+
197
+ def pairs_to_hash(node)
198
+ result = {}
199
+ each_pair(node) do |key, value_node|
200
+ result[key] = build_node(value_node)
201
+ end
202
+ result
203
+ end
204
+
205
+ def each_pair(node)
206
+ pairs = node.pairs
207
+ i = 0
208
+ while i < pairs.size
209
+ yield pairs[i], pairs[i + 1]
210
+ i += 2
211
+ end
212
+ end
213
+
214
+ def validate_tag!(tag)
215
+ return if @permitted_classes.include?(tag)
216
+ raise_disallowed_class!(tag)
217
+ end
218
+
219
+ def raise_disallowed_class!(tag)
220
+ if defined?(Psych::VERSION)
221
+ raise Psych::DisallowedClass.new("load", tag)
222
+ else
223
+ raise Psych::DisallowedClass, "Tried to load unspecified class: #{tag}"
224
+ end
225
+ end
226
+
227
+ def validate_symbol!(name)
228
+ return if @permitted_symbols.empty? || @permitted_symbols.include?(name)
229
+
230
+ label = ":#{name}"
231
+ if defined?(Psych::VERSION)
232
+ raise Psych::DisallowedClass.new("load", label)
233
+ else
234
+ raise Psych::DisallowedClass, "Tried to load unspecified class: #{label}"
235
+ end
236
+ end
237
+
238
+ def normalize_specification_version!(hash)
239
+ val = hash["specification_version"]
240
+ return unless val && !val.is_a?(Integer)
241
+ hash["specification_version"] = val.to_i if val.is_a?(String) && /\A\d+\z/.match?(val)
242
+ end
243
+
244
+ def normalize_array_fields!(hash)
245
+ ARRAY_FIELDS.each do |field|
246
+ hash[field] = normalize_array_field(hash[field]) if hash[field]
247
+ end
248
+ end
249
+
250
+ def normalize_array_field(value)
251
+ if value.is_a?(Hash)
252
+ value.values.flatten.compact
253
+ elsif !value.is_a?(Array) && value
254
+ [value].flatten.compact
255
+ else
256
+ value
257
+ end
258
+ end
259
+ end
260
+ end
261
+ end