Read about our upcoming Code of Conduct on this issue

repository.rb 30.5 KB
Newer Older
1
2
require 'securerandom'

3
class Repository
Lin Jen-Shin's avatar
Lin Jen-Shin committed
4
5
6
  REF_MERGE_REQUEST = 'merge-requests'.freeze
  REF_KEEP_AROUND = 'keep-around'.freeze
  REF_ENVIRONMENTS = 'environments'.freeze
7
  MAX_DIVERGING_COUNT = 1000
8
9
10
11

  RESERVED_REFS_NAMES = %W[
    heads
    tags
12
    replace
13
14
15
16
17
    #{REF_ENVIRONMENTS}
    #{REF_KEEP_AROUND}
    #{REF_ENVIRONMENTS}
  ].freeze

18
19
  include Gitlab::ShellAdapter

20
  attr_accessor :full_path, :disk_path, :project, :is_wiki
21

22
23
  delegate :ref_name_for_sha, to: :raw_repository

24
  CreateTreeError = Class.new(StandardError)
25

26
27
28
29
30
31
  # Methods that cache data from the Git repository.
  #
  # Each entry in this Array should have a corresponding method with the exact
  # same name. The cache key used by those methods must also match method's
  # name.
  #
32
33
34
  # For example, for entry `:commit_count` there's a method called `commit_count` which
  # stores its data in the `commit_count` cache key.
  CACHED_METHODS = %i(size commit_count rendered_readme contribution_guide
35
36
                      changelog license_blob license_key gitignore koding_yml
                      gitlab_ci_yml branch_names tag_names branch_count
Sean McGivern's avatar
Sean McGivern committed
37
38
                      tag_count avatar exists? empty? root_ref has_visible_content?
                      issue_template_names merge_request_template_names).freeze
39
40

  # Methods that use cache_method but only memoize the value
41
  MEMOIZED_CACHED_METHODS = %i(license).freeze
42
43
44
45
46

  # Certain method caches should be refreshed when certain types of files are
  # changed. This Hash maps file types (as returned by Gitlab::FileDetector) to
  # the corresponding methods to call for refreshing caches.
  METHOD_CACHES_FOR_FILE_TYPES = {
47
    readme: :rendered_readme,
48
    changelog: :changelog,
49
    license: %i(license_blob license_key license),
50
51
52
53
    contributing: :contribution_guide,
    gitignore: :gitignore,
    koding: :koding_yml,
    gitlab_ci: :gitlab_ci_yml,
Sean McGivern's avatar
Sean McGivern committed
54
55
56
    avatar: :avatar,
    issue_template: :issue_template_names,
    merge_request_template: :merge_request_template_names
Douwe Maan's avatar
Douwe Maan committed
57
  }.freeze
58
59
60
61
62

  # Wraps around the given method and caches its output in Redis and an instance
  # variable.
  #
  # This only works for methods that do not take any arguments.
63
  def self.cache_method(name, fallback: nil, memoize_only: false)
64
    original = :"_uncached_#{name}"
65

66
    alias_method(original, name)
67

68
    define_method(name) do
69
70
71
      cache_method_output(name, fallback: fallback, memoize_only: memoize_only) do
        __send__(original) # rubocop:disable GitlabSecurity/PublicSend
      end
72
    end
73
  end
74

75
  def initialize(full_path, project, disk_path: nil, is_wiki: false)
76
    @full_path = full_path
77
    @disk_path = disk_path || full_path
78
    @project = project
79
    @commit_cache = {}
80
    @is_wiki = is_wiki
81
  end
82

83
  def ==(other)
http://jneen.net/'s avatar
http://jneen.net/ committed
84
85
86
    @disk_path == other.disk_path
  end

87
  def raw_repository
88
    return nil unless full_path
89

90
    @raw_repository ||= initialize_raw_repository
91
92
  end

93
94
  alias_method :raw, :raw_repository

95
  # Return absolute path to repository
96
  def path_to_repo
97
    @path_to_repo ||= File.expand_path(
98
      File.join(repository_storage_path, disk_path + '.git')
99
    )
