To check out this repository please hg clone the following URL, or open the URL using EasyMercurial or your preferred Mercurial client.

Statistics Download as Zip
| Branch: | Tag: | Revision:

root / app / models / repository.rb @ 1566:ac2e4a54a6a6

History | View | Annotate | Download (12.3 KB)

1 441:cbce1fd3b1b7 Chris
# Redmine - project management software
2 1494:e248c7af89ec Chris
# Copyright (C) 2006-2014  Jean-Philippe Lang
3 0:513646585e45 Chris
#
4
# This program is free software; you can redistribute it and/or
5
# modify it under the terms of the GNU General Public License
6
# as published by the Free Software Foundation; either version 2
7
# of the License, or (at your option) any later version.
8 441:cbce1fd3b1b7 Chris
#
9 0:513646585e45 Chris
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU General Public License for more details.
13 441:cbce1fd3b1b7 Chris
#
14 0:513646585e45 Chris
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
17
18 909:cbb26bc654de Chris
class ScmFetchError < Exception; end
19
20 0:513646585e45 Chris
class Repository < ActiveRecord::Base
21 245:051f544170fe Chris
  include Redmine::Ciphering
22 1115:433d4f72a19b Chris
  include Redmine::SafeAttributes
23
24
  # Maximum length for repository identifiers
25
  IDENTIFIER_MAX_LENGTH = 255
26 441:cbce1fd3b1b7 Chris
27 0:513646585e45 Chris
  belongs_to :project
28
  has_many :changesets, :order => "#{Changeset.table_name}.committed_on DESC, #{Changeset.table_name}.id DESC"
29 1115:433d4f72a19b Chris
  has_many :filechanges, :class_name => 'Change', :through => :changesets
30 441:cbce1fd3b1b7 Chris
31
  serialize :extra_info
32
33 1115:433d4f72a19b Chris
  before_save :check_default
34
35 0:513646585e45 Chris
  # Raw SQL to delete changesets and changes in the database
36
  # has_many :changesets, :dependent => :destroy is too slow for big repositories
37
  before_destroy :clear_changesets
38 441:cbce1fd3b1b7 Chris
39 245:051f544170fe Chris
  validates_length_of :password, :maximum => 255, :allow_nil => true
40 1115:433d4f72a19b Chris
  validates_length_of :identifier, :maximum => IDENTIFIER_MAX_LENGTH, :allow_blank => true
41
  validates_presence_of :identifier, :unless => Proc.new { |r| r.is_default? || r.set_as_default? }
42
  validates_uniqueness_of :identifier, :scope => :project_id, :allow_blank => true
43 1517:dffacf8a6908 Chris
  validates_exclusion_of :identifier, :in => %w(browse show entry raw changes annotate diff statistics graph revisions revision)
44 1115:433d4f72a19b Chris
  # donwcase letters, digits, dashes, underscores but not digits only
45 1464:261b3d9a4903 Chris
  validates_format_of :identifier, :with => /\A(?!\d+$)[a-z0-9\-_]*\z/, :allow_blank => true
46 0:513646585e45 Chris
  # Checks if the SCM is enabled when creating a repository
47 909:cbb26bc654de Chris
  validate :repo_create_validation, :on => :create
48
49 1115:433d4f72a19b Chris
  safe_attributes 'identifier',
50
    'login',
51
    'password',
52
    'path_encoding',
53
    'log_encoding',
54 1355:3d01be97cb5a chris
    'is_external',
55
    'external_url',
56 1115:433d4f72a19b Chris
    'is_default'
57
58
  safe_attributes 'url',
59
    :if => lambda {|repository, user| repository.new_record?}
60
61 909:cbb26bc654de Chris
  def repo_create_validation
62
    unless Setting.enabled_scm.include?(self.class.name.demodulize)
63
      errors.add(:type, :invalid)
64
    end
65
  end
66 245:051f544170fe Chris
67 1115:433d4f72a19b Chris
  def self.human_attribute_name(attribute_key_name, *args)
68
    attr_name = attribute_key_name.to_s
