diff options
Diffstat (limited to 'lib/expand_variables.rb')
-rw-r--r-- | lib/expand_variables.rb | 53 |
1 files changed, 24 insertions, 29 deletions
diff --git a/lib/expand_variables.rb b/lib/expand_variables.rb index 06160b55f5c..51a66958ba0 100644 --- a/lib/expand_variables.rb +++ b/lib/expand_variables.rb @@ -4,15 +4,15 @@ module ExpandVariables VARIABLES_REGEXP = /\$([a-zA-Z_][a-zA-Z0-9_]*)|\${\g<1>}|%\g<1>%/.freeze class << self - def expand(value, variables) - replace_with(value, variables) do |vars_hash, last_match| - match_or_blank_value(vars_hash, last_match) + def expand(value, variables, expand_file_refs: true) + replace_with(value, variables) do |collection, last_match| + match_or_blank_value(collection, last_match, expand_file_refs: expand_file_refs) end end - def expand_existing(value, variables) - replace_with(value, variables) do |vars_hash, last_match| - match_or_original_value(vars_hash, last_match) + def expand_existing(value, variables, expand_file_refs: true) + replace_with(value, variables) do |collection, last_match| + match_or_original_value(collection, last_match, expand_file_refs: expand_file_refs) end end @@ -25,37 +25,32 @@ module ExpandVariables private def replace_with(value, variables) - variables_hash = nil + # We lazily fabricate the variables collection in case there is no variable in the value string. + # `collection` needs to be initialized to nil here + # so that it is memoized in the closure block for `gsub`. + collection = nil value.gsub(VARIABLES_REGEXP) do - variables_hash ||= transform_variables(variables) - yield(variables_hash, Regexp.last_match) + collection ||= Gitlab::Ci::Variables::Collection.fabricate(variables) + yield(collection, Regexp.last_match) end end - def match_or_blank_value(variables, last_match) - variables[last_match[1] || last_match[2]] - end - - def match_or_original_value(variables, last_match) - match_or_blank_value(variables, last_match) || last_match[0] - end + def match_or_blank_value(collection, last_match, expand_file_refs:) + match = last_match[1] || last_match[2] + replacement = collection[match] - def transform_variables(variables) - # Lazily initialise variables - variables = variables.call if variables.is_a?(Proc) - - # Convert Collection to variables - variables = variables.to_hash if variables.is_a?(Gitlab::Ci::Variables::Collection) - - # Convert hash array to variables - if variables.is_a?(Array) - variables = variables.each_with_object({}) do |variable, hash| - hash[variable[:key]] = variable[:value] - end + if replacement.nil? + nil + elsif replacement.file? + expand_file_refs ? replacement.value : last_match + else + replacement.value end + end - variables + def match_or_original_value(collection, last_match, expand_file_refs:) + match_or_blank_value(collection, last_match, expand_file_refs: expand_file_refs) || last_match[0] end end end |