Class: Label

Inherits:
ApplicationRecord show all
Includes:
CacheMarkdownField, EachBatch, FromUnion, Gitlab::SQL::Pattern, OptionallySearch, Presentable, Referable, Sortable, Subscribable
Defined in:
app/models/label.rb

Direct Known Subclasses

Admin::AbuseReportLabel, GroupLabel, ProjectLabel

Constant Summary collapse

DEFAULT_COLOR =
::Gitlab::Color.of('#6699cc')
DESCRIPTION_LENGTH_MAX =
512.kilobytes

Constants included from Gitlab::SQL::Pattern

Gitlab::SQL::Pattern::MIN_CHARS_FOR_PARTIAL_MATCHING, Gitlab::SQL::Pattern::REGEX_QUOTED_TERM

Constants included from CacheMarkdownField

CacheMarkdownField::INVALIDATED_BY

Constants inherited from ApplicationRecord

ApplicationRecord::MAX_PLUCK

Constants included from ResetOnUnionError

ResetOnUnionError::MAX_RESET_PERIOD

Instance Attribute Summary

Attributes included from CacheMarkdownField

#skip_markdown_cache_validation

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Gitlab::SQL::Pattern

split_query_to_search_terms

Methods included from Subscribable

#lazy_subscription, #set_subscription, #subscribe, #subscribed?, #subscribed_without_subscriptions?, #subscribers, #toggle_subscription, #unsubscribe

Methods included from Referable

#referable_inspect, #reference_link_text, #to_reference_base

Methods included from CacheMarkdownField

#attribute_invalidated?, #banzai_render_context, #cached_html_for, #cached_html_up_to_date?, #can_cache_field?, #invalidated_markdown_cache?, #latest_cached_markdown_version, #local_version, #mentionable_attributes_changed?, #mentioned_filtered_user_ids_for, #parent_user, #refresh_markdown_cache, #refresh_markdown_cache!, #rendered_field_content, #skip_project_check?, #store_mentions!, #updated_cached_html_for

Methods inherited from ApplicationRecord

cached_column_list, #create_or_load_association, declarative_enum, default_select_columns, id_in, id_not_in, iid_in, pluck_primary_key, primary_key_in, #readable_by?, safe_ensure_unique, safe_find_or_create_by, safe_find_or_create_by!, #to_ability_name, underscore, where_exists, where_not_exists, with_fast_read_statement_timeout, without_order

Methods included from SensitiveSerializableHash

#serializable_hash

Class Method Details

.ids_on_board(board_id) ⇒ Object



155
156
157
# File 'app/models/label.rb', line 155

def self.ids_on_board(board_id)
  on_board(board_id).pluck(:label_id)
end

.left_join_prioritiesObject



99
100
101
102
103
104
105
106
107
108
# File 'app/models/label.rb', line 99

def self.left_join_priorities
  labels = Label.arel_table
  priorities = LabelPriority.arel_table

  label_priorities = labels.join(priorities, Arel::Nodes::OuterJoin)
                            .on(labels[:id].eq(priorities[:label_id]))
                            .join_sources

  joins(label_priorities)
end


151
152
153
# File 'app/models/label.rb', line 151

def self.link_reference_pattern
  nil
end

.min_chars_for_partial_matchingObject

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.



173
174
175
# File 'app/models/label.rb', line 173

def self.min_chars_for_partial_matching
  1
end

.on_project_board?(project_id, label_id) ⇒ Boolean

Returns:

  • (Boolean)


177
178
179
180
181
# File 'app/models/label.rb', line 177

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

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

.optionally_subscribed_by(user_id) ⇒ Object



110
111
112
113
114
115
116
# File 'app/models/label.rb', line 110

def self.optionally_subscribed_by(user_id)
  if user_id
    subscribed_by(user_id)
  else
    all
  end
end

.pluck_titlesObject



78
79
80
# File 'app/models/label.rb', line 78

def self.pluck_titles
  pluck(:title)
end

.prioritized(project) ⇒ Object



82
83
84
85
86
# File 'app/models/label.rb', line 82

def self.prioritized(project)
  joins(:priorities)
    .where(label_priorities: { project_id: project })
    .reorder('label_priorities.priority ASC, labels.title ASC')
end

.reference_patternObject

Pattern used to extract label references from text

This pattern supports cross-project references.



129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
# File 'app/models/label.rb', line 129

