bundler 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.
@@ -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
@@ -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
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The Bundler gem ships this directory but not rubygems/yaml_serializer.rb, and
4
+ # requires this file directly. Bundler 2.4.21 to 4.0.x require
5
+ # "rubygems/yaml_serializer" by name and fall back to their own copy when it is
6
+ # missing. On RubyGems older than 3.4.21, a file under that name in an
7
+ # installed Bundler gem would answer that require instead, and RubyGems would
8
+ # activate that gem under the running Bundler.
9
+
10
+ # Skip reloading when an identical copy (e.g. the one shipped inside the Bundler
11
+ # gem) was already required from a different path, to avoid redefinition warnings.
12
+ return if defined?(Gem::YAMLSerializer)
13
+
14
+ require_relative "psych_errors"
15
+ require_relative "nodes"
16
+ require_relative "parser"
17
+ require_relative "builder"
18
+ require_relative "emitter"
19
+
20
+ module Gem
21
+ module YAMLSerializer
22
+ module_function
23
+
24
+ def dump(obj)
25
+ Emitter.new.emit(obj)
26
+ end
27
+
28
+ def load(str, permitted_classes: [], permitted_symbols: [], aliases: true)
29
+ ast = Parser.new(str).parse
30
+ result = Builder.new(
31
+ permitted_classes: permitted_classes,
32
+ permitted_symbols: permitted_symbols,
33
+ aliases: aliases
34
+ ).build(ast)
35
+ # Bundler 4.0 and older call Hash methods on what this returns for
36
+ # .bundle/config, which is just "---" once its last key is unset, so
37
+ # nil stays a Hash here as it did in RubyGems 4.0.
38
+ result.nil? ? {} : result
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,197 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Gem
4
+ module YAMLSerializer
5
+ class Emitter
6
+ STRING_ESCAPES = {
7
+ "\\" => "\\\\",
8
+ "\"" => "\\\"",
9
+ "\0" => "\\0",
10
+ "\a" => "\\a",
11
+ "\b" => "\\b",
12
+ "\t" => "\\t",
13
+ "\n" => "\\n",
14
+ "\v" => "\\v",
15
+ "\f" => "\\f",
16
+ "\r" => "\\r",
17
+ "\e" => "\\e",
18
+ }.freeze
19
+
20
+ def emit(obj)
21
+ res = "---#{emit_node(obj, 0)}"
22
+ res << "...\n" if @open_ended
23
+ res
24
+ end
25
+
26
+ private
27
+
28
+ def emit_node(obj, indent, quote: false)
29
+ case obj
30
+ when Gem::Specification then emit_specification(obj, indent)
31
+ when Gem::Version then emit_version(obj, indent)
32
+ when Gem::Platform then emit_platform(obj, indent)
33
+ when Gem::Requirement then emit_requirement(obj, indent)
34
+ when Gem::Dependency then emit_dependency(obj, indent)
35
+ when Hash then emit_hash(obj, indent)
36
+ when Array then emit_array(obj, indent)
37
+ when Time then emit_time(obj)
38
+ when String then emit_string(obj, indent, quote: quote)
39
+ when NilClass
40
+ "\n"
41
+ when Numeric, Symbol, TrueClass, FalseClass
42
+ " #{obj.inspect}\n"
43
+ else
44
+ " #{quote_string(obj.to_s)}\n"
45
+ end
46
+ end
47
+
48
+ def emit_specification(spec, indent)
49
+ parts = [" !ruby/object:Gem::Specification\n"]
50
+ parts << "#{pad(indent)}name:#{emit_node(spec.name, indent + 2)}"
51
+ parts << "#{pad(indent)}version:#{emit_node(spec.version, indent + 2)}"
52
+ parts << "#{pad(indent)}platform: #{spec.platform}\n"
53
+ if spec.platform.to_s != spec.original_platform.to_s
54
+ parts << "#{pad(indent)}original_platform: #{spec.original_platform}\n"
55
+ end
56
+
57
+ attributes = Gem::Specification.attribute_names.map(&:to_s).sort - %w[name version platform]
58
+ attributes.each do |name|
59
+ val = spec.instance_variable_get("@#{name}")
60
+ next if val.nil?
61
+ parts << "#{pad(indent)}#{name}:#{emit_node(val, indent + 2)}"
62
+ end
63
+
64
+ res = parts.join
65
+ res << "\n" unless res.end_with?("\n")
66
+ res
67
+ end
68
+
69
+ def emit_version(ver, indent)
70
+ " !ruby/object:Gem::Version\n" \
71
+ "#{pad(indent)}version: #{emit_node(ver.version.to_s, indent + 2).lstrip}"
72
+ end
73
+
74
+ def emit_platform(plat, indent)
75
+ " !ruby/object:Gem::Platform\n" \
76
+ "#{pad(indent)}cpu:#{emit_node(plat.cpu, indent + 2)}" \
77
+ "#{pad(indent)}os:#{emit_node(plat.os, indent + 2)}" \
78
+ "#{pad(indent)}version:#{emit_node(plat.version, indent + 2)}"
79
+ end
80
+
81
+ def emit_requirement(req, indent)
82
+ " !ruby/object:Gem::Requirement\n" \
83
+ "#{pad(indent)}requirements:#{emit_node(req.requirements, indent + 2)}"
84
+ end
85
+
86
+ def emit_dependency(dep, indent)
87
+ [
88
+ " !ruby/object:Gem::Dependency\n",
89
+ "#{pad(indent)}name: #{emit_node(dep.name, indent + 2).lstrip}",
90
+ "#{pad(indent)}requirement:#{emit_node(dep.requirement, indent + 2)}",
91
+ "#{pad(indent)}type: #{emit_node(dep.type, indent + 2).lstrip}",
92
+ "#{pad(indent)}prerelease: #{emit_node(dep.prerelease?, indent + 2).lstrip}",
93
+ "#{pad(indent)}version_requirements:#{emit_node(dep.requirement, indent + 2)}",
94
+ ].join
95
+ end
96
+
97
+ def emit_hash(hash, indent)
98
+ if hash.empty?
99
+ " {}\n"
100
+ else
101
+ parts = ["\n"]
102
+ hash.each do |k, v|
103
+ is_symbol = k.is_a?(Symbol) || (k.is_a?(String) && k.start_with?(":"))
104
+ key_str = k.is_a?(Symbol) ? k.inspect : k.to_s
105
+ key_str = quote_string(key_str) if !is_symbol && needs_quoting?(key_str, key: true)
106
+ parts << "#{pad(indent)}#{key_str}:#{emit_node(v, indent + 2, quote: is_symbol)}"
107
+ end
108
+ parts.join
109
+ end
110
+ end
111
+
112
+ def emit_array(arr, indent)
113
+ if arr.empty?
114
+ " []\n"
115
+ else
116
+ parts = ["\n"]
117
+ arr.each do |v|
118
+ parts << "#{pad(indent)}-#{emit_node(v, indent + 2)}"
119
+ end
120
+ parts.join
121
+ end
122
+ end
123
+
124
+ def emit_time(time)
125
+ " #{time.utc.strftime("%Y-%m-%d %H:%M:%S.%N Z")}\n"
126
+ end
127
+
128
+ def emit_string(str, indent, quote: false)
129
+ # A CR cannot be represented in a block scalar because parsing
130
+ # normalizes CRLF line breaks to LF, so quote and escape instead.
131
+ if str.include?("\n") && !str.include?("\r")
132
+ emit_block_scalar(str, indent)
133
+ elsif needs_quoting?(str, quote)
134
+ " #{quote_string(str)}\n"
135
+ else
136
+ " #{str}\n"
137
+ end
138
+ end
139
+
140
+ def emit_block_scalar(str, indent)
141
+ # The root node has no parent to be indented from, so indent its
142
+ # content by one level like libyaml does.
143
+ indent = 2 if indent.zero?
144
+ parts = [" |#{block_scalar_header(str)}\n"]
145
+ str.each_line do |line|
146
+ parts << (line == "\n" ? line : "#{pad(indent)}#{line}")
147
+ end
148
+ res = parts.join
149
+ res << "\n" unless res.end_with?("\n")
150
+ res
151
+ end
152
+
153
+ # Mirrors libyaml: an explicit indentation indicator when the first
154
+ # line is empty or starts with a space (a parser would otherwise take
155
+ # that whitespace as the block indentation and drop it), "-" when the
156
+ # content does not end with a line break and "+" when it ends with
157
+ # more than one, which also requires a document end marker.
158
+ def block_scalar_header(str)
159
+ header = +""
160
+ header << "2" if str.start_with?(" ", "\n")
161
+ if !str.end_with?("\n")
162
+ header << "-"
163
+ elsif str.end_with?("\n\n") || str == "\n"
164
+ header << "+"
165
+ @open_ended = true
166
+ end
167
+ header
168
+ end
169
+
170
+ def needs_quoting?(str, quote = false, key: false)
171
+ quote || str.empty? || str != str.strip || str =~ /[[:cntrl:]]/ ||
172
+ str =~ /^[!*&:@%$"'|`]/ || str =~ /^-?\d+(\.\d+)?$/ || str =~ /^[<>=-]/ ||
173
+ str == "true" || str == "false" || str == "nil" || str == "null" || str == "~" ||
174
+ (key ? colon_needs_quoting_in_key?(str) : str.include?(":")) ||
175
+ str.include?("#") || str.include?("[") || str.include?("]") ||
176
+ str.include?("{") || str.include?("}") || str.include?(",")
177
+ end
178
+
179
+ # The serializer that RubyGems 4.0 and Bundler 4.0 ship keeps quotes as
180
+ # part of a key, so keys like Bundler's mirror settings for a URL stay
181
+ # plain where YAML allows it, as libyaml writes them. A ":" only ends a
182
+ # plain key when a space or the line end follows it, and a key that
183
+ # starts with a letter is not read as a number or a time.
184
+ def colon_needs_quoting_in_key?(str)
185
+ str.include?(":") && (!str.match?(/\A[[:alpha:]]/) || str.match?(/:(?!\S)/))
186
+ end
187
+
188
+ def quote_string(str)
189
+ %("#{str.gsub(/[\\"]|[[:cntrl:]]/) {|c| STRING_ESCAPES[c] || format("\\x%02X", c.ord) }}")
190
+ end
191
+
192
+ def pad(indent)
193
+ " " * indent
194
+ end
195
+ end
196
+ end
197
+ end
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Gem
4
+ module YAMLSerializer
5
+ Scalar = Struct.new(:value, :tag, :anchor)
6
+ Mapping = Struct.new(:pairs, :tag, :anchor)
7
+ Sequence = Struct.new(:items, :tag, :anchor)
8
+ AliasRef = Struct.new(:name)
9
+ end
10
+ end