100
101
  end

102
103
104
105
  def inspect
    "#<#{self.class.name}:#{@disk_path}>"
  end

106
107
108
109
  def create_hooks
    Gitlab::Git::Repository.create_hooks(path_to_repo, Gitlab.config.gitlab_shell.hooks_path)
  end

110
  def commit(ref = 'HEAD')
111
    return nil unless exists?
112
    return ref if ref.is_a?(::Commit)
113

114
115
    find_commit(ref)
  end
116

117
118
119
120
121
122
  # Finding a commit by the passed SHA
  # Also takes care of caching, based on the SHA
  def commit_by(oid:)
    return @commit_cache[oid] if @commit_cache.key?(oid)

    @commit_cache[oid] = find_commit(oid)
123
124
  end

125
126
127
128
129
130
131
132
133
134
135
136
  def commits_by(oids:)
    return [] unless oids.present?

    commits = Gitlab::Git::Commit.batch_by_oid(raw_repository, oids)

    if commits.present?
      Commit.decorate(commits, @project)
    else
      []
    end
  end

137
  def commits(ref, path: nil, limit: nil, offset: nil, skip_merges: false, after: nil, before: nil)
138
    options = {
139
140
141
142
143
      repo: raw_repository,
      ref: ref,
      path: path,
      limit: limit,
      offset: offset,
144
145
      after: after,
      before: before,
146
      follow: Array(path).length == 1,
147
      skip_merges: skip_merges
148
149
150
    }

    commits = Gitlab::Git::Commit.where(options)
151
    commits = Commit.decorate(commits, @project) if commits.present?
152
153

    CommitCollection.new(project, commits, ref)
154
155
  end

156
157
  def commits_between(from, to)
    commits = Gitlab::Git::Commit.between(raw_repository, from, to)
158
    commits = Commit.decorate(commits, @project) if commits.present?
159
160
161
    commits
  end

Jacob Vosmaer's avatar
Jacob Vosmaer committed
162
  # Gitaly migration: https://gitlab.com/gitlab-org/gitaly/issues/384
163
  def find_commits_by_message(query, ref = nil, path = nil, limit = 1000, offset = 0)
164
165
166
167
    unless exists? && has_visible_content? && query.present?
      return []
    end

168
    raw_repository.gitaly_migrate(:commits_by_message) do |is_enabled|
169
170
171
172
173
174
175
176
      commits =
        if is_enabled
          find_commits_by_message_by_gitaly(query, ref, path, limit, offset)
        else
          find_commits_by_message_by_shelling_out(query, ref, path, limit, offset)
        end

      CommitCollection.new(project, commits, ref)
177
    end
178
179
  end

180
181
182
183
184
185
186
  def find_branch(name, fresh_repo: true)
    # Since the Repository object may have in-memory index changes, invalidating the memoized Repository object may
    # cause unintended side effects. Because finding a branch is a read-only operation, we can safely instantiate
    # a new repo here to ensure a consistent state to avoid a libgit2 bug where concurrent access (e.g. via git gc)
    # may cause the branch to "disappear" erroneously or have the wrong SHA.
    #
    # See: https://github.com/libgit2/libgit2/issues/1534 and https://gitlab.com/gitlab-org/gitlab-ce/issues/15392
187
    raw_repo = fresh_repo ? initialize_raw_repository : raw_repository
188
189

    raw_repo.find_branch(name)
190
191
192
  end

  def find_tag(name)
193
    tags.find { |tag| tag.name == name }
194
195
  end

196
  def add_branch(user, branch_name, ref)
197
    branch = raw_repository.add_branch(branch_name, user: user, target: ref)
198

199
    after_create_branch
200
201
202
203

    branch
  rescue Gitlab::Git::Repository::InvalidRef
    false
204
205
  end

206
  def add_tag(user, tag_name, target, message = nil)
207
    raw_repository.add_tag(tag_name, user: user, target: target, message: message)
208
209
  rescue Gitlab::Git::Repository::InvalidRef
    false
210
211
  end

212
  def rm_branch(user, branch_name)
