project.rb 22.4 KB
Newer Older
D
Dmitriy Zaporozhets 已提交
1 2 3 4 5 6 7 8
# == Schema Information
#
# Table name: projects
#
#  id                     :integer          not null, primary key
#  name                   :string(255)
#  path                   :string(255)
#  description            :text
D
Dmitriy Zaporozhets 已提交
9 10
#  created_at             :datetime
#  updated_at             :datetime
D
Dmitriy Zaporozhets 已提交
11
#  creator_id             :integer
D
Dmitriy Zaporozhets 已提交
12 13 14 15
#  issues_enabled         :boolean          default(TRUE), not null
#  wall_enabled           :boolean          default(TRUE), not null
#  merge_requests_enabled :boolean          default(TRUE), not null
#  wiki_enabled           :boolean          default(TRUE), not null
D
Dmitriy Zaporozhets 已提交
16
#  namespace_id           :integer
D
Dmitriy Zaporozhets 已提交
17
#  issues_tracker         :string(255)      default("gitlab"), not null
D
Dmitriy Zaporozhets 已提交
18
#  issues_tracker_id      :string(255)
D
Dmitriy Zaporozhets 已提交
19
#  snippets_enabled       :boolean          default(TRUE), not null
20
#  last_activity_at       :datetime
D
Dmitriy Zaporozhets 已提交
21
#  import_url             :string(255)
22
#  visibility_level       :integer          default(0), not null
D
Dmitriy Zaporozhets 已提交
23
#  archived               :boolean          default(FALSE), not null
A
Atsushi Ishida 已提交
24
#  avatar                 :string(255)
D
Dmitriy Zaporozhets 已提交
25
#  import_status          :string(255)
D
Dmitriy Zaporozhets 已提交
26 27
#  repository_size        :float            default(0.0)
#  star_count             :integer          default(0), not null
D
Dmitriy Zaporozhets 已提交
28 29
#  import_type            :string(255)
#  import_source          :string(255)
A
Atsushi Ishida 已提交
30
#  commit_count           :integer          default(0)
D
Dmitriy Zaporozhets 已提交
31 32
#

33 34 35
require 'carrierwave/orm/activerecord'
require 'file_size_validator'

G
gitlabhq 已提交
36
class Project < ActiveRecord::Base
37
  include Gitlab::ConfigHelper
38
  include Gitlab::ShellAdapter
39
  include Gitlab::VisibilityLevel
40 41
  include Referable
  include Sortable
42
  include AfterCommitQueue
43
  include CaseSensitivity
44
  include HasOwners
S
sue445 已提交
45

46
  extend Gitlab::ConfigHelper
47
  extend Enumerize
48

J
Jared Szechy 已提交
49 50
  UNKNOWN_IMPORT_URL = 'http://unknown.git'

51
  default_value_for :archived, false
52 53 54 55
  default_value_for :visibility_level, gitlab_config_features.visibility_level
  default_value_for :issues_enabled, gitlab_config_features.issues
  default_value_for :merge_requests_enabled, gitlab_config_features.merge_requests
  default_value_for :wiki_enabled, gitlab_config_features.wiki
56
  default_value_for :wall_enabled, false
57
  default_value_for :snippets_enabled, gitlab_config_features.snippets
58

59 60
  # set last_activity_at to the same as created_at
  after_create :set_last_activity_at
61
  def set_last_activity_at
62
    update_column(:last_activity_at, self.created_at)
63 64
  end

65
  ActsAsTaggableOn.strict_case_match = true
66
  acts_as_taggable_on :tags
D
Dmitriy Zaporozhets 已提交
67

68 69
  attr_accessor :new_default_branch

70
  # Relations
71
  belongs_to :creator, foreign_key: 'creator_id', class_name: 'User'
72
  belongs_to :group, -> { where(type: Group) }, foreign_key: 'namespace_id'
73
  belongs_to :namespace
74