69 441:cbce1fd3b1b7 Chris
    if attr_name == "log_encoding"
70
      attr_name = "commit_logs_encoding"
71
    end
72 1115:433d4f72a19b Chris
    super(attr_name, *args)
73 441:cbce1fd3b1b7 Chris
  end
74
75 0:513646585e45 Chris
  # Removes leading and trailing whitespace
76
  def url=(arg)
77
    write_attribute(:url, arg ? arg.to_s.strip : nil)
78
  end
79 245:051f544170fe Chris
80 0:513646585e45 Chris
  # Removes leading and trailing whitespace
81
  def root_url=(arg)
82
    write_attribute(:root_url, arg ? arg.to_s.strip : nil)
83
  end
84 441:cbce1fd3b1b7 Chris
85 245:051f544170fe Chris
  def password
86
    read_ciphered_attribute(:password)
87
  end
88 441:cbce1fd3b1b7 Chris
89 245:051f544170fe Chris
  def password=(arg)
90
    write_ciphered_attribute(:password, arg)
91
  end
92
93
  def scm_adapter
94
    self.class.scm_adapter_class
95
  end
96 0:513646585e45 Chris
97
  def scm
98 1115:433d4f72a19b Chris
    unless @scm
99
      @scm = self.scm_adapter.new(url, root_url,
100 245:051f544170fe Chris
                                  login, password, path_encoding)
101 1115:433d4f72a19b Chris
      if root_url.blank? && @scm.root_url.present?
102
        update_attribute(:root_url, @scm.root_url)
103
      end
104
    end
105 0:513646585e45 Chris
    @scm
106
  end
107 245:051f544170fe Chris
108 0:513646585e45 Chris
  def scm_name
109
    self.class.scm_name
110
  end
111 245:051f544170fe Chris
112 1115:433d4f72a19b Chris
  def name
113
    if identifier.present?
114
      identifier
115
    elsif is_default?
116
      l(:field_repository_is_default)
117
    else
118
      scm_name
119
    end
120
  end
121
122
  def identifier=(identifier)
123
    super unless identifier_frozen?
124
  end
125
126
  def identifier_frozen?
127
    errors[:identifier].blank? && !(new_record? || identifier.blank?)
128
  end
129
130
  def identifier_param
131
    if is_default?
132
      nil
133
    elsif identifier.present?
134
      identifier
135
    else
136
      id.to_s
137
    end
138
  end
139
140
  def <=>(repository)
141
    if is_default?
142
      -1
143
    elsif repository.is_default?
144
      1
145
    else
146
      identifier.to_s <=> repository.identifier.to_s
147
    end
148
  end
149
150
  def self.find_by_identifier_param(param)
151
    if param.to_s =~ /^\d+$/
152
      find_by_id(param)
153
    else
154
      find_by_identifier(param)
155
    end
156
  end
157
158 1494:e248c7af89ec Chris
  # TODO: should return an empty hash instead of nil to avoid many ||{}
159
  def extra_info
160
    h = read_attribute(:extra_info)
161
    h.is_a?(Hash) ? h : nil
162
  end
163
164 441:cbce1fd3b1b7 Chris
  def merge_extra_info(arg)
165
    h = extra_info || {}
166
    return h if arg.nil?
167
    h.merge!(arg)
168
    write_attribute(:extra_info, h)
169
  end
170
171
  def report_last_commit
172
    true
173
  end
174
175 0:513646585e45 Chris
  def supports_cat?
176
    scm.supports_cat?
177
  end
178
179
  def supports_annotate?
180
    scm.supports_annotate?
181
  end
182 441:cbce1fd3b1b7 Chris
183
  def supports_all_revisions?
184
    true
185
  end
186
187
  def supports_directory_revisions?
188
    false
189
  end
190
191 909:cbb26bc654de Chris
  def supports_revision_graph?
192
    false
193
  end
194
195 0:513646585e45 Chris
  def entry(path=nil, identifier=nil)
196
    scm.entry(path, identifier)
197
  end
