Strict type string_inreplace_extension

This commit is contained in:
Douglas Eichelberger 2023-07-23 15:56:26 -07:00
parent 0e8d1e0bec
commit c7369b7ea9
2 changed files with 11 additions and 6 deletions

View File

@ -47,6 +47,7 @@ module Utils
} }
def inreplace(paths, before = nil, after = nil, audit_result = true) # rubocop:disable Style/OptionalBooleanParameter def inreplace(paths, before = nil, after = nil, audit_result = true) # rubocop:disable Style/OptionalBooleanParameter
after &&= after.to_s after &&= after.to_s
before = before.to_s if before.is_a?(Pathname)
errors = {} errors = {}
@ -59,7 +60,7 @@ module Utils
if before.nil? && after.nil? if before.nil? && after.nil?
yield s yield s
else else
s.gsub!(T.must(before), after, audit_result) s.gsub!(T.must(before), T.must(after), audit_result)
end end
errors[path] = s.errors unless s.errors.empty? errors[path] = s.errors unless s.errors.empty?

View File

@ -1,16 +1,20 @@
# typed: true # typed: strict
# frozen_string_literal: true # frozen_string_literal: true
# Used by the `inreplace` function (in `utils.rb`). # Used by the `inreplace` function (in `utils.rb`).
# #
# @api private # @api private
class StringInreplaceExtension class StringInreplaceExtension
attr_accessor :errors, :inreplace_string sig { returns(T::Array[String]) }
attr_accessor :errors
sig { returns(String) }
attr_accessor :inreplace_string
sig { params(string: String).void } sig { params(string: String).void }
def initialize(string) def initialize(string)
@inreplace_string = string @inreplace_string = string
@errors = [] @errors = T.let([], T::Array[String])
end end
# Same as `String#sub!`, but warns if nothing was replaced. # Same as `String#sub!`, but warns if nothing was replaced.
@ -27,7 +31,7 @@ class StringInreplaceExtension
# #
# @api public # @api public
sig { sig {
params(before: T.any(Pathname, Regexp, String), after: T.nilable(String), audit_result: T::Boolean) params(before: T.any(Regexp, String), after: String, audit_result: T::Boolean)
.returns(T.nilable(String)) .returns(T.nilable(String))
} }
def gsub!(before, after, audit_result = true) # rubocop:disable Style/OptionalBooleanParameter def gsub!(before, after, audit_result = true) # rubocop:disable Style/OptionalBooleanParameter
@ -65,6 +69,6 @@ class StringInreplaceExtension
# @api public # @api public
sig { params(flag: String).returns(String) } sig { params(flag: String).returns(String) }
def get_make_var(flag) def get_make_var(flag)
inreplace_string[/^#{Regexp.escape(flag)}[ \t]*[\\?+:!]?=[ \t]*((?:.*\\\n)*.*)$/, 1] T.must(inreplace_string[/^#{Regexp.escape(flag)}[ \t]*[\\?+:!]?=[ \t]*((?:.*\\\n)*.*)$/, 1])
end end
end end