debian-mirror-gitlab/lib/gitlab/ci/variables/collection.rb

121 lines
2.9 KiB
Ruby
Raw Normal View History

2018-12-13 13:39:08 +05:30
# frozen_string_literal: true
2018-05-09 12:01:36 +05:30
module Gitlab
module Ci
module Variables
class Collection
include Enumerable
2021-04-17 20:07:23 +05:30
attr_reader :errors
def initialize(variables = [], errors = nil)
2018-05-09 12:01:36 +05:30
@variables = []
2021-04-17 20:07:23 +05:30
@variables_by_key = {}
@errors = errors
2018-05-09 12:01:36 +05:30
variables.each { |variable| self.append(variable) }
end
def append(resource)
2021-04-17 20:07:23 +05:30
item = Collection::Item.fabricate(resource)
@variables.append(item)
@variables_by_key[item[:key]] = item
self
2018-05-09 12:01:36 +05:30
end
2021-09-04 01:27:46 +05:30
def compact
Collection.new(select { |variable| !variable.value.nil? })
end
2018-05-09 12:01:36 +05:30
def concat(resources)
2019-07-07 11:18:12 +05:30
return self if resources.nil?
2018-05-09 12:01:36 +05:30
tap { resources.each { |variable| self.append(variable) } }
end
def each
@variables.each { |variable| yield variable }
end
def +(other)
self.class.new.tap do |collection|
self.each { |variable| collection.append(variable) }
other.each { |variable| collection.append(variable) }
end
end
2021-04-17 20:07:23 +05:30
def [](key)
@variables_by_key[key]
end
def size
@variables.size
end
2018-05-09 12:01:36 +05:30
def to_runner_variables
self.map(&:to_runner_variable)
end
def to_hash
self.to_runner_variables
2021-04-17 20:07:23 +05:30
.to_h { |env| [env.fetch(:key), env.fetch(:value)] }
.with_indifferent_access
2018-05-09 12:01:36 +05:30
end
2021-04-17 20:07:23 +05:30
def reject(&block)
Collection.new(@variables.reject(&block))
end
def expand_value(value, keep_undefined: false)
2021-09-04 01:27:46 +05:30
value.gsub(Item::VARIABLES_REGEXP) do
2021-04-17 20:07:23 +05:30
match = Regexp.last_match
2021-09-04 01:27:46 +05:30
if match[:key]
# we matched variable
if variable = @variables_by_key[match[:key]]
variable.value
elsif keep_undefined
match[0]
end
else
# we escape sequence
match[0]
end
2021-04-17 20:07:23 +05:30
end
end
def sort_and_expand_all(project, keep_undefined: false)
return self if Feature.disabled?(:variable_inside_variable, project)
sorted = Sort.new(self)
return self.class.new(self, sorted.errors) unless sorted.valid?
new_collection = self.class.new
sorted.tsort.each do |item|
unless item.depends_on
new_collection.append(item)
next
end
# expand variables as they are added
variable = item.to_runner_variable
variable[:value] = new_collection.expand_value(variable[:value], keep_undefined: keep_undefined)
new_collection.append(variable)
end
new_collection
end
def to_s
"#{@variables_by_key.keys}, @errors='#{@errors}'"
end
protected
attr_reader :variables
2018-05-09 12:01:36 +05:30
end
end
end
end