label.rb 8.28 KB
Newer Older
1 2
# frozen_string_literal: true

3
class Label < ApplicationRecord
4
  include CacheMarkdownField
5
  include Referable
6
  include Subscribable
7
  include Gitlab::SQL::Pattern
8
  include OptionallySearch
9
  include Sortable
10
  include FromUnion
11
  include Presentable
12

13 14
  cache_markdown_field :description, pipeline: :single_line

15
  DEFAULT_COLOR = '#428BCA'
16

Douwe Maan's avatar
Douwe Maan committed
17 18
  default_value_for :color, DEFAULT_COLOR

19
  has_many :lists, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
20
  has_many :priorities, class_name: 'LabelPriority'
21
  has_many :label_links, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
22 23
  has_many :issues, through: :label_links, source: :target, source_type: 'Issue'
  has_many :merge_requests, through: :label_links, source: :target, source_type: 'MergeRequest'
24

25 26
  before_validation :strip_whitespace_from_title_and_color

27
  validates :color, color: true, allow_blank: false
28

29
  # Don't allow ',' for label titles
30
  validates :title, presence: true, format: { with: /\A[^,]+\z/ }
31
  validates :title, uniqueness: { scope: [:group_id, :project_id] }
32
  validates :title, length: { maximum: 255 }
33

Nick Thomas's avatar
Nick Thomas committed
34
  default_scope { order(title: :asc) } # rubocop:disable Cop/DefaultScope
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
35

36
  scope :templates, -> { where(template: true, type: [Label.name, nil]) }
37
  scope :with_title, ->(title) { where(title: title) }
Felipe Artur's avatar
Felipe Artur committed
38 39
  scope :with_lists_and_board, -> { joins(lists: :board).merge(List.movable) }
  scope :on_project_boards, ->(project_id) { with_lists_and_board.where(boards: { project_id: project_id }) }
40
  scope :on_board, ->(board_id) { with_lists_and_board.where(boards: { id: board_id }) }
41 42
  scope :order_name_asc, -> { reorder(title: :asc) }
  scope :order_name_desc, -> { reorder(title: :desc) }
43
  scope :subscribed_by, ->(user_id) { joins(:subscriptions).where(subscriptions: { user_id: user_id, subscribed: true }) }
44

45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
  scope :top_labels_by_target, -> (target_relation) {
    label_id_column = arel_table[:id]

    # Window aggregation to count labels
    count_by_id = Arel::Nodes::Over.new(
      Arel::Nodes::NamedFunction.new('count', [label_id_column]),
      Arel::Nodes::Window.new.partition(label_id_column)
    ).as('count_by_id')

    select(arel_table[Arel.star], count_by_id)
      .joins(:label_links)
      .merge(LabelLink.where(target: target_relation))
      .reorder(count_by_id: :desc)
      .distinct
  }

61
  def self.prioritized(project)
62 63 64
    joins(:priorities)
      .where(label_priorities: { project_id: project })
      .reorder('label_priorities.priority ASC, labels.title ASC')
Alfredo Sumaran's avatar
Alfredo Sumaran committed
65
  end
66

67
  def self.unprioritized(project)
68 69 70
    labels = Label.arel_table
    priorities = LabelPriority.arel_table

71 72 73
    label_priorities = labels.join(priorities, Arel::Nodes::OuterJoin)
                              .on(labels[:id].eq(priorities[:label_id]).and(priorities[:project_id].eq(project.id)))
                              .join_sources
74 75

    joins(label_priorities).where(priorities[:priority].eq(nil))
Thijs Wouters's avatar
Thijs Wouters committed
76 77
  end

78 79 80 81
  def self.left_join_priorities
    labels = Label.arel_table
    priorities = LabelPriority.arel_table

82 83 84
    label_priorities = labels.join(priorities, Arel::Nodes::OuterJoin)
                              .on(labels[:id].eq(priorities[:label_id]))
                              .join_sources
85 86 87 88

    joins(label_priorities)
  end

89 90 91 92 93 94 95 96
  def self.optionally_subscribed_by(user_id)
    if user_id
      subscribed_by(user_id)
    else
      all
    end
  end

97
  alias_attribute :name, :title
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
98

99 100 101 102
  def self.reference_prefix
    '~'
  end

103
  ##
104
  # Pattern used to extract label references from text
105 106 107
  #
  # This pattern supports cross-project references.
  #
108
  def self.reference_pattern
109 110 111
    # NOTE: The id pattern only matches when all characters on the expression
    # are digits, so it will match ~2 but not ~2fa because that's probably a
    # label name and we want it to be matched as such.
