BigW Consortium Gitlab

label.rb 6.28 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'.freeze
15

Douwe Maan committed
16 17
  default_value_for :color, DEFAULT_COLOR

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

24 25
  before_validation :strip_whitespace_from_title_and_color

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

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

33
  default_scope { order(title: :asc) }
34

35 36
  scope :templates, -> { where(template: true) }
  scope :with_title, ->(title) { where(title: title) }
37
  scope :with_lists_and_board, -> { joins(lists: :board).merge(List.movable) }
38
  scope :on_group_boards, ->(group_id) { with_lists_and_board.where(boards: { group_id: group_id }) }
39
  scope :on_project_boards, ->(project_id) { with_lists_and_board.where(boards: { project_id: project_id }) }
40

41
  def self.prioritized(project)
42 43 44
    joins(:priorities)
      .where(label_priorities: { project_id: project })
      .reorder('label_priorities.priority ASC, labels.title ASC')
45
  end
46

47
  def self.unprioritized(project)
48 49 50
    labels = Label.arel_table
    priorities = LabelPriority.arel_table

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

    joins(label_priorities).where(priorities[:priority].eq(nil))
Thijs Wouters committed
56 57
  end

58 59 60 61
  def self.left_join_priorities
    labels = Label.arel_table
    priorities = LabelPriority.arel_table

62 63 64
    label_priorities = labels.join(priorities, Arel::Nodes::OuterJoin)
                              .on(labels[:id].eq(priorities[:label_id]))
                              .join_sources
65 66 67 68

    joins(label_priorities)
  end

69
  alias_attribute :name, :title
Dmitriy Zaporozhets committed
70

71 72 73 74
  def self.reference_prefix
    '~'
  end

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

97 98 99 100
  def self.link_reference_pattern
    nil
  end

101 102
  def open_issues_count(user = nil)
    issues_count(user, state: 'opened')
Dmitriy Zaporozhets committed
103
  end
Valery Sizov committed
104

105 106
  def closed_issues_count(user = nil)
    issues_count(user, state: 'closed')
107 108
  end

109 110 111 112 113 114 115 116 117
  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
118 119
  end

120 121 122 123 124 125 126 127 128 129 130
  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)
131 132 133 134 135
    priority = if priorities.loaded?
                 priorities.first { |p| p.project == project }
               else
                 priorities.find_by(project: project)
               end
136

137
    priority.try(:priority)
138 139
  end

Valery Sizov committed
140 141 142
  def template?
    template
  end
143

144 145 146 147
  def color
    super || DEFAULT_COLOR
  end

148
  def text_color
149
    LabelsHelper.text_color_for_bg(self.color)
150 151
  end

152
  def title=(value)
153
    write_attribute(:title, sanitize_title(value)) if value.present?
154 155
  end

156 157 158 159 160 161 162
  ##
  # Returns the String necessary to reference this Label in Markdown
  #
  # format - Symbol format to use (default: :id, optional: :name)
  #
  # Examples:
  #
163 164
  #   Label.first.to_reference                                     # => "~1"
  #   Label.first.to_reference(format: :name)                      # => "~\"bug\""
165 166
  #   Label.first.to_reference(project, target_project: same_namespace_project)    # => "gitlab-ce~1"
  #   Label.first.to_reference(project, target_project: another_namespace_project) # => "gitlab-org/gitlab-ce~1"
167 168 169
  #
  # Returns a String
  #
170
  def to_reference(from = nil, target_project: nil, format: :id, full: false)
171 172 173
    format_reference = label_format_reference(format)
    reference = "#{self.class.reference_prefix}#{format_reference}"

174 175
    if from
      "#{from.to_reference(target_project, full: full)}#{reference}"
176 177 178 179 180
    else
      reference
    end
  end

181 182
  def as_json(options = {})
    super(options).tap do |json|
Felipe Artur committed
183
      json[:type] = self.try(:type)
184
      json[:priority] = priority(options[:project]) if options.key?(:project)
185 186 187
    end
  end

188 189 190 191
  def hook_attrs
    attributes
  end

192 193
  private

194
  def issues_count(user, params = {})
195 196
    params.merge!(subject_foreign_key => subject.id, label_name: title, scope: 'all')
    IssuesFinder.new(user, params.with_indifferent_access).execute.count
197 198
  end

199 200 201 202
  def label_format_reference(format = :id)
    raise StandardError, 'Unknown format' unless [:id, :name].include?(format)

    if format == :name && !name.include?('"')
203
      %("#{name}")
204
    else
205
      id
206 207
    end
  end
Thijs Wouters committed
208

209
  def sanitize_title(value)
210
    CGI.unescapeHTML(Sanitize.clean(value.to_s))
211
  end
212 213 214 215

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