198 441:cbce1fd3b1b7 Chris
199 1517:dffacf8a6908 Chris
  def scm_entries(path=nil, identifier=nil)
200
    scm.entries(path, identifier)
201
  end
202
  protected :scm_entries
203
204 0:513646585e45 Chris
  def entries(path=nil, identifier=nil)
205 1517:dffacf8a6908 Chris
    entries = scm_entries(path, identifier)
206 1115:433d4f72a19b Chris
    load_entries_changesets(entries)
207
    entries
208 0:513646585e45 Chris
  end
209
210
  def branches
211
    scm.branches
212
  end
213
214
  def tags
215
    scm.tags
216
  end
217
218
  def default_branch
219 507:0c939c159af4 Chris
    nil
220 0:513646585e45 Chris
  end
221 441:cbce1fd3b1b7 Chris
222 0:513646585e45 Chris
  def properties(path, identifier=nil)
223
    scm.properties(path, identifier)
224
  end
225 441:cbce1fd3b1b7 Chris
226 0:513646585e45 Chris
  def cat(path, identifier=nil)
227
    scm.cat(path, identifier)
228
  end
229 441:cbce1fd3b1b7 Chris
230 0:513646585e45 Chris
  def diff(path, rev, rev_to)
231
    scm.diff(path, rev, rev_to)
232
  end
233 119:8661b858af72 Chris
234
  def diff_format_revisions(cs, cs_to, sep=':')
235
    text = ""
236
    text << cs_to.format_identifier + sep if cs_to
237
    text << cs.format_identifier if cs
238
    text
239
  end
240
241 0:513646585e45 Chris
  # Returns a path relative to the url of the repository
242
  def relative_path(path)
243
    path
244
  end
245 128:07fa8a8b56a8 Chris
246 0:513646585e45 Chris
  # Finds and returns a revision with a number or the beginning of a hash
247
  def find_changeset_by_name(name)
248 128:07fa8a8b56a8 Chris
    return nil if name.blank?
249 1115:433d4f72a19b Chris
    s = name.to_s
250 1464:261b3d9a4903 Chris
    if s.match(/^\d*$/)
251
      changesets.where("revision = ?", s).first
252
    else
253
      changesets.where("revision LIKE ?", s + '%').first
254
    end
255 0:513646585e45 Chris
  end
256 128:07fa8a8b56a8 Chris
257 0:513646585e45 Chris
  def latest_changeset
258 1464:261b3d9a4903 Chris
    @latest_changeset ||= changesets.first
259 0:513646585e45 Chris
  end
260
261
  # Returns the latest changesets for +path+
262
  # Default behaviour is to search in cached changesets
263
  def latest_changesets(path, rev, limit=10)
264
    if path.blank?
265 1464:261b3d9a4903 Chris
      changesets.
266
        reorder("#{Changeset.table_name}.committed_on DESC, #{Changeset.table_name}.id DESC").
267
        limit(limit).
268
        preload(:user).
269
        all
270 0:513646585e45 Chris
    else
271 1464:261b3d9a4903 Chris
      filechanges.
272
        where("path = ?", path.with_leading_slash).
273
        reorder("#{Changeset.table_name}.committed_on DESC, #{Changeset.table_name}.id DESC").
274
        limit(limit).
275
        preload(:changeset => :user).
276
        collect(&:changeset)
277 0:513646585e45 Chris
    end
278
  end
279 441:cbce1fd3b1b7 Chris
280 0:513646585e45 Chris
  def scan_changesets_for_issue_ids
281
    self.changesets.each(&:scan_comment_for_issue_ids)
282
  end
283
284
  # Returns an array of committers usernames and associated user_id
285
  def committers
286 441:cbce1fd3b1b7 Chris
    @committers ||= Changeset.connection.select_rows(
287
         "SELECT DISTINCT committer, user_id FROM #{Changeset.table_name} WHERE repository_id = #{id}")
288 0:513646585e45 Chris
  end
289 441:cbce1fd3b1b7 Chris
290 0:513646585e45 Chris
  # Maps committers username to a user ids
291
  def committer_ids=(h)
292
    if h.is_a?(Hash)
