BigW Consortium Gitlab

label.rb 5.48 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 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
  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
  validates :title, length: { maximum: 255 }
30

31
  default_scope { order(title: :asc) }
32

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

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

42
  def self.unprioritized(project)
43 44 45 46 47 48 49 50
    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 committed
51 52
  end

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

64
  alias_attribute :name, :title
Dmitriy Zaporozhets committed
65

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

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

92 93 94 95
  def self.link_reference_pattern
    nil
  end

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

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

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

115 116 117 118 119 120 121 122 123 124 125 126 127 128
  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
129 130 131
  def template?
    template
  end
132

133
  def text_color
134
    LabelsHelper.text_color_for_bg(self.color)
135 136
  end

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

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

159 160
    if from_project
      "#{from_project.to_reference(target_project, full: full)}#{reference}"
161 162 163 164 165
    else
      reference
    end
  end

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

172 173
  private

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

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

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

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