BigW Consortium Gitlab

label.rb 5.82 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
19
  has_many :priorities, class_name: 'LabelPriority'
20
  has_many :label_links, dependent: :destroy
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

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 :on_project_boards, ->(project_id) { joins(lists: :board).merge(List.movable).where(boards: { project_id: project_id }) }
38

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

45
  def self.unprioritized(project)
46 47 48
    labels = Label.arel_table
    priorities = LabelPriority.arel_table

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

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

56 57 58 59
  def self.left_join_priorities
    labels = Label.arel_table
    priorities = LabelPriority.arel_table

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

    joins(label_priorities)
  end

67
  alias_attribute :name, :title
Dmitriy Zaporozhets committed
68

69 70 71 72
  def self.reference_prefix
    '~'
  end

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

95 96 97 98
  def self.link_reference_pattern
    nil
  end

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

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

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

118 119 120 121 122 123 124 125 126 127 128 129 130 131
  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 committed
132 133 134
  def template?
    template
  end
135

136
  def text_color
137
    LabelsHelper.text_color_for_bg(self.color)
138 139
  end

140
  def title=(value)
141
    write_attribute(:title, sanitize_title(value)) if value.present?
142 143
  end

144 145 146 147 148 149 150
  ##
  # Returns the String necessary to reference this Label in Markdown
  #
  # format - Symbol format to use (default: :id, optional: :name)
  #
  # Examples:
  #
151 152
  #   Label.first.to_reference                                     # => "~1"
  #   Label.first.to_reference(format: :name)                      # => "~\"bug\""
153 154
  #   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"
155 156 157
  #
  # Returns a String
  #
158
  def to_reference(from_project = nil, target_project: nil, format: :id, full: false)
159 160 161
    format_reference = label_format_reference(format)
    reference = "#{self.class.reference_prefix}#{format_reference}"

162 163
    if from_project
      "#{from_project.to_reference(target_project, full: full)}#{reference}"
164 165 166 167 168
    else
      reference
    end
  end

169 170
  def as_json(options = {})
    super(options).tap do |json|
171
      json[:priority] = priority(options[:project]) if options.has_key?(:project)
172 173 174
    end
  end

175 176 177 178
  def hook_attrs
    attributes
  end

179 180
  private

181
  def issues_count(user, params = {})
182 183
    params.merge!(subject_foreign_key => subject.id, label_name: title, scope: 'all')
    IssuesFinder.new(user, params.with_indifferent_access).execute.count
184 185
  end

186 187 188 189
  def label_format_reference(format = :id)
    raise StandardError, 'Unknown format' unless [:id, :name].include?(format)

    if format == :name && !name.include?('"')
190
      %("#{name}")
191
    else
192
      id
193 194
    end
  end
Thijs Wouters committed
195

196
  def sanitize_title(value)
197
    CGI.unescapeHTML(Sanitize.clean(value.to_s))
198
  end
199 200 201 202

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