293
      committers.each do |committer, user_id|
294
        new_user_id = h[committer]
295
        if new_user_id && (new_user_id.to_i != user_id.to_i)
296
          new_user_id = (new_user_id.to_i > 0 ? new_user_id.to_i : nil)
297 1517:dffacf8a6908 Chris
          Changeset.where(["repository_id = ? AND committer = ?", id, committer]).
298
            update_all("user_id = #{new_user_id.nil? ? 'NULL' : new_user_id}")
299 0:513646585e45 Chris
        end
300
      end
301 441:cbce1fd3b1b7 Chris
      @committers            = nil
302 0:513646585e45 Chris
      @found_committer_users = nil
303
      true
304
    else
305
      false
306
    end
307
  end
308 441:cbce1fd3b1b7 Chris
309 0:513646585e45 Chris
  # Returns the Redmine User corresponding to the given +committer+
310
  # It will return nil if the committer is not yet mapped and if no User
311
  # with the same username or email was found
312
  def find_committer_user(committer)
313
    unless committer.blank?
314
      @found_committer_users ||= {}
315
      return @found_committer_users[committer] if @found_committer_users.has_key?(committer)
316 441:cbce1fd3b1b7 Chris
317 0:513646585e45 Chris
      user = nil
318 1464:261b3d9a4903 Chris
      c = changesets.where(:committer => committer).includes(:user).first
319 0:513646585e45 Chris
      if c && c.user
320
        user = c.user
321
      elsif committer.strip =~ /^([^<]+)(<(.*)>)?$/
322
        username, email = $1.strip, $3
323
        u = User.find_by_login(username)
324 1532:a0460a3d154f Chris
        if u.nil?
325
          if email.blank?
326
            if username.strip =~ /^([^ ]+) ([^ ]+)$/
327
              first, last = $1, $2
328 1533:59e13100ea95 Chris
              uu = User.where(:firstname => first, :lastname => last)
329 1541:2696466256ff Chris
              if uu.empty?
330
                logger.warn "find_committer_user: found no user with name matching #{username}, ignoring"
331
              elsif uu.length == 1
332 1533:59e13100ea95 Chris
                u = uu.first
333
              else
334
                logger.warn "find_committer_user: found more than one (#{uu.length}) results for user named #{username}, ignoring"
335
              end
336 1532:a0460a3d154f Chris
            end
337
          else
338
            u = User.find_by_mail(email)
339
          end
340
        end
341 0:513646585e45 Chris
        user = u
342
      end
343
      @found_committer_users[committer] = user
344
      user
345
    end
346
  end
347 245:051f544170fe Chris
348
  def repo_log_encoding
349
    encoding = log_encoding.to_s.strip
350
    encoding.blank? ? 'UTF-8' : encoding
351
  end
352
353 0:513646585e45 Chris
  # Fetches new changesets for all repositories of active projects
354
  # Can be called periodically by an external script
355
  # eg. ruby script/runner "Repository.fetch_changesets"
356
  def self.fetch_changesets
357 1115:433d4f72a19b Chris
    Project.active.has_module(:repository).all.each do |project|
358
      project.repositories.each do |repository|
359 245:051f544170fe Chris
        begin
360 1115:433d4f72a19b Chris
          repository.fetch_changesets
361 245:051f544170fe Chris
        rescue Redmine::Scm::Adapters::CommandFailed => e
362
          logger.error "scm: error during fetching changesets: #{e.message}"
363
        end
364 0:513646585e45 Chris
      end
365
    end
366
  end
367 245:051f544170fe Chris
368 0:513646585e45 Chris
  # scan changeset comments to find related and fixed issues for all repositories
369
  def self.scan_changesets_for_issue_ids
370 1464:261b3d9a4903 Chris
    all.each(&:scan_changesets_for_issue_ids)
371 0:513646585e45 Chris
  end
372
373
  def self.scm_name
374
    'Abstract'
375
  end
376 441:cbce1fd3b1b7 Chris
377 0:513646585e45 Chris
  def self.available_scm