75
  has_one :last_event, -> {order 'events.created_at DESC'}, class_name: 'Event', foreign_key: 'project_id'
76 77 78

  # Project services
  has_many :services
D
Dmitriy Zaporozhets 已提交
79
  has_one :gitlab_ci_service, dependent: :destroy
D
Dmitriy Zaporozhets 已提交
80
  has_one :campfire_service, dependent: :destroy
K
Kirilll Zaitsev 已提交
81
  has_one :drone_ci_service, dependent: :destroy
82
  has_one :emails_on_push_service, dependent: :destroy
A
Aorimn 已提交
83
  has_one :irker_service, dependent: :destroy
84
  has_one :pivotaltracker_service, dependent: :destroy
R
Ronald van Eede 已提交
85
  has_one :hipchat_service, dependent: :destroy
86
  has_one :flowdock_service, dependent: :destroy
C
Carlos Paramio 已提交
87
  has_one :assembla_service, dependent: :destroy
J
Jeremy 已提交
88
  has_one :asana_service, dependent: :destroy
89
  has_one :gemnasium_service, dependent: :destroy
90
  has_one :slack_service, dependent: :destroy
91
  has_one :buildkite_service, dependent: :destroy
D
Drew Blessing 已提交
92
  has_one :bamboo_service, dependent: :destroy
93
  has_one :teamcity_service, dependent: :destroy
94
  has_one :pushover_service, dependent: :destroy
95 96
  has_one :jira_service, dependent: :destroy
  has_one :redmine_service, dependent: :destroy
M
Marin Jankovski 已提交
97
  has_one :custom_issue_tracker_service, dependent: :destroy
98
  has_one :gitlab_issue_tracker_service, dependent: :destroy
D
Dmitriy Zaporozhets 已提交
99
  has_one :external_wiki_service, dependent: :destroy
100

101
  has_one :forked_project_link, dependent: :destroy, foreign_key: "forked_to_project_id"
102

103
  has_one :forked_from_project, through: :forked_project_link
104
  # Merge Requests for target project should be removed with it
105
  has_many :merge_requests,     dependent: :destroy, foreign_key: 'target_project_id'
106
  # Merge requests from source project should be kept when source project was removed
107
  has_many :fork_merge_requests, foreign_key: 'source_project_id', class_name: MergeRequest
108
  has_many :issues,             dependent: :destroy
109
  has_many :labels,             dependent: :destroy
110 111
  has_many :services,           dependent: :destroy
  has_many :events,             dependent: :destroy
112 113
  has_many :milestones,         dependent: :destroy
  has_many :notes,              dependent: :destroy
114 115
  has_many :snippets,           dependent: :destroy, class_name: 'ProjectSnippet'
  has_many :hooks,              dependent: :destroy, class_name: 'ProjectHook'
116
  has_many :protected_branches, dependent: :destroy
117
  has_many :project_members, dependent: :destroy, as: :source, class_name: 'ProjectMember'
118
  alias_method :my_members, :project_members
119
  has_many :users, through: :project_members
120 121
  has_many :deploy_keys_projects, dependent: :destroy
  has_many :deploy_keys, through: :deploy_keys_projects
C
Ciro Santilli 已提交
122 123
  has_many :users_star_projects, dependent: :destroy
  has_many :starrers, through: :users_star_projects, source: :user
124
  has_many :ci_commits, dependent: :destroy, class_name: 'Ci::Commit', foreign_key: :gl_project_id
K
Kamil Trzcinski 已提交
125
  has_many :ci_builds, through: :ci_commits, source: :builds, dependent: :destroy, class_name: 'Ci::Build'
126

127
  has_one :import_data, dependent: :destroy, class_name: "ProjectImportData"
128
  has_one :gitlab_ci_project, dependent: :destroy, class_name: "Ci::Project", foreign_key: :gitlab_id
129

130
  delegate :name, to: :owner, allow_nil: true, prefix: true
131
  delegate :members, to: :team, prefix: true
132

A
Andrey Kumanyaev 已提交
133
  # Validations
