1# frozen_string_literal: true
2
3class Ci::CommitWithPipeline < SimpleDelegator
4  include Presentable
5
6  def initialize(commit)
7    @latest_pipelines = {}
8    super(commit)
9  end
10
11  def pipelines
12    project.ci_pipelines.where(sha: sha)
13  end
14
15  def last_pipeline
16    strong_memoize(:last_pipeline) do
17      pipelines.last
18    end
19  end
20
21  def lazy_latest_pipeline
22    BatchLoader.for(sha).batch do |shas, loader|
23      preload_pipelines = project.ci_pipelines.latest_pipeline_per_commit(shas.compact)
24
25      shas.each do |sha|
26        pipeline = preload_pipelines[sha]
27
28        loader.call(sha, pipeline)
29      end
30    end
31  end
32
33  def latest_pipeline(ref = nil)
34    @latest_pipelines.fetch(ref) do |ref|
35      @latest_pipelines[ref] = if ref
36                                 latest_pipeline_for_project(ref, project)
37                               else
38                                 lazy_latest_pipeline&.itself
39                               end
40    end
41  end
42
43  def latest_pipeline_for_project(ref, pipeline_project)
44    pipeline_project.ci_pipelines.latest_pipeline_per_commit(id, ref)[id]
45  end
46
47  def set_latest_pipeline_for_ref(ref, pipeline)
48    @latest_pipelines[ref] = pipeline
49  end
50
51  def status(ref = nil)
52    latest_pipeline(ref)&.status
53  end
54end
55