1# frozen_string_literal: true
2
3# This concern is created to handle repository actions.
4# It should be include inside any object capable
5# of directly having a repository, like project or snippet.
6#
7# It also includes `Referable`, therefore the method
8# `to_reference` should be overridden in case the object
9# needs any special behavior.
10module HasRepository
11  extend ActiveSupport::Concern
12  include Referable
13  include Gitlab::ShellAdapter
14  include Gitlab::Utils::StrongMemoize
15
16  delegate :base_dir, :disk_path, to: :storage
17  delegate :change_head, to: :repository
18
19  def valid_repo?
20    repository.exists?
21  rescue StandardError
22    errors.add(:base, _('Invalid repository path'))
23    false
24  end
25
26  def repo_exists?
27    strong_memoize(:repo_exists) do
28      repository.exists?
29    rescue StandardError
30      false
31    end
32  end
33
34  def repository_exists?
35    !!repository.exists?
36  end
37
38  def root_ref?(branch)
39    repository.root_ref == branch
40  end
41
42  def commit(ref = 'HEAD')
43    repository.commit(ref)
44  end
45
46  def commit_by(oid:)
47    repository.commit_by(oid: oid)
48  end
49
50  def commits_by(oids:)
51    repository.commits_by(oids: oids)
52  end
53
54  def repository
55    raise NotImplementedError
56  end
57
58  def storage
59    raise NotImplementedError
60  end
61
62  def full_path
63    raise NotImplementedError
64  end
65
66  def lfs_enabled?
67    false
68  end
69
70  def empty_repo?
71    repository.empty?
72  end
73
74  def default_branch
75    @default_branch ||= repository.empty? ? default_branch_from_preferences : repository.root_ref
76  end
77
78  def default_branch_from_preferences
79    (default_branch_from_group_preferences || Gitlab::CurrentSettings.default_branch_name).presence
80  end
81
82  def default_branch_from_group_preferences
83    return unless respond_to?(:group)
84    return unless group
85
86    group.default_branch_name || group.root_ancestor.default_branch_name
87  end
88
89  def reload_default_branch
90    @default_branch = nil # rubocop:disable Gitlab/ModuleWithInstanceVariables
91
92    default_branch
93  end
94
95  def url_to_repo
96    ssh_url_to_repo
97  end
98
99  def ssh_url_to_repo
100    Gitlab::RepositoryUrlBuilder.build(repository.full_path, protocol: :ssh)
101  end
102
103  def http_url_to_repo
104    Gitlab::RepositoryUrlBuilder.build(repository.full_path, protocol: :http)
105  end
106
107  # Is overridden in EE::Project for Geo support
108  def lfs_http_url_to_repo(_operation = nil)
109    http_url_to_repo
110  end
111
112  def web_url(only_path: nil)
113    Gitlab::UrlBuilder.build(self, only_path: only_path)
114  end
115
116  def repository_size_checker
117    raise NotImplementedError
118  end
119
120  def after_repository_change_head
121    reload_default_branch
122  end
123
124  def after_change_head_branch_does_not_exist(branch)
125    # No-op (by default)
126  end
127end
128