transfer_service.rb 1.43 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Labels::TransferService class
#
# User for recreate the missing group labels at project level
#
module Labels
  class TransferService
    def initialize(current_user, group, project)
      @current_user = current_user
      @group = group
      @project = project
    end

    def execute
      return unless group.present?

      Label.transaction do
        labels_to_transfer = Label.where(id: label_links.select(:label_id).uniq)

        labels_to_transfer.find_each do |label|
          new_label_id = find_or_create_label!(label)

22
23
          next if new_label_id == label.id

24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
          LabelLink.where(label_id: label.id).update_all(label_id: new_label_id)
        end
      end
    end

    private

    attr_reader :current_user, :group, :project

    def label_links
      label_link_ids = []
      label_link_ids << LabelLink.where(target: project.issues, label: group.labels).select(:id)
      label_link_ids << LabelLink.where(target: project.merge_requests, label: group.labels).select(:id)

      union = Gitlab::SQL::Union.new(label_link_ids)

      LabelLink.where("label_links.id IN (#{union.to_sql})")
    end

    def labels
      @labels ||= LabelsFinder.new(current_user, project_id: project.id).execute
    end

    def find_or_create_label!(label)
      new_label = labels.find_by(title: label.title)
      new_label ||= project.labels.create!(label.attributes.slice("title", "description", "color"))

      new_label.id
    end
  end
end