213
    before_remove_branch
214

215
    raw_repository.rm_branch(branch_name, user: user)
216

217
    after_remove_branch
218
    true
219
220
  end

Lin Jen-Shin's avatar
Lin Jen-Shin committed
221
  def rm_tag(user, tag_name)
222
    before_remove_tag
223

224
    raw_repository.rm_tag(tag_name, user: user)
Lin Jen-Shin's avatar
Lin Jen-Shin committed
225
226
227

    after_remove_tag
    true
228
229
  end

230
231
232
233
  def ref_names
    branch_names + tag_names
  end

234
  def branch_exists?(branch_name)
235
236
    return false unless raw_repository

237
    branch_names.include?(branch_name)
238
239
  end

240
241
242
243
244
245
  def tag_exists?(tag_name)
    return false unless raw_repository

    tag_names.include?(tag_name)
  end

246
  def ref_exists?(ref)
247
248
    !!raw_repository&.ref_exists?(ref)
  rescue ArgumentError
249
    false
250
251
  end

Douwe Maan's avatar
Douwe Maan committed
252
253
254
255
  # Makes sure a commit is kept around when Git garbage collection runs.
  # Git GC will delete commits from the repository that are no longer in any
  # branches or tags, but we want to keep some of these commits around, for
  # example if they have comments or CI builds.
256
  def keep_around(sha)
257
    return unless sha && commit_by(oid: sha)
258
259
260

    return if kept_around?(sha)

261
262
    # This will still fail if the file is corrupted (e.g. 0 bytes)
    begin
263
      raw_repository.write_ref(keep_around_ref_name(sha), sha, shell: false)
264
265
266
267
    rescue Rugged::ReferenceError => ex
      Rails.logger.error "Unable to create #{REF_KEEP_AROUND} reference for repository #{path}: #{ex}"
    rescue Rugged::OSError => ex
      raise unless ex.message =~ /Failed to create locked file/ && ex.message =~ /File exists/
268

269
      Rails.logger.error "Unable to create #{REF_KEEP_AROUND} reference for repository #{path}: #{ex}"
270
    end
271
272
273
  end

  def kept_around?(sha)
274
    ref_exists?(keep_around_ref_name(sha))
275
  end
276

277
  def diverging_commit_counts(branch)
278
    root_ref_hash = raw_repository.commit(root_ref).id
Jeff Stubler's avatar
Jeff Stubler committed
279
    cache.fetch(:"diverging_commit_counts_#{branch.name}") do
280
281
      # Rugged seems to throw a `ReferenceError` when given branch_names rather
      # than SHA-1 hashes
282
283
284
285
286
287
      number_commits_behind, number_commits_ahead =
        raw_repository.count_commits_between(
          root_ref_hash,
          branch.dereferenced_target.sha,
          left_right: true,
          max_count: MAX_DIVERGING_COUNT)
288

289
290
291
      { behind: number_commits_behind, ahead: number_commits_ahead }
    end
  end
292

293
294
295
  def expire_tags_cache
    expire_method_caches(%i(tag_names tag_count))
    @tags = nil
296
  end
297

298
  def expire_branches_cache
299
    expire_method_caches(%i(branch_names branch_count has_visible_content?))
300
    @local_branches = nil
301
    @branch_exists_memo = nil
302
303
  end

304
305
  def expire_statistics_caches
    expire_method_caches(%i(size commit_count))
306
307
  end

308
309
  def expire_all_method_caches
    expire_method_caches(CACHED_METHODS)
Douwe Maan's avatar
Douwe Maan committed
310
311
  end

312
313
314
315
316
317
318
319
320
  # Expires the caches of a specific set of methods
  def expire_method_caches(methods)
    methods.each do |key|
      cache.expire(key)

      ivar = cache_instance_variable_name(key)

      remove_instance_variable(ivar) if instance_variable_defined?(ivar)
    end
Douwe Maan's avatar
Douwe Maan committed
321
322
  end

