create_builds_service.rb 1.85 KB
Newer Older
1 2
module Ci
  class CreateBuildsService
3 4
    def initialize(pipeline)
      @pipeline = pipeline
5
      @config = pipeline.config_processor
6 7 8
    end

    def execute(stage, user, status, trigger_request = nil)
9
      builds_attrs = @config.builds_for_stage_and_ref(stage, @pipeline.ref, @pipeline.tag, trigger_request)
Kamil Trzciński's avatar
Kamil Trzciński committed
10

11 12 13 14 15 16 17 18 19 20 21 22
      # check when to create next build
      builds_attrs = builds_attrs.select do |build_attrs|
        case build_attrs[:when]
        when 'on_success'
          status == 'success'
        when 'on_failure'
          status == 'failed'
        when 'always'
          %w(success failed).include?(status)
        end
      end

23 24
      # don't create the same build twice
      builds_attrs.reject! do |build_attrs|
25 26
        @pipeline.builds.find_by(ref: @pipeline.ref,
                                 tag: @pipeline.tag,
27 28
                                 trigger_request: trigger_request,
                                 name: build_attrs[:name])
29 30
      end

Kamil Trzciński's avatar
Kamil Trzciński committed
31
      builds_attrs.map do |build_attrs|
32 33 34 35 36 37
        build_attrs.slice!(:name,
                           :commands,
                           :tag_list,
                           :options,
                           :allow_failure,
                           :stage,
38
                           :stage_idx,
39 40 41
                           :environment,
                           :when,
                           :yaml_variables)
Kamil Trzciński's avatar
Kamil Trzciński committed
42

43 44 45
        build_attrs.merge!(pipeline: @pipeline,
                           ref: @pipeline.ref,
                           tag: @pipeline.tag,
46 47
                           trigger_request: trigger_request,
                           user: user,
48
                           project: @pipeline.project)
Kamil Trzciński's avatar
Kamil Trzciński committed
49

50 51
        ##
        # We do not persist new builds here.
52
        # Those will be persisted when @pipeline is saved.
53
        #
54
        @pipeline.builds.new(build_attrs)
55 56 57 58
      end
    end
  end
end