OSDN Git Service

Merge pull request #5841 from Popl7/archiving_old_projects
[wvm/gitlab.git] / app / models / project.rb
1 # == Schema Information
2 #
3 # Table name: projects
4 #
5 #  id                     :integer          not null, primary key
6 #  name                   :string(255)
7 #  path                   :string(255)
8 #  description            :text
9 #  created_at             :datetime         not null
10 #  updated_at             :datetime         not null
11 #  creator_id             :integer
12 #  issues_enabled         :boolean          default(TRUE), not null
13 #  wall_enabled           :boolean          default(TRUE), not null
14 #  merge_requests_enabled :boolean          default(TRUE), not null
15 #  wiki_enabled           :boolean          default(TRUE), not null
16 #  namespace_id           :integer
17 #  issues_tracker         :string(255)      default("gitlab"), not null
18 #  issues_tracker_id      :string(255)
19 #  snippets_enabled       :boolean          default(TRUE), not null
20 #  last_activity_at       :datetime
21 #  imported               :boolean          default(FALSE), not null
22 #  import_url             :string(255)
23 #  visibility_level       :integer          default(0), not null
24 #
25
26 class Project < ActiveRecord::Base
27   include Gitlab::ShellAdapter
28   include Gitlab::VisibilityLevel
29   extend Enumerize
30
31   ActsAsTaggableOn.strict_case_match = true
32
33   attr_accessible :name, :path, :description, :issues_tracker, :label_list,
34     :issues_enabled, :wall_enabled, :merge_requests_enabled, :snippets_enabled, :issues_tracker_id,
35     :wiki_enabled, :visibility_level, :import_url, :last_activity_at, as: [:default, :admin]
36
37   attr_accessible :namespace_id, :creator_id, as: :admin
38
39   acts_as_taggable_on :labels, :issues_default_labels
40
41   attr_accessor :new_default_branch
42
43   # Relations
44   belongs_to :creator,      foreign_key: "creator_id", class_name: "User"
45   belongs_to :group, -> { where(type: Group) }, foreign_key: "namespace_id"
46   belongs_to :namespace
47
48   has_one :last_event, -> {order 'events.created_at DESC'}, class_name: 'Event', foreign_key: 'project_id'
49   has_one :gitlab_ci_service, dependent: :destroy
50   has_one :campfire_service, dependent: :destroy
51   has_one :pivotaltracker_service, dependent: :destroy
52   has_one :hipchat_service, dependent: :destroy
53   has_one :flowdock_service, dependent: :destroy
54   has_one :assembla_service, dependent: :destroy
55   has_one :forked_project_link, dependent: :destroy, foreign_key: "forked_to_project_id"
56   has_one :forked_from_project, through: :forked_project_link
57
58   # Merge Requests for target project should be removed with it
59   has_many :merge_requests,     dependent: :destroy, foreign_key: "target_project_id"
60
61   # Merge requests from source project should be kept when source project was removed
62   has_many :fork_merge_requests, foreign_key: "source_project_id", class_name: MergeRequest
63
64   has_many :issues, -> { order "state DESC, created_at DESC" }, dependent: :destroy
65   has_many :services,           dependent: :destroy
66   has_many :events,             dependent: :destroy
67   has_many :milestones,         dependent: :destroy
68   has_many :notes,              dependent: :destroy
69   has_many :snippets,           dependent: :destroy, class_name: "ProjectSnippet"
70   has_many :hooks,              dependent: :destroy, class_name: "ProjectHook"
71   has_many :protected_branches, dependent: :destroy
72
73   has_many :users_projects, dependent: :destroy
74   has_many :users, through: :users_projects
75
76   has_many :deploy_keys_projects, dependent: :destroy
77   has_many :deploy_keys, through: :deploy_keys_projects
78
79   delegate :name, to: :owner, allow_nil: true, prefix: true
80   delegate :members, to: :team, prefix: true
81
82   # Validations
83   validates :creator, presence: true
84   validates :description, length: { maximum: 2000 }, allow_blank: true
85   validates :name, presence: true, length: { within: 0..255 },
86             format: { with: Gitlab::Regex.project_name_regex,
87                       message: "only letters, digits, spaces & '_' '-' '.' allowed. Letter or digit should be first" }
88   validates :path, presence: true, length: { within: 0..255 },
89             exclusion: { in: Gitlab::Blacklist.path },
90             format: { with: Gitlab::Regex.path_regex,
91                       message: "only letters, digits & '_' '-' '.' allowed. Letter or digit should be first" }
92   validates :issues_enabled, :wall_enabled, :merge_requests_enabled,
93             :wiki_enabled, inclusion: { in: [true, false] }
94   validates :issues_tracker_id, length: { maximum: 255 }, allow_blank: true
95
96   validates :namespace, presence: true
97   validates_uniqueness_of :name, scope: :namespace_id
98   validates_uniqueness_of :path, scope: :namespace_id
99
100   validates :import_url,
101     format: { with: URI::regexp(%w(git http https)), message: "should be a valid url" },
102     if: :import?
103
104   validate :check_limit, on: :create
105
106   # Scopes
107   scope :without_user, ->(user)  { where("projects.id NOT IN (:ids)", ids: user.authorized_projects.map(&:id) ) }
108   scope :without_team, ->(team) { team.projects.present? ? where("projects.id NOT IN (:ids)", ids: team.projects.map(&:id)) : scoped  }
109   scope :not_in_group, ->(group) { where("projects.id NOT IN (:ids)", ids: group.project_ids ) }
110   scope :in_team, ->(team) { where("projects.id IN (:ids)", ids: team.projects.map(&:id)) }
111   scope :in_namespace, ->(namespace) { where(namespace_id: namespace.id) }
112   scope :in_group_namespace, -> { joins(:group) }
113   scope :sorted_by_activity, -> { reorder("projects.last_activity_at DESC") }
114   scope :personal, ->(user) { where(namespace_id: user.namespace_id) }
115   scope :joined, ->(user) { where("namespace_id != ?", user.namespace_id) }
116   scope :public_only, -> { where(visibility_level: PUBLIC) }
117   scope :public_or_internal_only, ->(user) { where("visibility_level IN (:levels)", levels: user ? [ INTERNAL, PUBLIC ] : [ PUBLIC ]) }
118
119   scope :non_archived, -> { where(archived: false) }
120
121   enumerize :issues_tracker, in: (Gitlab.config.issues_tracker.keys).append(:gitlab), default: :gitlab
122
123   class << self
124     def abandoned
125       where('projects.last_activity_at < ?', 6.months.ago)
126     end
127
128     def with_push
129       includes(:events).where('events.action = ?', Event::PUSHED)
130     end
131
132     def active
133       joins(:issues, :notes, :merge_requests).order("issues.created_at, notes.created_at, merge_requests.created_at DESC")
134     end
135
136     def search query
137       joins(:namespace).where("projects.archived = ?", false).where("projects.name LIKE :query OR projects.path LIKE :query OR namespaces.name LIKE :query OR projects.description LIKE :query", query: "%#{query}%")
138     end
139
140     def find_with_namespace(id)
141       if id.include?("/")
142         id = id.split("/")
143         namespace = Namespace.find_by_path(id.first)
144         return nil unless namespace
145
146         where(namespace_id: namespace.id).find_by_path(id.second)
147       else
148         where(path: id, namespace_id: nil).last
149       end
150     end
151
152     def visibility_levels
153       Gitlab::VisibilityLevel.options
154     end
155   end
156
157   def team
158     @team ||= ProjectTeam.new(self)
159   end
160
161   def repository
162     @repository ||= Repository.new(path_with_namespace)
163   end
164
165   def saved?
166     id && persisted?
167   end
168
169   def import?
170     import_url.present?
171   end
172
173   def imported?
174     imported
175   end
176
177   def check_limit
178     unless creator.can_create_project?
179       errors[:limit_reached] << ("Your own projects limit is #{creator.projects_limit}! Please contact administrator to increase it")
180     end
181   rescue
182     errors[:base] << ("Can't check your ability to create project")
183   end
184
185   def to_param
186     namespace.path + "/" + path
187   end
188
189   def web_url
190     [Gitlab.config.gitlab.url, path_with_namespace].join("/")
191   end
192
193   def build_commit_note(commit)
194     notes.new(commit_id: commit.id, noteable_type: "Commit")
195   end
196
197   def last_activity
198     last_event
199   end
200
201   def last_activity_date
202     last_activity_at || updated_at
203   end
204
205   def project_id
206     self.id
207   end
208
209   def issues_labels
210     @issues_labels ||= (issues_default_labels + issues.tags_on(:labels)).uniq.sort_by(&:name)
211   end
212
213   def issue_exists?(issue_id)
214     if used_default_issues_tracker?
215       self.issues.where(iid: issue_id).first.present?
216     else
217       true
218     end
219   end
220
221   def used_default_issues_tracker?
222     self.issues_tracker == Project.issues_tracker.default_value
223   end
224
225   def can_have_issues_tracker_id?
226     self.issues_enabled && !self.used_default_issues_tracker?
227   end
228
229   def build_missing_services
230     available_services_names.each do |service_name|
231       service = services.find { |service| service.to_param == service_name }
232
233       # If service is available but missing in db
234       # we should create an instance. Ex `create_gitlab_ci_service`
235       service = self.send :"create_#{service_name}_service" if service.nil?
236     end
237   end
238
239   def available_services_names
240     %w(gitlab_ci campfire hipchat pivotaltracker flowdock assembla)
241   end
242
243   def gitlab_ci?
244     gitlab_ci_service && gitlab_ci_service.active
245   end
246
247   # For compatibility with old code
248   def code
249     path
250   end
251
252   def items_for entity
253     case entity
254     when 'issue' then
255       issues
256     when 'merge_request' then
257       merge_requests
258     end
259   end
260
261   def send_move_instructions
262     team.members.each do |user|
263       Notify.delay.project_was_moved_email(self.id, user.id)
264     end
265   end
266
267   def owner
268     if group
269       group
270     else
271       namespace.try(:owner)
272     end
273   end
274
275   def team_member_by_name_or_email(name = nil, email = nil)
276     user = users.where("name like ? or email like ?", name, email).first
277     users_projects.where(user: user) if user
278   end
279
280   # Get Team Member record by user id
281   def team_member_by_id(user_id)
282     users_projects.find_by_user_id(user_id)
283   end
284
285   def name_with_namespace
286     @name_with_namespace ||= begin
287                                if namespace
288                                  namespace.human_name + " / " + name
289                                else
290                                  name
291                                end
292                              end
293   end
294
295   def path_with_namespace
296     if namespace
297       namespace.path + '/' + path
298     else
299       path
300     end
301   end
302
303   def transfer(new_namespace)
304     ProjectTransferService.new.transfer(self, new_namespace)
305   end
306
307   def execute_hooks(data, hooks_scope = :push_hooks)
308     hooks.send(hooks_scope).each do |hook|
309       hook.async_execute(data)
310     end
311   end
312
313   def execute_services(data)
314     services.each do |service|
315
316       # Call service hook only if it is active
317       service.execute(data) if service.active
318     end
319   end
320
321   def update_merge_requests(oldrev, newrev, ref, user)
322     return true unless ref =~ /heads/
323     branch_name = ref.gsub("refs/heads/", "")
324     c_ids = self.repository.commits_between(oldrev, newrev).map(&:id)
325
326     # Update code for merge requests into project between project branches
327     mrs = self.merge_requests.opened.by_branch(branch_name).to_a
328     # Update code for merge requests between project and project fork
329     mrs += self.fork_merge_requests.opened.by_branch(branch_name).to_a
330
331     mrs.each { |merge_request| merge_request.reload_code; merge_request.mark_as_unchecked }
332
333     # Close merge requests
334     mrs = self.merge_requests.opened.where(target_branch: branch_name).to_a
335     mrs = mrs.select(&:last_commit).select { |mr| c_ids.include?(mr.last_commit.id) }
336     mrs.each { |merge_request| merge_request.merge!(user.id) }
337
338     true
339   end
340
341   def valid_repo?
342     repository.exists?
343   rescue
344     errors.add(:path, "Invalid repository path")
345     false
346   end
347
348   def empty_repo?
349     !repository.exists? || repository.empty?
350   end
351
352   def ensure_satellite_exists
353     self.satellite.create unless self.satellite.exists?
354   end
355
356   def satellite
357     @satellite ||= Gitlab::Satellite::Satellite.new(self)
358   end
359
360   def repo
361     repository.raw
362   end
363
364   def url_to_repo
365     gitlab_shell.url_to_repo(path_with_namespace)
366   end
367
368   def namespace_dir
369     namespace.try(:path) || ''
370   end
371
372   def repo_exists?
373     @repo_exists ||= repository.exists?
374   rescue
375     @repo_exists = false
376   end
377
378   def open_branches
379     all_branches = repository.branches
380
381     if protected_branches.present?
382       all_branches.reject! do |branch|
383         protected_branches_names.include?(branch.name)
384       end
385     end
386
387     all_branches
388   end
389
390   def protected_branches_names
391     @protected_branches_names ||= protected_branches.map(&:name)
392   end
393
394   def root_ref?(branch)
395     repository.root_ref == branch
396   end
397
398   def ssh_url_to_repo
399     url_to_repo
400   end
401
402   def http_url_to_repo
403     [Gitlab.config.gitlab.url, "/", path_with_namespace, ".git"].join('')
404   end
405
406   # Check if current branch name is marked as protected in the system
407   def protected_branch? branch_name
408     protected_branches_names.include?(branch_name)
409   end
410
411   def forked?
412     !(forked_project_link.nil? || forked_project_link.forked_from_project.nil?)
413   end
414
415   def personal?
416     !group
417   end
418
419   def rename_repo
420     old_path_with_namespace = File.join(namespace_dir, path_was)
421     new_path_with_namespace = File.join(namespace_dir, path)
422
423     if gitlab_shell.mv_repository(old_path_with_namespace, new_path_with_namespace)
424       # If repository moved successfully we need to remove old satellite
425       # and send update instructions to users.
426       # However we cannot allow rollback since we moved repository
427       # So we basically we mute exceptions in next actions
428       begin
429         gitlab_shell.mv_repository("#{old_path_with_namespace}.wiki", "#{new_path_with_namespace}.wiki")
430         gitlab_shell.rm_satellites(old_path_with_namespace)
431         ensure_satellite_exists
432         send_move_instructions
433         reset_events_cache
434       rescue
435         # Returning false does not rollback after_* transaction but gives
436         # us information about failing some of tasks
437         false
438       end
439     else
440       # if we cannot move namespace directory we should rollback
441       # db changes in order to prevent out of sync between db and fs
442       raise Exception.new('repository cannot be renamed')
443     end
444   end
445
446   # Reset events cache related to this project
447   #
448   # Since we do cache @event we need to reset cache in special cases:
449   # * when project was moved
450   # * when project was renamed
451   # Events cache stored like  events/23-20130109142513.
452   # The cache key includes updated_at timestamp.
453   # Thus it will automatically generate a new fragment
454   # when the event is updated because the key changes.
455   def reset_events_cache
456     Event.where(project_id: self.id).
457       order('id DESC').limit(100).
458       update_all(updated_at: Time.now)
459   end
460
461   def project_member(user)
462     users_projects.where(user_id: user).first
463   end
464
465   def default_branch
466     @default_branch ||= repository.root_ref if repository.exists?
467   end
468
469   def reload_default_branch
470     @default_branch = nil
471     default_branch
472   end
473
474   def visibility_level_field
475     visibility_level
476   end
477
478   def archive!
479     update_attribute(:archived, true)
480   end
481
482   def unarchive!
483     update_attribute(:archived, false)
484   end
485 end