Read about our upcoming Code of Conduct on this issue

label.rb 5.38 KB
Newer Older
1
class Label < ActiveRecord::Base
2
  include CacheMarkdownField
3
  include Referable
4
5
  include Subscribable

6
7
  # Represents a "No Label" state used for filtering Issues and Merge
  # Requests that have no label assigned.
8
9
  LabelStruct = Struct.new(:title, :name)
  None = LabelStruct.new('No Label', 'No Label')
10
  Any = LabelStruct.new('Any Label', '')
11

12
13
  cache_markdown_field :description, pipeline: :single_line

14
  DEFAULT_COLOR = '#428BCA'
15

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

18
  has_many :lists, dependent: :destroy
19
  has_many :priorities, class_name: 'LabelPriority'
20
  has_many :label_links, dependent: :destroy
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
21
  has_many :issues, through: :label_links, source: :target, source_type: 'Issue'
22
  has_many :merge_requests, through: :label_links, source: :target, source_type: 'MergeRequest'
23

Robert Speicher's avatar
Robert Speicher committed
24
  validates :color, color: true, allow_blank: false
25

26
  # Don't allow ',' for label titles
27
  validates :title, presence: true, format: { with: /\A[^,]+\z/ }
28
  validates :title, uniqueness: { scope: [:group_id, :project_id] }
29

30
  default_scope { order(title: :asc) }
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
31

32
33
  scope :templates, -> { where(template: true) }
  scope :with_title, ->(title) { where(title: title) }
34

35
36
37
38
  def self.prioritized(project)
    joins(:priorities)
      .where(label_priorities: { project_id: project })
      .reorder('label_priorities.priority ASC, labels.title ASC')
Alfredo Sumaran's avatar
Alfredo Sumaran committed
39
  end
40

41
  def self.unprioritized(project)
42
43
44
45
46
47
48
49
    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))
Thijs Wouters's avatar
Thijs Wouters committed
50
51
  end

52
53
54
55
56
57
58
59
60
61
62
  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

Robert Schilling's avatar
Robert Schilling committed
63
  alias_attribute :name, :title
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
64

65
66
67
68
  def self.reference_prefix
    '~'
  end

69
  ##
70
  # Pattern used to extract label references from text
71
72
73
  #
  # This pattern supports cross-project references.
  #
74
  def self.reference_pattern
75
76
77
    # 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.
78
    @reference_pattern ||= %r{
79
80
      (#{Project.reference_pattern})?
      #{Regexp.escape(reference_prefix)}
81
      (?:
82
        (?<label_id>\d+(?!\S\w)\b) | # Integer-based label ID, or
83
        (?<label_name>
84
          [A-Za-z0-9_\-\?\.&]+ | # String-based single-word label title, or
85
          ".+?"                  # String-based multi-word label surrounded in quotes
86
87
88
89
90
        )
      )
    }x
  end

91
92
93
94
  def self.link_reference_pattern
    nil
  end

95
96
  def open_issues_count(user = nil)
    issues_count(user, state: 'opened')
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
97
  end
Valery Sizov's avatar
Valery Sizov committed
98

99
100
  def closed_issues_count(user = nil)
    issues_count(user, state: 'closed')
101
102
  end

103
104
105
106
107
108
109
110
111
  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
112
113
  end

114
115
116
117
118
119
120
121
122
123
124
125
126
127
  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)
    priorities.find_by(project: project).try(:priority)
  end

Valery Sizov's avatar
Valery Sizov committed
128
129
130
  def template?
    template
  end
131

Phil Hughes's avatar
Phil Hughes committed
132
  def text_color
133
    LabelsHelper.text_color_for_bg(self.color)
Phil Hughes's avatar
Phil Hughes committed
134
135
  end

136
  def title=(value)
137
    write_attribute(:title, sanitize_title(value)) if value.present?
138
139
  end

140
141
142
143
144
145
146
  ##
  # Returns the String necessary to reference this Label in Markdown
  #
  # format - Symbol format to use (default: :id, optional: :name)
  #
  # Examples:
  #
147
148
149
150
  #   Label.first.to_reference                                     # => "~1"
  #   Label.first.to_reference(format: :name)                      # => "~\"bug\""
  #   Label.first.to_reference(project, same_namespace_project)    # => "gitlab-ce~1"
  #   Label.first.to_reference(project, another_namespace_project) # => "gitlab-org/gitlab-ce~1"
151
152
153
154
155
156
157
  #
  # Returns a String
  #
  def to_reference(source_project = nil, target_project = nil, format: :id)
    format_reference = label_format_reference(format)
    reference = "#{self.class.reference_prefix}#{format_reference}"

158
159
    if source_project
      "#{source_project.to_reference(target_project)}#{reference}"
160
161
162
163
164
    else
      reference
    end
  end

165
166
  def as_json(options = {})
    super(options).tap do |json|
167
      json[:priority] = priority(options[:project]) if options.has_key?(:project)
168
169
170
    end
  end

171
172
  private

173
  def issues_count(user, params = {})
174
175
    params.merge!(subject_foreign_key => subject.id, label_name: title, scope: 'all')
    IssuesFinder.new(user, params.with_indifferent_access).execute.count
176
177
  end

178
179
180
181
  def label_format_reference(format = :id)
    raise StandardError, 'Unknown format' unless [:id, :name].include?(format)

    if format == :name && !name.include?('"')
182
      %("#{name}")
183
    else
184
      id
185
186
    end
  end
Thijs Wouters's avatar
Thijs Wouters committed
187

188
  def sanitize_title(value)
189
    CGI.unescapeHTML(Sanitize.clean(value.to_s))
190
  end
191
end