323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
  def expire_avatar_cache
    expire_method_caches(%i(avatar))
  end

  # Refreshes the method caches of this repository.
  #
  # types - An Array of file types (e.g. `:readme`) used to refresh extra
  #         caches.
  def refresh_method_caches(types)
    to_refresh = []

    types.each do |type|
      methods = METHOD_CACHES_FOR_FILE_TYPES[type.to_sym]

      to_refresh.concat(Array(methods)) if methods
338
    end
339

340
    expire_method_caches(to_refresh)
341

342
    to_refresh.each { |method| send(method) } # rubocop:disable GitlabSecurity/PublicSend
343
  end
344

345
346
347
348
349
350
351
  def expire_branch_cache(branch_name = nil)
    # When we push to the root branch we have to flush the cache for all other
    # branches as their statistics are based on the commits relative to the
    # root branch.
    if !branch_name || branch_name == root_ref
      branches.each do |branch|
        cache.expire(:"diverging_commit_counts_#{branch.name}")
352
        cache.expire(:"commit_count_#{branch.name}")
353
354
355
356
357
      end
    # In case a commit is pushed to a non-root branch we only have to flush the
    # cache for said branch.
    else
      cache.expire(:"diverging_commit_counts_#{branch_name}")
358
      cache.expire(:"commit_count_#{branch_name}")
359
    end
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
360
361
  end

362
  def expire_root_ref_cache
363
    expire_method_caches(%i(root_ref))
364
365
  end

366
367
  # Expires the cache(s) used to determine if a repository is empty or not.
  def expire_emptiness_caches
368
    return unless empty?
369

370
    expire_method_caches(%i(empty? has_visible_content?))
371
372
  end

373
374
375
376
  def lookup_cache
    @lookup_cache ||= {}
  end

377
  def expire_exists_cache
378
    expire_method_caches(%i(exists?))
379
380
  end

381
382
383
384
385
386
387
  # expire cache that doesn't depend on repository data (when expiring)
  def expire_content_cache
    expire_tags_cache
    expire_branches_cache
    expire_root_ref_cache
    expire_emptiness_caches
    expire_exists_cache
388
    expire_statistics_caches
389
390
391
392
393
  end

  # Runs code after a repository has been created.
  def after_create
    expire_exists_cache
394
395
    expire_root_ref_cache
    expire_emptiness_caches
Yorick Peterse's avatar
Yorick Peterse committed
396
397

    repository_event(:create_repository)
398
399
  end

400
401
  # Runs code just before a repository is deleted.
  def before_delete
402
    expire_exists_cache
403
404
    expire_all_method_caches
    expire_branch_cache if exists?
405
    expire_content_cache
Yorick Peterse's avatar
Yorick Peterse committed
406
407

    repository_event(:remove_repository)
408
409
410
411
412
413
414
  end

  # Runs code just before the HEAD of a repository is changed.
  def before_change_head
    # Cached divergent commit counts are based on repository head
    expire_branch_cache
    expire_root_ref_cache
Yorick Peterse's avatar
Yorick Peterse committed
415
416

    repository_event(:change_default_branch)
417
418
  end

419
420
  # Runs code before pushing (= creating or removing) a tag.
  def before_push_tag
421
422
    expire_statistics_caches
    expire_emptiness_caches
423
    expire_tags_cache
Yorick Peterse's avatar
Yorick Peterse committed
424
425

    repository_event(:push_tag)
426
427
428
429
430
  end

  # Runs code before removing a tag.
  def before_remove_tag
    expire_tags_cache
431
    expire_statistics_caches
Yorick Peterse's avatar
Yorick Peterse committed
432
433

    repository_event(:remove_tag)
434
435
  end

Lin Jen-Shin's avatar
Lin Jen-Shin committed
436
437
438
439
440
  # Runs code after removing a tag.
  def after_remove_tag
    expire_tags_cache
  end

441
442
443
  # Runs code after the HEAD of a repository is changed.
  def after_change_head
    expire_method_caches(METHOD_CACHES_FOR_FILE_TYPES.keys)
444
445
  end

446
447
  # Runs code after a repository has been forked/imported.
  def after_import
448
    expire_content_cache