def self.reference_pattern
  # 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.
  @reference_pattern ||= %r{
    (#{Project.reference_pattern})?
    #{Regexp.escape(reference_prefix)}
    (?:
        (?<label_id>\d+(?!\S\w)\b)
      | # Integer-based label ID, or
        (?<label_name>
            # String-based single-word label title, or
            #{Gitlab::Regex.sep_by_1(/:{1,2}/, /[A-Za-z0-9_\-\?\.&]+/)}
            (?<!\.|\?)
          |
            # String-based multi-word label surrounded in quotes
            ".+?"
        )
    )
  }x
end

.reference_prefixObject



120
121
122
# File 'app/models/label.rb', line 120

def self.reference_prefix
  '~'
end

.search(query, **options) ⇒ Object

Searches for labels with a matching title or description.

This method uses ILIKE on PostgreSQL.

query - The search query as a String.

Returns an ActiveRecord::Relation.



166
167
168
# File 'app/models/label.rb', line 166

def self.search(query, **options)
  fuzzy_search(query, [:title, :description])
end

.unprioritized(project) ⇒ Object



88
89
90
91
92
93
94
95
96
97
# File 'app/models/label.rb', line 88

def self.unprioritized(project)
  labels = Label.arel_table
  priorities = LabelPriority.arel_table

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

  joins(label_priorities).where(priorities[:priority].eq(nil))
end

Instance Method Details

#as_json(options = {}) ⇒ Object



275
276
277
278
279
280
281
# File 'app/models/label.rb', line 275

def as_json(options = {})
  super(options).tap do |json|
    json[:type] = self.try(:type)
    json[:priority] = priority(options[:project]) if options.key?(:project)
    json[:textColor] = text_color
  end
end

#closed_issues_count(user = nil) ⇒ Object



187
188
189
# File 'app/models/label.rb', line 187

def closed_issues_count(user = nil)
  issues_count(user, state: 'closed')
end

#colorObject



226
227
228
# File 'app/models/label.rb', line 226

def color
  super || DEFAULT_COLOR
end

#description=(value) ⇒ Object



242
243
244
245
246
247
248
# File 'app/models/label.rb', line 242

def description=(value)
  if value.blank?
    super
  else
    write_attribute(:description, sanitize_value(value))
  end
end

#hook_attrsObject



283
284
285
# File 'app/models/label.rb', line 283

def hook_attrs
  attributes
end

#open_issues_count(user = nil) ⇒ Object



183
184
185
# File 'app/models/label.rb', line 183

def open_issues_count(user = nil)
  issues_count(user, state: 'opened')
end

#open_merge_requests_count(user = nil) ⇒ Object



191
192
193
194
195
196
197
198
199
200
# File 'app/models/label.rb', line 191

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
end

#present(attributes = {}) ⇒ Object



287
288
289
# File 'app/models/label.rb', line 287

def present(attributes = {})
  super(**attributes.merge(presenter_class: ::LabelPresenter))
end

#prioritize!(project, value) ⇒ Object



202
203
204
205
206
# File 'app/models/label.rb', line 202

def prioritize!(project, value)
  label_priority = priorities.find_or_initialize_by(project_id: project.id)
  label_priority.priority = value
  label_priority.save!
end

#priority(project) ⇒ Object



212
213
214
215
216
217
218
219
220
# File 'app/models/label.rb', line 212

def priority(project)
  priority = if priorities.loaded?
               priorities.first { |p| p.project == project }
             else
               priorities.find_by(project: project)
             end

  priority.try(:priority)
end

#priority?Boolean

Returns:

  • (Boolean)


222
223
224
# File 'app/models/label.rb', line 222

def priority?
  priorities.present?
end

#text_colorObject



230
231
232
# File 'app/models/label.rb', line 230

def text_color
  color.contrast
end

#title=(value) ⇒ Object



234
235
236
237
238
239
240
# File 'app/models/label.rb', line 234

def title=(value)
  if value.blank?
    super
  else
    write_attribute(:title, sanitize_value(value))
  end
end

#to_reference(from = nil, target_project: nil, format: :id, full: false) ⇒ Object

Returns the String necessary to reference this Label in Markdown

format - Symbol format to use (default: :id, optional: :name)

Examples:

Label.first.to_reference                                     # => "~1"
Label.first.to_reference(format: :name)                      # => "~\"bug\""
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"

Returns a String



264
265
266
267
268
269
270
271
272
273
# File 'app/models/label.rb', line 264

def to_reference(from = nil, target_project: nil, format: :id, full: false)
  format_reference = label_format_reference(format)
  reference = "#{self.class.reference_prefix}#{format_reference}"

  if from
    "#{from.to_reference_base(target_project, full: full)}#{reference}"
  else
    reference
  end
end

#unprioritize!(project) ⇒ Object



208
209
210
# File 'app/models/label.rb', line 208

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