134
  validates :creator, presence: true, on: :create
135
  validates :description, length: { maximum: 2000 }, allow_blank: true
136 137 138 139
  validates :name,
    presence: true,
    length: { within: 0..255 },
    format: { with: Gitlab::Regex.project_name_regex,
D
Douwe Maan 已提交
140
              message: Gitlab::Regex.project_name_regex_message }
141 142 143
  validates :path,
    presence: true,
    length: { within: 0..255 },
D
Douwe Maan 已提交
144 145
    format: { with: Gitlab::Regex.project_path_regex,
              message: Gitlab::Regex.project_path_regex_message }
D
Dmitriy Zaporozhets 已提交
146
  validates :issues_enabled, :merge_requests_enabled,
A
Andrey Kumanyaev 已提交
147
            :wiki_enabled, inclusion: { in: [true, false] }
148
  validates :issues_tracker_id, length: { maximum: 255 }, allow_blank: true
149
  validates :namespace, presence: true
150 151
  validates_uniqueness_of :name, scope: :namespace_id
  validates_uniqueness_of :path, scope: :namespace_id
152
  validates :import_url,
153
    format: { with: /\A#{URI.regexp(%w(ssh git http https))}\z/, message: 'should be a valid url' },
154
    if: :external_import?
155
  validates :star_count, numericality: { greater_than_or_equal_to: 0 }
156
  validate :check_limit, on: :create
157
  validate :avatar_type,
158
    if: ->(project) { project.avatar.present? && project.avatar_changed? }
159
  validates :avatar, file_size: { maximum: 200.kilobytes.to_i }
160

D
Douwe Maan 已提交
161
  mount_uploader :avatar, AvatarUploader
A
Andrey Kumanyaev 已提交
162

163
  # Scopes
164
  scope :sorted_by_activity, -> { reorder(last_activity_at: :desc) }
165 166 167
  scope :sorted_by_stars, -> { reorder('projects.star_count DESC') }
  scope :sorted_by_names, -> { joins(:namespace).reorder('namespaces.name ASC, projects.name ASC') }

168 169 170
  scope :without_user, ->(user)  { where('projects.id NOT IN (:ids)', ids: user.authorized_projects.map(&:id) ) }
  scope :without_team, ->(team) { team.projects.present? ? where('projects.id NOT IN (:ids)', ids: team.projects.map(&:id)) : scoped  }
  scope :not_in_group, ->(group) { where('projects.id NOT IN (:ids)', ids: group.project_ids ) }
171
  scope :in_namespace, ->(namespace_ids) { where(namespace_id: namespace_ids) }
A
Andrey Kumanyaev 已提交
172
  scope :in_group_namespace, -> { joins(:group) }
D
Dmitriy Zaporozhets 已提交
173
  scope :personal, ->(user) { where(namespace_id: user.namespace_id) }
174
  scope :joined, ->(user) { where('namespace_id != ?', user.namespace_id) }
175 176
  scope :public_only, -> { where(visibility_level: Project::PUBLIC) }
  scope :public_and_internal_only, -> { where(visibility_level: Project.public_and_internal_levels) }
177 178
  scope :non_archived, -> { where(archived: false) }

179 180
  state_machine :import_status, initial: :none do
    event :import_start do
181
      transition [:none, :finished] => :started
182 183 184
    end

    event :import_finish do
185
      transition started: :finished
186 187 188
    end

    event :import_fail do
189
      transition started: :failed
190 191 192
    end

    event :import_retry do
193
      transition failed: :started
194 195 196 197
    end

    state :started
    state :finished
198 199
    state :failed

200
    after_transition any => :started, do: :schedule_add_import_job
201
    after_transition any => :finished, do: :clear_import_data
202 203
  end

A
Andrey Kumanyaev 已提交
204
  class << self
205 206 207 208
    def public_and_internal_levels
      [Project::PUBLIC, Project::INTERNAL]
    end

209
    def abandoned
210
      where('projects.last_activity_at < ?', 6.months.ago)
211
    end
212

213 214
    def publicish(user)
      visibility_levels = [Project::PUBLIC]
215
      visibility_levels << Project::INTERNAL if user
216 217
      where(visibility_level: visibility_levels)
    end
218

219
    def with_push
220
      joins(:events).where('events.action = ?', Event::PUSHED)
221 222
    end

A
Andrey Kumanyaev 已提交
223
    def active
224
      joins(:issues, :notes, :merge_requests).order('issues.created_at, notes.created_at, merge_requests.created_at DESC')
A
Andrey Kumanyaev 已提交
225
    end
226

227
    def search(query)
228
      joins(:namespace).
229
        where('LOWER(projects.name) LIKE :query OR
D
Dmitriy Zaporozhets 已提交
230 231
              LOWER(projects.path) LIKE :query OR
              LOWER(namespaces.name) LIKE :query OR
232
              LOWER(projects.description) LIKE :query',
D
Dmitriy Zaporozhets 已提交
233
              query: "%#{query.try(:downcase)}%")
A
Andrey Kumanyaev 已提交
234
    end
235

236
    def search_by_title(query)
237
      where('projects.archived = ?', false).where('LOWER(projects.name) LIKE :query', query: "%#{query.downcase}%")
238 239
    end

240
    def find_with_namespace(id)
241 242 243 244 245 246 247
      namespace_path, project_path = id.split('/')

      return nil if !namespace_path || !project_path

      # Use of unscoped ensures we're not secretly adding any ORDER BYs, which
      # have a negative impact on performance (and aren't needed for this
      # query).
248
      projects = unscoped.
249
        joins(:namespace).
250 251
        iwhere('namespaces.path' => namespace_path)

252 253
      projects.where('projects.path' => project_path).take || 
        projects.iwhere('projects.path' => project_path).take
254
    end
255

256 257 258
    def visibility_levels
      Gitlab::VisibilityLevel.options
    end
259 260

    def sort(method)
261 262 263 264
      if method == 'repository_size_desc'
        reorder(repository_size: :desc, id: :desc)
      else
        order_by(method)
265 266
      end
    end
267 268 269 270 271

    def reference_pattern
      name_pattern = Gitlab::Regex::NAMESPACE_REGEX_STR
      %r{(?<project>#{name_pattern}/#{name_pattern})}
    end
Y
Yorick Peterse 已提交
272 273 274 275 276 277 278 279 280 281 282 283 284 285

    def trending(since = 1.month.ago)
      # By counting in the JOIN we don't expose the GROUP BY to the outer query.
      # This means that calls such as "any?" and "count" just return a number of
      # the total count, instead of the counts grouped per project as a Hash.
      join_body = "INNER JOIN (
        SELECT project_id, COUNT(*) AS amount
        FROM notes
        WHERE created_at >= #{sanitize(since)}
        GROUP BY project_id
      ) join_note_counts ON projects.id = join_note_counts.project_id"

      joins(join_body).reorder('join_note_counts.amount DESC')
    end
286 287
  end

D
Dmitriy Zaporozhets 已提交
288
  def team
289
    @team ||= ProjectTeam.new(self)
D
Dmitriy Zaporozhets 已提交
290 291 292
  end

  def repository
293 294 295
    @repository ||= Repository.new(path_with_namespace, nil, self)
  end

296
  def commit(id = 'HEAD')
297
    repository.commit(id)
D
Dmitriy Zaporozhets 已提交
298 299
  end

300
  def saved?
301
    id && persisted?
302 303
  end

304 305 306 307
  def schedule_add_import_job
    run_after_commit(:add_import_job)
  end

308
  def add_import_job
309 310 311 312 313
    if forked?
      unless RepositoryForkWorker.perform_async(id, forked_from_project.path_with_namespace, self.namespace.path)
        import_fail
      end
    else
314
      RepositoryImportWorker.perform_async(id)
315
    end
316 317
  end

318
  def clear_import_data
319
    self.import_data.destroy if self.import_data
320 321
  end

322
  def import?
323 324 325 326
    external_import? || forked?
  end

  def external_import?
327 328 329
    import_url.present?
  end

330
  def imported?
331 332 333 334 335 336 337 338 339 340 341 342 343
    import_finished?
  end

  def import_in_progress?
    import? && import_status == 'started'
  end

  def import_failed?
    import_status == 'failed'
  end

  def import_finished?
    import_status == 'finished'
344 345
  end

346
  def check_limit
347
    unless creator.can_create_project? or namespace.kind == 'group'
J
Josh Frye 已提交
348
      errors[:limit_reached] << ("Your project limit is #{creator.projects_limit} projects! Please contact your administrator to increase it")
349 350
    end
  rescue
R
Robert Speicher 已提交
351
    errors[:base] << ("Can't check your ability to create project")
G
gitlabhq 已提交
352 353
  end

354
  def to_param
V
Vinnie Okada 已提交
355
    path
356 357
  end

358 359 360 361
  def to_reference(_from_project = nil)
    path_with_namespace
  end

362
  def web_url
D
Douwe Maan 已提交
363
    Gitlab::Application.routes.url_helpers.namespace_project_url(self.namespace, self)
364 365
  end

366
  def web_url_without_protocol
367
    web_url.split('://')[1]
368 369
  end

370
  def build_commit_note(commit)
371
    notes.new(commit_id: commit.id, noteable_type: 'Commit')
G
gitlabhq 已提交
372
  end
N
Nihad Abbasov 已提交
373

N
Nihad Abbasov 已提交
374
  def last_activity
375
    last_event
G
gitlabhq 已提交
376 377 378
  end

  def last_activity_date
A
Andrey Kumanyaev 已提交
379
    last_activity_at || updated_at
D
Dmitriy Zaporozhets 已提交
380
  end
381

D
Dmitriy Zaporozhets 已提交
382 383 384
  def project_id
    self.id
  end
R
randx 已提交
385

R
Robert Speicher 已提交
386
  def get_issue(issue_id)
387
    if default_issues_tracker?
R
Robert Speicher 已提交
388
      issues.find_by(iid: issue_id)
389
    else
R
Robert Speicher 已提交
390
      ExternalIssue.new(issue_id, self)
391 392 393
    end
  end

R
Robert Speicher 已提交
394
  def issue_exists?(issue_id)
395
    get_issue(issue_id)
R
Robert Speicher 已提交
396 397
  end

398
  def default_issue_tracker
399
    gitlab_issue_tracker_service || create_gitlab_issue_tracker_service
400 401 402 403 404 405 406 407 408 409
  end

  def issues_tracker
    if external_issue_tracker
      external_issue_tracker
    else
      default_issue_tracker
    end
  end

410
  def default_issues_tracker?
411
    !external_issue_tracker
412 413 414
  end

  def external_issues_trackers
415
    services.select(&:issue_tracker?).reject(&:default?)
416 417 418 419 420 421
  end

  def external_issue_tracker
    @external_issues_tracker ||= external_issues_trackers.select(&:activated?).first
  end

A
Andrew8xx8 已提交
422
  def can_have_issues_tracker_id?
423
    self.issues_enabled && !self.default_issues_tracker?
A
Andrew8xx8 已提交
424 425
  end

426
  def build_missing_services
M
Marin Jankovski 已提交
427 428
    services_templates = Service.where(template: true)

429
    Service.available_services_names.each do |service_name|
M
Marin Jankovski 已提交
430
      service = find_service(services, service_name)
431 432

      # If service is available but missing in db
M
Marin Jankovski 已提交
433 434 435 436 437 438
      if service.nil?
        # We should check if template for the service exists
        template = find_service(services_templates, service_name)

        if template.nil?
          # If no template, we should create an instance. Ex `create_gitlab_ci_service`
G
Guilherme Garnier 已提交
439
          self.send :"create_#{service_name}_service"
M
Marin Jankovski 已提交
440 441 442 443
        else
          Service.create_from_template(self.id, template)
        end
      end
444 445 446
    end
  end

V
Valery Sizov 已提交
447 448 449 450 451 452 453 454 455
  def create_labels
    Label.templates.each do |label|
      label = label.dup
      label.template = nil
      label.project_id = self.id
      label.save
    end
  end

M
Marin Jankovski 已提交
456 457 458
  def find_service(list, name)
    list.find { |service| service.to_param == name }
  end
D
Dmitriy Zaporozhets 已提交
459 460

  def gitlab_ci?
461
    gitlab_ci_service && gitlab_ci_service.active && gitlab_ci_project.present?
D
Dmitriy Zaporozhets 已提交
462
  end
463

464 465 466 467 468
  def ci_services
    services.select { |service| service.category == :ci }
  end

  def ci_service
469
    @ci_service ||= ci_services.select(&:activated?).first
470 471
  end

472
  def avatar_type
473 474
    unless self.avatar.image?
      self.errors.add :avatar, 'only images allowed'
475 476 477 478 479 480 481 482 483 484
    end
  end

  def avatar_in_git
    @avatar_file ||= 'logo.png' if repository.blob_at_branch('master', 'logo.png')
    @avatar_file ||= 'logo.jpg' if repository.blob_at_branch('master', 'logo.jpg')
    @avatar_file ||= 'logo.gif' if repository.blob_at_branch('master', 'logo.gif')
    @avatar_file
  end

S
sue445 已提交
485 486 487 488
  def avatar_url
    if avatar.present?
      [gitlab_config.url, avatar.url].join
    elsif avatar_in_git
D
Douwe Maan 已提交
489
      Gitlab::Application.routes.url_helpers.namespace_project_avatar_url(namespace, self)
S
sue445 已提交
490 491 492
    end
  end

493 494 495 496 497
  # For compatibility with old code
  def code
    path
  end

498
  def items_for(entity)
D
Dmitriy Zaporozhets 已提交
499 500 501 502 503 504 505
    case entity
    when 'issue' then
      issues
    when 'merge_request' then
      merge_requests
    end
  end
506

507 508
  def send_move_instructions(old_path_with_namespace)
    NotificationService.new.project_was_moved(self, old_path_with_namespace)
509
  end
510 511

  def owner
512 513
    if group
      group
514
    else
515
      namespace.try(:owner)
516 517
    end
  end
D
Dmitriy Zaporozhets 已提交
518

519
  def project_member_by_name_or_email(name = nil, email = nil)
520
    user = users.where('name like ? or email like ?', name, email).first
521
    project_members.where(user: user) if user
D
Dmitriy Zaporozhets 已提交
522 523 524
  end

  # Get Team Member record by user id
525
  def project_member_by_id(user_id)
526
    project_members.find_by(user_id: user_id)
D
Dmitriy Zaporozhets 已提交
527 528 529 530 531
  end

  def name_with_namespace
    @name_with_namespace ||= begin
                               if namespace
532
                                 namespace.human_name + ' / ' + name
D
Dmitriy Zaporozhets 已提交
533 534 535 536 537 538 539 540 541 542 543 544 545 546
                               else
                                 name
                               end
                             end
  end

  def path_with_namespace
    if namespace
      namespace.path + '/' + path
    else
      path
    end
  end

547 548
  def execute_hooks(data, hooks_scope = :push_hooks)
    hooks.send(hooks_scope).each do |hook|
549
      hook.async_execute(data, hooks_scope.to_s)
550
    end
D
Dmitriy Zaporozhets 已提交
551 552
  end

553 554 555
  def execute_services(data, hooks_scope = :push_hooks)
    # Call only service hooks that are active for this scope
    services.send(hooks_scope).each do |service|
556
      service.async_execute(data)
D
Dmitriy Zaporozhets 已提交
557 558 559 560
    end
  end

  def update_merge_requests(oldrev, newrev, ref, user)
561 562
    MergeRequests::RefreshService.new(self, user).
      execute(oldrev, newrev, ref)
D
Dmitriy Zaporozhets 已提交
563 564 565
  end

  def valid_repo?
566
    repository.exists?
D
Dmitriy Zaporozhets 已提交
567
  rescue
568
    errors.add(:path, 'Invalid repository path')
D
Dmitriy Zaporozhets 已提交
569 570 571 572
    false
  end

  def empty_repo?
573
    !repository.exists? || !repository.has_visible_content?
D
Dmitriy Zaporozhets 已提交
574 575 576
  end

  def repo
D
Dmitriy Zaporozhets 已提交
577
    repository.raw
D
Dmitriy Zaporozhets 已提交
578 579 580
  end

  def url_to_repo
581
    gitlab_shell.url_to_repo(path_with_namespace)
D
Dmitriy Zaporozhets 已提交
582 583 584 585 586 587 588
  end

  def namespace_dir
    namespace.try(:path) || ''
  end

  def repo_exists?
589
    @repo_exists ||= repository.exists?
D
Dmitriy Zaporozhets 已提交
590 591 592 593 594
  rescue
    @repo_exists = false
  end

  def open_branches
595 596 597 598 599 600 601 602 603 604 605 606 607
    all_branches = repository.branches

    if protected_branches.present?
      all_branches.reject! do |branch|
        protected_branches_names.include?(branch.name)
      end
    end

    all_branches
  end

  def protected_branches_names
    @protected_branches_names ||= protected_branches.map(&:name)
D
Dmitriy Zaporozhets 已提交
608 609 610
  end

  def root_ref?(branch)
D
Dmitriy Zaporozhets 已提交
611
    repository.root_ref == branch
D
Dmitriy Zaporozhets 已提交
612 613 614 615 616 617 618
  end

  def ssh_url_to_repo
    url_to_repo
  end

  def http_url_to_repo
D
Douwe Maan 已提交
619
    "#{web_url}.git"
D
Dmitriy Zaporozhets 已提交
620 621 622
  end

  # Check if current branch name is marked as protected in the system
623
  def protected_branch?(branch_name)
624
    protected_branches_names.include?(branch_name)
D
Dmitriy Zaporozhets 已提交
625
  end
626

627
  def developers_can_push_to_protected_branch?(branch_name)
628
    protected_branches.any? { |pb| pb.name == branch_name && pb.developers_can_push }
629 630
  end

631 632 633
  def forked?
    !(forked_project_link.nil? || forked_project_link.forked_from_project.nil?)
  end
D
Dmitriy Zaporozhets 已提交
634

635 636 637 638
  def personal?
    !group
  end

D
Dmitriy Zaporozhets 已提交
639
  def rename_repo
640
    path_was = previous_changes['path'].first
D
Dmitriy Zaporozhets 已提交
641 642 643 644
    old_path_with_namespace = File.join(namespace_dir, path_was)
    new_path_with_namespace = File.join(namespace_dir, path)

    if gitlab_shell.mv_repository(old_path_with_namespace, new_path_with_namespace)
645
      # If repository moved successfully we need to send update instructions to users.
D
Dmitriy Zaporozhets 已提交
646 647 648
      # However we cannot allow rollback since we moved repository
      # So we basically we mute exceptions in next actions
      begin
649
        gitlab_shell.mv_repository("#{old_path_with_namespace}.wiki", "#{new_path_with_namespace}.wiki")
650
        send_move_instructions(old_path_with_namespace)
651
        reset_events_cache
D
Dmitriy Zaporozhets 已提交
652
      rescue
J
Johannes Schleifenbaum 已提交
653
        # Returning false does not rollback after_* transaction but gives
D
Dmitriy Zaporozhets 已提交
654 655 656 657 658 659 660 661
        # us information about failing some of tasks
        false
      end
    else
      # if we cannot move namespace directory we should rollback
      # db changes in order to prevent out of sync between db and fs
      raise Exception.new('repository cannot be renamed')
    end
662 663

    Gitlab::UploadsTransfer.new.rename_project(path_was, path, namespace.path)
D
Dmitriy Zaporozhets 已提交
664
  end
665

K
Kirill Zaitsev 已提交
666 667 668 669 670
  def hook_attrs
    {
      name: name,
      ssh_url: ssh_url_to_repo,
      http_url: http_url_to_repo,
K
Kirilll Zaitsev 已提交
671
      web_url: web_url,
K
Kirill Zaitsev 已提交
672 673 674 675 676
      namespace: namespace.name,
      visibility_level: visibility_level
    }
  end

677 678 679 680 681
  # Reset events cache related to this project
  #
  # Since we do cache @event we need to reset cache in special cases:
  # * when project was moved
  # * when project was renamed
682
  # * when the project avatar changes
683 684 685 686 687 688 689 690 691
  # Events cache stored like  events/23-20130109142513.
  # The cache key includes updated_at timestamp.
  # Thus it will automatically generate a new fragment
  # when the event is updated because the key changes.
  def reset_events_cache
    Event.where(project_id: self.id).
      order('id DESC').limit(100).
      update_all(updated_at: Time.now)
  end
692 693

  def project_member(user)
694
    project_members.where(user_id: user).first
695
  end
696 697 698 699

  def default_branch
    @default_branch ||= repository.root_ref if repository.exists?
  end
700 701 702 703 704

  def reload_default_branch
    @default_branch = nil
    default_branch
  end
705

706 707 708
  def visibility_level_field
    visibility_level
  end
709 710 711 712 713 714 715 716

  def archive!
    update_attribute(:archived, true)
  end

  def unarchive!
    update_attribute(:archived, false)
  end
717

718 719 720 721
  def change_head(branch)
    gitlab_shell.update_repository_head(self.path_with_namespace, branch)
    reload_default_branch
  end
722 723 724 725

  def forked_from?(project)
    forked? && project == forked_from_project
  end
726 727 728 729

  def update_repository_size
    update_attribute(:repository_size, repository.size)
  end
730

731 732 733 734
  def update_commit_count
    update_attribute(:commit_count, repository.commit_count)
  end

735 736 737
  def forks_count
    ForkedProjectLink.where(forked_from_project_id: self.id).count
  end
R
Robert Schilling 已提交
738 739 740 741

  def find_label(name)
    labels.find_by(name: name)
  end
742 743 744 745

  def origin_merge_requests
    merge_requests.where(source_project_id: self.id)
  end
746 747

  def create_repository
748 749
    # Forked import is handled asynchronously
    unless forked?
750 751 752
      if gitlab_shell.add_repository(path_with_namespace)
        true
      else
753
        errors.add(:base, 'Failed to create repository via gitlab-shell')
754 755
        false
      end
756 757 758 759 760 761 762 763 764 765
    end
  end

  def repository_exists?
    !!repository.exists?
  end

  def create_wiki
    ProjectWiki.new(self, self.owner).wiki
    true
G
Guilherme Garnier 已提交
766
  rescue ProjectWiki::CouldNotCreateWikiError
767
    errors.add(:base, 'Failed create wiki')
768 769
    false
  end
770 771

  def ci_commit(sha)
K
Kamil Trzcinski 已提交
772 773 774 775 776
    ci_commits.find_by(sha: sha)
  end

  def ensure_ci_commit(sha)
    ci_commit(sha) || ci_commits.create(sha: sha)
777
  end
778

779 780
  def ensure_gitlab_ci_project
    gitlab_ci_project || create_gitlab_ci_project
K
Kamil Trzcinski 已提交
781 782
  end

783
  def enable_ci
784 785 786 787
    service = gitlab_ci_service || create_gitlab_ci_service
    service.active = true
    service.save
  end
G
gitlabhq 已提交
788
end