449
450
451
  end

  # Runs code after a new commit has been pushed.
452
453
454
  def after_push_commit(branch_name)
    expire_statistics_caches
    expire_branch_cache(branch_name)
Yorick Peterse's avatar
Yorick Peterse committed
455
456

    repository_event(:push_commit, branch: branch_name)
457
458
459
460
  end

  # Runs code after a new branch has been created.
  def after_create_branch
461
    expire_branches_cache
Yorick Peterse's avatar
Yorick Peterse committed
462
463

    repository_event(:push_branch)
464
465
  end

466
467
468
  # Runs code before removing an existing branch.
  def before_remove_branch
    expire_branches_cache
Yorick Peterse's avatar
Yorick Peterse committed
469
470

    repository_event(:remove_branch)
471
472
  end

473
474
  # Runs code after an existing branch has been removed.
  def after_remove_branch
475
    expire_branches_cache
476
477
  end

478
  def method_missing(m, *args, &block)
479
480
    if m == :lookup && !block_given?
      lookup_cache[m] ||= {}
481
      lookup_cache[m][args.join(":")] ||= raw_repository.__send__(m, *args, &block) # rubocop:disable GitlabSecurity/PublicSend
482
    else
483
      raw_repository.__send__(m, *args, &block) # rubocop:disable GitlabSecurity/PublicSend
484
    end
485
486
  end

487
488
  def respond_to_missing?(method, include_private = false)
    raw_repository.respond_to?(method, include_private) || super
489
  end
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
490
491

  def blob_at(sha, path)
492
    Blob.decorate(raw_repository.blob_at(sha, path), project)
Douwe Maan's avatar
Douwe Maan committed
493
494
  rescue Gitlab::Git::Repository::NoRepository
    nil
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
495
  end
496

497
498
499
500
501
  # items is an Array like: [[oid, path], [oid1, path1]]
  def blobs_at(items)
    raw_repository.batch_blobs(items).map { |blob| Blob.decorate(blob, project) }
  end

502
503
504
505
506
507
508
  def root_ref
    if raw_repository
      raw_repository.root_ref
    else
      # When the repo does not exist we raise this error so no data is cached.
      raise Rugged::ReferenceError
    end
509
  end
510
  cache_method :root_ref
511

512
  # Gitaly migration: https://gitlab.com/gitlab-org/gitaly/issues/314
513
  def exists?
514
    return false unless full_path
515

516
    raw_repository.exists?
517
518
519
  end
  cache_method :exists?

520
521
522
523
524
  def empty?
    return true unless exists?

    !has_visible_content?
  end
525
526
527
528
529
530
531
532
533
534
535
536
537
  cache_method :empty?

  # The size of this repository in megabytes.
  def size
    exists? ? raw_repository.size : 0.0
  end
  cache_method :size, fallback: 0.0

  def commit_count
    root_ref ? raw_repository.commit_count(root_ref) : 0
  end
  cache_method :commit_count, fallback: 0

538
  def commit_count_for_ref(ref)
539
    return 0 unless exists?
540

541
542
543
544
    begin
      cache.fetch(:"commit_count_#{ref}") { raw_repository.commit_count(ref) }
    rescue Rugged::ReferenceError
      0
545
546
547
    end
  end

548
  delegate :branch_names, to: :raw_repository
549
550
  cache_method :branch_names, fallback: []

Douwe Maan's avatar
Douwe Maan committed
551
  delegate :tag_names, to: :raw_repository
552
553
  cache_method :tag_names, fallback: []

554
  delegate :branch_count, :tag_count, :has_visible_content?, to: :raw_repository
555
556
  cache_method :branch_count, fallback: 0
  cache_method :tag_count, fallback: 0
557
  cache_method :has_visible_content?, fallback: false
558
559

  def avatar
560
561
562
563
564
    # n+1: https://gitlab.com/gitlab-org/gitlab-ce/issues/38327
    Gitlab::GitalyClient.allow_n_plus_1_calls do
      if tree = file_on_head(:avatar)
        tree.path
      end
565
566
    end
  end
567
  cache_method :avatar
568