378
    subclasses.collect {|klass| [klass.scm_name, klass.name]}
379
  end
380 245:051f544170fe Chris
381 0:513646585e45 Chris
  def self.factory(klass_name, *args)
382
    klass = "Repository::#{klass_name}".constantize
383
    klass.new(*args)
384
  rescue
385
    nil
386
  end
387 245:051f544170fe Chris
388 437:102056ec2de9 chris
  def clear_cache
389
    clear_changesets
390
  end
391 443:350acce374a2 Chris
392 245:051f544170fe Chris
  def self.scm_adapter_class
393
    nil
394
  end
395
396
  def self.scm_command
397
    ret = ""
398
    begin
399
      ret = self.scm_adapter_class.client_command if self.scm_adapter_class
400 441:cbce1fd3b1b7 Chris
    rescue Exception => e
401 245:051f544170fe Chris
      logger.error "scm: error during get command: #{e.message}"
402
    end
403
    ret
404
  end
405
406
  def self.scm_version_string
407
    ret = ""
408
    begin
409
      ret = self.scm_adapter_class.client_version_string if self.scm_adapter_class
410 441:cbce1fd3b1b7 Chris
    rescue Exception => e
411 245:051f544170fe Chris
      logger.error "scm: error during get version string: #{e.message}"
412
    end
413
    ret
414
  end
415
416
  def self.scm_available
417
    ret = false
418
    begin
419 441:cbce1fd3b1b7 Chris
      ret = self.scm_adapter_class.client_available if self.scm_adapter_class
420
    rescue Exception => e
421 245:051f544170fe Chris
      logger.error "scm: error during get scm available: #{e.message}"
422
    end
423
    ret
424
  end
425
426 1115:433d4f72a19b Chris
  def set_as_default?
427 1464:261b3d9a4903 Chris
    new_record? && project && Repository.where(:project_id => project.id).empty?
428 1115:433d4f72a19b Chris
  end
429
430
  protected
431
432
  def check_default
433
    if !is_default? && set_as_default?
434
      self.is_default = true
435
    end
436
    if is_default? && is_default_changed?
437 1517:dffacf8a6908 Chris
      Repository.where(["project_id = ?", project_id]).update_all(["is_default = ?", false])
438 1115:433d4f72a19b Chris
    end
439
  end
440
441
  def load_entries_changesets(entries)
442
    if entries
443
      entries.each do |entry|
444
        if entry.lastrev && entry.lastrev.identifier
445
          entry.changeset = find_changeset_by_name(entry.lastrev.identifier)
446
        end
447
      end
448
    end
449
  end
450
451 0:513646585e45 Chris
  private
452 245:051f544170fe Chris
453 1115:433d4f72a19b Chris
  # Deletes repository data
454 0:513646585e45 Chris
  def clear_changesets
455 1115:433d4f72a19b Chris
    cs = Changeset.table_name
456
    ch = Change.table_name
457
    ci = "#{table_name_prefix}changesets_issues#{table_name_suffix}"
458
    cp = "#{table_name_prefix}changeset_parents#{table_name_suffix}"
459
460 0:513646585e45 Chris
    connection.delete("DELETE FROM #{ch} WHERE #{ch}.changeset_id IN (SELECT #{cs}.id FROM #{cs} WHERE #{cs}.repository_id = #{id})")
461
    connection.delete("DELETE FROM #{ci} WHERE #{ci}.changeset_id IN (SELECT #{cs}.id FROM #{cs} WHERE #{cs}.repository_id = #{id})")
462 1115:433d4f72a19b Chris
    connection.delete("DELETE FROM #{cp} WHERE #{cp}.changeset_id IN (SELECT #{cs}.id FROM #{cs} WHERE #{cs}.repository_id = #{id})")
463 0:513646585e45 Chris
    connection.delete("DELETE FROM #{cs} WHERE #{cs}.repository_id = #{id}")
464 1115:433d4f72a19b Chris
    clear_extra_info_of_changesets
465
  end
466
467
  def clear_extra_info_of_changesets
468 0:513646585e45 Chris
  end
469
end