Class: Label

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

Direct Known Subclasses

GroupLabel, ProjectLabel

Constant Summary collapse

DEFAULT_COLOR =
'#428BCA'

Constants included from Gitlab::SQL::Pattern

Gitlab::SQL::Pattern::MIN_CHARS_FOR_PARTIAL_MATCHING, Gitlab::SQL::Pattern::REGEX_QUOTED_WORD

Constants included from CacheMarkdownField

CacheMarkdownField::INVALIDATED_BY

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Subscribable

#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, #parent_user, #refresh_markdown_cache, #refresh_markdown_cache!, #rendered_field_content, #skip_project_check?, #updated_cached_html_for

Methods inherited from ApplicationRecord

at_most, id_in, id_not_in, iid_in, pluck_primary_key, primary_key_in, safe_ensure_unique, safe_find_or_create_by, safe_find_or_create_by!, underscore, without_order

Class Method Details

.color_for(value) ⇒ Object

Generate a hex color based on hex-encoded value


159
160
161
# File 'app/models/label.rb', line 159

def self.color_for(value)
  "##{Digest::MD5.hexdigest(value)[0..5]}"
end

.left_join_prioritiesObject


78
79
80
81
82
83
84
85
86
87
# File 'app/models/label.rb', line 78

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

130
131
132
# File 'app/models/label.rb', line 130

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.


148
149
150
# File 'app/models/label.rb', line 148

def self.min_chars_for_partial_matching
  1
end

.on_project_board?(project_id, label_id) ⇒ Boolean

Returns:

  • (Boolean)

152
153
154
155
156
# File 'app/models/label.rb', line 152

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


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

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

.prioritized(project) ⇒ Object


61
62
63
64
65
# File 'app/models/label.rb', line 61

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.


108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'app/models/label.rb', line 108

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
            [A-Za-z0-9_\-\?\.&]+
            (?<!\.|\?)
          |
            # String-based multi-word label surrounded in quotes
            ".+?"
        )
    )
  }x
end

.reference_prefixObject


99
100
101
# File 'app/models/label.rb', line 99

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.


141
142
143
# File 'app/models/label.rb', line 141

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

.unprioritized(project) ⇒ Object


67
68
69
70
71
72
73
74
75
76
# File 'app/models/label.rb', line 67

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


247
248
249
250
251
252
253
# File 'app/models/label.rb', line 247

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


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

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

#colorObject


206
207
208
# File 'app/models/label.rb', line 206

def color
  super || DEFAULT_COLOR
end

#description=(value) ⇒ Object


218
219
220
# File 'app/models/label.rb', line 218

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

#hook_attrsObject


255
256
257
# File 'app/models/label.rb', line 255

def hook_attrs
  attributes
end

#open_issues_count(user = nil) ⇒ Object


163
164
165
# File 'app/models/label.rb', line 163

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

#open_merge_requests_count(user = nil) ⇒ Object


171
172
173
174
175
176
177
178
179
180
# File 'app/models/label.rb', line 171

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


259
260
261
# File 'app/models/label.rb', line 259

def present(attributes)
  super(attributes.merge(presenter_class: ::LabelPresenter))
end

#prioritize!(project, value) ⇒ Object


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

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


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

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)

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

def priority?
  priorities.present?
end

#text_colorObject


210
211
212
# File 'app/models/label.rb', line 210

def text_color
  LabelsHelper.text_color_for_bg(self.color)
end

#title=(value) ⇒ Object


214
215
216
# File 'app/models/label.rb', line 214

def title=(value)
  write_attribute(:title, sanitize_value(value)) if value.present?
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


236
237
238
239
240
241
242
243
244
245
# File 'app/models/label.rb', line 236

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


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

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