Sean McGivern's avatar
Sean McGivern committed
569
570
571
572
573
574
575
576
577
578
  def issue_template_names
    Gitlab::Template::IssueTemplate.dropdown_names(project)
  end
  cache_method :issue_template_names, fallback: []

  def merge_request_template_names
    Gitlab::Template::MergeRequestTemplate.dropdown_names(project)
  end
  cache_method :merge_request_template_names, fallback: []

579
  def readme
580
581
    if readme = tree(:head)&.readme
      ReadmeBlob.new(readme, self)
582
    end
583
584
  end

585
  def rendered_readme
Toon Claes's avatar
Toon Claes committed
586
    MarkupHelper.markup_unsafe(readme.name, readme.data, project: project) if readme
587
588
  end
  cache_method :rendered_readme
589

590
  def contribution_guide
591
    file_on_head(:contributing)
592
  end
593
  cache_method :contribution_guide
594
595

  def changelog
596
    file_on_head(:changelog)
597
  end
598
  cache_method :changelog
599

600
  def license_blob
601
    file_on_head(:license)
602
  end
603
  cache_method :license_blob
Zeger-Jan van de Weg's avatar
Zeger-Jan van de Weg committed
604

605
  def license_key
606
    return unless exists?
607

608
    Licensee.license(path).try(:key)
609
  end
610
  cache_method :license_key
611

Douwe Maan's avatar
Douwe Maan committed
612
613
  def license
    return unless license_key
614

615
    Licensee::License.new(license_key)
616
  end
617
  cache_method :license, memoize_only: true
618
619

  def gitignore
620
    file_on_head(:gitignore)
621
  end
622
  cache_method :gitignore
623
624

  def koding_yml
625
    file_on_head(:koding)
626
  end
627
  cache_method :koding_yml
628

629
  def gitlab_ci_yml
630
    file_on_head(:gitlab_ci)
631
  end
632
  cache_method :gitlab_ci_yml
633

634
  def head_commit
635
636
637
638
    @head_commit ||= commit(self.root_ref)
  end

  def head_tree
639
640
641
    if head_commit
      @head_tree ||= Tree.new(self, head_commit.sha, nil)
    end
642
643
  end

644
  def tree(sha = :head, path = nil, recursive: false)
645
    if sha == :head
646
647
      return unless head_commit

648
649
650
651
652
      if path.nil?
        return head_tree
      else
        sha = head_commit.sha
      end
653
654
    end

655
    Tree.new(self, sha, path, recursive: recursive)
656
  end
657
658

  def blob_at_branch(branch_name, path)
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
659
    last_commit = commit(branch_name)
660

Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
661
662
663
664
665
    if last_commit
      blob_at(last_commit.sha, path)
    else
      nil
    end
666
  end
667

668
  def last_commit_for_path(sha, path)
669
670
671
672
673
674
675
    raw_repository.gitaly_migrate(:last_commit_for_path) do |is_enabled|
      if is_enabled
        last_commit_for_path_by_gitaly(sha, path)
      else
        last_commit_for_path_by_rugged(sha, path)
      end
    end
676
  end
677

Hiroyuki Sato's avatar
Hiroyuki Sato committed
678
679
  def last_commit_id_for_path(sha, path)
    key = path.blank? ? "last_commit_id_for_path:#{sha}" : "last_commit_id_for_path:#{sha}:#{Digest::SHA1.hexdigest(path)}"
Hiroyuki Sato's avatar
Hiroyuki Sato committed
680

Hiroyuki Sato's avatar
Hiroyuki Sato committed
681
    cache.fetch(key) do
682
683
684
685
686
687
688
      raw_repository.gitaly_migrate(:last_commit_for_path) do |is_enabled|
        if is_enabled
          last_commit_for_path_by_gitaly(sha, path).id
        else
          last_commit_id_for_path_by_shelling_out(sha, path)
        end
      end
Hiroyuki Sato's avatar
Hiroyuki Sato committed
689
690
691
    end
  end

692
  def next_branch(name, opts = {})
693
694
    branch_ids = self.branch_names.map do |n|
      next 1 if n == name