112
    @reference_pattern ||= %r{
113 114
      (#{Project.reference_pattern})?
      #{Regexp.escape(reference_prefix)}
115
      (?:
116 117 118 119 120 121 122 123 124 125
          (?<label_id>\d+(?!\S\w)\b)
        | # Integer-based label ID, or
          (?<label_name>
              # String-based single-word label title, or
              [A-Za-z0-9_\-\?\.&]+
              (?<!\.|\?)
            |
              # String-based multi-word label surrounded in quotes
              ".+?"
          )
126 127 128 129
      )
    }x
  end

130 131 132 133
  def self.link_reference_pattern
    nil
  end

134 135
  # Searches for labels with a matching title or description.
  #
136
  # This method uses ILIKE on PostgreSQL.
137 138 139 140
  #
  # query - The search query as a String.
  #
  # Returns an ActiveRecord::Relation.
141
  def self.search(query, **options)
142 143 144
    fuzzy_search(query, [:title, :description])
  end

145 146 147 148 149 150 151
  # Override Gitlab::SQL::Pattern.min_chars_for_partial_matching as
  # label queries are never global, and so will not use a trigram
  # index. That means we can have just one character in the LIKE.
  def self.min_chars_for_partial_matching
    1
  end

152 153 154 155
  def self.by_ids(ids)
    where(id: ids)
  end

156
  def self.on_project_board?(project_id, label_id)
157 158
    return false if label_id.blank?

159 160 161
    on_project_boards(project_id).where(id: label_id).exists?
  end

162 163 164 165 166
  # Generate a hex color based on hex-encoded value
  def self.color_for(value)
    "##{Digest::MD5.hexdigest(value)[0..5]}"
  end

167 168
  def open_issues_count(user = nil)
    issues_count(user, state: 'opened')
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
169
  end
Valery Sizov's avatar
Valery Sizov committed
170

171 172
  def closed_issues_count(user = nil)
    issues_count(user, state: 'closed')
173 174
  end

175 176 177 178 179 180 181 182 183
  def open_merge_requests_count(user = nil)
    params = {
      subject_foreign_key => subject.id,
      label_name: title,
      scope: 'all',
      state: 'opened'
    }

    MergeRequestsFinder.new(user, params.with_indifferent_access).execute.count
184 185
  end

186 187 188 189 190 191 192 193 194 195 196
  def prioritize!(project, value)
    label_priority = priorities.find_or_initialize_by(project_id: project.id)
    label_priority.priority = value
    label_priority.save!
  end

  def unprioritize!(project)
    priorities.where(project: project).delete_all
  end

  def priority(project)
197 198 199 200 201
    priority = if priorities.loaded?
                 priorities.first { |p| p.project == project }
               else
                 priorities.find_by(project: project)
               end
202

203
    priority.try(:priority)
204 205
  end

206 207 208 209
  def priority?
    priorities.present?
  end

210 211 212 213
  def color
    super || DEFAULT_COLOR
  end

214
  def text_color
215
    LabelsHelper.text_color_for_bg(self.color)
216 217
  end

218
  def title=(value)
219 220 221 222 223
    write_attribute(:title, sanitize_value(value)) if value.present?
  end

  def description=(value)
    write_attribute(:description, sanitize_value(value)) if value.present?
224 225
  end

226 227 228 229 230 231 232
  ##
  # Returns the String necessary to reference this Label in Markdown
  #
  # format - Symbol format to use (default: :id, optional: :name)
  #
  # Examples:
  #
233 234
  #   Label.first.to_reference                                     # => "~1"
  #   Label.first.to_reference(format: :name)                      # => "~\"bug\""
235 236
  #   Label.first.to_reference(project, target_project: same_namespace_project)    # => "gitlab-foss~1"
  #   Label.first.to_reference(project, target_project: another_namespace_project) # => "gitlab-org/gitlab-foss~1"
237 238 239
  #
  # Returns a String
  #
240
  def to_reference(from = nil, target_project: nil, format: :id, full: false)
241 242 243
    format_reference = label_format_reference(format)
    reference = "#{self.class.reference_prefix}#{format_reference}"

244
    if from
245
      "#{from.to_reference_base(target_project, full: full)}#{reference}"
246 247 248 249 250
    else
      reference
    end
  end

251 252
  def as_json(options = {})
    super(options).tap do |json|
Felipe Artur's avatar
Felipe Artur committed
253
      json[:type] = self.try(:type)
254
      json[:priority] = priority(options[:project]) if options.key?(:project)
255
      json[:textColor] = text_color
256 257 258
    end
  end

259 260 261 262
  def hook_attrs
    attributes
  end

263 264 265 266
  def present(attributes)
    super(attributes.merge(presenter_class: ::LabelPresenter))
  end

267 268
  private

269
  def issues_count(user, params = {})
270 271
    params.merge!(subject_foreign_key => subject.id, label_name: title, scope: 'all')
    IssuesFinder.new(user, params.with_indifferent_access).execute.count
272 273
  end

274 275 276 277
  def label_format_reference(format = :id)
    raise StandardError, 'Unknown format' unless [:id, :name].include?(format)

    if format == :name && !name.include?('"')
278
      %("#{name}")
279
    else
280
      id
281 282
    end
  end
Thijs Wouters's avatar
Thijs Wouters committed
283

284
  def sanitize_value(value)
285
    CGI.unescapeHTML(Sanitize.clean(value.to_s))
286
  end
287 288 289 290

  def strip_whitespace_from_title_and_color
    %w(color title).each { |attr| self[attr] = self[attr]&.strip }
  end
291
end
292

293
Label.prepend_if_ee('EE::Label')