695

696
      result = n.match(/\A#{name}-([0-9]+)\z/)
697
698
699
      result[1].to_i if result
    end.compact

700
    highest_branch_id = branch_ids.max || 0
701

702
703
704
    return name if opts[:mild] && 0 == highest_branch_id

    "#{name}-#{highest_branch_id + 1}"
705
706
  end

707
  def branches_sorted_by(value)
708
    raw_repository.local_branches(sort_by: value)
709
  end
710

711
712
  def tags_sorted_by(value)
    case value
haseeb's avatar
haseeb committed
713
714
715
    when 'name_asc'
      VersionSorter.sort(tags) { |tag| tag.name }
    when 'name_desc'
716
      VersionSorter.rsort(tags) { |tag| tag.name }
717
718
719
720
721
722
723
724
725
    when 'updated_desc'
      tags_sorted_by_committed_date.reverse
    when 'updated_asc'
      tags_sorted_by_committed_date
    else
      tags
    end
  end

726
727
728
729
730
  # Params:
  #
  # order_by: name|email|commits
  # sort: asc|desc default: 'asc'
  def contributors(order_by: nil, sort: 'asc')
731
    commits = self.commits(nil, limit: 2000, offset: 0, skip_merges: true)
732

733
    commits = commits.group_by(&:author_email).map do |email, commits|
734
735
      contributor = Gitlab::Contributor.new
      contributor.email = email
736

Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
737
      commits.each do |commit|
738
        if contributor.name.blank?
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
739
          contributor.name = commit.author_name
740
741
        end

742
        contributor.commits += 1
743
744
      end

745
746
      contributor
    end
747
    Commit.order_by(collection: commits, order_by: order_by, sort: sort)
748
  end
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
749

750
  def refs_contains_sha(ref_type, sha)
751
752
    args = %W(#{ref_type} --contains #{sha})
    names = run_git(args).first
753
754
755
756
757
758
759
760
761
762
763
764
765

    if names.respond_to?(:split)
      names = names.split("\n").map(&:strip)

      names.each do |name|
        name.slice! '* '
      end

      names
    else
      []
    end
  end
Hannes Rosenögger's avatar
Hannes Rosenögger committed
766

767
768
769
  def branch_names_contains(sha)
    refs_contains_sha('branch', sha)
  end
Hannes Rosenögger's avatar
Hannes Rosenögger committed
770

771
772
  def tag_names_contains(sha)
    refs_contains_sha('tag', sha)
Hannes Rosenögger's avatar
Hannes Rosenögger committed
773
  end
774

775
  def local_branches
776
    @local_branches ||= raw_repository.local_branches
777
778
  end

779
780
  alias_method :branches, :local_branches

781
782
783
784
  def tags
    @tags ||= raw_repository.tags
  end

Douwe Maan's avatar
Douwe Maan committed
785
786
  def create_dir(user, path, **options)
    options[:actions] = [{ action: :create_dir, file_path: path }]
787

788
    multi_action(user, **options)
Stan Hu's avatar
Stan Hu committed
789
790
  end

Douwe Maan's avatar
Douwe Maan committed
791
792
  def create_file(user, path, content, **options)
    options[:actions] = [{ action: :create, file_path: path, content: content }]
793

794
    multi_action(user, **options)
Stan Hu's avatar
Stan Hu committed
795
  end
796

Douwe Maan's avatar
Douwe Maan committed
797
798
799
  def update_file(user, path, content, **options)
    previous_path = options.delete(:previous_path)
    action = previous_path && previous_path != path ? :move : :update
800

Douwe Maan's avatar
Douwe Maan committed
801
    options[:actions] = [{ action: action, file_path: path, previous_path: previous_path, content: content }]
802

803
    multi_action(user, **options)
804
805
  end

Douwe Maan's avatar
Douwe Maan committed
806
807
  def delete_file(user, path, **options)
    options[:actions] = [{ action: :delete, file_path: path }]
808

809
    multi_action(user, **options)
810
811
  end

812
813
  def with_cache_hooks
    result = yield
814

815
    return unless result
816

817
818
    after_create if result.repo_created?
    after_create_branch if result.branch_created?
819

820
821
822
    result.newrev
  end

823
824
  def multi_action(user, **options)
    start_project = options.delete(:start_project)
Marc Siegfriedt's avatar
Marc Siegfriedt committed
825

826
827
    if start_project
      options[:start_repository] = start_project.repository.raw_repository
Marc Siegfriedt's avatar
Marc Siegfriedt committed
828
829
    end

830
    with_cache_hooks { raw.multi_action(user, **options) }
831
832
833
834
835
836
837
838
839
840
841
842
843
  end

  def can_be_merged?(source_sha, target_branch)
    our_commit = rugged.branches[target_branch].target
    their_commit = rugged.lookup(source_sha)

    if our_commit && their_commit
      !rugged.merge_commits(our_commit, their_commit).conflicts?
    else
      false
    end
  end

844
845
846
847
848
849
  def merge(user, source_sha, merge_request, message)
    with_cache_hooks do
      raw_repository.merge(user, source_sha, merge_request.target_branch, message) do |commit_id|
        merge_request.update(in_progress_merge_commit_sha: commit_id)
        nil # Return value does not matter.
      end
850
    end
851
852
  end

853
  def ff_merge(user, source, target_branch, merge_request: nil)
854
855
    their_commit_id = commit(source)&.id
    raise 'Invalid merge source' if their_commit_id.nil?
856

857
    merge_request&.update(in_progress_merge_commit_sha: their_commit_id)
858

859
    with_cache_hooks { raw.ff_merge(user, their_commit_id, target_branch) }
860
861
  end

862
  def revert(
863
    user, commit, branch_name, message,
864
    start_branch_name: nil, start_project: project)
865

866
867
868
869
870
871
872
873
874
    with_cache_hooks do
      raw_repository.revert(
        user: user,
        commit: commit.raw,
        branch_name: branch_name,
        message: message,
        start_branch_name: start_branch_name,
        start_repository: start_project.repository.raw_repository
      )
875
    end
876
877
  end

878
  def cherry_pick(
879
    user, commit, branch_name, message,
880
    start_branch_name: nil, start_project: project)
881

882
883
884
885
886
887
888
889
890
    with_cache_hooks do
      raw_repository.cherry_pick(
        user: user,
        commit: commit.raw,
        branch_name: branch_name,
        message: message,
        start_branch_name: start_branch_name,
        start_repository: start_project.repository.raw_repository
      )
891
892
893
    end
  end

894
  def merged_to_root_ref?(branch_or_name)
895
896
897
    branch = Gitlab::Git::Branch.find(self, branch_or_name)

    if branch
898
899
      same_head = branch.target == root_ref_sha
      merged = ancestor?(branch.target, root_ref_sha)
900
      !same_head && merged
901
902
903
904
905
    else
      nil
    end
  end

906
907
908
909
  def root_ref_sha
    @root_ref_sha ||= commit(root_ref).sha
  end

910
911
  delegate :merged_branch_names, to: :raw_repository

912
  def merge_base(first_commit_id, second_commit_id)
913
914
    first_commit_id = commit(first_commit_id).try(:id) || first_commit_id
    second_commit_id = commit(second_commit_id).try(:id) || second_commit_id
915
    raw_repository.merge_base(first_commit_id, second_commit_id)
Douwe Maan's avatar
Douwe Maan committed
916
917
  rescue Rugged::ReferenceError
    nil
918
919
  end

920
  def ancestor?(ancestor_id, descendant_id)
921
    return false if ancestor_id.nil? || descendant_id.nil?
922

923
924
    Gitlab::GitalyClient.migrate(:is_ancestor) do |is_enabled|
      if is_enabled
925
        raw_repository.ancestor?(ancestor_id, descendant_id)
926
      else
Jacob Vosmaer's avatar
Jacob Vosmaer committed
927
        rugged_is_ancestor?(ancestor_id, descendant_id)
928
929
      end
    end
930
931
  end

932
  def search_files_by_content(query, ref)